Monday, September 15, 2014

Work with Async

Asynchronous Programming

If you are working with applications such as windows store and Windows Phone applications you may be found lot of functions that with Async keyword. Why Async?
We need async because when working with applications that interact with network (web, local network) , database, Files and reading hardware in the device are much more slower than the usual execution. Because of it communication bottlenecks are occur.

To avoid those communication bottlenecks async is born.

What Async Does ?

Async allows to run those delayed tasks in the background and meanwhile program can do what ever operations that does not depend on the awaited task.
simply,
"With Async Application can continue with other works that doesn’t depend on blocked resource until the blocked task finished"

Asynchronous programming available with .NET framework 4,5 onwards with Visual studio 2012. If you working on visual Studio 2012 without installing any of other libraries you can work on async

Concepts

Task
Task encapsulate all units of works in the async. Task contains following properties

  • State : Running , Finished , Cancelled
  • Result
  • Thrown Exceptions
It will handle each and every exceptions and it throws all exceptions when task is finished.(await finished)


Important

If you really want to implement async methods and use them remember async and await keywords.

async keyword informs the compiler this method need to be handle separately by itself. Await keyword indicate the suspension of relative running async task.

When working with async,
  • Use Async Suffix  | e.g. DownloadAsync
  • Return Task or Task<T> according to situation
  • void for only event handlers  

Example Wpf Code with simple async operation

public partial class MainWindow : Window
  {
      public MainWindow()
      {
          InitializeComponent();
      }
      private void btnNormal_Click(object sender, RoutedEventArgs e)
      {
          resultTxt.Text = getString("sample");
          independentWork();
      }
      private async void btnAsync_Click(object sender, RoutedEventArgs e)
      {
          resultTxt.Text = await getStringAsync();
      }
      /// <summary>
      /// Method with waiting in synchronize way
      /// ///
      /// </summary>
      /// <returns></returns>
      private string getString(string name)
      {
          //Task.Delay(2000);
          Thread.Sleep(2000);
          return "My String";
      }
      /// <summary>
      /// same method calling from async
      /// </summary>
      /// <returns></returns>
      private async Task<string> getStringAsync()
      {
          Task<string> asyncTask = Task.Factory.StartNew(() => getString("sample"));
          independentWork();
          return await asyncTask;
      }
      
      /// <summary>
      /// this work is independent from others
      /// </summary>
      private void independentWork()
      {
          resultTxt.Text += "\n independent work is done ";
      }
  }





Download Sample Code Here

Saturday, September 13, 2014

Improve Performance of the Application

As and software producer all of us want to do is software product with correct functionality. Is that enough ? No. We need to give product with correct functionality with optimum resource consumption as well.

Today I'm going to tell you some tips and trikes about resource optimization. basically it is about Memory and CPU resources.

1. Switch for multiple If
 When you are using multiple If conditions ( Most of the time more than 2 ) CPU (Registry level) instructions check as far as use much If with code. It consume more registers in CPU. But with switch it just use check and Jump CPU instruction that far more faster than assignments. Using jump tables makes switches much faster than some if-statements

Use switch when ever possible once you find more than two if statements.

2. Use structures according to the situation
Execution of class is much more consume resources than class.  Whenever you don't need to use functions bind with objects and when you don't go with boxing and unboxing much with code.

3. Chunky calls
Don't let your functions to handle lot of task by itself. use modularity to avoid it.

4. Add Collections
Never try to assign collection items one by one to the another collection. Just try to use simple casting and try to add entire collection directly.

5. Working with strings.
When you are working with string most of the cases we try to concatenate string by '+'operator.(including me ). But sad story is there is more optimal solution than that. use string bulider to concatenate strings.

Here for start.

6. Use bits whenever as possible.
I saw most of the programmers use integers/strings to hold the simple states, flags. Please don't do that there is more than 2 states. Just use bit or bool to store states. It will optimize code and resource as well. ( Simply bit is smaller than more bits)

7. Array as possible
When we use simple basic array it will helpful to maintain machine instructions(registry). Other collections need more than array because most of them are derived form it. Array is basic element in modern machine instructions.

8. ObservableCollection vs List
Use List whenever that your items not binded with the UI. Observation collections are derived from List and it also holds the property changed notifications. If there is no use of property change go for List.  ObservableCollection check the property change when it on use and because of that it consume more.

9. For than foreach
Use while, for and do while loops wherever than foreah. foreach has good performance but basic loops are better than it.

10. ToString
Some  programmers use ToString method wherever elements are already strings. Use ToString wherever the element that con the string. don't use ToString as habit. With integers use
ToStringLookup will optimize memory heap that using with converting integer.

11. Don't sort collections already sorted.
Check collection already sorted or not before sort it.

12. Global variables.
Use global variables when you using same type of object frequently

13. Constant and static
Constants are not assignable memories but they are easy to load.

Static is more faster than instant creations. When load statics no need of run time to check the instance



Hope this is helps...



Wednesday, September 10, 2014

Starts with MVVM

With the growth of programming and application development  there are major requrement that emerged the design patterns. Such as MVP(Model View Presentation) and MVC (Model View Controller) are common design patterns that allows developer to isolate codes. Bu the advanced features of XAML such as data biding, data templates, commands and on demand interaction between application and logic's guide world to MVVM (Model View ViewModel)

MVVM basically derived from the MVC design pattern. It clearly  create separation between these MVVM layers more than MVC.














Model contains all abstraction of data  not any logic's behind data. View is contains XAML views still not the logics. Importance is Model and view are not directly inter action with each other.


ViewModel Contains all  business logic's and data bind properties such as Collections. And it will interact with the View and Model. It takes notifications from model and send them to View as well as other way around.

Ex: If new item added to collection in view It automatically notify and update the View without any interaction.

Study Simple MVVM code here










Full Code In Media Fire 
http://bit.ly/MvvMDemo

 






Amazing Lumia SensorCore SDK

Lumia SensorCore SDK is a collection of APIs utilising data from different sensors (for example, accelerometer) and also location information. This information can be used to track user’s physical activities and motion. The sensors are able to run constantly in the background, collecting and preserving data for up to past ten days. Even though they are constantly active, the sensors run in a low power mode, consuming only a negligible amount of battery. Since the sensors may provide access to user’s private data, data privacy is a critical part of the design. User has always the option of disabling SensorCore SDK sensors and clearing any collected data.
The Lumia SensorCore SDK will be available initially for Lumia 1520, Lumia Icon, Lumia 930, Lumia 630 and 635, running on Windows Phone 8.1 with Cyan firmware.

Lumia SensorCore SDK beta

The following features are included in Lumia SensorCore SDK beta:
  • Step counter counts the user's walking and running steps.
  • Activity monitor determines the current type of motion of the phone and the user.
  • Place monitor identifies user's home, work, and known visited places.
  • Track point monitor records location points along the route the user has taken.
Key characteristics of Lumia SensorCore SDK:
  • Power and memory efficient.
  • Secure data storage on the phone.
  • Access to Motion history for up to past ten days.

Friday, September 5, 2014

Variable Size Tile App Template By Me

This is One of Customized template that I created for windows 8. Took some of the Templates of codeplex as strach. It provide color bound variable aized grid in Main page and VAriable sized grid as musing datiddle page.



You can edit data sources as you wish by using classes in data Model. Those classes are in same manner that sample data templates provided by microsoft.



In detail page this template provide Rich textbox for display detailed descripton.



and some other colums for misalanious data.



You can change the layout and order of the grid view by editing LayoutClass directory ,



just edit the

_sequence = new List<Size> {

                LayoutSizes.PrimaryItem,

                LayoutSizes.SecondarySmallItem, LayoutSizes.SecondarySmallItem,

                LayoutSizes.SecondarySmallItem,

                LayoutSizes.SecondaryTallItem,

                LayoutSizes.OtherSmallItem, LayoutSizes.OtherSmallItem, LayoutSizes.OtherSmallItem,LayoutSizes.SecondaryTallItem, LayoutSizes.OtherSmallItem, LayoutSizes.OtherSmallItem,

                LayoutSizes.OtherSmallItem,LayoutSizes.OtherSmallItem,LayoutSizes.SecondaryTallItem,LayoutSizes.OtherSmallItem,LayoutSizes.OtherSmallItem,LayoutSizes.OtherSmallItem,

                LayoutSizes.SecondaryTallItem,LayoutSizes.OtherSmallItem,LayoutSizes.OtherSmallItem,LayoutSizes.OtherSmallItem,LayoutSizes.OtherSmallItem,LayoutSizes.SecondaryTallItem,

                LayoutSizes.OtherSmallItem,LayoutSizes.OtherSmallItem               

            };



in constructor of each class





http://bit.ly/VarGrid Download and Rate