Friday, May 30, 2008

Microsoft Innovation Days at Kochi

I attended the Microsoft Innovation Days event at Le Meridien Hotel, Kochi today. Innovation Days are day-long free events filled with technical and business sessions, during which one can learn about the Microsoft technology roadmap and are introduced to upcoming technologies. Microsoft also presents Partner Programs and benefits for ISV partners.

This year the event series in India started on 16-May-2008 at Chennai and is concluding at Pune on 02-Jun-2008. Besides Cochin, Ahmedabad is the only other city to host this event. One source from Microsoft indicated that the big cities like Bangalore, Mumbai and Delhi are getting 'abused' by events and the number of no-shows after signing up is increasing. That made them to choose Tier-II cities in India for such events where they are getting a very good response.


The day here started with a session by Nahas Mohammed on 'Building Rich Internet Applications Using Silverlight 2.0'. At the end of it, my colleague Jim Mangaly did a great presentation showcasing 'Lithium', a virtual vehicle gallery and showroom application developed in Silverlight. He explained how various awesome technologies in Silverlight were taken to full advantage for the development of this application. The 200 plus technology enthusiasts in town were quiet impressed with the presentation. Since our company IdentityMine is mostly focusing on US market, we are not so well known here. But the participation in events like this are slowly changing the scene.

The next session 'Building high performance .NET applications' by Harish Ranganathan focused on tips and tricks to make .NET applications perform better. He also did a demo of 'ASP.NET Dynamic Data' which is part of '.NET Framework 3.5 Service Pack 1 Beta'. It was scary to see him build a web site to manage all the data operations (add/edit/delete) for all the tables in a database just by pointing to a LINQ to SQL data context. The wizard created website was complete with proper navigation and validation.


After a heavy and delicious lunch, there were two more interesting sessions named 'LINQ: Working with data naturally!' and 'Getting the Best from SQL Box: Performance Tuning SQL Server'.

Microsoft also announced their partner program called Innovate On for Kochi. They distributed a lot of goodies for the early birds and for the question askers.

Wednesday, May 07, 2008

WPF Color Pad

Ever wanted to see the list of named colors available in WPF's System.Windows.Media.Colors? And fancied using it's hexa code to get the colors like 'Tomato' in your web page?

Here is a simple WPF Application called ColorPad that lists out all the named colors. Click on a color to see its hexa code value. Remember to remove the first two letters/digits that represents the transparency (Alpha value) if you are using this color in html pages.


The application can be downloaded from here.

The XAML Source Code:

<Window x:Class="ColorPad.Window1" Icon="ColorPad.ico"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ColorPad" Height="500" Width="300" WindowStyle="SingleBorderWindow" ResizeMode="NoResize">
<Window.Resources>
<DataTemplate x:Key="tempGrid">
<Rectangle Width="60" Height="20" Fill="{Binding Name}" Stroke="#FF000000"/>
</DataTemplate>
</Window.Resources>

<Grid x:Name="LayoutRoot" ShowGridLines="True">
<StackPanel Orientation="Vertical">
<TextBlock x:Name="uxTitle" Text="ColorPad Version 1.0.0" Width="210" TextAlignment="Center" />
<ListView Height="400" Width="210" Name="uxColorGrid">
<ListView.View>
<GridView x:Name="uxColorGridView">
<GridViewColumn Header="Color Name" DisplayMemberBinding="{Binding Path=Name}" />
<GridViewColumn CellTemplate="{DynamicResource tempGrid}" Header="Color" />
</GridView>
</ListView.View>
</ListView>
<TextBlock x:Name="uxFooter" Visibility="Collapsed" Width="200" Background="{Binding RelativeSource={RelativeSource Self}, Path=Text}" />
<TextBox x:Name="uxColorCode" Width="210" TextAlignment="Center" />
</StackPanel>
</Grid>
</Window>


And the Code Behind in C#:

using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Collections.Generic;

namespace ColorPad
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();

uxColorGrid.ItemsSource = typeof(Colors).GetProperties();
uxColorGrid.SelectionChanged += new SelectionChangedEventHandler(uxColorGrid_SelectionChanged);
}

void uxColorGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
PropertyInfo c = uxColorGrid.SelectedItem as PropertyInfo;
uxFooter.Text = c.Name;

SolidColorBrush scb = uxFooter.Background as SolidColorBrush;
uxColorCode.Text = scb.Color.ToString();
uxTitle.Foreground = uxFooter.Background;
}
}
}

Monday, May 05, 2008

ASP.NET 3.5

My last two major projects were in ASP.NET 2.0. That was just few months back. Now I am getting swamped in the .NET 3.5 world with WPF, Silverlight and LINQ and was bit worried when I had to consider ASP.NET as an option for a new project. By all chance, few months is longer than enough for Microsoft to flood us with new technologies and I was almost sure the new ASP.NET 3.5 will yet again look like an odd world for me.

But that was not the case. As with the .NET framework, the ASP.NET 3.5 is a set of additive features on top of ASP.NET 2.0. Most of the things I have learned in .NET 3.5 like the cool new C# features (LINQ, Query Expressions, Lambda Expressions, Type Inferencing (var), Class and Collection Initializers, Anonymous Types, Extension Methods) are useful in the web development world too. Moreover the new Visual Studio 2008 features (improved web page designer, css editing, javascript intellisense and debug support) are also much helpful for web developer.

Besides that there are very few ASP.NET specific new features. That includes ListView Control, DataPager control, and the integrated ASP.NET AJAX support.

ListView control is a beautiful data web control that can be bound to multiple records (like a grid) but still allows flexible layout. The DataPager only works with ListView Control and provides a paging user interface - next, previous, first, last buttons, for example.

AJAX support was earlier available in ASP.NET 2.0 as a separate download. Now it is part of ASP.NET 3.5. But if we want more AJAX controls, we still need to download the AJAX Control Tool Kit. You can unzip the contents to your computer (Somewhere like C:\Program Files\AjaxControlToolKit) and add them to Visual Studio. Make sure that the AjaxControlToolkit.dll is available in the Binaries folder. If not, you can either build the solution or copy it from the SampleWebSite's bin folder. By right clicking on the Toolbox in Visual Studio 2008, you can Add a new Tab and then Choose Items to browse for AjaxControlToolkit.dll to add all the AJAX controls into the tool box.

I did a sample AJAX website in few minutes. As usual start a new 'ASP.NET Web Application' project and make sure the target version of .NET Framework is 3.5. First we need to add the 'ScriptManager' and 'UpdatePanel' controls from AJAX Extensions tab in Toolbox and then we can add the controls to this panel. Try adding a Text Box, a Button, and a Label. On the designer, double click on the button to get the click event handler in the code behind. Change the label text to display something. (Label1.Text = "Hello " + TextBox1.Text;).



On the designer, an adorner appears on the supported controls and it can be used to add AJAX extenders. I tried adding a Confirmation Button Extender for the button and all I had to write was the ConfirmationText for this extender.

<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<cc1:ConfirmButtonExtender ID="Button1_ConfirmButtonExtender" runat="server"
ConfirmText="Are you sure?" Enabled="True" TargetControlID="Button1">
</cc1:ConfirmButtonExtender>

On running the application, a confirmation message box will appear while clicking this button, and the click event will be fired only after user confirmation. All this code will run at client side and the beauty is that I didn't write a single line of javascript.

Try adding PasswordStrength and DropShadowText extenders for the text box and have fun exploring more.

Monday, March 17, 2008

LINQ to SQL

Language-Integrated Query (LINQ) is a set of features in .NET Framework 3.5 (Visual Studio 2008) that extends powerful query capabilities to the language syntax of C# and Visual Basic. LINQ introduces standard, easily-learned patterns for querying and updating data, and the technology can be extended to support potentially any kind of data store. Visual Studio 2008 includes LINQ provider assemblies that enable the use of LINQ with .NET Framework collections, SQL Server databases, ADO.NET Datasets, and XML documents.

In Visual Studio you can write LINQ queries in Visual Basic or C# with SQL Server databases, XML documents, ADO.NET Datasets, and any collection of objects that supports IEnumerable or the generic IEnumerable<(Of <(T>)>) interface. LINQ support for the ADO.NET Entity Framework is also planned, and LINQ providers are being written by third parties for many Web services and other database implementations.
You can use LINQ queries in new projects, or alongside non-LINQ queries in existing projects. The only requirement is that the project target version 3.5 of the .NET Framework.

There are different variants of LINQ as listed below:
LINQ to Objects
LINQ to XML
LINQ to ADO.NET (Dataset)
LINQ to SQL
LINQ to SQL

LINQ to SQL is a component of .NET Framework version 3.5 that provides a run-time infrastructure for managing relational data as objects.

In LINQ to SQL, the data model of a relational database is mapped to an object model expressed in the programming language of the developer. When the application runs, LINQ to SQL translates into SQL the language-integrated queries in the object model and sends them to the database for execution. When the database returns the results, LINQ to SQL translates them back to objects that you can work with in your own programming language.

See also http://msdn2.microsoft.com/hi-in/library/bb425822(en-us).aspx

The DataContext
The DataContext is the main conduit by which you retrieve objects from the database and resubmit changes. You use it in the same way that you would use an ADO.NET Connection. In fact, the DataContext is initialized with a connection or connection string you supply. The purpose of the DataContext is to translate your requests for objects into SQL queries made against the database and then assemble objects out of the results. The DataContext enables language-integrated query by implementing the same operator pattern as the standard query operators such as Where and Select.

Implementing LINQ to SQL
LINQ to SQL is best implemented in a project using the built-in Object Relational Designer (O/R Designer) in Visual Studio 2008. O/R Designer auto generates the DataContext class and entity classes for all the tables in a specified database.

To launch it,
Visual Studio 2008 > Projects > Add New Item > Visual C# (Category) > LINQ to SQL Classes (Template)
(Eg Name: Northwind)

This will open a blank O/R Designer. Now open Server explorer and add a new data connection to the required database. Drag and drop the required tables to the O/R Designer and it will automatically generate all needed classes.

The DataContext class will be named as NorthwindDataContext and this can be used to do operations against the database.

Selecting Data


//Create the DataContext object
NorthwindDataContext db = new NorthwindDataContext();

//Write the Select Query
var prods = from p in db.Products
select p;

//Use the output in various ways
foreach (Product prod in prods)
{
MessageBox.Show(prod.ProductName);
}

//assigning as data source to a grid view
gvMain.DataSource = prod;


Updating Data


//Getting one row from the Products table
Product prod = db.Products.Single(p => p.ProductName == "First Prod");

//Updating two of its columns
prod.UnitPrice = 25;
prod.UnitsInStock = 50;

//Submitting the changes to database
db.SubmitChanges();


Inserting Data


//Creating a new category
Category cat = new Category();
cat.CategoryName = "New Test Category";
cat.Description = "This is a new type of category";

//Creating two new products
Product p1 = new Product();
p1.ProductName = "First Prod";

Product p2 = new Product();
p2.ProductName = "Second Prod";

//Add the products to new category
cat.Products.Add(p1);
cat.Products.Add(p2);

//Add category to database and save changes
db.Categories.InsertOnSubmit(cat);
db.SubmitChanges();


Deleting Data


//Get the required data to delete
var toyProds = from p in db.Products
where p.ProductName.Contains("toy")
select p;

//Delete it from database
db.Products.DeleteAllOnSubmit(toyProds);
db.SubmitChanges();


So start using LINQ and refer the 101 samples at http://msdn2.microsoft.com/en-us/vcsharp/aa336746.aspx to help you with any syntax issues.

Thursday, March 13, 2008

SharePoint - Web Part Deployment

This post is applicable to Microsoft Office SharePoint Server (MOSS) 2007. See my previous posts on Installing SharePoint, Creating Web Site, and Developing Web Parts.

This walk-through provides the steps for deploying a basic custom SharePoint Web Part by either copying the assembly dll to the Server (if not strong named) or by deploying to GAC (if strong named) and configuring it through SharePoint administration site.

1. Copy the web part dll file to the bin directory on the server’s web location if the assembly is not strong named.
a. Log into the computer where SharePoint Server is installed.
b. Copy the web part dll (HelloWebPart.dll) to the SharePoint web’s bin directory. Usually this location will be at C:\Inetpub\wwwroot\wss\VirtualDirectories\80\bin.
c. If the SharePoint was installed on a different port (say 37729), this location will be at C:\Inetpub\wwwroot\wss\VirtualDirectories\37729\bin.
d. This location can be easily found from the IIS Manager (Locate the appropriate portal, for which u want to deploy the web part, identified with the port number. Right click and have Properties. Under the Home Directory Tab, note the path in Local path text box).
e. If the bin folder doesn’t exist at this location, then you can create one.
2. If the assembly is strong named, deploy it to the GAC. (Note that either Step-1 or Step-2 is required; not both.)
a. Log into the computer where SharePoint Server is installed.
b. Drag and drop the web part dll to the C:\Windows\Assembly folder using windows explorer. This will install the assembly to Global Assemble Cache. After that, right click on the assembly name from here and choose Properties. Copy the Public Key Token value for using in the configuration.
3. Add a Safe Control entry in the web configuration file of SharePoint Server.
a. Open the web.config file from the server’s web location which will be at C:\Inetpub\wwwroot\wss\VirtualDirectories\80\ or at a port number as mentioned above.
b. Add a new entry within the section as below:

<SafeControl Assembly="HelloWebPart" Namespace="HelloWebPart" TypeName="*" Safe="True" />

This indicates that all(*) classes in the HelloWebPart namespace in the HelloWebPart assembly are safe web parts.

If the assembly is strong named, it should have the Public Key Token copied from the previous step.

<SafeControl Assembly="ControlSampleWebPart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c627d6df943a8393" Namespace="ControlSampleWebPart" TypeName="*" Safe="True" />

c. Save the web.config file and close it.
4. Configure the server to use this new web part.
a. Open the SharePoint Central Administration site from a browser using http://servername or http://servername:port ensuring that the current logged in user has the administrative rights on the portal site.
b. Go to Site Actions > Site Settings (top right menu button).
c. Go to Galleries > Web Parts to open the web part gallery.
d. Click on the New button.
e. The New Web Parts page displays all the web parts marked as safe on the server. Scroll down to the required web part in the list, check the check box on the left and click on the Populate Gallery button at the top of the page. This will result in the Web Part entry creation in the Web Part Gallery list, and hence it can be used from now on from the gallery. Notice that the Web Parts developed in latest .NET Frameworks has .webpart as extension while the older ones has .dwp as extension.
5. Add this web part to a page in a site.
a. Go to Site Actions > Edit Page (top right menu button). This displays the current page in edit mode.
b. Click on the Add a Web Part button on the desired section of the page.
c. Select the required web part (Hello) from the All Web Parts > Miscellaneous section of the web part gallery.
d. Click on the Add button.
e. Click on the Exit Edit Mode link on the top right corner to exit the edit mode of this page.