Monday, July 30, 2007

Consequences of Strong Naming Assembly in .NET

Any code you have that uses this assembly, will need to be recompiled with a reference to the new assembly with the newer version.

Strong named assemblies can only reference other strong named assemblies.

If your product includes many assemblies (.NET DLL's) and you want to ship only one of them as a hotfix, you will not be able to because your other assemblies will still refer to old version of the DLL. So either restrict to the same old version or use the .Net Framework configuration tool to forward the old version to the new version.

If you have classes that need to be serialized, the engine includes type information in the serialized data, that way it can be reconstituted later. If you the AssemblyFormat property is not set correctly, you could end up with a situation here you have stored some data, upgraded your application (maybe because of a bug fix), and then
error when you try to load your serialized database (even though nothing in that particular class has changed).

Unless your assemblies need to be placed in the GAC, or run as COM+ component, or some other special case,
strong-naming them probably is not necessary.

How to sign a .NET Assembly with a Strong Name

A strong name consists of the assembly's identity—its simple text name, version number, and culture information (if provided)—plus a public key and a digital signature. It is generated from an assembly file using the corresponding private key. (The assembly file contains the assembly manifest, which contains the names and hashes of all the files that make up the assembly.)

Security Note: A strong-named assembly can only use types from other strong-named assemblies. Otherwise, the security is already compromised.

It's pretty easy using Visual Studio .net 2005 IDE, but we will also talk about alternatives later.

  1. Go to "Property Pages" of your project from the Solution Explorer.
  2. Select the "Signing" Tab from the list of tabs on the left.
  3. Select the check-box "Sign the Assembly".
  4. Select "New..." from "Choose a strong name key file" drop-down list.
  5. Just finish the dialog by providing strong name key filename(new) and password(optional).

There you go!!

  • Alright, other alternatives are also mentioned here.

First of all, we need a cryptographic key pair to sign an assembly with a strong name.

This public and private cryptographic key pair is used during compilation to create a strong-named assembly. Microsoft has provided Strong Name Tool (sn.exe) to create this key pair in a file with ".snk" extension.

Open the command prompt and type the following command,

sn -k <filename> //e.g. sn -k mySgnKey.snk will create a keypair file named mySgnKey.snk

Delay Signing an Assembly:

If you intend to delay sign an assembly and you control the whole key pair (which is unlikely outside test scenarios), you can use the following commands to generate a key pair and then extract the public key from it into a separate file.

First Command: sn -k mySgnKey.snk

Second Command: sn -p mySgnKey.snk publicSgnKey.snk

Sign an Assembly with a Strong Name using Assembly Linker

al /out:<assembly name> <module name> /keyfile:<file name>

In this command, assembly name is the name of the assembly to sign with a strong name, module name is the name of the code module used to create the assembly, and file name is the name of the container or file that contains the key pair.

al /out:MyAssembly.dll Project.Module /keyfile:mySgnKey.snk

Signing an Assembly with a Strong Name using Assembly Attributes

C# usage: [assembly:AssemblyKeyFileAttribute(@"sgKey.snk")]

VB usage: <Assembly:AssemblyKeyFileAttribute("sgKey.snk")>

Note: When signing an assembly with a strong name, the Assembly Linker (Al.exe) looks for the key file relative to the current directory and to the output directory. When using command-line compilers, you can simply copy the key to the current directory containing your code modules.

How To Reference This Strongly Named Assembly

<compiler command> /reference:<assembly name>

In this command, compiler command is the compiler command for the language you are using, and assembly name is the name of the strong-named assembly being referenced. You can also use other compiler options, such as the /t:library option for creating a library assembly.

The following example creates an assembly called myAssembly.dll that references a strong-named assembly called myLibAssembly.dll from a code module called myAssembly.cs.

csc /t:library MyAssembly.cs /reference:MyProjectAssembly.dll

How To Make a Run-time Reference to this Strongly Named Assembly

We need to use the name of the assembly in following manner...

<assembly name>, <version number>, <culture>, <public key token>

C# usage: Assembly.Load("myAssemby,Version=1.0.0.1,Culture=neutral,PublicKeyToken=7b53aa32d4fc18b1");

VB usage: Assembly.Load("myAssemby,Version=1.0.0.1,Culture=neutral,PublicKeyToken=7b53aa32d4fc18b1")

Monday, July 23, 2007

Little RegEx Examples in .NET

If you want to use any of the special characters(viz. [,\, ^, $, . , , ?, *, + , (, ) ) as a literal in a regex, you need to escape them with a backslash.

e.g. Dot in the email pattern

\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b

Most regular expression flavors treat the brace { as a literal character, unless it is part of a repetition operator like {2,6}.

Using Character Classes, you can find text with particular set of characters.

e.g. To allow alphanumeric characters and underscores, use [A-Za-z_0-9]*

The only special characters or metacharacters inside a character class are the closing bracket (]), the backslash (\), the caret (^) and the hyphen (-).

Examples

1) Email Regular Expression

\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b

2) HTML Tag matching - Regular Expression

<([A-Z][A-Z0-9]*)[^>]*>(.*?)</\1>

This is very simple example and can't be used in real scenario, as it can't find the nested html tags.

3) Do you want to make RegEx for parsing ASP 3.0 Classic style written program/code?

This can help in matching. And it's a beautiful example of using named capture in Regular Expressions

.

(?<tbefore>.*?)(?<allcode><%(?<equals>=)*\s*(?<code>.*?)%>)(?<endtext>.*)

Here, tbefore name will capture all text before code starting tag <%.

allcode name will capture all code text within <% %> including signs.

code will capture all code within <% %>.

endtext name will capture all text after this code block.

Wednesday, July 18, 2007

Getting acquainted with Windows Powershell environment

The best way to get the help about it is,

get-command. What's that. The Get-Command cmdlet gets basic information about cmdlets and other elements of Windows PowerShell commands, such as files, functions, and Windows PowerShell providers.

get-help get-command -detailed

Where get-command is the cmdlet for which you wish to get the help.

and -detailed parameter indicates that we wish to get details regarding parameters and methods.

Optionally, -Full means complete help info. that's available

and -examples means to see only examples

and get-help get-command -parameter servicename would give you complete information about the parameter named 'servicename' that's part of the get-command returned object.

To display the help of all topics available, you can
get-help get-* and get-help about*

If you need help with any cmdlet that gets listed,

get-help <cmdlet-name or get-alias> -detailed

That's the best help to start with. It gives you list of all get commands and nouns for that matter as you may have observed the verb-noun pattern of powershell.

get-alias

to know the short names or aliases for many cmdlets in your powershell session.

Here are the few common verbs other than get.

More...for the next post!

Tuesday, July 17, 2007

Windows PowerShell

I'm trying to provide a very quick reference to windows powershell that could help the beginners and these are the same things that helped me.

Windows PowerShell is very different.

  • Windows PowerShell does not process text. Instead, it processes objects based on the .NET platform.

  • Windows PowerShell comes with a large set of built-in commands with a consistent interface.

  • All shell commands use the same command parser, instead of different parsers for each tool. This makes it much easier to learn how to use each command.

You can download and install it for free from this Microsoft web site. Make sure to check sys. requirements.

http://www.microsoft.com/technet/scriptcenter/topics/msh/download.mspx

Windows PowerShell Cmdlets

A cmdlet (pronounced "command-let") is a single-feature command that manipulates objects in Windows PowerShell. You can recognize Cmdlets by their name format -- a verb and noun separated by a dash (-), such as Get-Help, Get-Process, and Start-Service.

Ok, so here goes the question. How do you get to know which are the possible verbs and what are the possible nouns that you can use to constitute valid powershell commands or for that matter cmdlets.

The "get" cmdlets only retrieve data, the "set" cmdlets only establish or change data, the "format" cmdlets only format data, and the "out" cmdlets only direct the output to a specified destination.

Each cmdlet has a help file that you can access by typing:

get-help <cmdlet-name> -detailed

You can download the Graphical help file at this Microsoft site.
http://www.microsoft.com/downloads/details.aspx?familyid=3B3F7CE4-43EA-4A21-90CC-966A7FC6C6E8&displaylang=en

You can run Windows command-line programs in Windows PowerShell

All in PowerShell is your .NET Framework and .NET Objects world.

For example, when you get a process in Windows PowerShell, you are really getting an object that represents the process. When you view information about a process, you are viewing the properties of its process object. And, when you start a process, that is, when you change the Status property of the process to "started," you are using a method of the process object.

You can easily do string manipulation also to leverage the returned data.

Try this command in PS...

get-process findstr "iexplore"

and it will automatically filter the rows that had "iexplore" string...It gives you all the instances of Internet Explorer process... amazingly easy and handy...isn't it?

Tuesday, July 10, 2007

Paging Logic

I am trying to write a simple logic for paging the resultset of records.
It purely depends on a single querystring parameter like start = 161 or start=81
This would display records from 161 to 170 or 81 to 90.


int nStart = 1; //default start number i.e. very first record when first search hit.
int newStart;
string requestUri = Request.Url.AbsoluteUri; //actual complete URL
string newRequestUri;

if (Request.QueryString["start"] != null)
nStart = Convert.ToInt16(Request.QueryString["start"]);

int nMaxResultsInAPage = 10;
int pageNumber; //current page number

if (nStart == 1) //initially not divisible by 10 as it is possible with page 2nd and record 11
pageNumber = 1;
else //current page number....as start gives the record number
pageNumber = nStart / 10; // 2 = 21 / 10



//j... ... ...refers to the paging number to be iterated
//count... ... ...how many paging numbers to be shown in total for navigation

for (int j = pageNumber - 10 / 2, count = 0;count <> 0)
{
newStart = (j-1) * 10 + 1; //4th page represents records 31 to 40...so [4th Page] = 3 * 10 + 1
newRequestUri = requestUri.Replace("start=" + nStart.ToString(), "start=" + Convert.ToString(newStart));
if(count == 0)
ltrPageLinks.Text += " Previous - ";
else if (count == 11)
ltrPageLinks.Text += " Next - ";
else if (j == nStart / 10 - 1)
ltrPageLinks.Text += "" + j.ToString() + " - ";
else
ltrPageLinks.Text += "" + j.ToString() + " - ";


}
}

Tuesday, July 3, 2007

Good practice about DropDownList Databinding

Here is how one should bind the drop-downlist...and why is it good?
Because, in most cases we are executing some logic like loading another drop-down list on change of selected index of the first one.

Make functions to bind respective drop-down lists. And call them when needed to re-bind.

Page_Load
{
BindFirstDropDown();
FirstDropDown.Items.Insert(0,new ListItem("Select", "0"));
if(SecondDropDown.Items.Count == 0)
SecondDropDown.Items.Add(new ListItem("Select", "0"));
}

FirstDropDown_IndexChanged(...)
{
BindSecondDropDown();
SecondDropDown.Items.Insert(0,new ListItem("Select", "0"));

}
void BindFirstDropDown()
{
...
}

void BindSecondDropDown()
{
...
}

Monday, July 2, 2007

DataSet hell - Failed to enable constraints. One or more rows contain values...

I have found some great posts regarding
Typed DataSet regular problem that is faced by every programmer who starts working with datasets in good application.

http://weblogs.asp.net/rosherove/archive/2004/10/03/237260.aspx

What did I face?
Usually, as in most applications fields returns by every stored procedure even that's written on a gived table, are different.
So, result set of every stored procedure doesn't match the one specified in DataTable of Typed DataSet schema.

So, it's a good idea to setup individual table adapter for almost all procedures!!

Enum Types in .NET or C# .NET

Enum types implicitly inherit the System.Enum type in the Base Class Library (BCL). This also means that you can use the members of System.Enum to operate on enum types.

I have included few code snippets which are self-explanatory for use of enums.

public
enum Volume : byte
{
Low = 1,
Medium,
High
}


void ShowVolume(int v)

{

Volume vol = (Volume)v;

If(vol == Volume.Low)


}


// get a list of member names from Volume enum,
// figure out the numeric value, and display
foreach (string volume in Enum.GetNames(typeof(Volume)))
{
Console.WriteLine("Volume Member: {0}\n Value: {1}",
volume, (byte)Enum.Parse(typeof(Volume), volume));
}


// get all values (numeric values) from the Volume
// enum type, figure out member name, and display
foreach (byte val in Enum.GetValues(typeof(Volume)))
{
Console.WriteLine("Volume Value: {0}\n Member: {1}",
val, Enum.GetName(typeof(Volume), val));
}


Given the type of the enum, the GetValues method of System.Enum will return an array of the given enum's base.

Accessing Typed Datasets

How to access Typed DataSet from C# .NET code ?

Dim productsAdapter As New NorthwindTableAdapters.ProductsTableAdapter()

Dim products as Northwind.ProductsDataTable


products = productsAdapter.GetProducts()


For Each productRow As Northwind.ProductsRow In products

Response.Write("Product: " & productRow.ProductName & "<br />")

Next


Each object used in this example is also strongly-typed, allowing Visual Studio to provide IntelliSense and compile-time type checking. And best of all the DataTables returned by the TableAdapter can be bound to ASP.NET data Web controls, such as the GridView, DetailsView, DropDownList, CheckBoxList, and several others.


Parameterized Methods in Typed DataSet based Data Access Layer.

It's almost same as the normal select all query.
Just go to DataSet designer and Right-click the TableAdapter section.
Click to "Add Query…".

You can preferably select Stored Procedure or Ad-Hoc Query.

In the next dialog screen, specify the query or select the procedure.

Now just rename the Fill and Get methods as per your preference and the methods are ready to test as soon as you finish the dialog.

Right-click on the table adapter and choose preview data to enter parameter values and see the results.


Anyhow, this is the best article that I have found on Typed Datasets…everything you need to know about typed datasets creation and using them.

 
Dotster Domain Registration Special Offer