Wednesday, May 2, 2012

Windows 8 Metro Application Creation Step by Step

 

Sorry Friends after long time I am back to blog.  I was really busy with my Office and Personal work so not able to blog regularly. Now I got some free time so I downloaded Windows 8 Customer preview with VS.NET 2011 and start looking at new  Windows 8 Metro app.

In Windows 8 Run time called WinRT  I am not going to deep into WinRT now.    In Windows 8  we can develop Metro apps with two choices .

1)   C# , VB.NET , C++ , XAML

2)  HTML 5, CSS , and JavaScript. 

In this  blog I am going to use  C# and XAML to create simple Weather Forecast application. if you want to learn any new stuff better to create simple working application having said that we are going to create the following Windows 8 Metro App.

 

image

In this application I am calling Free Weather Web service passing the Zip code and getting XML and parsing and displaying  it in  Grid View controls.

Prerequisites

C# 5.0  ( async, await )

XAML

1) First create the Blank Windows Metro application

image

2) Open of the Blank Page.XAML and add the following XAML UI

<Page
    x:Class="WeatherApp.BlankPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:WeatherApp"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <UserControl.Resources>
        <Style TargetType="TextBlock" x:Key="mytxtBlk">
            <Setter Property="Margin" Value="10"/>
            <Setter Property="FontFamily"  Value="Aerial Black"/>
            <Setter Property="FontSize" Value="18"/>
            <Setter Property="FontWeight" Value="ExtraBold"/>
        </Style>
    </UserControl.Resources>
    <Grid Background="{StaticResource ApplicationPageBackgroundBrush}">
        <Grid.RowDefinitions>
            <RowDefinition  Height="73"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <StackPanel Orientation="Horizontal" Grid.Row="0" Height="50" VerticalAlignment="Top" HorizontalAlignment="Center" Margin="143,0,277,0" Width="946" d:LayoutOverrides="VerticalMargin">
            <TextBlock Text="Sreeni.NET" Style="{StaticResource mytxtBlk}"/>
            <TextBlock Text="Enter the ZipCode to get Forecast"  VerticalAlignment="Center" HorizontalAlignment="Center" FontFamily="Arial Black" FontSize="30" Style="{StaticResource mytxtBlk}"></TextBlock>
        <TextBox Width="200"  VerticalAlignment="Center"   x:Name="txtzipcode" HorizontalAlignment="Center"></TextBox>
        <Button Content="Get Weather"  VerticalAlignment="Center" HorizontalAlignment="Center" Click="Button_Click_1"/>
        </StackPanel>
    
        <GridView x:Name="wg" Grid.Row="1" >
            <GridView.ItemTemplate>
             
                <DataTemplate>
                    <StackPanel Orientation="Vertical" Width="250" Height="250" Background="#FF161C8F">
                        <TextBlock Style="{StaticResource mytxtBlk}" >
                            <Run Text="City :"></Run>
                            <Run Text="{Binding City}" />
                        </TextBlock>
                        <TextBlock  Style="{StaticResource mytxtBlk}">
                             <Run Text="State :"/>
                            <Run   Text="{Binding State}"/>
                        </TextBlock>
                        <TextBlock Text="{Binding Date}" Style="{StaticResource mytxtBlk}">
                              <Run Text="Date :"/>
                               <Run Text="{Binding Date}"/>
                        </TextBlock>
                        <TextBlock  Style="{StaticResource mytxtBlk}">
                             <Run Text="Min :"/>
                               <Run Text="{Binding Min}"/>
                        </TextBlock>
                        <TextBlock  Style="{StaticResource mytxtBlk}">
                             <Run Text="Max :"/>
                               <Run Text="{Binding Max}"/>
                        </TextBlock>
                        <TextBlock  Style="{StaticResource mytxtBlk}">
                             <Run Text="Description :"/>
                               <Run Text="{Binding Description}"/>
                        </TextBlock>
                       
                    </StackPanel>
                </DataTemplate>
            </GridView.ItemTemplate>
          
        </GridView>
       
    </Grid>
</Page>

3) Add code to call web service and parse the response XML as shown below.

 

  public async Task<List<WeatherInfo>> GetWeatherInfo(string zipcode)
{
HttpClient httpclient = new HttpClient();
var weatherinfo= await httpclient.GetStringAsync("http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityForecastByZIP?ZIP=" + zipcode);

XNamespace ns = "http://ws.cdyne.com/WeatherWS/";
var xmlWeatherInfo=XElement.Parse(weatherinfo);

var city = xmlWeatherInfo.Element(ns + "City").Value;
var state = xmlWeatherInfo.Element(ns + "State").Value;
List<WeatherInfo> winfo = (from weather in xmlWeatherInfo.Descendants(ns+"Forecast")
select new WeatherInfo
{
State=state,
City=city,
Date =weather.Element(ns+"Date").Value,
Description=weather.Element(ns+"Desciption").Value,
Max = weather.Element(ns+"Temperatures").Element(ns+"DaytimeHigh").Value ,
Min = weather.Element(ns+"Temperatures").Element(ns + "MorningLow").Value

}).ToList<WeatherInfo>();

return winfo;
}

private async void Button_Click_1(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(txtzipcode.Text))
return;
var wdata = await GetWeatherInfo(txtzipcode.Text);

wg.ItemsSource = wdata;
}


}


public class WeatherInfo
{
public string City { get; set; }
public string Date { get; set; }
public string State { get; set; }
public string Description { get; set; }
public string Min { get; set; }
public string Max { get; set; }

}




Nandri(Thanks)



Sreenivasaragavan

Wednesday, June 22, 2011

Friday, June 17, 2011

Windows Azure 30 Days Pass- Try it out

IF you want to try out Microsoft Windows Azure Application Development

image

http://windowsazurepass.com/?campid=56742C47-F0FB-DF11-B2EA-001F29C6FB82

Nandri(Thanks)

Sreenivasaragavan

Monday, June 13, 2011

Debugger Canvas - VS.NET 2010 Extension

 

This is really cool Extension for VS.NET 2010 with SP1, when it hits breakpoint  Debugger canvas shows just the methods that you are debugging  with call lines and local variables as shown below.

image

 

Here below image I invoked two methods from different class so it opens different windows for each method with Local variables.

image

Here the following images shows the method and its Local Variables .

image

Here is the different options we can set for Debugger canvas, to get here click debug-> Options & Settings from VS.NET 2010 Menu.

image

If you like and wanted to load please Point your IE  to

http://msdn.microsoft.com/en-us/devlabs/debuggercanvas and download

download

FYI. The Debugger Canvas is built on technologies that only ship with Visual Studio Ultimate, such as IntelliTrace and the code analysis features in the Architecture tools.

Nandri(Thanks)

SreenivasaRagavan,

Sunday, June 5, 2011

How to Host WCF Service in BasicHttpBinding & HTTPS

Today One of my Best Friend asked me how to host WCF service in IIS with HTTPS binding . I showed the demo to him from my machine then I thought let me share in my blog here it is.

To host WCF service in HTTPS here are basic steps we need to follow

1) First Create Self contained Certificate ( we are doing in Development )

2) Create Web Site with Port 443 ( Https –secure )

3) Change the some settings in Web.config

First to create Self contained Server Certificate  Open IIS  Manger and select the Server Certificates Icon Under IIS section as shown below

image

image

image

Next Create the Web site with HTTPS binding and 443 port number

image

Next we need to change web.config to set Security mode as  Transport

image

Now browse the site with HTTPS

image

For Production environment you can obtain the Certificates from Verisign or CA and install on the server . 

 

Nandri(Thanks)

Sreenivasa ragavan.

EF 4.1 Code First Approach

In this Blog post we are going to see Entity Framework 4.1 Code First approach.  Here I am going to create Small console application to demonstrate. First of all you may ask question what is code first?

EF code first means first Define the classes this is nothing but our MODEL , then EF will work with theses classes this is called CODE FIRST APPROACH. Here I am going to use  Nuget to get EF 4.1 Reference assemblies from the Internet.  Here is how you get it.

First Create C# Console application then go to tools menu in VS.NET 2010 

image

Once you click Package Manager Console you will provided to execute the  Windows PowerShell prompt to execute the command . The command we need to execute to get  EF 4.0 assemblies is

Install-Package EntityFramework.

image

Next create the Entity class and Context class as shown below

 

DB Context

public class ContactCtx :DbContext
  {
      public DbSet<Contact> Contacts
      {
          get;
          set;
      }
  }

 

Entity


public class Contact
   {
       public int Id
       {
           get;
           set;
       }
       public string Name
       {
           get;
           set;
       }
       public string Phone
       {
           get;
           set;
       }

       public string Email
       {
           get;
           set;
       }
   }

Here I am creating a contact that will be saved in DB.

class Program
  {
      static void Main(string[] args)
      {
          ContactCtx db = new ContactCtx();
         
          db.Contacts.Add(new Contact
          {
              Name = "Vasanth.v",
              Phone = "23232323",
              Email = "v@v.com"
          });
        int a=  db.SaveChanges();
        Console.WriteLine("DB ID is " +a);

       Contact c= db.Contacts.Find(1);
      }

    
  }

when you execute the program the DB is created and the records are added .  EF use SQL Express by default if do not specify .

image

Nandri(Thanks)

SreenivasaRagavan

Thursday, June 2, 2011

Sunday, April 17, 2011

Exposing POCO as OData Service.

OData – Open Protocol Data aka WCF Data Services.

We all know that using EF(Entity Framework) Data model exposing any relational Data source is very very easy.  But here I am going to show how to expose Plain Old CLR Objects as  OData Service.

1) First Create Empty ASP.NET Web Application.

2) Second we need define or create the Entity Classes and we need to define Primary key using DataServiceKey Attribute for each entity as shown below

image

3) Next we need to create the class which exposes the IQueryable properties which returns the collection of Each entity which we created about. here I have defined the Entity as Contact so my IQueryable properties returns collection of Contacts.

image

image

Next we need to add WCF Data Service Template to this project to host the OData Service with the above Entities.

image

Once we added WCF Data Service Template next we need to specify the Entity class name as shown below.  Next we can set the Access rule for Entity

here I set all Entity have read only access.

image

Now run the service you will see the ODataservice with Two Entity exposed .

image

IF we browse the following URL we get  Contacts details http://localhost:52200/WcfDataService1.svc/MyContacts 

image

Nandri(Thanks)

SreenivasaRagavan

Friday, April 15, 2011

Get Silverlight 5.0 Beta

Silverlight 5 continues the pace of rapid innovation, building on Silverlight 4's capabilities in the areas of rich applications and premium media experiences. With over 40 new features, the Silverlight 5 beta highlights dramatic video quality and performance improvements, as well as new capabilities that improve developer productivity

image

Here is the URL where you can download Silverlight 5.0 beta http://www.silverlight.net/getstarted/silverlight-5-beta/

Nandri(Thanks)

Sreenivasaragavan.R

Wednesday, April 6, 2011

Escape Sequence for { in C#

Today there was need for me to print {} char in my console output. I knew there are standard Escape Sequences in C# but I was not aware of Escape Sequence for  {.  when I was binging I found the solution to this problem I just wanted to share with my Blog readers.

image

Nandri(Thanks)

Sreenivasaragavan.

Sunday, March 27, 2011

System.Runtime.Caching Namespace for Caching-II

In this Blog Post we are going to see how we can use this API in .NET Applications.

image

Here I am going create my own CacheLib class with the following   Add, Get, Remove methods as shown above.

First Let me create a C# class file called  CacheLib.cs  in which  I am going to implement all the CURD methods for the Cache object. to do let us create ObjectCache Cache = MemoryCache.Default . (Memory Cache) Then we Add Get, Add, Remove Methods.

Add any object to Cache:

Here  I am created the Generic Add method.

image

Get or Retrieve Cached Item from Cache Object: Generic get method

image

Remove or Delete from Cache:

image

User Defined class to store in Cache.

image

the following Code snippet shows how to add and retrieve data from Cache object .

image

Nandri(Thanks)

Sreenivasa Ragavan

Wednesday, March 23, 2011

System.Runtime.Caching Namespace for Caching

Today I happened to come across System.Runtime.Caching  new API in .NET Framework  4.0 this System.Runtime.Caching namespace contains types that let you implement caching in NET Framework applications. The good thing about this API is we can use this API same as  ASP.NET Out Caching functionality but without a dependency on the System.Web assembly.

When I Reference System.Runtime.Caching  assembly in my project it was showing not available then after looking project properties I found out this Namespace NOT part of the .NET 4 client profile, it is only in the full .NET 4 Framework.  then I changed my project to Full .NET Framework as shown below.

image

Next Post we will see how we can use this API to Cache.

Nandri(Thanks)

Sreenivasaragavan

Wednesday, March 16, 2011

IE 9 Released

Point your Old browser to the following URL and see More Beautiful WEB – We Exchange Bytes

image

http://windows.microsoft.com/en-US/internet-explorer/downloads/ie-9/worldwide-languages

Nandri(Thanks)

SreenivasaRagavan

Going Full Screen Mode in Silverlight

In Silverlight Application using App.Current.Host.Content  IsFullScreen property we can go Full Screen mode.

First get the App.Current.Host.Content value and change to True if IsFullScreen is False.

image

image

when you click Full Screen Button here is the button click  event handler code.

image

Here is the FullScreenChanged Event Handler.

image

 

Nandri(Thanks)

SreenivasaRagavan

Thursday, March 10, 2011

Visual Studio 2010 SP-1 Released

 

MS Released SP-1 for VS.NET 2010.

image

http://www.microsoft.com/downloads/en/details.aspx?FamilyID=75568aa6-8107-475d-948a-ef22627e57a5&displaylang=en

I downloaded and Installed it went without  any  ERROR.

image

Nandri(Thanks)

Sreenivasaragavan

Tuesday, March 1, 2011

Debugger.Break Method().

This method lives inside System.Diagnostics Namespace. This method Signals a breakpoint to an attached debugger.

image

This is really useful when we debugging .NET Windows Service.   In your Program  add the following line of code wherever you want to break into debug mode:
System.Diagnostics.Debugger.Break()

Nandri(Thanks)

Sreenivasaragavan