Visual Studio 11 Developer Preview

Wednesday 14th Sept, during the keynote with Satya Nadella, Scott Guthrie, Jason Zander Visual Studio 11 Developer Preview and .NET 4.5 were announced.

ASP.NET 4.5 Developer Preview includes new core functionality like WebSockets, anti-XSS encoding, granular request validation. It also includes Web Forms improvements like model binding, support for HTML5 and unobtrusive JavaScript. And there have many performance improvements in ASP.NET when combined with Windows 8 Server can decrease startup time by 30% and reduce the memory footprint by 30%.

You can read more about all the new features that are enabled in this release by reading the What's new in ASP.NET 4.5 and Visual Studio Web Developer whitepaper here: http://www.asp.net/vnext/whats-new.

 

 

 

 

 

Other link where you can start learning and developing your application with Visual Studio 11 Framework 4.5. http://msdn.microsoft.com/en-us/vstudio/hh127353

Posted by bmdayal | with no comments

Rows and Columns Merging in ASP.NET GridView Control

Its been a long time I have written any article on ASP.NET. Just few weeks back I got a very intresting requirement where I had to customize my GridView by Grouping the Columns and also merging the Rows by using Colspan properties. So while in View mode of GridView the data should be display in Rows and Columns format, but when I click on Edit it will display in List Format where we can place the controls in any format we want. You can refer to the figure below for the final target what I am going to show in this article.

image

In the figure above you can see the Employee Details and Address Details are grouped together. Also in Edit Mode the same data is displayed in List Format where we are free to put the controls in any format. I have used different colours for different groups so that groups of similar items can be easily identifiable in any format.

To keep simple I am using SqlDataSource control for databinding and Employee table of Northwind database. Assuming that you must be aware of the basics of databinding and asp.net I am going directly to the topic. This topic covers mostly the control properties of ASP.NET so you may connect to any datasource or databinding controls as per your requirement.

Before I start I have done the following steps

  1. Created a empty ASP.NET web application.
  2. In default.asp page added a GridView control and a SqlDataSource.
  3. Configured the SqlDataSource to connect to SqlServer Northwind Database.
  4. Selected Employee table from the Database, and from the Advanced property of the Configuration screen of SqlDataSource I have selected to Generate Insert, Update and Delete Statement.

Refer the figure below for the specific configuration of SqlDataSource mentioned above.

image

image

Once you save these changes you can select to Bind the GridView with the SqlDataSource. Now configure the GridColumns by Selecting the EditColumns as given in the screen below.

image

This will open the popup where you can customize the individual columns, to customize the columns as per our requirement convert all the fields into TemplateFields which you can do from the same popup screen.

image

Once these changes are done, Our configuration part is done and now we are ready to move to the coding part where each and every steps will define the look and feel of our required screen.

First of all I am going to show my default.aspx page, while doing the steps above my VS2010 tools have generated lots of code. I am going to clean up the codes which I dont want at this movement and which is out of scope of this article. If you can see the code below I have cleared the InsertParameter, DeleteParameter, InsertCommand and DeleteCommand codes from SqlDataSource. The only part right now I am interested in is SelectCommand, UpdateCommand and UpdateParameters. And leaving rest of the codes untouched.

   1: <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
   2:     SelectCommand="SELECT * FROM [Employees]" 
   3:     UpdateCommand="UPDATE [Employees] SET [LastName] = @LastName, [FirstName] = @FirstName, [Address] = @Address, [City] = @City, [Region] = @Region, [PostalCode] = @PostalCode, [Country] = @Country WHERE [EmployeeID] = @EmployeeID">
   4:     <UpdateParameters>
   5:         <asp:Parameter Name="LastName" Type="String" />
   6:         <asp:Parameter Name="FirstName" Type="String" />
   7:         <asp:Parameter Name="Address" Type="String" />
   8:         <asp:Parameter Name="City" Type="String" />
   9:         <asp:Parameter Name="Region" Type="String" />
  10:         <asp:Parameter Name="PostalCode" Type="String" />
  11:         <asp:Parameter Name="Country" Type="String" />
  12:         <asp:Parameter Name="EmployeeID" Type="Int32" />
  13:     </UpdateParameters>
  14: </asp:SqlDataSource>

Now let me run my program, this gives me the following output. This is just the default layout which my asp.net page gave me.

image

So let me start with the customization. First I am going to merge the Columns. To get this I have to write just simple few lines of code on RowCreated event of my Employee GridView.

protected void EmployeeGrid_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        //Creating a gridview object            
        GridView objGridView = (GridView)sender;
 
        //Creating a gridview row object
        GridViewRow objgridviewrow = new GridViewRow(1, 0, DataControlRowType.Header, DataControlRowState.Insert);
 
        //Creating a table cell object
        TableCell objtablecell = new TableCell();
 
        #region Merge cells
 
        //Add a blank cell at the first three cell headers
        //This can be achieved by making the colspan property of the table cell object as 3
        // and the text property of the table cell object will be blank
        //Henceforth, add the table cell object to the grid view row object
        AddMergedCells(objgridviewrow, objtablecell, 3, "Employee Detail", System.Drawing.Color.LightGreen.Name);
 
        //Merge columns d,e (i.e.Address, City, Region, Postal Code, Country) under the column name "Address Details"
        //This can be achieved by making the colspan property of the table cell object as 2
        //and setting it's text to "Address Details" 
        //Henceforth, add the table cell object to the grid view row object
        AddMergedCells(objgridviewrow, objtablecell, 5, "Address Details", System.Drawing.Color.LightSkyBlue.Name);
 
        //Lastly add the gridrow object to the gridview object at the 0th position
        //Because,the header row position is 0.
        objGridView.Controls[0].Controls.AddAt(0, objgridviewrow);
 
        #endregion
    }
}

This code is referring to the method AddMergedCells with GridView, TableCell, number of Columns to merge, Title of the Merged Cells with the background color as an argument. In the code above first I took the instance of the Current GridView with GridView row oblect and TableCell object. And with these empty cells we finally created the Merged cells and added to the top of the current instance of the GridView.

protected void AddMergedCells(GridViewRow objgridviewrow,
    TableCell objtablecell, int colspan, string celltext, string backcolor)
{
    objtablecell = new TableCell();
    objtablecell.Text = celltext;
    objtablecell.ColumnSpan = colspan;
    objtablecell.Style.Add("background-color", backcolor);
    objtablecell.HorizontalAlign = HorizontalAlign.Center;
    objgridviewrow.Cells.Add(objtablecell);
}

In AddMergedCells, we have just few lines of code which basically sets the different properties of the TableCells and using the ColSpan it creates the Merged cells and add to the GridView. Now once you run the code ideally we should get the following output.

image

As you can see above the same grid is little decorated now, with merged columns. This takes us one step closer to our requirement. Now our next target is to Create the Merged cells. To get this  first I have created a simple table with all the columns in the custom format which I wish to display, alternatively you can use any other layout too. Code of which is given below.

<table style="float: left" width="100%">
    <tr align="left" style="background-color: LightGreen">
        <td>
            EmployeeID :
        </td>
        <td>
            <asp:Label ID="lblEmployeeID" runat="server" Text='<%# Bind("EmployeeID") %>'></asp:Label>
        </td>
        <td>
            Last Name
        </td>
        <td>
            <asp:TextBox ID="txtLastName" runat="server" Text='<%# Bind("LastName") %>'></asp:TextBox>
        </td>
        <td>
            First Name
        </td>
        <td>
            <asp:TextBox ID="txtFirstName" runat="server" Text='<%# Bind("FirstName") %>' />
            <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ErrorMessage="First Name is Required."
                ControlToValidate="txtFirstName" CssClass="Error"></asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr align="left" style="background-color: LightSkyBlue">
        <td>
            Address
        </td>
        <td>
            <asp:TextBox ID="txtAddress" runat="server" Text='<%# Bind("Address") %>' />
        </td>
        <td>
            City
        </td>
        <td>
            <asp:TextBox ID="txtCity" runat="server" Text='<%# Bind("City") %>' />
        </td>
        <td>
            Region
        </td>
        <td>
            <asp:TextBox ID="txtRegion" runat="server" Text='<%# Bind("Region") %>' />
        </td>
    </tr>
    <tr align="left" style="background-color: LightSkyBlue">
        <td>
            Postal Code
        </td>
        <td>
            <asp:TextBox ID="txtPostalCode" runat="server" Text='<%# Bind("PostalCode") %>' />
        </td>
        </td>
        <td>
            Country
        </td>
        <td colspan="4" align="left">
            <asp:TextBox ID="txtCountry" runat="server" Text='<%# Bind("Country") %>' />
        </td>
    </tr>
</table>

Now coming to the rest of the code you have to remove all the EditItemTemplate codes from all the columns except the first Column EmployeeID, cause this column is now going to span over rest of the Columns. Next paste the above table layout format into the EditItemTemplate of the EmployeeID. Which will give you the code as below. This is also our complete code of the ASPX page.

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
        SelectCommand="SELECT * FROM [Employees]" 
        UpdateCommand="UPDATE [Employees] SET [LastName] = @LastName, [FirstName] = @FirstName, [Address] = @Address, [City] = @City, [Region] = @Region, [PostalCode] = @PostalCode, [Country] = @Country WHERE [EmployeeID] = @EmployeeID">
        <UpdateParameters>
            <asp:Parameter Name="LastName" Type="String" />
            <asp:Parameter Name="FirstName" Type="String" />
            <asp:Parameter Name="Address" Type="String" />
            <asp:Parameter Name="City" Type="String" />
            <asp:Parameter Name="Region" Type="String" />
            <asp:Parameter Name="PostalCode" Type="String" />
            <asp:Parameter Name="Country" Type="String" />
            <asp:Parameter Name="EmployeeID" Type="Int32" />
        </UpdateParameters>
    </asp:SqlDataSource>
    <asp:GridView ID="EmployeeGrid" runat="server" AutoGenerateColumns="False" 
    OnRowDataBound="EmployeeGrid_RowDataBound" DataKeyNames="EmployeeID" DataSourceID="SqlDataSource1" 
    OnRowCreated="EmployeeGrid_RowCreated" OnRowUpdating="EmployeeGrid_RowUpdating">
        <Columns>
            <asp:TemplateField HeaderText="EmployeeID" InsertVisible="False" HeaderStyle-BackColor="LightGreen"
                SortExpression="EmployeeID">
                <EditItemTemplate>
                    <table style="float: left" width="100%">
                        <tr align="left" style="background-color: LightGreen">
                            <td>
                                EmployeeID :
                            </td>
                            <td>
                                <asp:Label ID="lblEmployeeID" runat="server" Text='<%# Bind("EmployeeID") %>'></asp:Label>
                            </td>
                            <td>
                                Last Name
                            </td>
                            <td>
                                <asp:TextBox ID="txtLastName" runat="server" Text='<%# Bind("LastName") %>'></asp:TextBox>
                            </td>
                            <td>
                                First Name
                            </td>
                            <td>
                                <asp:TextBox ID="txtFirstName" runat="server" Text='<%# Bind("FirstName") %>' />
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ErrorMessage="First Name is Required."
                                    ControlToValidate="txtFirstName" CssClass="Error"></asp:RequiredFieldValidator>
                            </td>
                        </tr>
                        <tr align="left" style="background-color: LightSkyBlue">
                            <td>
                                Address
                            </td>
                            <td>
                                <asp:TextBox ID="txtAddress" runat="server" Text='<%# Bind("Address") %>' />
                            </td>
                            <td>
                                City
                            </td>
                            <td>
                                <asp:TextBox ID="txtCity" runat="server" Text='<%# Bind("City") %>' />
                            </td>
                            <td>
                                Region
                            </td>
                            <td>
                                <asp:TextBox ID="txtRegion" runat="server" Text='<%# Bind("Region") %>' />
                            </td>
                        </tr>
                        <tr align="left" style="background-color: LightSkyBlue">
                            <td>
                                Postal Code
                            </td>
                            <td>
                                <asp:TextBox ID="txtPostalCode" runat="server" Text='<%# Bind("PostalCode") %>' />
                            </td>
                            </td>
                            <td>
                                Country
                            </td>
                            <td colspan="4" align="left">
                                <asp:TextBox ID="txtCountry" runat="server" Text='<%# Bind("Country") %>' />
                            </td>
                        </tr>
                    </table>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label8" runat="server" Text='<%# Bind("EmployeeID") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="LastName" SortExpression="LastName" HeaderStyle-BackColor="LightGreen">
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("LastName") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="FirstName" SortExpression="FirstName" HeaderStyle-BackColor="LightGreen">
                <ItemTemplate>
                    <asp:Label ID="Label2" runat="server" Text='<%# Bind("FirstName") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Address" SortExpression="Address" HeaderStyle-BackColor="LightSkyBlue">
                <ItemTemplate>
                    <asp:Label ID="Label3" runat="server" Text='<%# Bind("Address") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="City" SortExpression="City" HeaderStyle-BackColor="LightSkyBlue">
                <ItemTemplate>
                    <asp:Label ID="Label4" runat="server" Text='<%# Bind("City") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Region" SortExpression="Region" HeaderStyle-BackColor="LightSkyBlue">
                <ItemTemplate>
                    <asp:Label ID="Label5" runat="server" Text='<%# Bind("Region") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="PostalCode" SortExpression="PostalCode" HeaderStyle-BackColor="LightSkyBlue">
                <ItemTemplate>
                    <asp:Label ID="Label6" runat="server" Text='<%# Bind("PostalCode") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Country" SortExpression="Country" HeaderStyle-BackColor="LightSkyBlue">
                <ItemTemplate>
                    <asp:Label ID="Label7" runat="server" Text='<%# Bind("Country") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:CommandField ShowEditButton="True" />
        </Columns>
    </asp:GridView>
</asp:Content>

Now since the first columns are spanning into the rest of the Columns, so we have to write few lines of code to hide the rest of the columns. So here in the RowDataBound of EmployeeGrid, I have hidden rest of the columns except the Last column where we have kept our Command Buttons and the first Column where basically our code sits which spans in the other columns.

protected void EmployeeGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowState.ToString().Contains("Edit"))
    {
        GridView editGrid = sender as GridView;
        int colSpan = editGrid.Columns.Count;
        for (int i = 1; i < colSpan - 1; i++)
        {
            e.Row.CellsIdea.Visible = false;
            e.Row.CellsIdea.Controls.Clear();
        }
 
        e.Row.Cells[0].Attributes["ColSpan"] = (colSpan - 1).ToString();
    }
 
}

Now lets run the example code, so we are almost done now, as you can see in the screen below this is exactly what we were expecting. But just wait a moment, this are just the visual layout what about saving the modified data?

image

Ok, now first thing we have to do is to rename all the controls properly so that we can refer the controls in the FindControl methods in code behind. And now I have to capture the Updating event of the SqlDataSource, where basically I will get the reference of the input controls with the modified data if any and set the DefaultValue of the UpdateParameters of SqlDataSource control.

protected void EmployeeGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    //Employee Grid Controls
    //Update the values. 
    GridViewRow row = EmployeeGrid.Rows[e.RowIndex];
    SqlDataSource1.UpdateParameters["LastName"].DefaultValue = ((TextBox)(row.Cells[4].FindControl("txtLastName"))).Text;
    SqlDataSource1.UpdateParameters["FirstName"].DefaultValue = ((TextBox)(row.Cells[4].FindControl("txtFirstName"))).Text;
    SqlDataSource1.UpdateParameters["Address"].DefaultValue = ((TextBox)(row.Cells[0].FindControl("txtAddress"))).Text;
 
    SqlDataSource1.UpdateParameters["EmployeeID"].DefaultValue = ((Label)(row.Cells[1].FindControl("lblEmployeeID"))).Text; ;
 
    SqlDataSource1.UpdateParameters["City"].DefaultValue = ((TextBox)(row.Cells[2].FindControl("txtCity"))).Text;
    SqlDataSource1.UpdateParameters["Region"].DefaultValue = ((TextBox)(row.Cells[3].FindControl("txtRegion"))).Text;
    SqlDataSource1.UpdateParameters["PostalCode"].DefaultValue = ((TextBox)(row.Cells[4].FindControl("txtPostalCode"))).Text;
    SqlDataSource1.UpdateParameters["Country"].DefaultValue = ((TextBox)(row.Cells[0].FindControl("txtCountry"))).Text;
}

So with this I have completed my end to end databinding, column merging, row merging, updating our grid view control using SqlDataSource. In this example I have used Northwind database which you can get online. And this example is compatible with ASP.NET 2.0 and above.

On top of this you can customize this according to your requirements, like changing the layout in some other format, add images, other controls, adding validation controls, Inserting new record, deletion, etc.

You can download the complete application VS2010 Source Code from here.

Posted by bmdayal | with no comments

Passing Objects between ASP.NET and Silverlight Controls.

This is Part –2 of my previous post “Passing parameters between Silverlight and ASP.NET – Part 1

In my previous post I have showed how to pass parameters between Silverlight and ASP.NET using Query Strings, Init Parameters and HtmlPage.Document. These techniques are good as long as you are dealing with small amount of data and have certain limitation. There are some scenario where we have to pass large number of data from asp.net to Silverlight and back from Silverlight to asp.net and our architecture design does not permit us to connect to Database directly from Silverlight component.

Today I am going to show you how we can use Object Serialization to achieve the same. but remember using this also poses some serious performance issues, so use this only when you really need this scenario. Internally this technique uses the HtmpPage.Document method only.

Just to give you a fair idea how I can do this I have created a sample Silverlight Application using Visual Studio Web Developer 2010, and added a class file called Employee.cs. This file just holds few entities of Employee and EmployeeDetails. Just to give you a feel of actual scenario I have created the Employee and EmployeeAddress as a separate class and written a method to return the sample data from this classes.

EmployeeAddress Class

   1: public class EmployeeAddress
   2: {
   3:     [XmlAttribute]
   4:     public string Address { get; set; }
   5:     
   6:     [XmlAttribute]
   7:     public string City { get; set; }
   8:  
   9:     [XmlAttribute]
  10:     public string PinCode { get; set; }
  11: }

Employee Class

   1: [XmlRoot("Employee")]
   2: public class Employee
   3: {
   4:     [XmlElement]
   5:     public string EmployeeName { get; set; }
   6:  
   7:     [XmlElement]
   8:     public EmployeeAddress EmployeeAddresses { get; set; }
   9:  
  10:     [XmlElement]
  11:     public int Age { get; set; }
  12:  
  13:     public List<Employee> GetEmployeeData()
  14:     { 
  15:         List<Employee> employees = new List<Employee>();
  16:         employees.Add(new Employee { EmployeeAddresses = new EmployeeAddress { Address = "V.B.Layout", City = "Bangalore", PinCode = "560076" }, Age = 33, EmployeeName = "Brij Mohan" });
  17:         employees.Add(new Employee { EmployeeAddresses = new EmployeeAddress { Address = "Beauty Layout", City = "Delhi", PinCode = "111111" }, Age = 33, EmployeeName = "Arun Dayal Udai" });
  18:         employees.Add(new Employee { EmployeeAddresses = new EmployeeAddress { Address = "Mumbai Filmcity Layout", City = "Mumbai", PinCode = "444444" }, Age = 33, EmployeeName = "Sarosh Kumar" });
  19:         employees.Add(new Employee { EmployeeAddresses = new EmployeeAddress { Address = "Dimna Road", City = "Jamshedpur", PinCode = "831018" }, Age = 33, EmployeeName = "Bharti Priyadarshini" });
  20:  
  21:         return employees;
  22:     }
  23:  
  24:     public string GetSerializedEmployeeData()
  25:     {
  26:         MemoryStream mem = new MemoryStream();
  27:         System.Xml.Serialization.XmlSerializer xs = new XmlSerializer(typeof(List<Employee>));
  28:         mem.Seek(0, SeekOrigin.Begin);
  29:         xs.Serialize(mem, GetEmployeeData());
  30:         byte[] data = mem.GetBuffer();
  31:         string xmlString = Encoding.UTF8.GetString(data, 0, data.Length);
  32:         return xmlString;
  33:     }
  34:  
  35:     public List<Employee> GetDesializedEmployeeObject(string xmlData)
  36:     {
  37:         StringReader sr = new StringReader(xmlData);
  38:         XmlSerializer xs = new XmlSerializer(typeof(List<Employee>));
  39:         object employees = xs.Deserialize(sr);
  40:  
  41:         return (List<Employee>)employees;
  42:     }
  43: }

In the employee class above I have also written few helper methods to Serialize and de-serialize the objects, using XMLSerializer.

Now coming back to the code behind of my default.aspx page, here I am only trying to simulate the actual scenarion. On Page load I am getting my dummy data and putting this data into a Hidden Filed. In actual environment you may get this data from Database and then putting this into some hidden field.

   1: protected void Page_Load(object sender, EventArgs e)
   2: {
   3:     Employee emp = new Employee();
   4:     txtValue.Text = HttpUtility.HtmlEncode(emp.GetSerializedEmployeeData());
   5: }

You may notice that I have used HttpUtility.HtmlEncode, this is very important because we are passing XML Data during Postbacks, failing to use this may give you the following error, which you may not like to see.

Server Error in '/' Application.

A potentially dangerous Request.Form value was detected from the client (txtValue="<?xml version="1.0"?...").

image

Ok now my asp.net is ready to send data to Silverlight Control, its now Silverlight turn to get this data and parse it into Silverlight recognized format which Silverlight controls will understand.

First I am adding the same employee class to Silverlight project for de serializing the received serialized data from ASP.NET. To avoid duplication of data, I am adding the same class file to my Silverlight Project using Add as Link option from file dialogue.

First right click you Silverlight Project and Select Add –> Existing Item

image

Now, locate you Employee.cs file from the ASP.NET website project, and select Add As Link option from Add. This will basically create a shortcut to Employee.cs from your ASP.NET Application to your Silverlight Project, basically both are same copy so before make any ASP.NET only specific changes to this file make sure this should compile in your Silverlight application too, or  Vice Versa.

image

Now once the shortcut of the Employee is created in your Silverlight Application, we can use this class just like the normal class file. Now coming back to my Silverlight Application open the MainPage.xaml, open the XAML View. To display the data I have added a DataGrid and ListView of the Address Item on the XAML Page.

   1: <Grid x:Name="LayoutRoot" Background="White">
   2:         <sdk:DataGrid AutoGenerateColumns="False" Height="200" HorizontalAlignment="Left" ItemsSource="{Binding}" Name="employeeDataGrid" RowDetailsVisibilityMode="VisibleWhenSelected" VerticalAlignment="Top" Width="361" SelectionChanged="employeeDataGrid_SelectionChanged">
   3:         <sdk:DataGrid.Columns>
   4:             <sdk:DataGridTextColumn x:Name="ageColumn" Binding="{Binding Path=Age}" Header="Age" Width="SizeToHeader" />
   5:             <sdk:DataGridTextColumn x:Name="employeeNameColumn" Binding="{Binding Path=EmployeeName}" Header="Employee Name" Width="SizeToHeader" />
   6:         </sdk:DataGrid.Columns>
   7:     </sdk:DataGrid>
   8:     <Grid x:Name="employeeDetailList" HorizontalAlignment="Left" Margin="454,19,0,0" VerticalAlignment="Top">
   9:         <Grid.ColumnDefinitions>
  10:             <ColumnDefinition Width="Auto" />
  11:             <ColumnDefinition Width="Auto" />
  12:         </Grid.ColumnDefinitions>
  13:         <Grid.RowDefinitions>
  14:             <RowDefinition Height="Auto" />
  15:             <RowDefinition Height="Auto" />
  16:             <RowDefinition Height="Auto" />
  17:         </Grid.RowDefinitions>
  18:         <sdk:Label Content="Address:" Grid.Column="0" Grid.Row="0" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
  19:         <TextBox Grid.Column="1" Grid.Row="0" Height="23" HorizontalAlignment="Left" Margin="3" Name="addressTextBox" Text="{Binding Path=EmployeeAddresses.Address, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
  20:         <sdk:Label Content="City:" Grid.Column="0" Grid.Row="1" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
  21:         <TextBox Grid.Column="1" Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="3" Name="cityTextBox" Text="{Binding Path=EmployeeAddresses.City, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
  22:         <sdk:Label Content="Pin Code:" Grid.Column="0" Grid.Row="2" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
  23:         <TextBox Grid.Column="1" Grid.Row="2" Height="23" HorizontalAlignment="Left" Margin="3" Name="pinCodeTextBox" Text="{Binding Path=EmployeeAddresses.PinCode, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
  24:     </Grid>
  25: </Grid>

In the code behind of MainPage.xaml I have just added few lines of code to load and bind the Data from the ASP.NET page hidden field where we have kept our employee Serialized data.

   1: public partial class MainPage : UserControl
   2: {
   3:     List<Web.Employee> employees = null;
   4:     public MainPage()
   5:     {
   6:         InitializeComponent();
   7:     }
   8:  
   9:     private void UserControl_Loaded(object sender, RoutedEventArgs e)
  10:     {
  11:         if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
  12:         {
  13:             var result = HttpUtility.HtmlDecode(HtmlPage.Document.GetElementById("txtValue").GetProperty("value").ToString());
  14:  
  15:             SLAppCommunication.Web.Employee employee = new Web.Employee();
  16:             employees = employee.GetDesializedEmployeeObject(result.ToString());
  17:             employeeDataGrid.ItemsSource = employees;
  18:         }
  19:  
  20:     }
  21:  
  22:     private void employeeDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
  23:     {
  24:         Web.Employee emp = ((DataGrid)sender).SelectedItem as Web.Employee;
  25:         employeeDetailList.DataContext = emp;
  26:     }
  27: }

Here after the Load event of Silverlight Control I am reading the Data from the HTML Page textbox and then using HttpUtility.HtmlDecode to decode the Encoded string from the textbox. This will give me the actual Serialized String. Now since we want our data into an Object format so we are actually doing the reverse of what we already did in ASP.NET application. We are going to pass this XML Data into our function  GetDesializedEmployeeObject this function will basically return me the List<Employee> which we can directly bind it to our DataGrid control. Now lets run the application.

image

Ok so this gives me all the data which we have created in our ASP.NET application, Just I have added a employeeDataGrid_SelectionChanged event so that when we select any rows in our Grid it displays the detailed information of the same. And yes using this method we can avoid any calls to DB directly from Silverlight component. Here Silverlight is just a component plugged in into our ASP.NET page container.

Hope you liked this Post, to get the proper formatted and running example to the source code, you can download from here.

Source Code.

Passing parameters between Silverlight and ASP.NET – Part 1

While working with Silverlight applications, we may face some scenarios where we may need to embed Silverlight as a component, like for e.g in Sharepoint Webpars or simple we can have the same with ASP.NET. The biggest challenge comes when we have to pass the parameters from ASP.NET to Silverlight components or back from Silverlight to ASP.NET.

We have lots of ways we can do this, like using InitParams, QueryStrings, using HTML objects in Silverlight, etc. All these different techniques have some advantages or disadvantages or limitations. Lets see one by one why we should choose one and what are the ways to achieve the same.

1. InitParams:

Lets start with InitParams, Start your Visual Studio 2010 IDE, and Create a Silverlight Application, give any name. Now go to the ASP.NET WebProject which is used to Host the Silverlight XAP component. You will find lots of different tags are used by Silverlight object as <params> tags. To use InitParams, Silverlight provides us with a tag called InitParams which we can use to pass parameters to Silverlight object from ASP.NET.

   1: <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
   2:   <param name="source" value="ClientBin/SilverlightApp.xap"/>
   3:   <param name="onError" value="onSilverlightError" />
   4:   <param name="background" value="white" />
   5:   <param name="minRuntimeVersion" value="4.0.50826.0" />
   6:   <param name="initparams" id="initParams" runat="server" value=""/>
   7:   <param name="autoUpgrade" value="true" />
   8:   <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50826.0" style="text-decoration:none">
   9:        <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
  10:   </a>
  11: </object>
Here in the code above I have included a initParam as a param tag (line 6), now in the page load I will add a line
   1: initParams.Attributes.Add("value", "key1=Brij, key2=Mohan");

This basically add a value parameter inside the initParam. So thats all we need in our ASP.NET side, now coming to the Silverlight Code open the code behind of App.xaml and add the following lines of code.

   1: private string firstKey, secondKey;
   2: private void Application_Startup(object sender, StartupEventArgs e)
   3: {
   4:     if (e.InitParams.ContainsKey("key1"))
   5:         this.firstKey = e.InitParams["key1"];
   6:     if (e.InitParams.ContainsKey("key2"))
   7:         this.secondKey = e.InitParams["key2"];
   8:     this.RootVisual = new MainPage(firstKey, secondKey);
   9: }

This code fetch the init params and pass it to our MainPage.xaml constructor, in the MainPage.xaml we can use these variables according to our requirement, here in this example I am simply displaying the variables in a Message Box.

   1: public MainPage(string param1, string param2)
   2: {
   3:     InitializeComponent();
   4:     MessageBox.Show("Welcome, " + param1 + " " + param2);
   5: }
imageThis will give you a sample output as

Limitations: Depending on the browsers you have some limitation on the overall string length of the parameters you can pass. To get more details on this limitation, you can refer to this link :http://www.boutell.com/newfaq/misc/urllength.html

2. QueryStrings

To show this example I am taking the scenario where we have a default.aspx page and we are going to the SIlverlightTestPage.aspx, and we have to work with the parameters which was passed by default.aspx in the SilverlightTestPage.aspx Silverlight Component.

So first I will add a new page in my application which contains a button with ID =btnNext, and on click of the button I will redirect my page to my SilverlightTestAppPage.aspx with the required query strings.

Code of Default.aspx

   1: protected void btnNext_Click(object sender, EventArgs e)
   2: {
   3:     Response.Redirect("~/SilverlightAppTestPage.aspx?FName=Brij" + "&LName=Mohan");
   4: }

Code of MainPage.xaml.cs

   1: public partial class MainPage : UserControl
   2: {
   3:     public MainPage()
   4:     {
   5:         InitializeComponent();
   6:         this.Loaded += new RoutedEventHandler(MainPage_Loaded);
   7:     }
   8:  
   9:     void MainPage_Loaded(object sender, RoutedEventArgs e)
  10:     {
  11:         IDictionary<string, string> qString = HtmlPage.Document.QueryString;
  12:         string firstName = string.Empty;
  13:         string lastName = string.Empty;
  14:         foreach (KeyValuePair<string, string> keyValuePair in qString)
  15:         {
  16:             string key = keyValuePair.Key;
  17:             string value = keyValuePair.Value;
  18:             if (key == "FName")
  19:                 firstName = value;
  20:             else if (key == "LName")
  21:                 lastName = value;
  22:         }
  23:         MessageBox.Show("Welcome, " + firstName + " " + lastName);
  24:     }
  25: }

Set the Startup page as Default.aspx, now run the application. This will give you the following output:

imageSince here also you are using the Query Strings to pass your parameters, so you are depending on the browser capabilities of the length of the query strings it can pass. Here also you can refer the limitation which I have mentioned in my previous example for the length of parameters you can use.

 

3. Using HtmlPage.Document

Silverlight to ASP.NET <—> ASP.NET to Silverlight: To show this I setup a sample Silverlight Application with Buttons Get Data and Set Data with the Data Text Box. In ASP.NET page I kep a TextBox to Show how the values passed to and From Silverlight to ASP.NET reflects back. My page with Silverlight control looks like this.

image

When I Say Get Data it pulls the data from ASP.NET to Silverlight Control Text Box, and When I say Set data it basically Set the Value from Silverlight Control TextBox to ASP.NET TextBox. Now let see the code how it is doing.

This is my ASP.NET Source Code. Here I have just created a TextBox named : txtData

   1: <body>
   2:     <form id="form1" runat="server" style="height:100%">
   3:     <div id="silverlightControlHost">
   4:     ASP.NET TextBox:  <input type="text" runat="server" id="txtData" value="Some Data" />
   5:         <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
   6:           <param name="source" value="ClientBin/SilverlightApplication1.xap"/>
   7:           <param name="onError" value="onSilverlightError" />
   8:           <param name="background" value="white" />
   9:           <param name="minRuntimeVersion" value="4.0.50826.0" />
  10:           <param name="autoUpgrade" value="true" />
  11:           <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50826.0" style="text-decoration:none">
  12:                <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
  13:           </a>
  14:         </object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe>
  15:         </div>
  16:     </form>
  17: </body>

My actual logic for getting and setting the data lies in my Silverlight Control, this is my XAML code with TextBox and Buttons.

   1: <Grid x:Name="LayoutRoot" Background="White" Height="100" Width="450" VerticalAlignment="Top">
   2:     <Grid.ColumnDefinitions>
   3:         <ColumnDefinition Width="110" />
   4:         <ColumnDefinition Width="110" />
   5:         <ColumnDefinition Width="110" />
   6:         <ColumnDefinition Width="110" />
   7:     </Grid.ColumnDefinitions>
   8:     <TextBlock Text="Silverlight Text Box: " Grid.Column="0" VerticalAlignment="Center"></TextBlock>
   9:     <TextBox x:Name="DataText" Width="100" Grid.Column="1" Height="20"></TextBox>
  10:     <Button x:Name="GetData" Width="100" Click="GetData_Click" Grid.Column="2" Height="30" Content="Get Data"></Button>
  11:     <Button x:Name="SetData" Width="100" Click="SetData_Click" Grid.Column="3" Height="30" Content="Set Data"></Button>
  12: </Grid>

Now we have to write few lines of Button Events for Get Data and Set Data which basically make use of Windows.System.Browser namespace.

   1: private void GetData_Click(object sender, RoutedEventArgs e)
   2: {
   3:     DataText.Text = HtmlPage.Document.GetElementById("txtData").GetProperty("value").ToString();
   4: }
   5:  
   6: private void SetData_Click(object sender, RoutedEventArgs e)
   7: {
   8:     HtmlPage.Document.GetElementById("txtData").SetProperty("value", DataText.Text);
   9: }

That’s it so when we run this application my Form will look like this.

image

4. Using Object Serialization.

This is a useful when we want to pass Objects of Data from our ASP.NET application to Silverlight Controls and back. This technique basically uses the above technique I mentioned in Pint 3 above. Since this itself is a length topic so details of this I am going to cover in Part 2 of this Post with Sample Code Example very soon.

MphasiS – Spirit of Winning Award, May 2011

I am glad to announce that I received MphasiS – Spirit of Winning award for the month of May 2011. This award is presented to the individual for living by the MphasiS Values and demonstrating the Winning Spirit.

image

Thanks to all my colleagues and managers for their support.

Posted by bmdayal | with no comments

Article Published On – Electronics For You, June 2011 Issue Vol. 43 No. 6

I am happy to announce that my article has been published on Electronics For You June 2011 Issue Vol. 43 No. 6 magazine.

You can Get an Overview of the Article (AVR Programmer Using AVR910 Protocol ) on http://www.efymag.com/currentissue.asp?id=12

EFY-June11-tilted

You can grab your copies from the newsstand.

Source codes for this article can be downloaded from the link: Download source code

Thanks to Arun Dayal Udai (Co-Author) for his extended support and providing me an opportunity to write the VB.NET Source codes supporting his concepts. Also thanks to all my readers/well wishers who has inspired me to post/write useful content. I will try my best to provide useful articles in upcoming days as well.

Free eBook on Windows Azure

I just found a free 96 pages eBook available from Eric Nelson about the windows azure platform. Looked through it very quickly and I thought it would be a very good book to learn the overall of Windows Azure, SQL Azure and the software architecture which will be deployed on Azure. You can download it here.

image

You can also read the book Cloud Computing with Windows Azure Platform by Roger Jennings online from here. Remember this is just the online version, so you cannot download or print this.

image

To Get the feel of this book, you can buy from the Amazon link below.

Posted by bmdayal | with no comments
Filed under:

Free eBook on Windows Phone 7 with Silverlight

Free eBook on Windows Phone 7 with Silverlight

Free book that walks through how to use Silverlight and Visual Studio to build Windows Phone 7 applications.

Posted by bmdayal | with no comments

Head First Design Patterns - Code Examples in C#

The only thing which bothered me while reading this book (Head First Design Pattern) was the code which was provided in Java.

I was very happy to learn that this is no longer an issue because now you can download all the codes in you native C# Language that too in Framework 4.0 :-)

You can download the codes from codeplex using the link below.

http://hfpatternsincsharp.codeplex.com/

Posted by bmdayal | with no comments

.NET Windows Development: Everyday Tips, Tricks & Optimization - Alberto Población

This is one of the best book I have came across so far, This book is so indulging that once you start reading this book you will want to finish all the chapters in one go, actually same thing happened to me too.

This book covers Tips, Tricks and Optimization techniques for Visual Studio 2005, 2008 and 2010 and also new features of Windows 7 too and most important is this is not only theory, In fact these are the collection of techniques which we use day to day in our work and  professional career.

Alberto has been in computer industry for more then 27 years and also Microsoft MVP in C# because of his great impact teaching others about .NET development both as a trainer as well as a top answerer in newsgroup and forums. Alberto Población poured the cream of his knowledge into this book. I would recommend all my readers to read this book at least once.You can get a fair idea of this book by reading the Table of Contents and Index @ Amazon.

I can assure that this book will help you to write more optimized and better code, you can also complete your task more quickly and effectively.

To buy this book you can go to this Amazon link “.NET Windows Development- Everyday Tips, Tricks & Optimization.”.

You can download the Example Source Codes used in this book from here : http://www.krasis.com/krasispress/Downloads.htm

Some of the Topics this book covers are:

  • Special techniques for accessing data.
  • New features in Windows 7 and Programming with these features.
  • Using Graphics, Serialization and Reflection
  • Various techniques that should be well-known, but aren't.
  • Tips and Tricks of Windows Forms application.

I don't know Alberto personally, but after reading this book I can say this was his very nice effort and I just request Alberto Población to keep sharing more of his knowledge like this in his future publications too.

“Article of the Day” – ASP.NET Forum

I am happy to announce that my article has been published on http://www.asp.net site Tuesday, May 17, 2011

You can visit the http://www.asp.net/community and Select “Article of the day” section in asp.net site & check out the following entry for my article.

Create and Deploy Windows Azure Application (http://www.dotnetglobe.com/2011/05/create-and-deploy-windows-azure.html)

Thanks to all my readers/well wishers who has inspired me to post/write useful content on the blog. I will try my best to provide useful information in upcoming days as well.

Posted by bmdayal | with no comments

SQL Server Date-Time Formats

Here's a summary of the different date formats that come standard in SQL Server as part of the CONVERT function. Following the standard date formats are some extended date formats

Standard Date Formats
Date Format Standard SQL Statement Sample Output
Mon DD YYYY
HH:MIAM (or PM)
Default SELECT CONVERT(VARCHAR(20), GETDATE(), 100) Jan 1 2005 1:29PM
MM/DD/YY USA SELECT CONVERT(VARCHAR(8), GETDATE(), 1) AS [MM/DD/YY] 11/23/98
MM/DD/YYYY USA SELECT CONVERT(VARCHAR(10), GETDATE(), 101) AS [MM/DD/YYYY] 11/23/1998
YY.MM.DD ANSI SELECT CONVERT(VARCHAR(8), GETDATE(), 2) AS [YY.MM.DD] 72.01.01
YYYY.MM.DD ANSI SELECT CONVERT(VARCHAR(10), GETDATE(), 102) AS [YYYY.MM.DD] 1972.01.01
DD/MM/YY British/French SELECT CONVERT(VARCHAR(8), GETDATE(), 3) AS [DD/MM/YY] 19/02/72
DD/MM/YYYY British/French SELECT CONVERT(VARCHAR(10), GETDATE(), 103) AS [DD/MM/YYYY] 19/02/1972
DD.MM.YY German SELECT CONVERT(VARCHAR(8), GETDATE(), 4) AS [DD.MM.YY] 25.12.05
DD.MM.YYYY German SELECT CONVERT(VARCHAR(10), GETDATE(), 104) AS [DD.MM.YYYY] 25.12.2005
DD-MM-YY Italian SELECT CONVERT(VARCHAR(8), GETDATE(), 5) AS [DD-MM-YY] 24-01-98
DD-MM-YYYY Italian SELECT CONVERT(VARCHAR(10), GETDATE(), 105) AS [DD-MM-YYYY] 24-01-1998
DD Mon YY - SELECT CONVERT(VARCHAR(9), GETDATE(), 6) AS [DD MON YY] 04 Jul 06
DD Mon YYYY - SELECT CONVERT(VARCHAR(11), GETDATE(), 106) AS [DD MON YYYY] 04 Jul 2006
Mon DD, YY - SELECT CONVERT(VARCHAR(10), GETDATE(), 7) AS [Mon DD, YY] Jan 24, 98
Mon DD, YYYY - SELECT CONVERT(VARCHAR(12), GETDATE(), 107) AS [Mon DD, YYYY] Jan 24, 1998
HH:MM:SS - SELECT CONVERT(VARCHAR(8), GETDATE(), 108) 03:24:53
Mon DD YYYY HH:MI:SS:MMMAM (or PM) Default +
milliseconds
SELECT CONVERT(VARCHAR(26), GETDATE(), 109) Apr 28 2006 12:32:29:253PM
MM-DD-YY USA SELECT CONVERT(VARCHAR(8), GETDATE(), 10) AS [MM-DD-YY] 01-01-06
MM-DD-YYYY USA SELECT CONVERT(VARCHAR(10), GETDATE(), 110) AS [MM-DD-YYYY] 01-01-2006
YY/MM/DD - SELECT CONVERT(VARCHAR(8), GETDATE(), 11) AS [YY/MM/DD] 98/11/23
YYYY/MM/DD - SELECT CONVERT(VARCHAR(10), GETDATE(), 111) AS [YYYY/MM/DD] 1998/11/23
YYMMDD ISO SELECT CONVERT(VARCHAR(6), GETDATE(), 12) AS [YYMMDD] 980124
YYYYMMDD ISO SELECT CONVERT(VARCHAR(8), GETDATE(), 112) AS [YYYYMMDD] 19980124
DD Mon YYYY HH:MM:SS:MMM(24h) Europe default + milliseconds SELECT CONVERT(VARCHAR(24), GETDATE(), 113) 28 Apr 2006 00:34:55:190
HH:MI:SS:MMM(24H) - SELECT CONVERT(VARCHAR(12), GETDATE(), 114) AS [HH:MI:SS:MMM(24H)] 11:34:23:013
YYYY-MM-DD HH:MI:SS(24h) ODBC Canonical SELECT CONVERT(VARCHAR(19), GETDATE(), 120) 1972-01-01 13:42:24
YYYY-MM-DD HH:MI:SS.MMM(24h) ODBC Canonical
(with milliseconds)
SELECT CONVERT(VARCHAR(23), GETDATE(), 121) 1972-02-19 06:35:24.489
YYYY-MM-DDTHH:MM:SS:MMM ISO8601 SELECT CONVERT(VARCHAR(23), GETDATE(), 126) 1998-11-23T11:25:43:250
DD Mon YYYY HH:MI:SS:MMMAM Kuwaiti SELECT CONVERT(VARCHAR(26), GETDATE(), 130) 28 Apr 2006 12:39:32:429AM
DD/MM/YYYY HH:MI:SS:MMMAM Kuwaiti SELECT CONVERT(VARCHAR(25), GETDATE(), 131) 28/04/2006 12:39:32:429AM

Some more date formats that does not come standard in SQL Server as part of the CONVERT function.

Extended Date Formats
Date Format SQL Statement Sample Output
YY-MM-DD
SELECT SUBSTRING(CONVERT(VARCHAR(10), GETDATE(), 120), 3, 8) AS [YY-MM-DD]
SELECT REPLACE(CONVERT(VARCHAR(8), GETDATE(), 11), '/', '-') AS [YY-MM-DD]
99-01-24
YYYY-MM-DD
SELECT CONVERT(VARCHAR(10), GETDATE(), 120) AS [YYYY-MM-DD]
SELECT REPLACE(CONVERT(VARCHAR(10), GETDATE(), 111), '/', '-') AS [YYYY-MM-DD]
1999-01-24
MM/YY SELECT RIGHT(CONVERT(VARCHAR(8), GETDATE(), 3), 5) AS [MM/YY]
SELECT SUBSTRING(CONVERT(VARCHAR(8), GETDATE(), 3), 4, 5) AS [MM/YY]
08/99
MM/YYYY SELECT RIGHT(CONVERT(VARCHAR(10), GETDATE(), 103), 7) AS [MM/YYYY] 12/2005
YY/MM SELECT CONVERT(VARCHAR(5), GETDATE(), 11) AS [YY/MM] 99/08
YYYY/MM SELECT CONVERT(VARCHAR(7), GETDATE(), 111) AS [YYYY/MM] 2005/12
Month DD, YYYY SELECT DATENAME(MM, GETDATE()) + RIGHT(CONVERT(VARCHAR(12), GETDATE(), 107), 9) AS [Month DD, YYYY] July 04, 2006
Mon YYYY SELECT SUBSTRING(CONVERT(VARCHAR(11), GETDATE(), 113), 4, 8) AS [Mon YYYY] Apr 2006
Month YYYY SELECT DATENAME(MM, GETDATE()) + ' ' + CAST(YEAR(GETDATE()) AS VARCHAR(4)) AS [Month YYYY] February 2006
DD Month SELECT CAST(DAY(GETDATE()) AS VARCHAR(2)) + ' ' + DATENAME(MM, GETDATE()) AS [DD Month] 11 September
Month DD SELECT DATENAME(MM, GETDATE()) + ' ' + CAST(DAY(GETDATE()) AS VARCHAR(2)) AS [Month DD] September 11
DD Month YY SELECT CAST(DAY(GETDATE()) AS VARCHAR(2)) + ' ' + DATENAME(MM, GETDATE()) + ' ' + RIGHT(CAST(YEAR(GETDATE()) AS VARCHAR(4)), 2) AS [DD Month YY] 19 February 72
DD Month YYYY SELECT CAST(DAY(GETDATE()) AS VARCHAR(2)) + ' ' + DATENAME(MM, GETDATE()) + ' ' + CAST(YEAR(GETDATE()) AS VARCHAR(4)) AS [DD Month YYYY] 11 September 2002
MM-YY SELECT RIGHT(CONVERT(VARCHAR(8), GETDATE(), 5), 5) AS [MM-YY]
SELECT SUBSTRING(CONVERT(VARCHAR(8), GETDATE(), 5), 4, 5) AS [MM-YY]
12/92
MM-YYYY SELECT RIGHT(CONVERT(VARCHAR(10), GETDATE(), 105), 7) AS [MM-YYYY] 05-2006
YY-MM SELECT RIGHT(CONVERT(VARCHAR(7), GETDATE(), 120), 5) AS [YY-MM]
SELECT SUBSTRING(CONVERT(VARCHAR(10), GETDATE(), 120), 3, 5) AS [YY-MM]
92/12
YYYY-MM SELECT CONVERT(VARCHAR(7), GETDATE(), 120) AS [YYYY-MM] 2006-05
MMDDYY SELECT REPLACE(CONVERT(VARCHAR(10), GETDATE(), 1), '/', '') AS [MMDDYY] 122506
MMDDYYYY SELECT REPLACE(CONVERT(VARCHAR(10), GETDATE(), 101), '/', '') AS [MMDDYYYY] 12252006
DDMMYY SELECT REPLACE(CONVERT(VARCHAR(10), GETDATE(), 3), '/', '') AS [DDMMYY] 240702
DDMMYYYY SELECT REPLACE(CONVERT(VARCHAR(10), GETDATE(), 103), '/', '') AS [DDMMYYYY] 24072002
Mon-YY SELECT REPLACE(RIGHT(CONVERT(VARCHAR(9), GETDATE(), 6), 6), ' ', '-') AS [Mon-YY] Sep-02
Mon-YYYY SELECT REPLACE(RIGHT(CONVERT(VARCHAR(11), GETDATE(), 106), 8), ' ', '-') AS [Mon-YYYY] Sep-2002
DD-Mon-YY SELECT REPLACE(CONVERT(VARCHAR(9), GETDATE(), 6), ' ', '-') AS [DD-Mon-YY] 25-Dec-05
DD-Mon-YYYY SELECT REPLACE(CONVERT(VARCHAR(11), GETDATE(), 106), ' ', '-') AS [DD-Mon-YYYY] 25-Dec-2005
Posted by bmdayal | with no comments

Deploying Windows Azure Application – VS2010 IDE

This is with reference to my previous post where I showed how to deploy ASP.NET Windows Azure application manually on the Windows Azure Server.

In this post I am going to show you how to deploy Windows Azure application using Visual Studio 2010 IDE, this I guess is quite simpler as compared to the previous approach i.e. doing it manually.

Once you ready with your Windows Azure Application, Select Deploy option from the Windows Azure Application. To see how to create a basic application you can refer to my previous post.

image

Now from the Deploy Select

1. Create your Windows Azure project to Windows Azure Option

image

2. From the Credential Select Add option if you don’t have Server certificate already present. This will open a Popup for you to enter the details of the Certificate.

image

3. Here again I am selecting Create Option from the Dropdown. This will open another popup for entering the name of your certificate. Once you done Click Ok.

image

4. From the Second option Select the Copy full path and now its time for you to open you Windows Azure Site to upload your Certificate. By Selecting the Copy Full Path option basically this is copying the certificate path for you to clipboard, which you can paste later in Windows Azure Site.

image

5. Once you logged into your Windows Azure Website (https://windows.azure.com), Select ‘Hosted Service, Storage Accounts & CDN then Management Certificates and at the End Select Add Certificated as given in the Screen shot below as 1,2,3.

image

6. This will open a Popup screen for you to upload your certificate, I hope during these time you have not copied anything else in your Clipboard and you still have the path copied which I have mentioned in Step 4.

image

7. Select your Subscription and then Select Browse and paste the Path which you have copied earlier in the File Name of Select file dialogue. Select Open. and then Select Ok from the Popup menu given below.

image

8. So this will create a certificate on Windows Azure Server, and Create a Subscription Id for you Copy the Subscription Id using Ctrl+C, remember right click will not work since this is Silverlight Interface.

image

9. Now come back to your Visual Studio IDE with once you copied the Subscription Id from Windows Azure Site. and paste in the Step 3 of the popup screen as given below. Enter any desired name for your credentials and Click on Ok button.

image

If you get the Error: No Subscription found. As given in the screen below, this means either you have not created the Storage Account or Hosted Service or may be both.

image

To get this things working you have to go to Windows Azure Site and Create a Hosted Service with Do not deploy option selected, as we want to deploy using our Visual Studio IDE.

image

Similarly you have to create a Storage Account too. Hope after doing this you may not face any other issues. So once you have done with these things then

Again you have to Start from Step 1 above, but instead of Adding a new Certificate you can select the one which you have already created. Skip the Steps for uploading the certificate on Windows Azure Server and try again Deploying your application.

This should show you the Status of the Deployment activity in Windows Azure Activity Log, once finished your application is ready to browse from Windows Azure Staging Environment.

Hope this helps.

Create and Deploy Windows Azure Application.

Well we have lots of Blog post which gives us how to deploy our .NET apps on Azure, but I just tried to describe it in my way using more Images which will give much clear understanding(a picture speaks thousand words!!!).

Ok, so to start with first you need to have Windows Azure Access, you can request for Trial licence here. Then for .NET developers will have to download the Azure SDK 1.4 (April 2011) using this link. And of course you need Visual Studio 2010 SP1, you can download it from here. Please note Windows Azure SDK is not compatible with Express editions of VS2010 IDE.

Now run the Visual Studio 2010 in elevated mode, i.e. you have to right click the Visual Studio 2010 icon in Program Files and Select “Run as Administrator”. Once you got the IDE you have to Select New Project and Select Cloud from the left menu, and Select Windows Azure Project from the right Selection menu. I am selecting this as C# project but you can select VB.NET too.

image

Name you application as you like, I named it as FirstWindowsAzure, and selected Ok button.

.image

Once you say Ok, this will show another window providing you with different options to select from. I am not going into very depth of each and every Roles, just to give you brief idea,

A Windows Azure role is an individually scalable component running in the cloud where each instance of a role corresponds to a virtual machine (VM) instance.

There are two types of role:

  • A Web role is a Web application running on IIS. It is accessible via an HTTP or HTTPS endpoint.
  • A Worker role is a background processing application that runs arbitrary .NET code. It also has the ability to expose Internet-facing and internal endpoints.

We also have a special type of Role called as VM Role. You can get more details on MSDN Link about Architecture of Windows Azure Roles.

To keep it simple and focussed I have created a WebRole and named it as MyFirstApp. Once I say Ok my Solution looks something like as below.

image

It is easy to add or remove roles in the cloud service after project creation has completed. To add other roles to this cloud service, right-click on the Roles node in the cloud service and select Add -> New Web Role Project or Add -> New Worker Role Project. Selecting either of these options brings up the Add New Role dialog where you can choose which project template to use when adding the role.

You can add any ASP.NET Web Role project to the solution by right-clicking on the Roles node, selecting Add -> Web Role Project in the solution, and selecting the project to associate as a Web role.

To delete, simply select the role to delete and hit the Delete key. The project can then be removed.

Now coming back to my application. I am keeping all the default codes which was created by the designer and hit F5. Visual Studio will build your project, start the Development Fabric, initialize the Development Storage (if run for the first time), package the deployment, attach to all role instances, and then launch the browser pointing to the Web role.

image

You can see the notifications area of the taskbar shows the Development Fabric has started. The Development Fabric is a simulation environment that runs role instances on your machine in much the way they run in the real cloud.

image

Right-click on the Windows Azure notification icon in the taskbar and click on Show Compute Emulator UI. This will launch the Windows Azure Compute Emulator itself, which allows you to perform various operations on your deployments, such as viewing logs and restarting and deleting deployments. Notice that the Development Fabric contains a new deployment that hosts one Web role instance and one Worker role instance.

image

I hope up to this point you have not encountered any exceptions/errors. Now your sample  application is ready for deployment. If you have already got access to https://windows.azure.com then you can open the site using your credentials. Once you logged in successfully you will get nice UI build on Silverlight 4.0 interface. This is the new UI, you can switch back the old one too if you like.

image

To start the deployment process first you have to Publish the FirstWindowsAzure using the following options (Create Service Package Only). This will create the Package and Service Configuration named named FirstWindowsAzure.cspkg and ServiceConfiguration.cscfg respectively in \bin\Debug\Publish directory.

image

image

Now in the Web Interface of Windows Azure Platform, Select New Hosted Service from the Top Menu Ribbon

image

This will Popup the menu as below.

You have to choose the Desired Subscription, Provide Name, URL Prefix, Region, Deployment options, Deployment Name, Package location and configuration file location.

Since the domain cloudapp.net and is common for all the users prefix with the URL Prefix provided by you, so your prefix has to be unique and not taken by any other users. Select the Staging environment for testing purpose, Keep the Start after successful deployment checked. This will start your Service as soon as its get created. For Package location and Configuration files you have to Browse locally for the files FirstWindowsAzure.cspkg and ServiceConfiguration.cscfg respectively in \bin\Debug\Publish directory. If you enter the URL Prefix which is already taken then it will give you the following error.

image

Once you enter all the required information you can Click Ok in the popup. This will validate your information's which you have entered and may give you a warning, you can simply ignore this warning.

image

This will start creating your application. Once it finishes, your application is ready to browse and hosted in Cloud. Remember this process may take a while during this time don't refresh your browser.

image

image

Once your hosted service is hosted and started, the Azure service will generate a random id for staging environment, which can be used to browse your application remotely, as given below.

Devil" border="0" alt="image_thumbDevil" src="http://dotnetslackers.com/Community/blogs/bmdayal/image_thumb6_0A6E7AF0.png" width="454" height="163" />

image_thumb[4]

This is just the basics which I wanted to share in this Post, you can also refer to MSDN article Code Quick Start: Create and deploy an ASP.NET application in Windows Azure. Both post are very much similar. I just tried to give more pictorial representation of the same for much better understanding for those who are starting from scratch.

Note: For evaluation licence of Windows Azure you one limitation is you can create only one hosted services. So before winding up just to let you know how to delete the already created hosted services.

First you have to stop the Service you have created if any, once it stopped, you can see the Delete button gets enabled. Then you can comfortably delete the created service and create the new service.

image

Other very useful link : http://blogs.msdn.com/b/jnak/

Hope this helps.

MIX11 videos download in one click.

image

You can download all the MIX11 Videos in Single click from here. This has got nice Silverlight interface to select your desired files and click on Download. Since Silverlight has some security restriction, so this download button will just create a batch file in you system. To run this batch file you have to download a program called wget.

If you still have some issues with download you can refer this link.

image

Alternately you can also download the Videos from the Official Website too.

~Brij Mohan

Posted by bmdayal | with no comments
Filed under:
More Posts Next page »