Thursday, July 27, 2006

Important .NET Command Line tools

Assembly Linker

The Assembly Linker generates a file with an assembly manifest from one or more files that are either modules or resource files. A module is a Microsoft intermediate language (MSIL) file that doesn't have an assembly manifest. All Visual Studio compilers produce assemblies. However, if you have one or more modules (metadata without a manifest), you can use Al.exe creates an assembly with the manifest in a separate file.

Examples

Following examples shows a delay sigining using Assembly Linker

Al.exe Sample1.netmodule, Sample2.netmodule /delaysign+ /Keyfile:SamplePublicKey.snk /out:SignedSample.exe

-------------------------------------------------------------

Installer tool

Installutill.exe is used to install the assemblies which contain additional component resources. This tool works in conjunction with classes in System.Configuration.Install namespace. This tool performs installation in the transactional manner. If one of the assemblies fails to install, it roll backs the installation of all the assemblies. For example, this tool can be used when installing a window service.

Examples

To install the resourse in assembly Assembly1.dll, you need to execute the following command:

Installutil.exe Assembly1.dll

-------------------------------------------------------------

Native Image Generator

The Native Image Generator creates a native image from a managed assembly and installs it into the native image cache on the local computer. The native image cache is a reserved area of the GAC. Once you create a native image for an assembly, the runtime automatically uses that native image each time it runs the assembly.

Examples

Following example create native image of C:\MyApplication\bin\Assembly1.dll in current native image cache.

Ngen.exe /silent C:\MyApplication\bin\Assembly1.exe

Following examples create native image for assembly which directly reference to other assemblies. You must supply fully specified names of the references assemblies. ILDASM.EXE tool can be used to get fully specified assembly name.

Ngen.exe Assembly1.exe "myLibOne, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0038abc9deabfle5", "myLibTwo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0038abc9deabfle5"

-------------------------------------------------------------

Assembly Binding Log Viewer

Fuslogvw.exe tool display details for assembly bind. This information is very useful in case of failure in loading assembly due to location/culture mismatch.

Example

fuslogvw.exe

-------------------------------------------------------------

GacUtil

This command line utility is useful for adding/removing the assemblies from GAC in the automated environment.

Example

Following example list all the assemblies in GAC

Gacutil.exe /l

Following example uninstall assembly from GAC

Gacutil.exe /u RandomNumberGenerator

Following example uninstall a specific version and culture of assembly from GAC

gacutil /u hello, Version=1.0.0.1, Culture="de",PublicKeyToken=45e343aae32233ca

Following example install list of assemblies from a file

gacutil /il assemblyList.txt

---------------------------------------------------

Type Library Importer

COM components do not have manifest file embedded in assembly itself, instead meta data is stored in separate Type Library. A type library can be a separate file or it can be embedded within another file. Type Library Importer tool (tlbimp.exe) can make a RCW component from meta data stored in Type Library.

Example

Tlbimp.exe MyCustomerCOM.dll /out:MyCustomerNET.dll

---------------------------------------------------

DISCO.EXE

The Web Services Discover Tool (disco.exe) retrieves the discovery document if the web services includes a static discovery document (.disco file). The .disco file is an XML file containing useful URLs. These include the URL for the WSDL file describing the service, the URL for the documentation of the service, and the URL to which SOAP messages should be sent.

Example

disco.exe http://localhost/MyWebservice/service1.asmx /out:MyWebSerDocs

It generates two files, first is service1.wsdl and other is results.discomap. Wsdl is a XML file which contains description of interfaces of web services.

---------------------------------------------------

WSDL.EXE

This tool is used to generate web proxy class from wsdl file. In can be understand in this way that output of disco.exe is input of wsdl.exe.

Example

Wsdl.exe service1.wsdl

Wsdl.exe results.discomap

---------------------------------------------------

Continue...

Friday, July 21, 2006

Pros and Cons of DataBinder.Eval()

Although DataBinder.Eval() function is very easy to use, it imposes performance penality due to late binding. This can be avoided using explicit casting. Following code snippet shows both the approaches:

Using DataBinder:
<%# DataBinder.Eval(Container.DataItem, "TotalAmount", "{0:n}" %>

Using Explicit Casting:
<%# String.Format("{0:n}", ( (DataRow)(Container.DataItem))["TotalAmount"]) %>

Tuesday, July 18, 2006

SSW Code Audit Tool

Got chance to play with this cool tool for code review.
Here is my feedback:

Features:

· Visual Studio Plug-in

· SSW works on source code directly unlike to FXCop which works on assembly. In this way, rules can be run on any type of text file like html, sql, xml, ascx, aspx, etc.

· Easily extensible – New rules can be added using Regular expressions(Tested)/Wild Cards (Tested)/ Xml Validate (not tested)/ Visual C#/VB.NET Code (not tested)

· Support for testing rules in tool itself before activating the rule

· Rules Exception – You can define exception conditions for particular rule

· Command Line/Batch File options to automate the review process

· Built-In Email and Scheduling options

· XML Output with default XLST file to provide Online Report. Report can be changed into different formats like By rules, By Files, By Ignored Files etc.

· SSW has rich rule repository. Rules can be categorized for particular needs:

1. ASP.NET – Migration Rules

2. C#/VB.NET UI & Code Rules

3. File Rules

4. Image Rules

5. Report/Reporting Service Rules

6. TEXT Rules

7. Web Rules

Down Sides:

  1. Although there is online knowledgebase, proper documentation is not available
  2. No support for Peer review like Jupiter Plug-in for Eclipse


Wednesday, July 12, 2006

Javascript - Converting m/d/yy date to mm/dd/yyyy using regular expressions

Following Javascript code snippet can be used to convert m/d/yy date to mm/dd/yyyy

var objtxtDate = document.getElementById("textboxDate");
var regex = /^\d{1,2}\/\d{1,2}\/\d{1,2}$/;
if (objtxtShipDate.value.match(regex))
{
var dateArr = objtxtShipDate.value.split("/");
var regex1 = /^(\d)$/; // for dd and mm
var regex2 = /^(\d\d)$/; // for yy

dateArr[0] = dateArr[0].replace(regex1, "0$1");
dateArr[1] = dateArr[1].replace(regex1, "0$1");

var now = new Date();
var year = now.getYear();
if(year < 2000) { year = year + 1900; }
var currentYear = year + '';
var regexYear = /^(\d\d)\d\d$/;
currentYear = currentYear.replace(regexYear, "$1");

dateArr[2] = dateArr[2].replace(regex2, currentYear + "$1");
objtxtDate.value = dateArr.join("/");
}

Tuesday, July 04, 2006

C# Late Binding

In Object Oriented Programming, Polymorphism allows programmers to have same interface for different type of Objects. Depending upon the type of object, interface produces different results.

This is called late-binding. In C#, it is achieved by combination of virtual functions, derived classes, and with 'new' & 'override' keywords.


using System;

public class Parent
{
public virtual void Print()
{
Console.WriteLine ("
This is parent class");

}

public virtual void Print2()
{
Console.WriteLine ("
Print2: This is parent class");

}

}

public class Child : Parent
{
public override void Print()
{
Console.WriteLine ("
This is child class");
}

public new void Print()
{
Console.WriteLine ("
Print2: This is child class");
}

}

public class MyClass

{

public static void Main()
{
Parent p;
p =
new Parent();
p.Print(); p.Print2();
p =
new Child();
p.Print(); p.Print2();
}

}



Following is the output:

This is parent class
Print2: This is parent class
This is child class
Print2: This is parent class

If we use 'new' keyword instead of 'override' keyword, it doesn't override base class function but hide it from base class object.

Monday, July 03, 2006

SQL 2000 Database Recovery from Network Drive using SQL commands

In my current project, we frequently need to update our QA database with our production database. We get production database backup copy by FTP. SQL Enterprise Manager donot support recovery of database from remote file. UI only support only local backup file. Following SQL commands came as rescue:

-- Command to list database from remote drive
restore filelistonly FROM disk='\\remotemachine\DB Backup\Northwind.bak'

-- Command to recover database using this list
RESTORE Database Core FROM disk='\\remotemachine\DB Backup\Northwind.bak''
WITH
move 'Northwind_Data'
TO 'C:\Program Files\Microsoft SQL Server\MSSQL$INSTANCE2\Data\Northwind.mdf',
move 'Northwind_Index'
TO 'C:\Program Files\Microsoft SQL Server\MSSQL$INSTANCE2\Data\Northwind_1.mdf',
move 'Northwind_Log'
TO 'C:\Program Files\Microsoft SQL Server\MSSQL$INSTANCE2\DataNorthwind_log.ldf',
Partial, Recovery

Thursday, June 29, 2006

Practical Uses of .NET Reflection

New to .NET Reflection? Following are good articles to start with:
  1. Part 1
  2. Part 2
  3. Practical Uses of .NET Reflection
In short, some of .NET Reflection Practical Uses:
  • Custom Collection Sorting
  • Designing Plug-in architecture
  • Designing External tools that operates on Codes - Lutz Rodeder's Reflector, FxCop, Nunit
  • Visual Studio uses in Property Dialog
  • Examine assembly at runtimes

Thursday, June 22, 2006

CSV Engine in MySQL

MySql 5.1 has fully functional CSV Engine. This aricle nicely explains its features and practical usages.

Monday, June 19, 2006

Access Denied Exception - New Excel.Application

I was having trouble in getting Excel Application object:
objExcel = New Excel.Application

It was giving exception :

Access is denied.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.UnauthorizedAccessException: Access is denied.

ASP.NET is not authorized to access the requested resource. Consider granting access rights to the resource to the ASP.NET request identity. ASP.NET has a base process identity (typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6) that is used if the application is not impersonating. If the application is impersonating via , the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.

To grant ASP.NET write access to a file, right-click the file in Explorer, choose "Properties" and select the Security tab. Click "Add" to add the appropriate user or group. Highlight the ASP.NET account, and check the boxes for the desired access.



I solved problem going through following steps:

  1. Run "dcomcnfg"
  2. Go Component Services -> DCOM Config -> Microsoft Excel Application
  3. Right Click on it and open Properties dialog.
  4. Go to security and give appropriate launch permission to \ASPNET user.

Saturday, March 11, 2006

My trip to Manali

Spectacular View of Shelang Valley. Posted by Picasa

Monday, January 16, 2006

Caching techniques in Perl

'Memoize' is very handy module available on CPAN for caching expensive operation in Perl.
Combining with 'DB_File' module, this module can be also used for persistence caching.

Thursday, December 29, 2005

Wednesday, December 28, 2005

Regular Expression: Multiple replacement in one go

One of the overloaded form of Regex.Replace function takes MatchEvaluator delegate as a parameter. We can use this form to achieve multiple (conditional) replacement in one go.

For Example:
// Replace Textboxes
string regex = "\\
";
System.Text.RegularExpressions.RegexOptions options = ((System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace
| System.Text.RegularExpressions.RegexOptions.Multiline)
| System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regex, options);
pageContent = reg.Replace(pageContent,new MatchEvaluator(RemoveFormElement));

protected string RemoveFormElement(Match m)
{
if(m.Value.IndexOf("RemoveFeedback") != -1)
{
string feedback = Regex.Replace(txtFeedback.Text,"\\n","
"
);
return ""+feedback+"";
}
else if (m.Value.IndexOf("RemoveContextHeader") != -1)
{
return ""+ contextHeader +"";
}
else
{
return m.Value;
}

}

Monday, December 05, 2005

Useful Window Tricks

Check out these 10 useful window tricks.

http://www.practicalpc.co.uk/computing/windows/top10tricks1.htm

Binding of DictionaryBase object with Datagrid instead of Collection Object

Following excerpts demonstrate how we can bind dictionary object with datagrid.

<asp:Label id="Label1" runat="server" Width="64px">
<%#((DictionaryEntry)Container.DataItem).Key %>
<br>
<%# ((TestApplication.ContactsInfo)((DictionaryEntry)Container.DataItem).Value).age%>

Prometric Test Centers in India

To find out prometric centers of your preferred location, visit following link:
http://www.register.prometric.com/Centers.asp

Following are some of the centers in New Delhi:

SQL STAR INTERNATIONAL LTD
NEW DELHI, Delhi 110003
Phone: 24601539 Site Code: IIU1 3RD FLOOR,
ANDHRA ASSOCIATION BULDING
24 & 25,
LODHI ROAD

C-NET EDUCATION
NOIDA, Uttar Pradesh
Phone: 5320373,2440594 Site Code: IIF94 D-3
SECTOR -10

IACL (Institute of Advance computer Learning)
NEW DELHI, Delhi 110049
Phone: 55484641 Site Code: IIG66 IACL
H-28,2ND-FLOOR
SOUTH EXTENSION PART-I

CMC LIMITED
NEW DELHI, Delhi 110058
Phone: 25572355 Site Code: IIG29 C-58,9TH FLOOR, SHAHPURI TIRATH SINGH TOWER
BEHIND JANAK CINEMA, JANAKPURI

VIVEKANAND INSTITUTE OF COMPUTER EDUCATION(VICE)-MOBILE SITE
DELHI, Delhi 110009
Phone: 55278088 Site Code: IIM83 VIVEKANAND INST. OF COMPUTER EDUCATION-MOBILE
2647
HUDSON LINE
NEAR NORTH CAMPUS
PATEL CHEST

Wednesday, November 30, 2005

PHP script Example

Below is basic PHP script which demonstrates MySQL and Active Directory communication :

";
mysql_close($dblink);


/* Going a step forward now we will connect to ldap server */
$ldapserver = "xxxx";

$user = "cn=Ashish Srivastava,cn=Users,dc=mydomamin,dc=com";
$passwd = "ashish";
$base = "cn=Users,dc=mydomamin,dc=com";


// Connect to ldap server
$dsCon = ldap_connect($ldapserver);


// Make sure we connected
if (!($dsCon))
{

print("Sorry, cannot contact LDAP server");
exit(2);

}


// Set Active Directory Specific Options
ldap_set_option($dsCon,LDAP_OPT_REFERRALS, 0);


// Bind LDAP
$bindresult = ldap_bind($dsCon,$user,$passwd);

if(!$bindresult){
$errno = ldap_errno($dsCon);
$error = ldap_error($dsCon);

print "LDAP Error ($errno): $error";
exit(3);
}


// Now Perform Search
$attributes = array("cn"); // attributes which you want

$search_filter = "(&(objectclass=user)(objectcategory=user)(sAMAccountName=ashish.srivastava))";
$search_result=ldap_search($dsCon, $base, $search_filter, $attributes);
if(!$search_result){
$errno = ldap_errno($dsCon);
$error = ldap_error($dsCon);

print "LDAP Error ($errno): $error";
exit(4);
}


// Getting Entries
$entry = ldap_get_entries($dsCon,$search_result);

if(!$entry){
$errno = ldap_errno($dsCon);
$error = ldap_error($dsCon);

print "LDAP Error ($errno): $error";
exit(4);
}


$cn = $entry[0]["cn"][0];
//var_dump($entry);
print "Common Name: $cn
";
ldap_close($dsCon);
?>

Tuesday, November 29, 2005

Codus - Code generation tool for .NET

Codus, a code generation tool by Adapdev Technologies provide excellent integration with variety of databases like SQL Server, Oracle and MySQL.

Cool Tools for .NET developers

Check out these cool tools. They are really handy.
Cool Tools

C# Interface Explained

I have never got so good explaination even in the good C# books. Interview in this article beautifully explains C# Interface.
http://dotnet.org.za/brianwilson/archive/2005/04/19/18306.aspx

Custom HTTP Modules

Custom HTTP Modules

HTTP Modules provides an opportunity to examine each incoming and outgoing request before request processing.
A typical use of HTTP module is URL rewriting on the basis of content of URL string. For example if i want to convert URL like "mywebproject/ashish/default.aspx" into "mywebproject/default.aspx?user=ashish" or vice-versa.

Creating custom HTTP Modules:

  • Make a class for implementing your custom module and implement IHttpModule Interface.
  • Add event handlers for BeginRequest and EndRequest events
  • Register your custom HTTP Module using web.config
Make a class and adding Event Handlers:
 public class UrlMapperModule : IHttpModule
{
private EventHandler onBeginRequest;

public UrlMapperModule()
{
onBeginRequest = new EventHandler(this.HandleBeginRequest);
}

void IHttpModule.Dispose()
{
}

void IHttpModule.Init(HttpApplication context)
{
context.BeginRequest += onBeginRequest;
}


private void HandleBeginRequest( object sender, EventArgs evargs )
{
// Now check every request
string requestUrl = app.Context.Request.Url.PathAndQuery;
}
}
Registering Custom HTTP Module in web.config: