Windows 8 Consumer Preview is available to Download

image

Folks on the leap day of lap year 2012 are you feeling Metrofied ? Certainly I am , Eventually we have got what we have been waiting since BUILD. Windows 8 Consumer Preview is available to download.

Download ISO image of Windows 8 Consumer Preview from here

clip_image001

Image taken from web.

As they are saying there are more than 10000 changes in consumer preview from the developer preview. Seems there are apps like Kindle, Dictionary etc. are there in the preview.

Download ISO image of Windows 8 Consumer Preview from here

Download Windows 8 and enjoy. I will be doing more developer centric blog post on the same in coming days.

 

How to create WCF REST Service and host in Windows Azure

In this post, we will create a WCF REST Service and host in Windows Azure. We will learn following things in this post

  • Working with WCF Web Role
  • Enabling REST on WCF Web Role
  • Returning XML and JSON from REST service
  • Deploying WCF Service Web Role to Windows Azure

We need to host WCF Service in Windows Azure. So create project choosing WCF Service Web Role from Cloud tab.

image

We are going to return list of Players from the Service as XML and JSON. For that add a class to project called Players and attribute it as DataContract. Below I am creating Players class and attributing the class as DataContract and all the properties as DataMember.


[DataContract]
public class Players
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Sports { get; set; }
[DataMember]
public string Country { get; set; }
[DataMember]
public string ImageUrl { get; set; }

}

After creating DataContract, we need to create ServiceContract. I am creating ServiceContract with two OperationContracts. One OperationContract is retuning XML whereas another is returning JSON. ServiceContract is given below,

IService1.cs


[ServiceContract]
public interface IService1
{

[WebGet(UriTemplate="/GetPlayersXml",
RequestFormat=WebMessageFormat.Xml,
ResponseFormat=WebMessageFormat.Xml,
BodyStyle= WebMessageBodyStyle.Bare)]
List<Players> GetPlayersXml();

[WebGet(UriTemplate = "/GetPlayersJson",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare)]
List<Players> GetPlayersJson();

}

  • There are two operation contracts.
  • GetPlayersXml function will be returning XML as response.
  • GetPlayersJson function will be rturning JSON as response.
  • Using WebGet attribute REST behavior has been enabled on the Operation Contracts.
  • We can get Players as XML at Uri baseaddress/Service1.svc/GetPlayersXml and as JSON at Uri baseaddress/Service1.svc/GetPlayersJson

We have created DataContract and defined the ServiceContract. Next we need to implement service. In implementing I am returning hardcoded data however you can return data from SQL Azure or Azure Storage as well. Service is implemented as below,

Service1.svc.cs


public class Service1 : IService1
{
public List<Players> GetPlayersXml()
{
return GetPlayers();
}

public List<Players> GetPlayersJson()
{
return GetPlayers();

}

private List<Players> GetPlayers()
{
List<Players> Players = new List<Players>
{
new Players
{
Country ="India", Name="Sachin Tendulkar",Sports ="Cricket", ImageUrl="sachin.jpg"
},
new Players
{
Country ="India", Name="MS Dhoni",Sports ="Cricket", ImageUrl="dhoni.jpg"
},
new Players
{
Country ="Australia", Name="Rickey Ponting",Sports ="Cricket", ImageUrl="rickey.jpg"
},
new Players
{
Country ="India", Name="Sandeep Singh",Sports ="Hockey", ImageUrl="sandeep.jpg"
},

};
return Players;
}
}

In service implementation I have created a function named GetPlayers(). This function is returning List of Players and calling same function in both function GetPlayerXml and GetPlayerJson.

Last step we need to perform is to enable REST EndPoint on the service. For that we need to configure EndPoint behavior as below,

image

And then we need to create EndPoint with WebHttpBinding to enable REST on WCF Service. EndPoint will be as below,

image

In contract PlayerData is namespace and IService1 is ServiceContract we created in previous step. Finally configuration will be as below,


<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="servicebehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="restbehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name ="PlayerData.Service1" behaviorConfiguration ="servicebehavior" >
<endpoint name ="RESTEndPoint"
contract ="PlayerData.IService1"
binding ="webHttpBinding"
address =""
behaviorConfiguration ="restbehavior"/>
</service>
</services>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>

This is what all we need to do to create a WCF REST Service to be hosted on Windows Azure. Press F5 to run and test WCF Service Web Role in local development fabric. Make sure that you have set Windows Azure project as startup project.

On running you can see output in browser as below. I am calling GetPlayerXml function

image

You can see that Players data as XML is accessible at baseaddress/Service1.svc/GetPlayersXml. Since currently we are running WCF Service Web Role in local azure emulator so base address is IP address of localhost at port 81.

Next after testing locally you can deploy service at Windows Azure. For that right click at Windows Azure project and select Package. Next choose Service Configuration as Cloud and Build Configuration as Release and click Package.

image

After successful package you can see Service Package File and Cloud Service Configuration file in the folder explorer. We need to upload these two files to deploy application on Microsoft Data Center. And later upload this package in Windows Azure Hosted service to host created WCF Service Web Role in Windows Azure.

In another way to publish see this post wriiten by me to publish from Visual Studio

In this way you can create a WCF REST Service and host in Windows Azure. I hope this post is useful. Thanks for reading.

Step by Step Guide to Create First Windows Azure Application

Target audience: Beginners in Windows Azure or Level 100

One can argue that why this step by step guide after so many years of Windows Azure? and why I wrote this article after my more than 80 articles on Azure?

image

Answer is, when I started writing this article, my objective was very much clear in my mind. I wanted to help people starting with Windows Azure from installation of SDK to Deployment to Microsoft Data Center. In this article I am targeting people who want to start learning and developing for Windows Azure.

Article is divided into five parts

  1. Installation of Windows Azure SDK
  2. Developing First Windows Azure Web Application
  3. Deploying application locally in Development Storage Fabric
  4. Registration for free Windows Azure Trial
  5. Deployment of the Application in Microsoft Data Center

I will start fresh with installation of Windows Azure SDK and I will conclude this post with deployment of simple application in Windows Azure Hosted Service. I am not going to create a complex application since purpose of this post is to walkthrough with all the steps from installation, development, debugging to deployment. In further post we will get into more complex applications. Proceed through rest of the post to create your first application for Windows Azure.

Installation of Windows Azure SDK

Step 1

Go to official site of Windows Azure at link http://www.windowsazure.com/en-us/

Step 2

In bottom of page, you will get Develop option. Click on Show Me More.

clip_image001

Step 3

Now you need to choose the language you want to work with. You can develop application in any of the language given in option and deploy it on the Microsoft managed datacenters. Below are the available languages.

clip_image002

To start developing using .NET, click on .NET.

Step 4

You will be navigated to Home Page of .NET Developer Center. You will get all the resources related to .NET development on Windows Azure here. Now click on Install to install Windows Azure SDK. I am assuming here that you are already having VS2010 on your machine.

clip_image003

Windows Azure SDK and tools are available to install via Web Installer. Click on the Install in the dialog window.

clip_image005

Next dialog windows will prompt you to agreement. Select I Accept option to proceed.

clip_image007

You will be getting dialog window indicating Windows Azure SDK being installed.

clip_image009

After successful installation you will get confirmation dialog windows as below.

clip_image011

Now click on Finish and Exit.

Congratulation by now you has installed Windows Azure SDK on your machine.

 

Developing First Application

Open Visual Studio 2010 as administrator and create a new project. Open File -> New->Project. From Cloud tab select Windows Azure Project.

image

Next you need to click on your preferred language. You can use any of the three languages to develop application to be deployed on Windows Azure. I am choosing language Visual C#. After clicking on the language you will get options to select as either Web Role or Worker Role.

clip_image001[6]

Before we proceed further, let us stop by and try to understand what are the Web Role are Worker Role?

Web Role takes HTTP input and Process it. It gives output as HTTP Response. It takes input from user via a user interface.

clip_image002[6]

Web Role can be summarized as below,

clip_image004

You create any application as Web Role instance. For example,

  • If you want to create a Web Application using ASP.Net then you will be choosing an ASP.Net Web Role in the project template
  • If you want to create a WCF Service and deploy it on Azure then you will be choosing WCF Service Web Role.
  • If you want to create ASP.Net MVC application then you will be choosing ASP.Net MVC Web Role.

Worker Role runs in the background. It is used to perform some background task. It does not take input from user. It takes input from Azure Storage or web Role.

Worker Role can be summarized as below,

image

Let us get back to creating first web application to be deployed on Windows Azure. Go ahead and select ASP.NET Web Role and click on arrow button. If you want you can change name of the Web Role. Since this is your first application so for the simplicity leave default name. After selecting Web Role click on Ok.

image

On exploring solution explorer you will find that there are two projects. One project is Widows Azure Project and other is ASP.Net Web Role.

image

Let us explore Windows Azure Project. Project got two Service Configuration files. Extension of Service Configuration file is cscfg

image

One Service configuration file is for local deployment and one contains configuration details to deploy to Microsoft Data Center. On opening service configuration file, you will get below XML.

image

Below information’s are provided in service configuration file.

  • Operating system version
  • Operating system family
  • Connection string settings
  • Instance counts

By default instance count is set to 1. It means there will be one instance of Web Role will be running for the deployment. Let us go ahead and increase instance count to 2. Change value to 2 in Instance count entry as below and save the file.

image

Next important file is Service Definition file. Extension of Service Definition file is csdef

image

On Opening service definition file you will get below XML

image

Service definition file contains information about binding and different sites. It contains information about EndPoints and default port number. In normal scenario, you may not need to edit this file.

Next important file is WebRole1. If you remember we did not change name of the Web Role while creating it in previous step.

image

When you click on WebRole1, you will get below UI.

image

In this UI you can,

  • Manage Settings
  • Configure Web Role
  • Configure local storage
  • Manage settings
  • Configure End Points
  • Manage virtual networks

In later post we will go into details of each of the section of this UI. As of now we can proceed with default values.

Now we have a bit understating on different files in Windows Azure project in the solution. Other project is normal ASP.NET Web Application project with one extra file called WebRole.cs. This file is used to host web application in Windows Azure.

image

Let us open default.aspx and modify it as below, I have deleted all the default codes from MainContent and put one H1 tag as below.

image

By this, we have created a simple ASP.Net Web Role Application to be deployed on Windows Azure.

 

Deploying Application Locally

You deploy application in two steps. First you deploy it locally to do testing that if everything is working as expected. You can debug application deployed on local development fabric. A Windows Azure emulator run locally is also known as Windows Azure Development Fabric.

To run Windows Azure Web Role application locally makes sure that Windows azure project is set as startup project and press F5. To make Windows azure project as startup project right click on that and select set up as startup project

image

After setting startup project press F5 to run application on local development fabric. After pressing F5 you can see that in bottom you are getting messages like initializing the Windows Azure storage emulator etc.

image

On successful deployment you should be getting Ready message at bottom

image

After successful deployment browser will get launched and you can see your Windows Azure Application running on local development fabric.

image

You can see application is running on port 81 and default start page is default.aspx. Let us explore local development fabric. To open local development fabric from the task bar right clicks on Windows Azure icon.

image

Right click on the Windows Azure icon and select Show Compute Emulator UI. You will get Windows Azure Compute Emulator UI. In emulator you can see health of the Web Role instances. There are two instances running since we configured two instance of Web Role in service configuration file.

image

On right clicking on the Web Role instance you can set logging level and can open local store.

image

In further post we will get into details of logging and health of Web Role instances. As of now we have seen the way to create Windows Azure Web Role Application and deploy it locally. Now let is deploy created application in Microsoft Data Center or on real cloud.

 

Deploying Application On Windows Azure Portal

To deploy application on Microsoft Data Center you need to have a Windows Azure Account. Windows Azure is a paid service however you can start with free trial. To register for free account follow the below steps.

Register for Free Account

Step 1

Go to official site of Windows Azure at link http://www.windowsazure.com/en-us/

Step 2

In right hand side click on free trail

clip_image001[8]

Step3

Next click on Try it free.

clip_image003

Step 4

You will be asked to login using Live ID. Provide your live id and login. If you don’t have live ID create one to work with Windows Azure Free Trail

clip_image005[6]

Next proceed through the screen to create free account.

clip_image007[6]

After successful registration you will be getting a success registration message. After registration go back to visual studio and right click on Windows Azure Project and select Package.

image

Next choose Service Configuration as Cloud and Build Configuration as Release and click Package.

clip_image001[10]

After successful package you can see Service Package File and Cloud Service Configuration file in the folder explorer. We need to upload these two files to deploy application on Microsoft Data Center.

clip_image003[6]

After successful registration for free account again browse to https://www.windowsazure.com/ and click on Management Portal from Account section in bottom.

clip_image004

You will be navigated to live login page. Provide same live id and password you used to create Free Trial. After successful authenticating you will be navigated to Management Portal.

To deploy on Microsoft Data Center, first you need to create Hosted Service. To create Hosted Service from left tab select Hosted Service, Storage, Account and CDN

clip_image005

In top you will get three options. Their purpose is very much clear with their name.

clip_image006

Click on New Hosted Service to create a Hosted service. Provide information as below to create hosted service.

clip_image007

Choose Subscription Name. It should be the same as your registered subscription of previous step.

  • Enter name of the service
  • Enter URL of the service. This URL need to be unique. On this URL you will be accessing the application. So this application will be used at URL debugmodemyfirstservice.cloudapp.net
  • Choose a region from the drop down. In further post we will get into details of affinity group.
  • In Deployment option choose, Deploy to production environment.
  • Give a deployment name.

Next to upload package select browse locally. On browsing navigate to folder YourFolderName\MyFirstWindowsAzureApplication\MyFirstWindowsAzureApplication\bin\Release\app.publish and choose files.

image

As of now for simplicity don’t add any Certificate and click on Ok to create a hosted service with package of application created in last step. You will get a warning message. Click Yes on warning and proceed.

image

Now you need to wait for 5 to 10 minutes to get your application ready to use. Once service is ready you can see ready status for the Web Role.

image

After stats are ready, you are successfully created and deployed first web application in Windows Azure. Browse to URL http://debugmodemyfirstservice.cloudapp.net/ to see your application running from Microsoft Data Center.

image

In this way you can start developing for Windows Azure. In further post we will go into many details. I hope this post is useful. Thanks for reading.

 

Select ListBox Item on the Hold event in Windows Phone

I was working on an application and I had to select a List Box Item on the hold event. My List Box was as below,

image

You see in the List Box, I have put an Image control and binding Source and Tag dependency property of the image to the data source.

At the code behind, I got an entity class Photo as below,

image

Finally, I am setting ItemsSource of ListBox as below. lstPhotos is list of Photo.

image

Now question comes that how to set a particular image from list of images in ListBox on the hold event. When user hold a particular image in ListBox that image should get selected. For that I have raised a hold event on the Image control in List Box and in the hold event need to fetch the selected image as data context.

image

In above code you cans see that I am getting data context of selected image in instance of entity class photo. In this way you can select a ListBox item on the hold event.

Before I conclude one point keep in mind that you need to raise Hold event on the container inside the ListBox. For example, if you have a StackPanel inside DataTemplate then you need to raise the Hold event on StackPanel. In my case there is no container but an Image so I am raising Hold event on the Image control. Avoid raising hold event on ListBox itself else you will get NullReference exception.

I hope this quick post is useful. Thanks for reading.

Reviewing Programming Entity Framework : Code First by Julie Lerman and Rowan Miller

image

Title: Programming Entity Framework: Code First

Number of Pages < 200

Price: $9.99 Kindle Edition

      $21.59 Paperback

Buy here

I got an opportunity to get a copy of book Programming Entity Framework: Code First from well-known author, speaker and an authority on Entity Framework Julie Lerman . I was very excited to get book directly from the author. I got amazed seeing how skillfully and with dexterity both of the authors has written such an important and depth topic in less than 200 pages. Book contains all together 8 chapters and If you are developer working on database centric applications then this book is for you. This book focuses on Code First approach of architecting the application. While you flip through the pages of the books, you will experience the authority of Julie Lerman on the subject.

Before I go ahead and write my experience on this this awesome book, let me give a try to make you understand what is Code First?

Most popular way of architecting an application is to design database first. First you model the requirement into database and then using different API like ADO.Net or ORM like LINQ to SQL Class, NHibernate etc. work with the database. This approach of architecting an application is called as Database First Approach

clip_image002

In .NET 3.5 Microsoft came up with ADO.Net Entity Framework, It was helping developers to create conceptual model.

  • It was creating Conceptual model into XML File.
  • Extension of XML file is EDMX.
  • XML file can be seen in designer where developers can edit the design on conceptual model.

ADO.Net Entity Framework was working on concepts of Database first approach where conceptual model gets created on existing database.

One of the most popular ways of architecting your application is to have Model First. You may have mapped database requirement in a XML file and create database from the XML file. This approach of architecting database is called Model First Approach.

image

In Model first approach you can start working on project without having a database. You can design the conceptual model using Visual Studio designer and later database can be created from this conceptual model.

In .NET 4.0 and Visual Studio 2010, Microsoft came up with new version of ADO.Net Entity Framework version 4.0 and it was supporting developers to architect their application as Model First approach.

Regardless of the approach you use in your application automatically lot of codes get created as classes and you work with the classes. Here comes a third way of creating Database and that is Code First approach. In this you model your requirement in plain classes and then databases gets created from these classes. Developers first create Domain Classes and then later database gets created from these domain classes.

image

In your application POCO classes are model and they are used to create the database. This approach of architecting an application is called “CODE FIRST”.

Now if you have a basic understanding of Code first approach after reading above paragraph then you should be thanking Julie Lerman rather me because my understating was based on first two paragraph of first chapter of book titled Programming Entity Framework: CODE FIRST

Table Of Contents

image

By seeing table of contents you must have got an idea that how useful this book would be if you are a developer working on Database centric applications.

About Authors

image

Julia Lerman is the leading independent authority on the Entity Framework and has been using and teaching the technology since its inception in 2006. She is the author of the highly acclaimed book, Programming Entity Framework, 1st and 2nd editions and is well known in the .NET community as a Microsoft MVP, ASPInsider, and INETA Speaker. Julia is a frequent presenter at technical conferences around the world and writes articles for many well-known technical publications including the Data Points column in MSDN Magazine. Julia blogs at http://thedatafarm.com/blog

Rowan Miller is Program Manager in ADO.Net Entity Framework team at Microsoft.

Conclusion

I strongly suggest to you to read this book and take your expertise to next level. All 8 chapters’ of this book will help you to have a better understating on the Code First approach and codes samples will help you to understand better way of modeling your database from the code.

CSharp Interview Question: What is Action in CSharp

One of my friends called me after his interview as for a developer role in an esteemed organization. One of the question, interviewer asked him,

image

After talking to him, I thought why not to blog about it? I am trying here to use minimum words and optimum code samples can be discussed with interviewer as answer of this question.

Action is type of delegate

  1. It returns no value.
  2. It may take 0 parameter to 16 parameters.

For example below Action can encapsulates a method taking two integer input parameter and returning void.

 

image

So if you have method like below,

clip_image002

You can encapsulate method Display in Action MyDelegate as below,

image

An Action with one input parameter is defined in System namespace as below,

image

Where in T is type of input parameter and T obj is value passed for the parameter.

Action with Anonymous method

You can work with Action and anonymous method as well. You can assign anonymous method to Action as below,

image

Above code will print 9 as output.

Action with Lambda Expression

Like any other delegates, Action can be worked with lambda expression also as below,

image

Above code will also print 9 as output.

Passing Action as input parameter

You can pass Action as parameter of a function also. Let us say you have a class

image

And two functions called Display and Show to display Name and RollNumber of Student.

image

Now you got a function where you need to pass either Display or Show. Or in other words you need to pass any function with the same signature of Display or Show. In that case you will be passing a delegate as input parameter to the function.

image

You can call CallingAction method in Main as below,

image

Above we are creating instance of Student class and one by one passing Display function and Show function as input parameter to CallingAction function. In CallingAction function, we are printing name of the function being passed as input parameter. On running you will get below output.

image

I hope now you would be able to answer what is Action in simple words. I hope this post is useful. Thanks for reading.

 

Page Stack in Windows Phone

In your application there may be many pages and you will come across requirement to navigate between pages. Windows Phone navigation model allows you to navigate between pages. Windows Phone navigation model is same as web based page navigation model. Even though name suggests in Windows Phone, pages are not windows. In your application, you can navigate between many pages and Windows Phone operating system stores those pages on stack. At any given time you have navigation history stored in the page stack. Windows phone operating system pushes all the pages on the stack and popped out pages with back key. When only one page left on page stack on clicking of hardware back button application gets terminated.

Page stack can be understand with below diagram,

You navigated from Page 1 to Page2 then page stack will be as below,

clip_image001

You navigated from Page2 to Page3. Now Page 3 has been pushed to Page Stack.

clip_image002

On Page 3 you pressed hardware back button so Page 3 has been popped out from the Page Stack.

clip_image003

Now on Page 2 you pressed hardware back button so Page 2 has been popped out from the Page Stack.

clip_image004

In last you have navigated back to start page of the application. And only one page is left on the Page Stack. Now if you press hardware back button you will come out of the application.

You can iterate the Page Stack by calling BackStack property of NavigationService class.

clip_image005

BackStack property is having only getter and not setter. So you can read all the pages from the stack but cannot manipulate that.

clip_image006

You can read Uri of all the pages in PageStack as below,

clip_image007

In this way you can work with Page Stack in Windows Phone. I hope this post is useful. Thanks for reading.

 

Arrays in C

Arrays are the linear data structure and stores same types of data in continuous memory location. Arrays are best used to store data in continuous memory location. However array can have definite size of data. Maximum size of an array must be set while declaring the array.

An array can be defined as below,

image

Diagrammatically myarray can be shown as below,

Note : sorry for typo error in below image, last memory location is 2064H not 2060H sorry !!!!

clip_image002

Some information about above array can be drawn as below,

  • Name of the array is myarray.
  • This is an integer array
  • Size of the array is 5
  • Base address of array is 2000H
  • One element takes 2 bytes in memory. I am assuming we are using language C, so an integer takes 2 bytes in memory.
  • 0,1,2,3,4 are index of the array
  • 99, 13,77,567,9 are elements of the array.
  • You can say 77 is array element at 2nd position of the array.
  • Notation to fetch array elements is as below,

myarray[2]=77

If you need to find memory location of 20th element in above array then you can get that using below formula,

Base Memory location + (Memory size of elements * (Element Position -1))

In above case,

  • Base memory location = 2000H
  • Size of elements = 16 Bits
  • Element position = 20

Memory location of 20th element = 2000 + (16 * (20-1)) = 2000 + 16 *19 = 2304H

On an array usually below native operations can be performed

  • Traversing an array
  • Search an element in array
  • Insert an element at given position in array
  • Delete and element from a given position in array
  • Reverse an array

Array in C

In C we can create an array as below,

clip_image002[6]

We created three different types of array. They are as below,

image

You can store values in array as below,

image

And you can print them as below,

image

Traversing an Array

Traversing an array means iterate through each element of the array once and perform some operation on each element.

image

In above pseudo code K is a variable, A is array and N is upper limit of the array. In C a function to traverse an array and print all the elements can be as below,


int  traverse(int *myarray)
{
int i;
for(i=0;i<5;i++)
{
printf("%d\n",myarray[i]);
}
return 0;
}

And in the main function array is declared as below,


#include<stdio.h>
#include<conio.h>
void main()
{
int myarray[5];
myarray[0]=9;
myarray[4]=99;
traverse(myarray);
getch();
}

You should get output as below,

image

You can see in the output that for 2nd, 3rd and 4th position elements are having some garbage value because we did not assign any values to these positions in array.

Insert in Array

You can insert an element to a given position in array following below algorithm. Let us say,

  • K: position to insert element
  • Element: element to insert
  • N : Size of the array
  • A : Name of the array

image

In C function to insert an element in given position in array can be written as below,


int insertelement(int *myarray, int position, int element)
{
int i;
for(i=4;i>=position;i--)
{
myarray[i]=myarray[i-1];

}
myarray[i]=element;
return 0;
}

And in main function you can call this function as below,


#include<stdio.h>
#include<conio.h>
#define MAX 5
void main()
{
int myarray[5];
myarray[0]=9;
myarray[4]=99;
traverse(myarray);
insertelement(myarray,2,99);
traverse(myarray);
getch();
}

When you run above program you will find 99 has been inserted at 2nd position as below,

image

You will notice all the elements after 2nd position has been shifted by one place.

Delete in Array

You can delete an element to a given position in array following below algorithm. Let us say,

  • K: position to delete element
  • N : Size of the array
  • A : Name of the array

image

In C you can write a function to delete and element from specified position as below,


int deleteelement(int *myarray,int position)
{
int i;
for(i=position; i<5; i++)
{
myarray[i-1]=myarray[i];
}
myarray[i-1]=0;
return 0;
}

Search in Array

There are two types of search you can perform on an array,

  1. Linear Search
  2. Binary Search

Binary search works on divide and conquer algorithm principal and I will take this topic separate in other blog post. Linear search can be performed as below,


int search(int *myarray, int element)
{
int i;
int flag=0;
for(i=0;i<5;i++)
{
if(myarray[i]==element)
{
flag=1;
return i+1;
break;
}
}
if(flag==0)
{
return 0;
}
}

In this way you can start working with arrays in C. in further post I will show you how to work with pointers and array together. Thanks for reading.

Capture Picture from Camera and Save in Media Library in Windows Phone

In this post we will see the way to capture a photo using camera and saving that in Media Library.

CameraCaptureTask chooser is used to capture photo using Windows Phone Camera. To work with CameraCaptureTask , first you need add namespace

image

Then define a global variable,

image

In constructor of the page, you need to instantiate CameraCaptureTask and attach completed event handler.

image

Next you need to show camera to user. You can call Show function anywhere as per your business requirement however I am calling it on click event of a button as below,

image

 

Now in the completed event of the CameraCaptureTask we need to save the image in Media Library. To work with Medialibrary, you need to add reference of Microsoft.Xna.Framework. After adding the reference add below namespace,

image

In completed event of CameraCaptureTask, make instance of MediaLibrary and call SavePicture method as below,

image

As you see SavePicture function takes two input parameters. It takes Name of picture as one input parameter and picture stream as another. In this example we are saving picture taken from camera. You may also save picture downloaded from services as stream.

For your reference full source code is given as below,



using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using Microsoft.Xna.Framework.Media;

namespace PhoneApp17
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
CameraCaptureTask cameraTask;
public MainPage()
{
InitializeComponent();
cameraTask = new CameraCaptureTask();
cameraTask.Completed += new EventHandler<PhotoResult>(cameraTask_Completed);

}

void cameraTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
MediaLibrary medialibrary = new MediaLibrary();
medialibrary.SavePicture("givenameofimage", e.ChosenPhoto);

}
}

private void btnShowCamera_Click(object sender, RoutedEventArgs e)
{
cameraTask.Show();
}
}
}


In this way you can save picture to Media Library. I hope this post is useful. Thanks for reading.

 

How to write and run a C Program in Visual Studio 2010

image

Today I was recalling good days of language C and got tempted to play around POINTERS, STRUCTURE, and DATA STRUCTURE etc. I started to write some C code and as soon as I started, the first hurdle came that where to write code? I was running on 64 bit Windows 7 machine with Visual Studio 2010. I binged and found much suggestion to download this and install that etc. However being fan and loyal user of Visual Studio, I was more desired to use rich IDE of Visual studio for my C program. To my surprise it is quite possible to use Visual Studio 2010 to write and compile code in C language.

In this post I am going to walkthrough writing C program in Visual Studio 2010. Follow the steps as below,

  • Create a new project by clicking File->New->Project.
  • From Installed Template choose other language
  • Choose language Visual C++
  • In Visual C++ choose tab Win32
  • Choose project type Win32 Console Application

See the image below,

image

From the dialog box click on Next button

image

Next screen is of Application Setting. You need to make sure

  • Application type is set a Console Application
  • In Additional options uncheck the Precompiled Header.

image

After clicking Finish you will find a project has been created with below structure. Open solution explorer to see the structure

image

To start programming, right click on Source Files and add a new item. You need to make sure below two points,

  • Select C++ File to add
  • But in name change extension to .C, default is .CPP. To work with C language program source file name should be with extension .C. In this case I am giving source file name as Sample1.C

image

Now open Sample1.c and write a hello world program as below,

Sample1.c


#include<stdio.h>
#include<conio.h>
void main()
{
printf("hello C from Visual Stido 2010");
getch();
}


To compile and run the program, simply press F5 and you should get output in console windows as below,

image

You can see that CSample2.exe is running and this is name of the project.

Next let us go ahead and write some code to print address of a variable using Pointer.

Sample1.c


#include<stdio.h>
#include<conio.h>
void main()
{
int number1=9;
int *ptrNumber1;
printf("hello C from Visual Stido 2010\n");
ptrNumber1= &number1;
printf("%d\n",number1);
printf("%d\n",*ptrNumber1);
printf("%d\n",ptrNumber1);
printf("%d\n",&number1);
getch();
}


Above code is quiet simple,

  • Declaring a pointer variable
  • Declaring a pointer
  • Assigning integer variable to pointer
  • Printing values and address of integer variable

In this way you can work with C language programs in visual studio. I am yet to explore how to execute data structures programs like Stack, Link List etc. in Visual Studio. Allow me to explore that and expect further blog posts on the same. I hope this post is useful. Thanks for reading.