Saturday, February 13, 2010

WebControl Event's Not working?... Here is the solution.

Few days back i had a strange issue during my webcontrol development .The issue was that child control events like button click’s , DropDownlist’s SelectedIndexChanged are not working. On a simple glance everything was done as per the regular flow of coding… I search on Bing,Live,Google etc…. Didnt find much effective solution on the first day.. On a deep dive to webcontrol development i found some articles,books,blogs that mentioning about the influence of implementation INamingContainer interface to the WebControl Class. Actually this interface does nothing when we do the implementation . Means we except must implemented functions from the interface. But in case INamingContainer there is nothing like that… its a marker interface.By this interface it allows unique naming of the dynamically generated server control instances within the WebControl.

Please go through this link to see the creation of sample webcontrol.

Friday, April 18, 2008

Inserting Is Easy With ASP.NET GridView

Inserting With GridView

We all are familiar with ASP.NET 2.0 Gridview,very useful listing control ie widely used in all ASP.NET application.By default our Gridview is capable of Editing,Deleting and Selecting,which works very fine.But many Web Developer's find a difficulty with this gridview that is its not capable of Data inserting by default.Microsoft provides controls like Detailsview for inserting,but it displays only 1 data at a time.Many Web users find easiness of inline data entering into the listing control like Gridview.Because of this incapability of Gridview many developers go for third party list controls for inline Data Entering.

Here is a small Example for altering the ASP.NET 2.0 GridView to make it useful for Inserting Data.In order to understand this post the reader must have a simple knowledge of Gridview.Here i dont provide information for by default capabilities like Editing,Deleting,Seleting.So lets have a trick with Gridview for make it capable of Inserting.

Get a view on the DataBase,which is a very simple Product-Category Scenario.

ie Products table do a have Foreign Key(FK_CategoryID) relation with Categories.

Lets starts with Categories table Data insertion using Gridview.Because Categories table dont have any foreign key column,a very simple one.

1. Drag a Gridview to your Page.Configure a Sqldatasource for Categories table with Insert,Delete,Update,Select Queries/Stored Procedures.

2. Make "ShowFooter" Property of Gridview to True.

3.Enable Edit/Delete or Add a Command Field.

4.Turn all Fields to Templates(Go through Edit Columns Option of Gridview Smart Tag.Convert Fields to Template Fields.)

5.Utilise FooterTemplates of TemplateFields to make input controls for Insert.Go through the image given below.

6.In the Category GridView i have placed a linkbutton(lbInsert) in Command Field's Footer Template.its CommandName Property is Set to 'Insert'.I placed a TextBox named txtCategoryName in Categoryname TemplateField's FooterTemplate and a textbox txtDescription in Corresponding field's FooterTemplate.

7.In short Gridview will look this.

8.The above steps is all about setting the GridView.Next i will show you how to code for it.
In the Code behind we want to handle Sqldatasource's Inserting event and Gridview's RowCommand Event.

Protected Sub sdsCategories_Inserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs) _
Handles sdsCategories.Inserting

Dim txtcategoryname As New TextBox
Dim txtdescription As New TextBox

txtcategoryname = CType(GridView1.FooterRow.FindControl("txtCategoryName"), TextBox)
txtdescription = CType(GridView1.FooterRow.FindControl("txtDescription"), TextBox)

e.Command.Parameters("@CategoryName").Value = txtcategoryname.Text
e.Command.Parameters("@Description").Value = txtdescription.Text

End Sub

In the above event we are giving values to the insert parameters of Sqldatasource from values entered in Controls of GridView's Footer using FindControl() Method of the FooterRow.

Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand

If (e.CommandName = "Insert") Then


End If

End Sub

We are handling RowCommand Event of gridview because we have set CommandName Property of insert linkbutton to "Insert". In RowCommand We are using Insert() Method of SqlDatasource to insert values entered in Controls in Footer of GridView.

Insertion When a Foreign Key Column is Present

This scenario comes in the Product table,here Category is Refered as foreign Key from
Categories table.Here there is a little change needed.So in Footer Template of FKCategoryID Column of the Product GridView is Placed with a dropDownList(ddlcategories) or any other simple list Control as Shown in Image.

Here categories DropDownList is Configured with another datasource and it is set with categoryId as Data Key Field and Category name as Data Text Field.

Only Difference in code is Value for Insert parameter of FKCategoryID is Supplied from SelectedValue property of Category DropDownList in Footer.Code is shown below.

Protected Sub sdsProducts_Inserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs) Handles sdsProducts.Inserting

Dim txtProductname As New TextBox
Dim ddlCategories As New DropDownList
Dim txtDescription As New TextBox
Dim txtManufacture As New TextBox
Dim txtSKU As New TextBox
Dim txtStock As New TextBox

txtProductname = CType(GridView1.FooterRow.FindControl("txtProductName"), TextBox)
ddlCategories = CType(GridView1.FooterRow.FindControl("ddlCategories"), DropDownList)
txtDescription = CType(GridView1.FooterRow.FindControl("txtDescription"), TextBox)
txtManufacture = CType(GridView1.FooterRow.FindControl("txtManufacture"), TextBox)
txtSKU = CType(GridView1.FooterRow.FindControl("txtSKU"), TextBox)
txtStock = CType(GridView1.FooterRow.FindControl("txtStock"), TextBox)

e.Command.Parameters("@ProductName").Value = txtProductname.Text
e.Command.Parameters("@Description").Value = txtDescription.Text
e.Command.Parameters("@Manufacture").Value = txtManufacture.Text
e.Command.Parameters("@SKU").Value = txtSKU.Text
e.Command.Parameters("@Stock").Value = txtStock.Text

End Sub

Wednesday, March 5, 2008

Obfuscation and .NET

Reverse Engineering

Reverse engineering is the process of extracting the knowledge or design blueprints
from anything man-made. The concept has been around since long
before computers or modern technology, and probably dates back to the days
of the industrial revolution. It is very similar to scientific research, in which a
researcher is attempting to work out the “blueprint” of the atom or the human
mind. The difference between reverse engineering and conventional scientific
research is that with reverse engineering the artifact being investigated is manmade,
unlike scientific research where it is a natural phenomenon

Traditionally, reverse engineering has been about taking shrink-wrapped
products and physically dissecting them to uncover the secrets of their design.
Such secrets were then typically used to make similar or better products. In
many industries, reverse engineering involves examining the product under a
microscope or taking it apart and figuring out what each piece does.

Assemblies generated under .NET may be decompiled into easily recognized source code that is either identical or similar to the original source code. Individuals or companies deploying .NET generated assemblies that are targeted for client machines may unwittingly be distributing their source code – in most cases an unintended consequence.Since source code is generally considered a valuable intellectual asset, measures should be taken to prevent decompilation into easily recognized source code.

MSIL Disassembler (Ildasm.exe)
The MSIL Disassembler is a companion tool to the MSIL Assembler (Ilasm.exe). Ildasm.exe takes a portable executable (PE) file that contains Microsoft intermediate language (MSIL) code and creates a text file suitable as input to Ilasm.exe

Steps to use ILDASM

1.Pick the ILDASM.exe from “\Microsoft Visual Studio .Net 2005\ SDK\v2.0\Bin\ildasm.exe”

2.Click on the ILDASm.exe and this will popup with an ILDASM program

3.Click on file and the open and pick the exe or dll which you want to view. This will display the IL code of the exe or dll.

Note:- After step 3, you are able to view a tree structure that will display the information about the dll or exe .

4.On double click on the “MANIFEST” node, we are able to view the details of the Assembly, internal IL code.

5.Click on the other nodes or namespaces that are at the top of the hierarchy.

6.Further you can view the internals by clicking on the sub nodes.

DotNet Reflection
Contains a decompiler, and a powerful object browser.
Lutz Roeder's .NET Reflector
Reflector is a class browser for .NET components. It supports assembly and namespace views, type and member search, XML documentation, call and callee graphs, IL, Visual Basic, Delphi and C# decompiler, dependency trees, base type and derived type hierarchies and resource viewers.

NDepend analyses source code and .NET assemblies. It allows controlling the complexity, the internal dependencies and the quality of .NET code. NDepend provides a language (CQL Code Query Language) dedicated to query and constraint a codebase. It also comes from with advanced code visualization (Dependencies Matrix, Metric treemap, Box and Arrows graph...), more than 60 metrics, facilities to generate reports and to be integrated with mainstream build technologies and development tools. NDepend also allows to compare precisely different versions of your codebase.

Lattix LDM
LDM reads in .NET code to extract intermodule dependencies which are then used to visualize and manage the architecture of .NET applications. The architecture is represented in a Dependency Structure Matrix (DSM) for a highly scalable representation that allows unwanted dependencies, often a result of unwanted architectural creep, to be identified quickly.

The Nature of .NET Assemblies

Assemblies in .NET consist of two major components: metadata and intermediate language code. The reflection capabilities of .NET languages and the metadata features of an assembly that include its classes and associated method signatures, fields properties and events make it possible to reverse engineer and retrieve this intellectual property. The intermediate language code provides information regarding the details of each method implementation. This enables well constructed decompilers to reveal the details of proprietary algorithms that you would typically not want users to have access to.

The Nature of Obfuscation

An ideal obfuscator mangles the large features(namespaces, class, names,methods,signatures and fields) and small features (method details and in particular string values defined as fields and within a method) of your assembly without changing its functionality. The more aggressive the mangling, the more likely that the obfuscated assembly will not run the same way as the original assembly. It is essential that an obfuscator keep the functionality of the software totally intact while making the original source code unrecognizable if the obfuscated assembly is decompiled.There are several well known problem areas that a well designed obfuscator must allow the user to deal with. When runtime type identification is used in an application to determine whether an object is of a particular type, the class name of the type being sought is used. If the obfuscator has mangled this class name, the dynamic type identification will fail in the obfuscated assembly. The user of the obfuscator must be given the option of selecting features that are not to be mangled. These include class,field and method names. The same issue exists when dynamic class loading is performed within the assembly or serialization or remoting is used.

One of the side-effects of obfuscation is the difficulty of debugging obfuscated code.An exception that is generated and reported by a user will typically include mangled method and class names making it almost impossible to identify the root cause. Providing a clearly labeled map file in the obfuscation tool is essential to the user in interpreting debugger output from the obfuscated assembly.Hackers often search deployed assemblies for strings that contain keywords such as “Password” or “Enter password”. By locating such strings, hackers attempt to circumvent the password protection embedded in the product that they are hacking. Some obfuscators provide the option of string encryption. Although this may introduce a small performance penalty because of the need to decrypt strings at runtime, the overhead associated with such string encryption and decryption is often negligible.

Some obfuscator products include the ability to statically analyze the application and determine the parts that are not being used. This includes unused types, unused methods,and unused fields. This could be of great benefit if memory footprint is a concern.Some obfuscators provide control of flow obfuscation. Control flow obfuscation typically introduces false conditional statements and other misleading constructs in order to confuse decompilers. Some obfuscators destroy the code patterns that decompilers use to recreate source code. The trick is to confuse the decompiler without changing the functionality of the obfuscate assembly.Incremental obfuscation allows the developer to make changes to the original sources after releasing an obfuscated assembly and then provide a patch to the user that reflects the changes to the original application while preserving the name-mapping used in the original release. In order to accomplish this, a map file must be saved and later used to ensure that the renaming is preserved when making changes and re-releasing the obfuscated assembly. Some obfuscator products support this useful capability. Finally, some obfuscators enable the user to embed watermarks such as user names and registration codes into the internal binary structures within the assembly.

Watermarking can assist in tracking distribution of the product on a per-executable basis if it is illicitly distributed or obtained.Several well known obfuscator products were sought and obtained for this review.Only two survived the rigorous tests that each obfuscator was subjected to. The obfuscators that failed generally produced assemblies that would not run or did not provide sufficient features to be of use for deploying commercial obfuscated assemblies.

Saturday, December 22, 2007

What is a .NET Assembly?

You must have heard the word "assembly" many times in .NET documentation. In this article I will share some thing about .NET assemblies.

What is an assembly?

An Assembly is a logical unit of code
Assembly physically exist as DLLs or EXEs
One assembly can contain one or more files
The constituent files can include any file types like image files, text files etc. along with DLLs or EXEs
When you compile your source code by default the exe/dll generated is actually an assembly
Unless your code is bundled as assembly it can not be used in any other application
When you talk about version of a component you are actually talking about version of the assembly to which the component belongs.
Every assembly file contains information about itself. This information is called as Assembly Manifest.

What is assembly manifest?

Assembly manifest is a data structure which stores information about an assembly
This information is stored within the assembly file(DLL/EXE) itself
The information includes version information, list of constituent files etc.
What is private and shared assembly?
The assembly which is used only by a single application is called as private assembly. Suppose you created a DLL which encapsulates your business logic. This DLL will be used by your client application only and not by any other application. In order to run the application properly your DLL must reside in the same folder in which the client application is installed. Thus the assembly is private to your application.

Suppose that you are creating a general purpose DLL which provides functionality which will be used by variety of applications. Now, instead of each client application having its own copy of DLL you can place the DLL in 'global assembly cache(GAC)'. Such assemblies are called as shared assemblies.

What is Global Assembly Cache?

Global assembly cache is nothing but a special disk folder where all the shared assemblies will be kept. It is located under :\WinNT\Assembly folder.

How assemblies avoid DLL Hell?

As stated earlier most of the assemblies are private. Hence each client application refers assemblies from its own installation folder. So, even though there are multiple versions of same assembly they will not conflict with each other. Consider following example :

You created assembly Assembly1
You also created a client application which uses Assembly1 say Client1
You installed the client in C:\MyApp1 and also placed Assembly1 in this folder
After some days you changed Assembly1
You now created another application Client2 which uses this changed Assembly1
You installed Client2 in C:\MyApp2 and also placed changed Assembly1 in this folder
Since both the clients are referring to their own versions of Assembly1 everything goes on smoothly
Now consider the case when you develop assembly that is shared one. In this case it is important to know how assemblies are versioned. All assemblies has a version number in the form:

If you change the original assembly the changed version will be considered compatible with existing one if the major and minor versions of both the assemblies match.

When the client application requests assembly the requested version number is matched against available versions and the version matching major and minor version numbers and having most latest build and revision number are supplied.

How do I create shared assemblies?

Following steps are involved in creating shared assemblies :

Create your DLL/EXE source code
Generate unique assembly name using SN utility
Sign your DLL/EXE with the private key by modifying AssemblyInfo file
Compile your DLL/EXE
Place the resultant DLL/EXE in global assembly cache using AL utility
How do I create unique assembly name?
Microsoft now uses a public-private key pair to uniquely identify an assembly. These keys are generated using a utility called SN.exe (SN stands for shared name). The most common syntax of is :

sn -k mykeyfile.key

Where k represents that we want to generate a key and the file name followed is the file in which the keys will be stored.

How do I sign my DLL/EXE?

Before placing the assembly into shared cache you need to sign it using the keys we just generated. You mention the signing information in a special file called AssemblyInfo. Open the file from VS.NET solution explorer and change it to include following lines :


Now recompile the project and the assembly will be signed for you.

Note : You can also supply the key file information during command line compilation via /a.keyfile switch.

How do I place the assembly in shared cache?
Microsoft has provided a utility called AL.exe to actually place your assembly in shared cache.

AL /i:my_dll.dll

Now your dll will be placed at proper location by the utility.

Hands On...
Now, that we have understood the basics of assemblies let us apply our knowledge by developing a simple shared assembly.

In this example we will create a VB.NET component called SampleGAC ( GAC stands for Global Assembly Cache). We will also create a key file named sample.key. We will sign our component with this key file and place it in Global Assembly Cache.

Step 1 : Creating our sample component
Here is the code for the component. It just includes one method which returns a string.

imports system namespace BAJComponents public class Sample public function GetData() as string return "hello world" end function end class end namespace
Step 2 : Generate a key file
To generate the key file issue following command at command prompt.

sn -k sample.key
This will generate the key file in the same folder

Step 3 : Sign your component with the key
Now, wee will sign the assembly with the key file we just created.

vbc sampleGAC.vb /t:library /a.keyfile:sample.key
Step 4 : Host the signed assembly in Global Assembly Cache
We will use AL utility to place the assembly in Global Assembly Cache.

AL /i:sampleGAC.dll
After hosting the assembly just go to WINNT\Assembly folder and you will find your assembly listed there. Note how the assembly folder is treated differently that normal folders.

Step 5 : Test that our assembly works
Now, we will create a sample client application which uses our shared assembly. Just create a sample code as listed below :

imports system imports BAJComponents public class SampleTest shared sub main() dim x as new sample dim s as string="x".getdata() console.writeline(s) end sub end class
Compile above code using :

vbc sampletest.vb /t:exe /r:
Now, copy the resulting EXE in any other folder and run it. It will display "Hello World" indicating that it is using our shared assembly.