Windows phone 8 Kids corner issue which makes it useless

There is a great feature in windows phone 8 that is kids corner, it is a privacy and protection mechanism that keeps kids from the main course of phone and give them there own space to play and learn.

The point is “You cannot password protect your phone main area while using kids corner, in fact both gets password protected.” Good way could be that if system is password protected, kids corner should be opened easily so kids can do there stuff without getting on your nerves each and every minute.

May be they can easy out this flow in later builds.

Good news is finally here

The wait is finally over. By the Grace of Almighty Allah, I have just became MVP (Microsoft Most Valuable Professional) for Visual C#. Its an achievement I have been thriving for and I finally reached the mark. I am excited and happy now!!

I would like to thanks the whole Microsoft Pakistan DPE TEAM, specially the DPE Lead Mr. Tahir Masood for the guidance and efforts put into this award. I would also like to thank my MVP Lead Hande for all the efforts put into this. And my whole family who were always there for me.

I will look forward to put my best in near future.

Good way to write code – A

Lots of time, we can increase readability and performance of our app by using good programming practices. Like I was doing once like below:

if (IsolatedStorageWrapper.LoadString(“ShowTipsAndTricks”) == “”)
{
IsolatedStorageWrapper.SaveString(“ShowTipsAndTricks”, “true”);
}
else
{
IsolatedStorageWrapper.SaveString(“ShowTipsAndTricks”, “”);
}

now this is something we do most of the times, but all this can be done in one line of code as well, see below:

IsolatedStorageWrapper.SaveString(“ShowTipsAndTricks”, IsolatedStorageWrapper.LoadString(“ShowTipsAndTricks”) == “” ? “true” : “”);

The compiler will have to traverse through less lines, and we might some less CPU cycles :)

An Introduction to New Features in C# 5.0

Introduction of New Features in C# 5.0

 1. C# Evolution Matrix

Microsoft just published a new version of C# : 5.0 beta with CLR version 4.5 (Visual Studio 11 beta). In order to get a big picture of the whole evolution of C# language, I summarized all the key features into a C# Evolution Matrix for your reference as below diagram shows:

In C# version 5.0, there are two key features: Async Programming and Caller Information.

2. Async Feature

b. Caller Information

‘Is’ Operator in C#

It is possible for a program with some local variable x:

bool b = x is FooBar;

to assign true to b at runtime, even though there is no conversion, implicit or explicit, from x to FooBar allowed by the compiler! That is,

FooBar foobar = (FooBar)x;

would not be allowed by the compiler in that same program.

The intention of the operator is to determine if the runtime value of x is actually a useful value of the type T, (*) and therefore we add a few additional caveats:
•T may not be a pointer type
•x may not be a lambda or anonymous method
•if x is classified as a method group or is the null literal (**) then the result is false
•if the runtime type of x is a reference type and its value is a null reference then the result is false
•if the runtime type of x is a nullable value type and the HasValue property of its value is false then the result is false
•if the runtime type of x is a nullable value type and the HasValue property of its value is true then the result is computed as though you were checking x.Value is T

C# is a strongly type language or a weakly typed language

A debate that can hold different point of views in different scenarios. It is impossible to say because it depends on the point of view of the speaker, it depends on what they are comparing it to, and it depends on their attitude towards various language features.

C# is a pragmatic language there is a way to override all three of those safety systems. Cast operators and “dynamic” in C# 4 override compile-time type checking and replace it with runtime type checking, and “unsafe” blocks allow you to turn off type safety and memory safety should you need to. Someone who thinks that “strongly typed” means “the language absolutely positively guarantees static typing, type safety and memory safety under all circumstances” would quite rightly classify C# as “weakly typed”. C# is not as strongly typed as languages that do enforce these restrictions all the time.

Lets keep it simple by saying that C# is a strongly typed language as well as holds features of weakly typed language as well, and it depends on how we want to mold it according to scenarios. And I guess this adaptability makes C# a strong language competitor if there is to make a choice.

Using Sterling as DB for Windows phone 8

Sterling is a nice option for NO SQL fans, who intent to save C# POCO objects into Isolated Storage container of windows phone 8. I will make life easier by pasting in the snippets for initializing the sterling engine, registering tables in a database, Saving data into the db. in a pretty straight forward manner.

Initializing the database:
public class FakeDatabase : BaseDatabaseInstance
{
protected override System.Collections.Generic.List RegisterTables()
{
return new List()
{
this.CreateTableDefinition(c=>c.Id)
};

}
}
Defining our POCO entity:
public class Info
{
public int Id { get; set; }
public string name { get; set; }
}
Registering and saving in the DB:
public partial class login : PhoneApplicationPage
{
private SterlingEngine engine;
private SterlingDefaultLogger logger;
public static ISterlingDatabaseInstance DB { get; set; }

public login()
{
InitializeComponent();
InitDB();

}
private void InitDB()
{
engine = new SterlingEngine();
engine.SterlingDatabase.RegisterSerializer();
engine.Activate();

DB = engine.SterlingDatabase.RegisterDatabase(new IsolatedStorageDriver());
IEnumerable ListItems;
ListItems = DB.Query().Select(c => c.LazyValue.Value);
var listItems = ListItems as Info[] ?? ListItems.ToArray();
DB.Save(new Info() { Id = listItems.Count() + 1, name = “Ali” + (listItems.Count() + 1).ToString(CultureInfo.InvariantCulture) });
DB.Flush();
ListItems = DB.Query().Select(c => c.LazyValue.Value);
listItems = ListItems as Info[] ?? ListItems.ToArray();
MessageBox.Show(listItems.Count().ToString(CultureInfo.InvariantCulture));
}

private void Button_Click_1(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri(“/MainPage.xaml”,UriKind.Relative));
}

private void Button_Click_2(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri(“/ForgotPassword.xaml”, UriKind.Relative));
}
}

Windows Azure Overview

1st March 2013
Venue: Talented Earth Organization
Speaker: Ali Sufyan Butt

This is intended for TEO community, but we do want to invite at least 10 candidates from outside teo to come and join the session. Interested people should email me at pentiumali@gmail.com

Switch or If-Else

It’s extremely unlikely that an if/else or a switch is going to be the source of your performance woes. If you’re having performance problems, you should do a performance profiling analysis first to determine where the slow spots are. Premature optimization is the root of all evil!

Still, you did ask about performance, and it’s possible to talk about the relative performance of switch vs. if/else with the Java compiler optimizations. First note that in Java, switch statements operate on a very limited domain — integers. In general, you can view a switch statement as follows:

switch () {
case c_0: …
case c_1: …

case c_n: …
default: …
}

where c_0, c_1, …, and c_N are integral numbers that are targets of the switch statement, and must resolve to an integer expression.

•If this set is “dense” — that is, (max(ci) + 1 – min(ci)) / n > α, where 0 < k < α < 1, where k is larger than some empirical value, a jump table can be generated, which is highly efficient. •If this set is not very dense, but n >= β, a binary search tree can find the target in O(2 * log(n)) which is still efficient too.

For all other cases, a switch statement is exactly as efficient as the equivalent series of if/else statements. The precise values of α and β depend on a number of factors and are determined by the compiler’s code-optimiziation module.

Finally, of course, if the domain of is not the integers, a switch statement is completely useless.

Rapid Competition

Make a windows 8 combo app ( An app that is on both wp8 and windows 8 metro platform ) and win rewards:

Criteria:
========
1- Nice graphics ( Metro Style )
2- Functionality ( Value added feature/s )
3- Uniqueness ( Never heard before )
4- Technology Usage ( Tiles, Push Notifications, Hardware .. )
5- Number of downloads / Number of ratings / Purchases ( A factor would be applied on overall winning rating based on these as well )

Rewards for the winner:
======================
1- 2GB Windows Azure USB by Microsoft
2- Your app would be highlighted on our website
3- If you app reaches high sales above 300$, first payment would be made to the developer, after that all profits to us :)
4- Microsoft writing pads (5)

Last date of entries is 28th Feb, Hurry up guys to get the perks.

Send your entries to portal@technocrux.com with subject as “Rapid Competition”, also lookout on this entry for further details as well.

WPF Hyperlink Button Style

Here is an implementation to style a button as a link button in WPF


                

Setting Initial Focus in WPF Form

In WPF dialog boxes, I quite often see some code which looks like the following code. example.

private void OnLoaded(object sender, EventArgs e)
{
    this._textSearch.Focus();
}

This is usually accompanied by some XAML that likes like the following XAML example.

<Window ...
        Loaded="OnLoaded">

Occasionally, I also see the event being setup up in the constructor. For some reason this really gets on my nerves. I much prefer to see event handlers defined in the XAML. I’m not quite sure what my objection is; I think I just prefer to see all the UI things in one place.

What this actually achieves (as you can probably work out), is that the control (in this case a TextBox) named _textSearch has focus when the dialog box is loaded. In actual fact, WPF provides a much easier way of setting the initial focus by using the FocusManager. The FocusManager provides a set of static methods, properties, and events that you use to determine and set the focus scope[1] and to set the focused element within the focus scope.

So, using the FocusManager, you don’t need to handle the Loaded event and manually calling the Focus method as shown in the previous code examples, you can simply set the FocusedElement on the FocusManager as shown in the following code example.

<Window ...
        FocusManager.FocusedElement="{Binding ElementName=_textSearch}">

 

Simple, neat, all in one place, and no code-behind :)

Nvidia unveils Project SHIELD Android and PC gaming console

Nvidia has announced Project SHIELD, a portable gaming console that can play Android games or stream games from the Steam library of Nvidia-powered PCs.

The handheld console comes with the new Nvidia Tegra 4 mobile processor, which combines ARM’s quad-core Cortex-A15 and Nvidia’s custom 72-core GeForce graphics chip, resulting in what the company claims is the fastest processor for mobile devices in the world, while also delivering much-needed power saving features for power-hungry portable computing.

On the surface of it Project SHIELD looks much like MOGA, a handheld Android gaming system, but one of the many key differences is that Nvidia’s device packs everything in, not requiring a user to attach their smartphone to act as a screen and the processing power behind everything.

Project SHIELD has a built-in 5-inch multitouch screen, with a resolution of 1280×720, that folds down over the controller, which is more like a traditional console controller than the ones we have encountered with other handheld consoles from Nintendo and Sony.

Another major feature is the ability to play Windows games, thanks to streaming content. While the operating system is Android Jelly Bean, and users can access games from Google Play or Nvidia’s Tegrazone, the built-in Wi-Fi allows for streaming games from a PC using Nvidia architecture, including titles from Steam, opening up a huge collection of games that Android-only devices do not have.

“Project SHIELD was created by NVIDIA engineers who love to game and imagined a new way to play,” said Jen-Hsun Huang, CEO and co-founder of Nvidia. “We were inspired by a vision that the rise of mobile and cloud technologies will free us from our boxes, letting us game anywhere, on any screen. We imagined a device that would do for games what the iPod and Kindle have done for music and books, letting us play in a cool new way. We hope other gamers love SHIELD as much as we do.”

The move is a major shift for Nvidia, which is usually powering the systems under the hood of many gaming rigs. Now it is set to become potentially a major player in the handheld console market, taking advantage of the mobile gaming boom to deliver a two-in-one system with potent architecture to power it.

We will likely find out more, such as pricing and a release date, at this year’s E3.

Kinect Advance Programming Session at HEC Islamabad

today I gave a session at Higher Education commission Pakistan about Kinect Programming. The agenda was to use common features in programming Kinect app like, ColorImageFrame, DepthImageFrame, SkeletonFrame, Skeleton tracking, Making gestures, Speech recognition, see device capabilities, possible applications. The overall response was great and I saw people interested in making apps using this device in future.

Universities attending the session were,

University ok Karachi
Virtual University
Sindh Agriculture University
Govt. Collage Uni Lahore
Lahore collage for Women University
IBA Karachi

Please find the Kinect Session Slides below:

Kinect Session Slides

Basics of Kinect – Demo App

In this app, we will do ColorImageFrame, Skeletal Tracking, add a normal gesture that if you move your hand above your head it will show a message to user. We will also see how to use depth Frame as well.

UI CODE:
///////






    
        

            
            
            
            
            
            
        
    





CODE BEHIND:
///////////




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Kinect;
using Microsoft.Kinect.Toolkit;
using Microsoft.Kinect.Toolkit.FaceTracking;

using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace KinectDemo1
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        private static readonly int Bgr32BytesPerPixel = (PixelFormats.Bgr32.BitsPerPixel + 7) / 8;
        private readonly KinectSensorChooser sensorChooser = new KinectSensorChooser();
        private WriteableBitmap colorImageWritableBitmap;
        private byte[] colorImageData;
        private ColorImageFormat currentColorImageFormat = ColorImageFormat.Undefined;
        bool closing = false;
        const int skeletonCount = 6;
        Skeleton[] allSkeletons = new Skeleton[skeletonCount];


        public MainWindow()
        {
            InitializeComponent();

            sensorChooser.KinectChanged += sensorChooser_KinectChanged;

            sensorChooser.Start();
            
        }

        void _sensor_AllFramesReady(object sender, AllFramesReadyEventArgs e)
        {
            if (closing)
            {
                return;
            }
            
           

            
        }


        void sensorChooser_KinectChanged(object sender, KinectChangedEventArgs e)
        {
            KinectSensor oldSensor = e.OldSensor;
            StopKinect(oldSensor);


            KinectSensor newSensor = e.NewSensor;


            var parameters = new TransformSmoothParameters
            {
                Smoothing = 0.3f,
                Correction = 0.0f,
                Prediction = 0.0f,
                JitterRadius = 1.0f,
                MaxDeviationRadius = 0.5f
            };

            this.colorPixels = new byte[newSensor.ColorStream.FramePixelDataLength];
            this.colorPixelsDepth = new byte[newSensor.ColorStream.FramePixelDataLength];
            // This is the bitmap we'll display on-screen
            this.colorBitmap = new WriteableBitmap(newSensor.ColorStream.FrameWidth, newSensor.ColorStream.FrameHeight, 96.0, 96.0, PixelFormats.Bgr32, null);
            this.colorBitmapDepth = new WriteableBitmap(newSensor.ColorStream.FrameWidth, newSensor.ColorStream.FrameHeight, 96.0, 96.0, PixelFormats.Bgr32, null);
            
            newSensor.AllFramesReady += new EventHandler(_sensor_AllFramesReady);
            newSensor.ColorFrameReady += newSensor_ColorFrameReady;
            newSensor.SkeletonFrameReady += newSensor_SkeletonFrameReady;
            newSensor.DepthFrameReady += newSensor_DepthFrameReady;
            newSensor.ColorStream.Enable(ColorImageFormat.RgbResolution640x480Fps30);
            newSensor.DepthStream.Enable(DepthImageFormat.Resolution640x480Fps30);
            
            newSensor.SkeletonStream.Enable(parameters);


            try
            {
                newSensor.Start();
            }
            catch (System.IO.IOException)
            {
                sensorChooser.TryResolveConflict();


            }
        }

        void newSensor_DepthFrameReady(object sender, DepthImageFrameReadyEventArgs e)
        {
            DepthImageFrame imageFrame = e.OpenDepthImageFrame();
                if (imageFrame != null)
                {
                    short[] pixelData =  new short[imageFrame.PixelDataLength];
                    imageFrame.CopyPixelDataTo(pixelData);
                
                int[] depth = new int[
                    imageFrame.PixelDataLength];
                int[] player = new int[
                                imageFrame.PixelDataLength];

                for (int i = 0; i < depth.Length; i++)
                {
                    player[i] = pixelData[i] &
                           DepthImageFrame.PlayerIndexBitmask;
                    depth[i] = ((ushort)pixelData[i]) >>
                        DepthImageFrame.PlayerIndexBitmaskWidth;
                }
                this.colorBitmapDepth.WritePixels(
                            new Int32Rect(0, 0, this.colorBitmapDepth.PixelWidth, this.colorBitmapDepth.PixelHeight),
                            this.colorPixelsDepth,
                            this.colorBitmapDepth.PixelWidth * sizeof(int),
                            0);
                imgKinectDepth.Source = colorBitmapDepth;
                }
        }

        

        void newSensor_SkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
        {
            using (SkeletonFrame skeletonFrameData = e.OpenSkeletonFrame())
            {
                if (skeletonFrameData != null)
                {
                    
                

                skeletonFrameData.CopySkeletonDataTo(allSkeletons);

                Skeleton first = (from s in allSkeletons
                                  where s.TrackingState == SkeletonTrackingState.Tracked
                                  select s).FirstOrDefault();
                    if (first != null)
                    {
                        SetEllipsePosition(Head, first.Joints[JointType.Head]);
                        SetEllipsePosition(leftHand, first.Joints[JointType.HandLeft]);
                        SetEllipsePosition(rightHand, first.Joints[JointType.HandRight]);
                        ProcessHandsUpGesture(first.Joints[JointType.Head], first.Joints[JointType.HandLeft], first.Joints[JointType.HandRight]);

                    }
                }
            }
        }
        /// 
        /// Bitmap that will hold color information
        /// 
        private WriteableBitmap colorBitmap;
        private WriteableBitmap colorBitmapDepth;
        /// 
        /// Intermediate storage for the color data received from the camera
        /// 
        private byte[] colorPixels;
        private byte[] colorPixelsDepth;

        void newSensor_ColorFrameReady(object sender, ColorImageFrameReadyEventArgs e)
        {

            using (ColorImageFrame colorFrame = e.OpenColorImageFrame())
            {
                if (colorFrame != null)
                {
                    // Copy the pixel data from the image to a temporary array
                    colorFrame.CopyPixelDataTo(this.colorPixels);

                    // Write the pixel data into our bitmap
                    this.colorBitmap.WritePixels(
                        new Int32Rect(0, 0, this.colorBitmap.PixelWidth, this.colorBitmap.PixelHeight),
                        this.colorPixels,
                        this.colorBitmap.PixelWidth * sizeof(int),
                        0);
                }
            }
            imgKinect.Source = colorBitmap;

        }


        void StopKinect(KinectSensor sensor)
        {
            if (sensor != null)
            {
                sensor.Stop();
                sensor.AudioSource.Stop();

            }
        }

        private void ProcessHandsUpGesture(Joint head, Joint handleft, Joint handright)
        {
            if (handright.Position.Y > head.Position.Y)
            {
                this.Title = "Your Hand Is Above Your Head";
            }
        }

        private void SetEllipsePosition(Ellipse ellipse, Joint joint)
        {
            SkeletonPoint vector = new SkeletonPoint();
            vector.X = ScaleVector(640, joint.Position.X);
            vector.Y = ScaleVector(480, -joint.Position.Y);
            vector.Z = joint.Position.Z;

            Joint updatedJoint = new Joint();
            //updatedJoint = joint.ID;
            updatedJoint.TrackingState = JointTrackingState.Tracked;
            updatedJoint.Position = vector;

            Canvas.SetLeft(ellipse, updatedJoint.Position.X);
            Canvas.SetTop(ellipse, updatedJoint.Position.Y);


        }

        private float ScaleVector(int length, float position)
        {
            float value = (((((float)length) / 1f) / 2f) * position) + (length / 2);
            if (value > length)
            {
                return (float)length;
            }
            if (value < 0f)
            {
                return 0f;
            }
            return value;
        }


        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            StopKinect(sensorChooser.Kinect);
        }


    }
}