Friday, April 30, 2010

C# 4 Optional Parameters and COM no ref

Pro .NET 4 Parallel Programming in C#COM had the concept of Optional Parameters. For example the COM TreeView control's Nodes.Add method expects six parameters. The last two parameters and Image and Selected Image.

Working with such controls from C# requires embedding a lot of Type.Missing statements which makes the code bulky as described in the latter part of my blog Using COM Controls in .Net

In that blog I have demonstrated working with COM controls from both VB .Net and C#.

With the introduction of Optional Parameters in C# 4 you can call COM Components by reducing unwanted tweaking.

COM no ref

COM Components also expect certain parameters to be of pass by ref and you had to explicitly mention the ref keyword in the previous version of C#. C# 4 relaxes the code by allowing you to omit the ref modified.

Here is the C# 4 code

private void Form1_Load(object sender, EventArgs e)
{
mscomctl.Node Nodx;
Nodx = axTreeView1.Nodes.Add(Type.Missing, Type.Missing, "India", "India");
Nodx = axTreeView1.Nodes.Add("India", mscomctl.TreeRelationshipConstants.tvwChild, "Kerala", "Kerala");
Nodx.EnsureVisible();

axTreeView1.Nodes.Add(Nodx);
}



Asp .Net MVC 2 with Visual Studio 2010 or Visual Web Developer 2010

Pro ASP.NET MVC 3 Framework, Third EditionAsp .net Mvc is the Web Development framework from Microsoft based on
the MVC architecture.

Asp .Net MVC is getting installed as a part of Visual Studio 2010 and
Visual Web Developer 2010.

Asp .Net 2 MVC Empty Web Application Project

Asp .Net MVC 2 Web Application comes with predefined
Membership and other frills which makes it easy
to get a head start, but abstracts away the inner working of MVC.

But I am taking another route. There is another
Asp .Net MVC 2 Empty Web Application Project.

Asp .Net MVC






















Lets start with Controllers. Controllers are responsible for handling
incoming request. It's a class that inherits from System.Web.Mvc.Controller.























I am naming the controller HomeController.

















I am replacing the existing code of HomeController which expects a View (which will be explained late) with a function that returns a string.
























If you run the application you will see a web page with the value of function.





















Views


Now Let's turn our attention to Views. A view is typically what you see in an Asp .Net MVC Application.

Preferably start a new new Asp .Net MVC 2 Empty Web Application so that we can start afresh.


The following diagram shows the default code within the HomeController class.































If you run the application you will receive a detailed error message stating that the view is missing.

































So right click the Index method and select Add View.



















Make sure you check off the Select MasterPage option because we haven't introduced Master Pages.
A view template called Index.aspx will created for you under ~/Views/Home/ directory.

Which comprises of plain HTML.





































Now if you run the application you will receive a blank form.


Lets replace the existing code with the code below. The code will return a
ViewData structure



public ViewResult Index()
{
ViewData["Blog"] = "ShalvinPD.blogspot.com";
return View();
}



Now lets show the ViewData in the View.
















Asp .Net MVC Views


Easiest way to develop Asp .Net MVC views are by using Html Helpers.


Name <%: Html.TextBox("Name") %>

<br />
<%: Html.CheckBox(".Net", true) %>.Net

<br />
<%: Html.RadioButton("Male", true) %>Male
<br />
<%: Html.RadioButton("Female", false) %>Female
<div>
Password <%: Html.Password("myPassword")%>
</div>
<div>
Address <%: Html.TextArea("Address", "Shalvin P D", 5, 20, null)%>
</div>

Kmug<%: Html.DropDownList("Kmug", new SelectList(new[] { "Shalvin", "Mathew" }), "Shalvin") %>

<br />
Technologies<%: Html.ListBox("myList", new SelectList(new[] { "Asp .Net", "Asp .Net Mvc" }), "Shalvin") %>

Tuesday, April 6, 2010

Asp .Net Membership -III aspnet_regsql command tool, configuring the Site to using Instance Database and Working with Membership and Roles Api

Membership and Role Api Methods


In the blog Asp .Net Membership - II aspnet_regsql to port Membership API database to Sql Server we saw aspnet_regsql tool.


The tool can also be invoked from command prompt, which provides fine grained support on which tables you want to dump to sql server Instance database.

If you want to dump just Membership and Role tables to Sql Server you issue the command as follows:

>aspnet_regsql -S . -E -d Shalvin -A mr


Here -S denoted the Sql Serve instance. Since I am using Sql server 2000 I am specifying a dot. -E denoted integrated security. Optionally you can specify user name and password if you are using Sql Server Security. -d denoted the database name. -A is used for adding the tables. Here I am adding Membership and Role tables.
Like wise you can remove tables using -R.

Next order of business it the instruct your Asp .Net project to use Instance database instead of File System Database.

For that you have edit the web.config as follows:









<configuration>
<connectionStrings>
<add name="ShalvinConnectionString" connectionString="Data Source=.\shalvin;Initial Catalog=Shalvin;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>

<roleManager enabled="true">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ShalvinConnectionString"/>
</providers>
</roleManager>

<authentication mode="Forms"/>

<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ShalvinConnectionString"/>
</providers>
</membership>
</system.web>
</configuration>



Programmatic working with Membership and Roles Api

using System.Web.Security;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlUsers.DataSource = Membership.GetAllUsers();
ddlRole.DataSource = Roles.GetAllRoles();

DataBind();
}
}
protected void btnAddUserToRole_Click(object sender, EventArgs e)
{
try
{
Roles.AddUserToRole(ddlUsers.Text, ddlRole.Text);
Response.Write("User Added to role");
}
catch (Exception ex)
{
Response.Write(String.Format("{0} is already an {1}",
ddlUsers.Text, ddlRole.Text));
}
}






Related Blog
Asp .Net 2.0 Membership I - LoginStatus, Login and LoginView Controls
Asp .Net Membership - II aspnet_regsql to port Membership API database to Sql Server

Monday, March 22, 2010

Silverlight Dynamically Creating Controls and Attaching Event Handlers

Pro Silverlight 4 in C#Dynamically creating controls in Silverlight is a breeze.
I am using Visual Studio 2010 Release Candidate.
I am starting a Silverlight Application Project.














I am selecting Asp .Net Web Project as new Web Project Typer.
















As mentioned in the previous blog VS 2010 comes with excellent tool support for Silverlight.

I am adding a Stack Panel (stp1)to hold the dynamically created controls and a TextBlock to display the message based on the control selected.















Going to the load event of Main Page I am dynamically creating Buttons.


List<string> lstr = new List<string> { "Shalvin", "Praseed Pai" };

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
Button btn;
foreach (string str in lstr)
{
btn = new Button();
btn.Content = str;
btn.Tag = str;
btn.Click += new RoutedEventHandler(btn_Click);
stp1.Children.Add(btn);
}
}

Notice I have only one event Handler for the whole set of controls.
I am going to have different functionlity for different buttons by identifying the tag property of Button.

private void btn_Click(object sender, RoutedEventArgs e)
{
Button btn = sender as Button;
string txtTag = btn.Tag.ToString();
tblMessage.Text = txtTag;
}









Monday, February 22, 2010

Asp .Net 4 Empty Web Site and Clean Web.Config

One thing I hate about previous Web.Config in previous versions of Asp .Net is its sheer size.

Asp .Net 4 has done a wonderful job in reducing the size of Web.Config by offloading the job to Machine.Config.

Inorder to take advantage of this you should start a Empty Web Site.














Tuesday, February 2, 2010

Asp .Net Membership - II aspnet_regsql to port Membership API database to Sql Server

In the blog Asp .Net Membership I - LoginStatus, Login and LoginView Controls
we saw how to work with Asp .Net Membership service.

By default the Membership Provider is creating a File System Database called AspNetDb.mdf under App_Data folder. This will suffice for small projects, where you can create rest of the tables in AspNetDb.mdf.
This by no means is an elegant solution, since usually the database will reside on Sql Server as Instance database and not in File System database. In effect there will be two database one for membership, role, profile, personalization, etc. and another for the application.

It is possible to merge the membeership database with out application database.

For that you can use aspnet_regql tool found in C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727 folder incase. Incase you are using Asp .net 4 the folder will be C:\WINDOWS\Microsoft.NET\Framework\v4.0.30128.

The wizard will prompt for the database to which you want to dump the membership, role, profile and personalization tables and associated database objects.

Related Blog

Asp .Net 2.0 Membership I - LoginStatus, Login and LoginView Controls

Wednesday, January 20, 2010

Microsoft Community Tech Day - 30th Jan 2010 - Kochi

Microsoft Community Tech Day - 30th Jan 2010 - Kochi

IMA House, J. N. International Stadium Road,Palarivattom P.O., Cochin 682025, Kerala

Agenda
09:15 - 09:30 Welcome Speech
09.30 - 10:30 Write your own .NET compiler - Praseed Pai
10.30 - 11:15 Building Apps with ASP.NET MVC 2 and Entity Framework - Shiju Varghese
Tea Break (15 min)
11.30 - 12:15 Beyond the relational SQL server 2008 - Jeen Shene Stanislaus
12.15 - 01:15 Microsoft Expression and Introduction to Silverlight - Roopak Nair
Lunch Break (45 min)
02.00 - 03:00 Writing Secure Code - Jairam Ramesh
03:00 - 04:00 Diving to Silverlight - Anoop Madhusudanan
04.00 - 05:00 Programming for Windows 7 - Shoban Kumar
05:00 - 05:30 Prize distribution and Closing Ceremony

Free Registration either at http://communitytechdays.com/ (if you have live id)

Or

Click and Registier

Monday, December 21, 2009

Globalization in Windows Forms - Application with multi language support

This blog is the continuation of .Net Globalization blog.
If you want to have a global market for your project then you have to plan for implementing multi language support.

Create a form as shown below.










Add Another form. This is the form whose language text we are planning to change based on the selection from the combobox of first form. Give English Texts to Form and Controls.










Select the form set the Localizable property to True and Language to French(France).

















Now select the existing controls and change its Text property to corresponding French equivalent as shown in the figure.



















Go back to the first form where you can select the language.
In this form we are going to change the culture of the current thread based on the culture
Explanations and additional information will follow soon.


using System.Globalization;
using System.Threading;

private void cboLang_SelectedIndexChanged(object

sender, EventArgs e)
{
if(cboLang.Text == "French")
Thread.CurrentThread.CurrentUICulture = new

CultureInfo("fr-FR");
else
Thread.CurrentThread.CurrentUICulture = new

CultureInfo("en-US");

}

private void btnShowForm_Click(object sender, EventArgs

e)
{
frmLang fl = new frmLang();
fl.Show();
}

VB .Net

Imports System.Globalization
Imports System.Threading

Public Class Form1


Private Sub cboLang_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboLang.SelectedIndexChanged

If cboLang.Text = "English" Then
Thread.CurrentThread.CurrentUICulture = New CultureInfo("en-US")
Else
Thread.CurrentThread.CurrentUICulture = New CultureInfo("fr-FR")
End If

End Sub


Private Sub btnShowForm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShowForm.Click

Dim fl As New frmLang
fl.Show()
End Sub

End Class


Now when you run the application, select French from the ComboBox and click show form the French form will appear and when you select English, English form will appear.



















Windows Forms VB .Net Generated Code
'Form1


Private Sub InitializeComponent()
Me.Label1 = New System.Windows.Forms.Label
Me.cboLang = New System.Windows.Forms.ComboBox
Me.btnShowForm = New System.Windows.Forms.Button
Me.SuspendLayout()
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.Location = New System.Drawing.Point(52, 70)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(88, 13)
Me.Label1.TabIndex = 0
Me.Label1.Text = "Select Language"
'
'cboLang
'
Me.cboLang.FormattingEnabled = True
Me.cboLang.Items.AddRange(New Object() {"English", "French"})
Me.cboLang.Location = New System.Drawing.Point(159, 62)
Me.cboLang.Name = "cboLang"
Me.cboLang.Size = New System.Drawing.Size(121, 21)
Me.cboLang.TabIndex = 1
'
'btnShowForm
'
Me.btnShowForm.Location = New System.Drawing.Point(159, 113)
Me.btnShowForm.Name = "btnShowForm"
Me.btnShowForm.Size = New System.Drawing.Size(75, 23)
Me.btnShowForm.TabIndex = 2
Me.btnShowForm.Text = "&Show Form"
Me.btnShowForm.UseVisualStyleBackColor = True
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(292, 266)
Me.Controls.Add(Me.btnShowForm)
Me.Controls.Add(Me.cboLang)
Me.Controls.Add(Me.Label1)
Me.Name = "Form1"
Me.Text = "Shalvin.com"
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub

Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents cboLang As System.Windows.Forms.ComboBox
Friend WithEvents btnShowForm As System.Windows.Forms.Button






'frmLang


Private Sub InitializeComponent()
Me.Label1 = New System.Windows.Forms.Label
Me.txtName = New System.Windows.Forms.TextBox
Me.Label2 = New System.Windows.Forms.Label
Me.txtPhone = New System.Windows.Forms.TextBox
Me.btnSave = New System.Windows.Forms.Button
Me.SuspendLayout()
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.Location = New System.Drawing.Point(41, 55)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(35, 13)
Me.Label1.TabIndex = 0
Me.Label1.Text = "Name"
'
'txtName
'
Me.txtName.Location = New System.Drawing.Point(103, 48)
Me.txtName.Name = "txtName"
Me.txtName.Size = New System.Drawing.Size(100, 20)
Me.txtName.TabIndex = 1
'
'Label2
'
Me.Label2.AutoSize = True
Me.Label2.Location = New System.Drawing.Point(41, 105)
Me.Label2.Name = "Label2"
Me.Label2.Size = New System.Drawing.Size(38, 13)
Me.Label2.TabIndex = 2
Me.Label2.Text = "Phone"
'
'txtPhone
'
Me.txtPhone.Location = New System.Drawing.Point(103, 98)
Me.txtPhone.Name = "txtPhone"
Me.txtPhone.Size = New System.Drawing.Size(100, 20)
Me.txtPhone.TabIndex = 3
'
'btnSave
'
Me.btnSave.Location = New System.Drawing.Point(103, 140)
Me.btnSave.Name = "btnSave"
Me.btnSave.Size = New System.Drawing.Size(75, 23)
Me.btnSave.TabIndex = 4
Me.btnSave.Text = "Save"
Me.btnSave.UseVisualStyleBackColor = True
'
'frmLang
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(292, 266)
Me.Controls.Add(Me.btnSave)
Me.Controls.Add(Me.txtPhone)
Me.Controls.Add(Me.Label2)
Me.Controls.Add(Me.txtName)
Me.Controls.Add(Me.Label1)
Me.Name = "frmLang"
Me.Text = "English"
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents txtName As System.Windows.Forms.TextBox
Friend WithEvents Label2 As System.Windows.Forms.Label
Friend WithEvents txtPhone As System.Windows.Forms.TextBox
Friend WithEvents btnSave As System.Windows.Forms.Button