Tuesday, December 11, 2007

To display the content in the web browser status bar

<’''body id="samplepage" onload ="window.status='First Page'">
<''form id="Form1" method="post" runat="server">

<''/form>
<’''/body>
Disabling the right click in the webpage
" <" body id="”samplepage”" oncontextmenu="return false;">

<"/body>"
Getting the client browser / system details through ASP.NET

HttpBrowserCapabilities bc=new HttpBrowserCapabilities();
bc=Request.Browser;
Response.Write(bc.Cookies.ToString());
Response.Write(bc.ActiveXControls.ToString());
Response.Write(bc.Platform.ToString());

Here HttpBrowserCapabilities is an class which is available in the system.web namespace ,first create an object and assign the client browser to it then we can get the details of the client browser with this the different property available

Response.Write( HttpContext.Current.Server.MachineName ) ;


This is used to get the client system name

Wednesday, December 05, 2007

Using shared variables in Crystal report

1. Create a formula in mainreport as @iammainformula with shared variable declared as Shared stringVar amtword := {?amntInWords};


2. Create a formula in subreport as @iamsubformaula with the shared variable with same name as we declared in the main report
Shared stringVar amtword ;
amtword;

now we can access the value from the main report in the sub report

Sunday, October 14, 2007

How do i learn from my Job ?


Many of well-wishers and friends had advised me to learn from the present job and try to go for a better job. At the beginning I am very confused about “Learning the Job “, because I thought learning the technology is enough to grow up in the carrier but that’s not a true apart from learning that, there are lot of other things are there to learned. When I grew up in my carrier I started understanding the real meaning for “Learning the Job”. So I thought of sharing my view with you all. Basically, learning means what we grasped from the work which we do or what we grasped from the environment which we are. Just a very small list that I used to follow

1. Learn professionalism both in the work the and culture
2. Learn the best use of Technologies
3. Learn to Update yourself with latest technology and news
4. Learn how to Speak
5. Learn how to write and maintain documents
6. Learn how to handle the situations
7. Learn the real Business
8. Learn how to present yourself
9. Learn how to motivate other and to get self-motivated
10. Learn how to deal with peoples
11. Learn the way to analyze the situations
12. Learn how to build a team
13. Learn your Duties
14. Learn to take responsibility
15. Learn to plan and Execute
16. Learn to Manage Time
17. Learn to make good relation with your co-workers
18. Learn how to earn
19. Learn how to set a target and focus on that
20. Learn all the bad things in your profession which will help you to do the good things
21. Learn to be loyal
22. and finally learn to LOVE your work


These are all a very small list which I had given. There are lot to learn .Learning the work and the work culture will vary from the company to company and the locality to locality and that to depend on the team which you work .don’t scold me if there is any grammatical mistake .sorry .hahaha
Generating KeyPair using SN.EXE

The Strong Name tool helps to sign assemblies with strong names. SN Stands for Strong Name
The Strong Name Consists of the Assembly Identification like Assembly Name ,Version ,Culture ,Public Key, and digital signature

The Public Key can be generated by using the .Net Framework tool (SN.EXE).

The key pair generated can be used for different assembly
The Strong name solves the versioning problem and naming problem
The user can deploy an assembly with the same name and same key pair in the GAC just by changing the version number

The simple syntax to generate strong name
Go to visual studio 2003 Command prompt and type the following command to generate the Key pay

Sn – K C:\Strongname.snk
When you type enter the strong name file will be generated in the specified location
To export the key from 1 file format to another
Sn – o C:\Strongname.snk C:\Strongname.txt
Sn – p C:\Strongname.snk C:\Strongname.txt

To Verify
Sn – v Sample.dll
It will verify for the strong name signature in the assembly if you put –vf instead of –v it’s a force verification

Wednesday, August 08, 2007

Hi,
If you want to disable the right click option in the browser, include the following lines of code in the header portion of the page.
<SCRIPT>
function noRightClick()
{

if (event.button == 2)
{
alert("Right Click Not Allowed!");
return false;
}

}
document.onmousedown = noRightClick
</SCRIPT>

Regards,
Sasikumar
Protecting your SAM Database


How to I protect my system. How to make my PC more secure on windows environment there are few common way we can protect our PC

By setting the BIOS password.
By Setting Windows password
By using system Hardware key


By using SYSKEY Utility.

I know most of will know the first 3 way of protecting and the fourth is quite different. Even thought SYSKEY Utility. is part of our OS we are not used to it . Let me explain about it .first we will know where this SYSKEY Utility resides inside our OS it’s in C:\WINDOWS\system32 folder. This utility is used to protect the System Account Manager Database (SAM) to run this utility go to run and type syskey




Fig1
The SYSKEY Utility will open now



Fig 2

Ok what is SAM what it does, this is the place where the OS will maintain the system username and password in encrypted format, now what the SYSKEY utility will do . it will move the decryption key to the floppy disk so that if you put the Floppy disk, only the system will open . Lets explain what’s there in the fig 2 here we have the Encryption Disabled and Encryption Enabled.

When you select the Encryption Disabled it will not encrypt the syskey if you select Encryption Enabled it will encrypt. After that clink the update button




Fig 3
In this screen we have the two options first the password setup which the user can give for their own or else we can select the system generated password. Again here we have the two way of storing the password. When you select the store startup key on floppy disk. The encrypted key will be stored in the floppy or if you select the store startup key locally it will be stored in the local system itself. This one of the most secure way to protect your system the data.







Wednesday, July 18, 2007

Trciks to play Minesweeper Game.

Press X, Y, Z, Z, Y, Shift +Enter, Enter


Now open the Minesweeper and watch the Top Left Corner of the screen and move your mouse cursor over the mine in the game. If there is no boom the Top Left Corner pixel will be set to 1 or else it will be set to 0 so you can see the difference in the Top Left Corner pixel. Based on this you can easily finish the game

Monday, July 16, 2007

Enabling Arabic in SQL server /Arabic is not recognized in SQL server it displays as “???????”.i had seen may query like this in many discussion group and I had also faced the same problem .These are the few tips which I had followed to solve the problem

Solution 1:
Set the collation for the field to Arabic while creating the table

How do I change the collation for the existing table?

ALTER TABLE #studrelation ALTER COLUMN stu_rela_code
Nvarchar(100) COLLATE Arabic_CI_AS NOT NULL



Here Arabic_CI_AS

Arabic – Language which you need
CI/CS - Case Insensitive / Case Sensitive
AS/KS/WS - Accent sensitivity/ Kana Sensitivity/ Width sensitivity


Solution 2:

Arabic will be recognized only with data type Nvarchar, text if you insert in varchar data type it won’t work.

CREATE TABLE #studrelation
( stud_id int,
stu_rela_code Nvarchar(100)
)
Insert into #studrelation(stud_id,stu_rela_code)values(1,'رسوم كتب')

select * from studrelation where stu_rela_code like N'%رسوم كتب%'

Friday, July 13, 2007

In this we will learn about the WinCV tool, I am going to give just a short summary about WinCV and its usage and how to use this tool more effectively for the programming

Before learning about the WinCV tool we will learn the real scenario

Many times while programming, will be blinking before the monitor without knowing the proper object or class available , then what’s the next step only Google its it right. How it will be if we have a tool that will allow you search for class the objects in the .net library yes we have the inbuilt tool called WinCV.exe which is available at C:\Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\Bin, just you can open the tool and type the class or object which you need to find out it will list out all the content the assembly name, field, Constructors, Properties, Events, Methods

Ok Then what to do if we have our own assembly and how to browse the objects in that .There is a web configuration file called WinCV.exe in the same location you can edit the configuration file and add your assembly in the tag [] then you can browse your assembly.

Saturday, June 30, 2007

This kind of error will occur in crystal report when you export the report to any other format. For example from “.rpt” to “.pdf” /”.doc” like that. The error message will be like this

Problem:

Invalid export DLL or Export Format

Cause /Reason:
The problem is in the export dll used in the crystal report.. since its not properly registered this problem will occur

Solution:
Uninstall the acrobat reader and reinstall it this problem will be solved
Some time we may face the Error While we load the Crystal report in the application . the error message which we will face is

Problem:
Error : Load Report failed

Cause /Reason:
When the report file (.rpt file) is not in the Specific path which you had mention in the application this error will occur

Solution:
Place the specific .rpt file in the path specified.

Friday, June 29, 2007



Regional Settings for IIS

Some time we may get problem in language or the numeric/ date time format while you deployed an asp.net application or in the development itself.

Problem:
The problem is in the date time format that your system displays. Actually the date should be in “dd/MM/yyyy” format but it displays as “dd-MM-yyyy” or some other format. Even though you try by setting the regional setting also its wont work. But the same application works in another server / PC with “dd/MM/yyyy” format and the month name is also displaying in Different language .

Cause:

In the Globalization attribute in the machine.config file if the culture if not set this problem arise. You can find the configuration file in “C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\CONFIG” this location

Solution:

Give the culture name the Globalization attribute


So the asp.net application will take the regional settings from the machine.Config file. Here I had set to US English you can set to any other language format if you need.

Note: This setting is for all the application deployed in that IIS Server

Thursday, June 07, 2007

Weather Microsoft is watching your system. Don’t they have any other work than that. “wpa.dbl “.WPA stands for Windows Product Activation for Windows XP and above version of Microsoft OS is using the wpa.dbl file to activate the product. There are lot of rumours that, by using this file Microsoft is going to watch your activities. Ya its may be true but not all your personal activities ,it will check for the OS license only . Ok how MS is going to check the license, weather they are going to take my H/W info. Yes they are, there are few listed H/W which they are going to check they are

NIC & MAC address
HDD Serial Number
processor number
Display Adapter
SCSI Adapter
IDE Adapter (effectively the motherboard)
RAM Amount Range (i.e., 0-64mb, 64-128mb, etc.)
Processor Type
CD-ROM / CD-RW / DVD-ROM

The “wpa.dbl “ is going to have the info of the above said H/W. Then What its does? Every time you boot you system the OS will check the H/W serial number with the number in the “wpa.dbl “ file, if your version of OS pass 7 checks then only your OS will be considered as licensed one. If else you can all MS through phone and you can activate it

What happen when I change the H/W?
If you change 1 or 2 H/W there is no problem if the OS passes less then 7 checks then you want to reactivate your OS through phone call. So this what “wpa.dbl “file is going to do in your system

Wednesday, May 30, 2007

Here is the code to add the controls dynamically to the form and to generate events for the generated controls .the code is an C# code

private void Form1_Load(object sender, System.EventArgs e)
{
int y=16,x=72;
for (int i=1; i<=5;i++) { btn=new Button();
panel1.Controls.Add(btn);
btn.Location=new System.Drawing.Point(x, y);
btn.Text ="Button"+i.ToString();
y=y+30;
btn.Click+=new EventHandler(btn_Click);
}
}

private void btn_Click(object sender, EventArgs e)
{
Button bt=(Button)sender;
MessageBox.Show(bt.Text);

}

Code description

Create a new instance for the button object btn=new Button(); then add the object to the form or panel here I am using panel to place the button control. Then the event is generated in the look it self. The btn_Click event is for the generated buttons.

The top 10 dead (or dying) computer skills

1. Cobol
2. No relational DBMS
3. Non-IP networks
4. cc: Mail
5. Cold Fusion
6. C programming
7. PowerBuilder
8. Certified NetWare Engineers
9. PC network administrators
10. OS/2

Reference:
http://www.computerworld.com/action/article.do?command=printArticleBasic&articleId=9020942

Friday, May 18, 2007

Working with a Database in C#

PublicJoe's - Sample Chapter - Teach Yourself C# in 24 Hours - Chapter 21 - Working with a Database in C#
Teach Yourself C# in 24 Hours - Chapter 21 - Working with a Database
in C#
By James Foxall and Wendy Haro-Chun.
ISBN: 0-6723-2287-0
 
You've heard it so many times that it's almost a cliché: This is the information age. Information is data, and managing information means working with databases. Database design is a skill unto itself, and entire books are devoted to database design and management. In this hour, you'll learn the basics of working with a database using ADO.NET, Microsoft's newest database technology. Although  high-end solutions are built around advanced database technologies such as Microsoft's SQL Server, the Microsoft Jet database (used by Microsoft Access) is more readily available and easier to learn, so you'll build working examples that use a Jet database.
 
The highlights of this hour include the following:
  • l Introduction to ADO.NET
  • l Connecting to a database
  • l Understanding DataTables
  • l Creating a DataAdapter
  • l Referencing fields in a DataRow
  • l Navigating records
  • l Adding, editing, and deleting records
  • l Building an ADO.NET example
NOTE
You'll learn a lot in this hour, but realize that this material is really the tip of the iceberg. Database programming can be, and often is, very complex. This hour is intended to get you writing database code as
quickly as possible, but if you plan on doing a lot of database programming, you'll want to consult a dedicated book (or two) on the subject. Start by creating a new Windows Application named Database Example. Change the name of the default formto fclsMain and set its Text property to Database Example. Next, click the View Code button on the Solution Explorer window to access the form's code, scroll down and locate the procedure Main(), and change the reference of Form1 to fclsMain. Finally, click the Form1.cs tab to return to the form designer.
 
Introduction to ADO.NET
ADO.NET is the .NET platform's new database technology, and it builds on ADO (Active Data Objects). ADO. NET defines DataSet and DataTable objects that are optimized  for moving disconnected sets of data across intranets and Internets, including through firewalls. At the same time, ADO.NET includes the traditional Connection and Command objects, as well as an object called a DataReader that resembles a forward-only, readonly ADO recordset. Together these objects provide the very best performance and throughput for retrieving
data from a database.
 
Connecting to a Database
 
To access data in a database, you must first establish a connection using an ADO.NET connection object. Two connection objects are included in the .NET Framework: the OleDbConnection object, for working with the same OLE DB data providers you would access through traditional ADO, and the SqlConnection object, for optimized access to Microsoft SQL Server. Because these examples connect to the Microsoft Jet Database, you'll be using the OleDbConnection object. To create an object variable of type OleDbConnection and
initialize the variable to a new connection, you could use a statement such as the following:
 
OleDbConnection cnADONetConnection = new OleDbConnection();
 
To use ADO.NET, the first step that you need to take is to add the proper Namespace to your project. Doubleclick the form now to access its events. Scroll to the top of the class and add  the following using statement on the line below the other using statements:
 
using System.Data.OleDb;
 
You're going to create a module-level variable to hold the connection, so  place the cursor below the left bracket ({) that follows the statement public class fclsMain : System.Windows.Forms.Form and
press Enter to create a new line. Enter the following statement:
 
OleDbConnection m_cnADONetConnection = new OleDbConnection();
Before using this connection, you must specify the data source to which you want to connect. This is done through the ConnectionString property of the ADO.NET connection object. The ConnectionString
contains connection information such as the name of the provider, username, and password. The ConnectionString might contain many connection parameters; the set of parameters available varies
depending on the source of data that you are connecting to. Some of the parameters used in the OLE DB ConnectionString are listed in Table 21.1. If you specify multiple parameters, separate them with a
semicolon.
 
Table 21.1 - Possible Parameters for ConnectionString
Parameter Description
Provider The name of the data provider (Jet, SQL, and so on) to use.
Data Source= The name of the data source (database) to connect to.
UID= A valid username to use when connecting to the data source.
PWD= A password to use when connecting to the data source.
DRIVER= The name of the database driver to use. This isn't required if a DSN is specified.
SERVER= The network name of the data source server.
The Provider= parameter is one of the most important at this point and is governed by the type of database you're accessing. For example, when accessing a SQL database, you specify the provider information for SQL; when accessing a Jet database, you specify the provider for Jet. In this example, you'll be accessing a Jet (Microsoft Access) database, so you'll use the provider information for Jet.In addition to specifying the provider, you're also going to specify the database. I've provided a sample database at the Web site for this book. This code assumes that you've placed the database in a folder called C: \Temp. If you are using a different folder, you'll need to change the code accordingly.
To specify the ConnectionString property of your ADO.NET connection, place the following statement in the Load event of your form:
 
m_cnADONetConnection.ConnectionString =
@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\temp\contacts.mdb";
 
After the connection string is defined, a connection to a data source is established by using the Open()method of the connection object. The Open() method has the following syntax:
objectvariable.Open();
 
NOTE
Refer to the online documentation for information on the connection strings for providers other than Jet.When you attach to an unsecured Jet database, it's not necessary to provide a username and password. When attaching to a secured Jet database, however, you'll have to provide a username and a password. This is done by passing the username and password as parameters in the ConnectionString property. The sample database I've provided isn't secured, so it's not necessary to provide a username and password.
 
Closing a Connection to a Data Source
You should always explicitly close a connection to a data source. This means that you should not rely on a variable going out of scope to close a connection, but you should force an explicit disconnect via code. This is
accomplished by calling the Close() method of the connection object.
You're now going to write code to explicitly close the connection when the form is closed. Start by clicking the Form1.cs tab to return to the form designer. Next, click the Events button on the Properties window (the lightening bolt) to access the list of events for the form. Double-click the Closed event to create a new event handler. Enter the following statement in the Closed event:
m_cnADONetConnection.Close();
 
Manipulating Data
The easiest way to manipulate data using ADO.NET is to create a DataTable object containing the resultset of a table, query, or stored procedure. Using a DataTable, you can add, edit, delete, find, and navigate records. The following sections explain how to use DataTables.
 
Understanding DataTables
DataTables contain a snapshot of the data in the data source. You generally start by filling a DataTable, and then you manipulate the results of the DataTable before finally sending the changes back to the data source.The DataTable is populated using the Fill() method of a DataAdapter object, and changes are sent back to the database using the Update() method of a DataAdapter. Any changes made to the DataTable appear only in the local copy of the data until you call the Update() method. Having a local copy of the data reduces contention by preventing users from blocking others from reading the data while it is being viewed. This is similar to the Optimistic Batch Client Cursor in ADO.
 
Creating a DataAdapter
 
To populate a DataTable, you need to create a DataAdapter, an object  that provides a set of properties and methods to retrieve and save data between a DataSet and its source data. The DataAdapter you're going to create will use the connection you've already defined to connect to the data source and will then execute a query you'll provide. The results of that query will be pushed into a DataTable. Just as two ADO.NET connection objects are in the .NET Framework, there are two ADO.NET DataAdapter Objects as well: the OleDbDataAdapter and the SqlDataAdapter. Again, you'll be using the
OleDbDataAdapter because you aren't connecting to Microsoft SQL Server. The constructor for the DataAdapter optionally takes the command  to execute when filling a DataTable or DataSet, as well as a connection specifying the data source. (You could have multiple  nnections open in a single project.) This constructor has the following syntax:
 
OleDbDataAdapter cnADONetAdapter = new
OleDbDataAdapter([CommandText],[Connection]);
 
To add the DataAdapter to your project, first add the following statement immediately below the statement you entered to declare the m_cnADONewConnection object.
 
OleDbDataAdapter m_daDataAdapter = new OleDbDataAdapter();
Next, add the following statement to the Load event of the form, immediately following the statement that creates the connection:
 
_daDataAdapter =
new OleDbDataAdapter("Select * From Contacts",m_cnADONetConnection);
 
Because you're going to use the DataAdapter to update the original data source, you need to specify the insert, update, and delete statements to use to submit changes from the DataTable to the data source. ADO. NET lets you customize how updates are submitted by allowing you to manually specify these statements as database commands or stored procedures. In this case, you're going to have ADO.NET automatically generate these statements for you by creating a CommandBuilder object. Enter the following statement to create the
CommandBuilder.
OleDbCommandBuilder m_cbCommandBuilder =
new OleDbCommandBuilder(m_daDataAdapter);
 
When you create the CommandBuilder, you pass into the constructor the DataAdapter that you want the CommandBuilder to work with. The CommandBuilder then registers for update events on the DataAdapter
and provides the insert, update, and delete commands as needed. You don't need to do anything further with the CommandBuilder.
 
NOTE
When using a Jet database, the CommandBuilder object can create the dynamic SQL code only if the table in question has a primary key defined.
Creating and Populating DataTables
 
You're going to create a module-level DataTable in your project. First, create the DataTable variable by adding the following statement on the line below the statement you entered previously to declare a new modulelevel m_daDataAdapter object:
 
DataTable m_dtContacts = new DataTable();
 
You are going to use an integer variable to keep track of the user's current position within the DataTable. To do this, add the following statement immediately below the statement you just entered to declare the new DataTable object:
 
int m_rowPosition = 0;
 
Next, add the following statement to the Load event of the form, immediately following the statement that creates the CommandBuilder:
 
m_daDataAdapter.Fill(m_dtContacts);
 
NOTE
Because the DataTable doesn't hold a connection to the data source, it's not necessary to close it when you're finished.
Your class should now look like the one in
Figure 21.1.
Figure 21.1 - This code accesses a database and creates a DataTable that can be used anywhere in the class.
 
Referencing Columns in a DataRow
DataTables contain a collection of DataRows. To access a row within the DataTable, you specify the ordinal of that DataRow. For example, you could access the first row of your DataTable like this:
DataRow m_rwContact = m_dtContacts.Rows[0];
 
Data elements in a DataRow are called columns. For example, two   olumns, ContactName and State, are in the Contacts table I've created. To reference the value of a column, you can pass the column name to the DataRow like this:
 
m_rwContact["ContactName"] = "Bob Brown";
or
Debug.WriteLine(m_rwContact["ContactName"]);
 
NOTE
If you spell a column name incorrectly, an exception occurs when the statement executes at runtime. You're now going to create a procedure that is used to display the current record in the database. To display
the data, you need to add a few controls to the form. Create a new text box and set its properties as follows (you'll probably need to click the Properties button on the Properties window to view the text box's properties rather than its events):
Property Value
Name txtContactName
Text (make blank)
Location 48, 112
Size 112, 20
Add a second text box to the form and set its properties according to the following table:
Property Value
Name txtState
Text (make blank)
Location 168, 112
Size 80, 20
Next, click the Form1.cs tab in the IDE to return to the code window. Position the cursor after the right bracket that ends the fclsMain_Closed() event and press Enter a few times to create some blank lines. Next, enter the following procedure in its entirety:
 
private void ShowCurrentRecord()
{
if( m_dtContacts.Rows.Count == 0 )
{
txtContactName.Text = "";
txtState.Text = "";
return;
}
txtContactName.Text =
m_dtContacts.Rows[m_rowPosition]["ContactName"].ToString();
txtState.Text = m_dtContacts.Rows[m_rowPosition]["State"].ToString();
}
Ensure that the first record is shown when the form loads by adding the following statement to the Load event, after the statement that fills the DataTable: this.ShowCurrentRecord();
You've now ensured that the first record in the DataTable is shown when the form first loads. Next, you'll learn how to navigate and modify records in a DataTable.
 
Navigating and Modifying Records
The ADO.NET DataTable object supports a number of methods that can be used to access its DataRows. The simplest of these is the ordinal accessor that you used in your ShowCurrentRecord() method. Because the DataTable has no dependency on the source of the data, this same functionality is available regardless of where the data came from.
You're now going to create buttons that the user can click to navigate the DataTable. The first button is used to move to the first record in the DataTable. Add a new button to the form and set its properties as follows:
 
Property Value
Name btnMoveFirst
Text <<
Location 16, 152
Size 32, 23
Double-click the button and add the following code to its Click event:
m_rowPosition = 0;
this.ShowCurrentRecord();
A second button is used to move to the previous record in the  DataTable. Add another button to the form and set its properties as shown in the following table:
 
Property Value
Name btnMovePrevious
Text <
Location 56, 152
Size 32, 23
Double-click the button and add the following code to its Click event:
if( m_rowPosition > 0 )
{
m_rowPosition = m_rowPosition - 1;
this.ShowCurrentRecord();
}
A third button is used to move to the next record in the DataTable. Add a third button to the form and set its properties as shown in the  following table:
 
Property Value
Name btnMoveNext
Text >
Location 96, 152
Size 32, 23
Double-click the button and add the following code to its Click event:
if( m_rowPosition < m_dtContacts.Rows.Count - 1 )
{
m_rowPosition = m_rowPosition + 1;
this.ShowCurrentRecord();
}
A fourth button is used to move to the last record in the DataTable. Add yet another button to the form and set its properties as shown in the following table:
Property Value
Name btnMoveLast
Text >>
Location 136, 152
Size 32, 23
Double-click the button and add the following code to its Click event:
if( m_dtContacts.Rows.Count != 0 )
{
m_rowPosition = m_dtContacts.Rows.Count - 1;
this.ShowCurrentRecord();
}
 
Editing Records
To edit records in a DataTable, simply change the value of a particular column in the desired DataRow. Remember, however, that changes are not made to the original data source until you call Update() on the
DataAdapter, passing in the DataTable containing the changes.
You're now going to add a button that the user can click to update the current record. Add a new button to the form now and set its properties as follows:
Property Value
Name btnSave
Text Save
Location 176, 152
Size 40, 23
Double-click the Save button and add the following code to its Click event:
if( m_dtContacts.Rows.Count != 0 )
{
m_dtContacts.Rows[m_rowPosition]["ContactName"] = txtContactName.Text;
m_dtContacts.Rows[m_rowPosition]["State"] = txtState.Text;
m_daDataAdapter.Update(m_dtContacts);
}
Creating New Records
Adding records to a DataTable is performed very much like editing records. However, to create a new row in the DataTable, you must first call the NewRow() method. After creating the new row, you can set its column values. The row isn't actually added to the DataTable, however, until you call the Add() method on the DataTable's RowCollection.
You're now going to modify your interface so that the user can add new records. You'll use one text box for the contact name and a second text box for the state. When the user clicks a button you'll provide, the values in these text boxes will be written to the Contacts table as a new record. Start by adding a group box to the form and set its properties as shown in the following table:
Property Value
Name grpNewRecord
Text New Contact
Location 16, 192
Size 264, 64
Next, add a new text box to the group box and set its properties as follows:
Property Value
Name txtNewContactName
Text (make blank)
Location 8, 24
Size 112, 20
Add a second text box to the group box and set its properties as shown:
Property Value
Name txtNewState
Text (make blank)
Location 126, 24
Size 80, 20
Finally, add a button to the group box and set its properties as follows:
Property Value
Name btnAddNew
Text Add
Location 214, 24
Size 40, 23
Double-click the Add button and add the following code to its Click event:
DataRow drNewRow = m_dtContacts.NewRow();
drNewRow["ContactName"] = txtNewContactName.Text;
drNewRow["State"] = txtNewState.Text;
m_dtContacts.Rows.Add(drNewRow);
m_daDataAdapter.Update(m_dtContacts);
m_rowPosition = m_dtContacts.Rows.Count - 1;
this.ShowCurrentRecord();
Notice that after the new record is added, the position is set to the last row and the ShowCurrentRecord() procedure is called. This causes the new record to appear in the text boxes you created earlier.
Deleting Records
To delete a record from a DataTable, you call the Delete() method on the DataRow to be deleted. Add a new button to your form (not to the group box) and set its properties as shown in the following table.
Property Value
Name btnDelete
Text Delete
Location 224, 152
Size 56, 23
 
Double-click the Delete button and add the following code to its Click event:
if( m_dtContacts.Rows.Count != 0 )
{
m_dtContacts.Rows[m_rowPosition].Delete();
m_daDataAdapter.Update(m_dtContacts);
m_rowPosition = 0;
this.ShowCurrentRecord();
}
Your form should now look like that in Figure 21.2.
Figure 21.2 - A basic data-entry form.
Running the Database Example
Press F5 to run the project. If you entered all the code correctly, and you placed the Contacts database into the C:\Temp folder (or modified the path used in code), the form should display without errors, and the first record in the database will appear. Click the navigation buttons to move forward and backward. Feel free to change the information of a contact, click the Save button, and your changes will be made to the underlying database. Next, enter your name and state into the New Contact section of the form and click Add. Your name will be added to the database and displayed in the appropriate text boxes.
 
Using the Data Form Wizard
Visual Basic .NET includes a tool to help introduce you to ADO.NET - the Data Form Wizard. In this section, you're going to use the Data Form Wizard to create a form that is bound to the same database you used in the previous example. Start by creating a new Windows Application titled Data Form Example. The Data Form Wizard is run by adding it to your project as a form template. Choose Add Windows Form from the Project menu to display the Add New Item dialog box, click the Data Form Wizard icon, change the name to fclsDataForm.cs (see Figure 21.3), and click Open to start the wizard.
 
Figure 21.3 - The Data Form Wizard as a form template.
The first page of the wizard is simply an introduction. Click Next to get to the first "real" page. This next page is used to choose the dataset you want to bind to the form. ADO.NET datasets hold a collection of
DataTables. Enter AllContacts into the text box (see Figure 21.4) and click Next to continue.
 
Figure 21.4 - A DataTable is similar to an ADO recordset.
The next page of the wizard is used to specify a connection to a data source (see Figure 21.5). Note: Because you haven't previously defined a connection to the Contacts database, your drop-down list will be empty. Click the New Connection button to display the Data Link Properties dialog box. Notice that this dialog box opens with the Connection page visible. Click the Provider tab to see the list of installed providers on your computer (see Figure 21.6), choose Microsoft Jet 4.0 OLE DB Provider to select it, and then click the Connection tab once more.
 
Figure 21.5 - Use this page to specify a data source.
Figure 21.6 - You must specify the appropriate provider for the type of data source to which you are connecting. Now that you've selected the provider, you need to locate and select the data source (your Jet database). Click the build button next to the database name text box, and then locate and select the contacts.mdb database. Next, click Test Connection to make sure the information you have supplied creates a valid connection to the database. If the test succeeded, click OK to close the Data Link Properties dialog box. The database should
now appear in the Connection drop-down list. Click Next to continue.
The next step in completing the wizard is to choose the table or tables you want to use (see Figure 21.7). The tables you choose here will be used to supply the data that is bound to your form. Double-click the Contacts table to add it to the Selected Items list and click Next to continue.
 
Figure 21.7 - Use this page to choose the data to bind to the form.
This page shown in Figure 21.8 is used to specify the columns that you want bound on the form. The two columns in your Contacts table are already selected by default, so click Next to continue.
 
Figure 21.8 - You don't have to select all the fields in a table.
The last step of the wizard is specifying the style in which you want the data to appear (see Figure 21.9). Because the previous example had you add individual controls for each column, leave the All Records in a Grid
radio button, selected (this will create a data grid). Click Finish to create your new data form, which will appear in the form designer (see Figure 21.10).
Figure 21.9 - The Data Form Wizard gives you a number of choices for displaying your data.
Figure 21.10 - This bound grid was created by the Data Form Wizard.
To test your form, you'll have to display it. Click Form1.cs to display the designer for the default form in your
project and add a new button to the form. Set the button's properties as follows:
 
Property Value
Name btnShowDataForm
Text Show Data Form
Location 96, 120
Size 104, 23
Next, double-click the button to access its Click event and add the following code:
fclsDataForm objDataForm = new fclsDataForm ();
objDataForm.Show();
Press F5 to run the project, and then click the button and your bound form will appear. To load the grid with records, click the Load button (see Figure 21.11). Figure 21.11 - This grid is bound to the record source. Stop the running project, click fclsDataForm.cs in the Solution Explorer, and then click the View Code button on the Solution Explorer to view the class. Notice that the Data Form Wizard created all the ADO.NET code for you, and even included rudimentary error handling. The Data Form Wizard is a great way to get started with ADO.NET, but it will take you only so far. To create robust ADO.NET applications, you will need to find one or more dedicated resources that focus on the intricacies of ADO.NET.
 
Summary
Most commercial applications use some sort of database. Becoming a good database programmer requires extending your skills beyond being just a good programmer. There is so much to know about optimizing database and database code, creating usable database interfaces, creating a database scheme - the list goes on. However, writing any database application begins with the basic skills you learned in this hour. You learned how to connect to a database, create and populate a DataTable, and navigate the records in the DataTable. In addition, you learned how to edit records and how to add and delete reco rds. Finally, you learned how to use the Data Form Wizard to create a basic ADO.NET bound form. You are now prepared to write simple, yet
functional, database applications.
 


Samiyappan Prabakar ,Mobile : +971 50 9042741
 
 


Need a vacation? Get great deals to amazing places on Yahoo! Travel.

Saturday, May 05, 2007

Error Message: Could not copy temporary files to the output directory.
Or
Cannot copy sample.dll to D:\Prabakar\Sharpurdotnet\...


We may receive this error message many time while your build your application or the specific project. I too had this problem many time and the reason for the error and the solution is here.

Reason:

Check the property of the output weather the COPY LOCAL property is false
May be all of your output path may refer a single folder.
Solution:


Change the output folder
And set the COPY LOCAL Property to true
Delete the bin and obj folder and rebuild the project

Thursday, May 03, 2007


Using IIS 7 for visual studio 2003 in Microsoft Vista. We can have both VS2003 and VS2005 in the single system and for VS2005 the default Server is IIS 7 ,since the IIS 6 and IIS 7 can not run in single system the IIS 7 manager will disable the II6, So we can make the IIS 7 as comparable to VS2003 by enabling the Compatibility option in the control panel


Click the Turn Windows features on or off then in the popup window check the IIS 6 Management compatibility

Now run your VS2003 web application in admin mode ,this process will enable the VS2003 to use IIS 7



Disable Back Button in the browser

Hi guys,
 
If you want to disable back button in web browser, include the following JavaScript code inside the <head> portion of the HTML,

<script type="text/JavaScript">
     history. forward();
</script>
 
Regards,
Sasikumar



----------------------------------------------------------------DISCLAIMER---------------------------------------------------------
Information transmitted by this EMAIL is proprietary to iGATE Group of Companies and is intended for use only by the individual 
or entity to whom it is addressed and may contain information that is privileged, confidential, or exempt from disclosure under 
applicable law. If you are not the intended recipient of this EMAIL immediately notify the sender at iGATE or mailadmin@igate.com 
and delete this EMAIL including any attachments

Wednesday, April 18, 2007

Nice Link for web services which we can use for our line application .For example they have the currency converted web services which will have the running dollars rates so u will get the exact rate as of now

http://www.webservicex.net/WCF/default.aspx

They have different services like this just go and check

Wednesday, April 04, 2007

Mono .net only alternative for MS .net, Which runs on windows, Linux and Solaris and Mac OS ,Article tells more about more and its usage .Link.

Monday, April 02, 2007

It’s a Real Great News from Yahoo that it had announced to given access to the web services through SOAP .Here is the article link http://developer.yahoo.net/blog/archives/2007/03/mail.html
Decompiler are very useful when you don’t have your source and if you have only the assembly (dll).at this time we can decompiler and get the source .there are different decompiler available but most of them are too costly .in our .net framework itself we have decompiler Ildasm.exe but the output will be in MSIL, Hence we are going for third party decompiler. In that way reflector is very useful and freeware .few of the articles which I gone through are http://aspnet.4guysfromrolla.com/articles/080404-1.aspx

Thursday, March 29, 2007

FTP for E-BOOKS

ftp://ftp.uar.net/pub/e-books/  ftp with lot of ebooks download ASAP

Samiyappan Prabakar ,Mobile : +971 50 9042741
 
 


Don't pick lemons.
See all the new 2007 cars at Yahoo! Autos.

Wednesday, March 28, 2007

Query Engine Error: 'D:\IIMS\Finance\Reports\RptWorkOrderEmployee.rpt'
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: CrystalDecisions।CrystalReports।Engine.DataSourceException: Query Engine Error: 'D:\IIMS\Finance\Reports\RptWorkOrderEmployee.rpt'


Reason:

When there is the difference in the Field in the report and the dataset which you bind to the report file, Check the data type of the fields name then the number of fields in the report and the dataset


Thursday, March 22, 2007

Normalization

First normal form (1NF) sets the very basic rules for an organized database:

  • Eliminate duplicative columns from the same table.
  • Create separate tables for each group of related data and identify each row with a unique column or set of columns (the primary key).

Second normal form (2NF) further addresses the concept of removing duplicative data:

  • Meet all the requirements of the first normal form.
  • Remove subsets of data that apply to multiple rows of a table and place them in separate tables.
  • Create relationships between these new tables and their predecessors through the use of foreign keys.

Third normal form (3NF) goes one large step further:

  • Meet all the requirements of the second normal form.
  • Remove columns that are not dependent upon the primary key.

Finally, fourth normal form (4NF) has one additional requirement:

  • Meet all the requirements of the third normal form.
  • A relation is in 4NF if it has no multi-valued dependencies.

Remember, these normalization guidelines are cumulative. For a database to be in 2NF, it must first fulfill all the criteria of a 1NF database.

 

Regards,

Sasikumar




----------------------------------------------------------------DISCLAIMER---------------------------------------------------------
Information transmitted by this EMAIL is proprietary to iGATE Group of Companies and is intended for use only by the individual 
or entity to whom it is addressed and may contain information that is privileged, confidential, or exempt from disclosure under 
applicable law. If you are not the intended recipient of this EMAIL immediately notify the sender at iGATE or mailadmin@igate.com 
and delete this EMAIL including any attachments

Wednesday, March 21, 2007

Error in Crystal Report While Exporting

Error in Crystal Report While Exporting
 
"Missing parameter field current value" this error occurs while exporting the crystal report to PDF /word/excel. I had found the query regarding this error in many pages that's the reason I had posed it
 
Reason:
 
          Due to the parameter mismatch in the report file and the assigned parameter
 
Solution:
 
          1. Check weather all the parameter is passed or not
          2. Verify database of the report to update the table
 
 
 


Samiyappan Prabakar ,Mobile : +971 50 9042741
 
 


We won't tell. Get more on shows you hate to love
(and love to hate): Yahoo! TV's Guilty Pleasures list.

Tuesday, March 20, 2007

Basic Assembly in .NET

 

+

Creating an assembly

Changing the search path for private assemblies

 

Creating strongly named assembly

Adding assembly into the global assembly cache

Creating a Delay signed shared assembly

 

Using Assembly Version Policy

Creating a Publisher Policy Assembly

 

Getting the types in an assembly

Creating assembly on the fly

Dynamic Binding a Assembly

 

Serializing using XmlSerializer

Serializing using SoapSerializer

Serializing using BinarSerializer

Creating a Domain

 

 

 

Module MyModule

          public sub Main(args() as string)

                   System.Console.WriteLine("Hello Vb")

          end sub

end Module

 

Using the command-line compiler provided with Visual Studio, such a program can be compiled with the command line directive

c:\> vbc Hello.vb

 

 

 

class CA

{

          public static void Main(string[] args)

          {

                   System.Console.WriteLine("Hello World");

          }

}

 

Using the command-line compiler provided with Visual Studio, such a program can be compiled with the command line directive

c:\> csc  Hello.cs

 

c:\> ildasm Hello.exe

 

Creating an assembly

 

namespace MathLibrary

{

          public class CMath

          {

                   public long AddFun(long x,long y)

                   {

                             Console.WriteLine("Addfun");

                             return x + y;

                   }

                   public long SubFun(long x,long y)

                   {

                             Console.WriteLine("AubFun");

                             return x - y;

                   }

          }

}

 

c:\> csc /t:libary Math.cs

 

 

public class CMath

          public function AddFun(x as long,y as long) as long

                   return x + y

          end function

end class

 

How Do I...Change the search path for private assemblies?

Private assemblies are assemblies that are visible to only one application. The .NET Framework enables developers to build applications that are isolated from changes made to the system by other applications. Private assemblies must be deployed in the directory structure of the containing application and are found during runtime through a process called probing, which is simply a mapping from an assembly's identity to a file on disk that contains the manifest.

 

By default, probing for private assemblies is done in the application base (the root directory of the application) and the subdirectories that follow naming conventions based on assembly name and culture. You can customize this behavior by specifying a privatePath in your application's configuration file. The privatePath is a semi-colon delimited list of directories in which the common language runtime will search for private assemblies. These directory names are relative to the application base - they cannot point outside the application base. The directories on privatePath will be searched after the application base itself. The following configuration file adds a bin directory to the assembly search path:

 

<configuration>  

    <runtime>

        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">

     

            <probing privatePath="bin"/>

 

        </assemblyBinding>

    </runtime>

</configuration>

 

How Do I...Create an assembly with a strong name?

Assemblies can be assigned a cryptographic signature, called a strong name, which provides name uniqueness for the assembly and prevents someone from taking over the name of your assembly (name spoofing). If you are deploying an assembly that will be shared among many applications on the same machine, it must have a strong name. Even if you only use the assembly within your application, using a strong name ensures that the correct version of the assembly gets loaded

 

The first step in building an assembly with a strong name is to obtain a cryptographic key pair. The .NET Framework SDK includes a Strong Name tool (Sn.exe) that can be used to generate a key pair. The key pair that is generated by the Strong Name tool can be kept in a file or you can store it in your local machine's Crytographic Service Provider (CSP). The following command uses the Strong Name tool to generate a new key pair and store it in a file called TestKey.snk:

 

c:\> SN -k TestKey.snk

 

 

c:\> SN -tp TestKey.snk

 

Once you have obtained the key pair, you need to add the proper custom attribute to your source in order for the compiler to emit the assembly with a strong name. Choosing the correct attribute depends on whether the key pair used for the signing is contained in a file or in a key container within the CSP. For keys stored in a file, use System.Reflection.AssemblyKeyFileAttribute. For keys stored in the CSP use System.Reflection.AssemblyKeyNameAttribute

 

The following example uses AssemblyKeyFileAttribute to specify the name of the file containing the key pair.

 

using System;

using System.Reflection;

 

[assembly : AssemblyKeyFile("TestKey.snk ")]

 

namespace MathLibrary

{

          public class CMath

          {

                   public long AddFun(long x,long y)

                   {

                             Console.WriteLine("Addfun");

                             return x + y;

                   }

                   public long SubFun(long x,long y)

                   {

                             Console.WriteLine("AubFun");

                             return x - y;

                   }

          }

}

 

 

How to add assembly into the global assembly cache ?

 

The global assembly cache is a machine-wide store used to hold assemblies that are intended to be shared by several applications on the machine. The .NET Framework provides two tools for working with the cache. One is a Windows shell extension that allows you to work with the cache using a Graphical User Interface (GUI). The other is a command line tool, called the Global Assembly tool (Gacutil.exe), that is typically used in build and test scripts. The command line tool is called the Global Assembly Cache tool (Gacutil.exe).

 

All assemblies in the global cache must have strong names.

Viewing the Contents of the Assembly Cache

Navigate to %winnt%\assembly using the Windows Explorer to activate the shell extension. The default view shows the contents of the assembly cache. You can also view the contents of the cache with the /l option of the Global Assembly Cache tool:

 

gacutil /l

 

Installing Assemblies

To install an assembly using the shell extension simply drag and drop the file containing the assembly's manifest into the global assembly cache directory. To install an assembly using the Global Assembly Cache tool, use the /i option:

 

gacutil /i math.dll

 

Uninstalling Assemblies

To delete an assembly with the shell extension, right click on it and select Delete. The /u option of the Global Assembly Cache tool can also be used:

 

gacutil /u math,ver=1.0.0.0

 

The version of Windows Installer (1.5) that will ship in the Visual Studio .NET timeframe has native support for the assembly cache. When creating an Installer package with the Visual Studio Deployment tool or another setup tool, you can specify which assemblies you'd like installed in the cache. Using the Windows Installer to work with the assembly cache gives you the standard Installer benefits like install-on-demand, advertisement, publishing, and so on.

 

 

using System;

using MathLibrary;

 

class CMain

{

          public static void Main(string[] args)

          {

                   long x = long.Parse(args[0]);

                   long y = long.Parse(args[1]);

 

                   CMath obj = new CMath();

                  

                   long ans = obj.AddFun(x,y);

                  

          Console.WriteLine(" {0} + {1} = {2} ", x,y,ans);

          }

}

 

How to create a Delay signed shared assembly ?

 

Giving an assembly a strong name requires two cryptographic keys: a public key and a private key. This key pair is passed to the compiler at build time. However, the person building the assembly does not always have access to the private key required for strong naming. This is most common in corporations that have a central signing entity closely guards private keys. Only a few select people have access to these keys. Also, the process of assigning a strong name cannot be done after building because the public key is part of the assembly's identity and must be supplied at build time so that clients of the assembly can compile against the full assembly identity.

 

·         1. Creates a key-pair using sn -K.

·         2. Separates the public key from the private key and stores the public key in its own file.

·         3. Creates a delay signed assembly in either Visual Basic or C#.

·         4. Uses the Strong Name tool to request that signature verification be skipped for the assembly just generated.

·         5. Generates a valid signature using the Strong Name tool. This typically happens just before you ship the assembly.

 

The .NET Framework offers delay signing, which effectively splits the process of assigning the strong name into two steps:

·         1. At build time, the public key is given to the compiler so it can be recorded in the PublicKey field in the assembly manifest. Also, space is reserved in the file for the signature, although the actual signature is not generated at this time.

·         2. At a later time, the the actual signature is generated and stored in the file. Signature generation is done with the -R switch to the Strong Named tool (Sn.exe).

 

When you include the System.Reflection.AssemblyDelaySignAttribute in your source code, it indicates to the compiler that the assembly needs to be created with delay signing. You also need to include the public key, using AssemblyKeyFileAttribute. Typically, the signing entity will use the SN -k to generate a key pair and store it in a file. Next, it pulls the public key out of the file using SN -p. The public key can then be given out, with the private key still secret.

 

sn -k Testkey.snk

sn -p Testkey.snk TestPublicKey.snk

 

The following example uses AssemblyKeyFileAttribute and AssemblyDelaySignAttribute to create a delay signed assembly.

 

using System;

using System.Reflection;

 

[assembly:AssemblyKeyFileAttribute("TestPublicKey.snk")]

[assembly:AssemblyDelaySignAttribute(true)]

 

 

Since the assembly in the example does not have a valid signature, the signature validation performed by the common language runtime will fail when you try to install the assembly into the global assembly cache or load it from an application directory. However, the Strong Name tool can be used to disable signature verification of a particular assembly by using the -Vr option:

 

sn -Vr DelaySign.dll

 

A valid signature must be generated before the assembly is shipped to customers using sn -R. This is typically done by the company signing entity. You must supply the full key pair to create a valid signature.

 

sn -R DelaySign.dll Testkey.snk

 

To create and sign an assembly with a strong name using the Assembly Linker

 

At the command prompt, type the following command:

 

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.

 

The following example signs the assembly MyAssembly.dll with a strong name using the key file sgKey.snk.

 

al /out:MyAssembly.dll MyModule.netmodule /keyfile:sgKey.snk

 

 

How to Use Assembly Version Policy?

A primary goal of the deployment system in the .NET Framework is to eliminate conflicts between applications caused by shared components and shared states (or DLL conflicts). A key solution to this problem is a robust versioning system. The .NET Framework records information about an application's dependencies in the assembly manifest. This dependency information includes a version number that is used at runtime to load the proper version of a dependency.

 

 

By default, the common language runtime will load the version of a dependency that is specified in the manifest. This is preferred in the majority of scenarios. However, there are cases where running an application with a different version of a dependency can be useful. In order to accomplish this, version policies can be included in an application's configuration file. For example, the following XML code fragment redirects references to version 5.0.0.0 of a shared assembly called "caclR" up to version 6.0.0.0 of that assembly:

 

 

<configuration>  

    <runtime>

        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">

 

 

            <dependentAssembly>

                <assemblyIdentity name="calcR"

                                  publicKeyToken="a1690a5ea44bab32"

                                  culture=""/>

             

               

                <bindingRedirect oldVersion="5.0.0.0"

                                 newVersion="6.0.0.0"/>

 

 

            </dependentAssembly>

        </assemblyBinding>

    </runtime>

</configuration>

 

 

How to Create a Publisher Policy Assembly?

A Publisher policy statement describes the compatibility of an assembly issued by the publisher of that shared assembly. Publisher policy is commonly used in service pack scenarios. For example, a publisher may produce a number of small releases that enhances certain features for a particular customer. For maintenance reasons, the publisher may wish to collect all of these fixes into a single service pack release and have all exsiting customers upgrade to the new service pack.

 

A publisher policy statement is an XML configuration file wrapped as a separate assembly. There are three reasons that publisher policies are shipped as assemblies. The first is to ensure that the policy statement comes from the author of the assembly that the policy is making the compatibility statement about. This is accomplished by requiring that the policy assembly has a strong name generated with the same key-pair as the original assembly. The second reason is ease of deployment. Publishers or administrators can ship policy statements using the assembly deployment mechansims provided by the .NET Framework, including the Windows Installer and code download. Using the Windows Installer is particularly convenient because all policy assemblies must be installed in the global assembly cache. Finally, assemblies ship policy statements so that they can be versioned. This allows a publisher to ship a subsequent statement if a previous policy is found not to work in some scenarios. In effect, this allows a publisher to change his mind about the compatibility of his assembly independent of when it was shipped. The flexibility enabled by decoupling the compatibility statements from the code makes it much easier to fix broken applications in the .NET Framework. If multiple versions of a given policy assembly are found in the assembly cache, the .NET Framework will use the policy assembly with the highest version number.

 

In general, there are two steps required to create a publisher policy assembly:

·         1. Create the XML file containing the compatibility statement. You will have to use an XML editor to create this file.

·         2. Use the Assembly Generation tool (Al.exe) to create an assembly containing the XML file.

 

The format of the xml file, along with rules about how the elements relate, is described in detail in the .NET Framework SDK Guide. Here is an example file:

 

<configuration>

    <runtime>

        <assemblyBinding>

 

            <dependentAssembly>

                <assemblyIdentity name="myasm"

                                  publicKeyToken="e9b4c4996039ede8"

                                  culture="en-us"/>

 

                <bindingRedirect oldVersion="1.0.0.0-1.0.9.9"

                                 newVersion="2.0.0.0"/>

 

                <codeBase version="2.0.0.0"

                          href="http://www.foo.com/bar.dll"/>

            </dependentAssembly>

        </assemblyBinding>

    </runtime>

</configuration>

 

After the xml file is created, use the Assembly Generation tool to create a policy assembly. The following switches to the Assembly Generation tool are required:

 

1.      /link: links the xml file into the assembly.

2.      /out: gives the resulting policy assembly a name. Policy assemblies are found in the global assembly cache by naming convention. Therefore, their names must be:

policy.<major number>.<minor number>.<main assembly name>

For example, policy.2.0.myasm

3.      /keyfile: The key pair used to give the assembly a strong name (or at least the public key if delay signing is used). As described earlier, this key pair must be the same key pair used to sign the assembly to which this policy statement applies.

4.      /version: The version number of the policy assembly.

 

The following example shows a command line that uses the Assembly Generation tool:

 

Al /link:publisher.cfg /out:policy.2.0.myasm /keyfile:myasm.snk /version:2.0.0.0

 

 

In addition to policies specified at the application level, the .NET Framework also provides two other policy levels: publisher and administrator. A Publisher policy statement describes the compatibility of an assembly issued by the publisher of that shared assembly. Administrator policy is created using the same XML syntax as application level policy. The administrator policy file is called machine.config, and resides in the common language runtime install directory. The three policy levels are evaluated in the following order:

 

·         Application Policy

·         Publisher Policy

·         Administrator Policy

 

 

 

How Do I...Get the types in an assembly?

 

using System; Once you have an object reference to the assembly of interest, you can call the GetTypes method on that assembly, which returns an array of all the types in that assembly. You can use control logic to identify the more specific types in that array, and use iterating logic to parse your array, returning the type information to the user if needed. The ability to retrieve type information can be useful for determining alternative types you could use for a given task, or identifying existing elements which could provide you with the functionality you need.

 

The first thing to learn when retrieving types from a particular assembly is, how to identify an assembly.The first is by identifying a particular object that you want to find the assembly of, and requesting the assembly for the module of that object (remember that a module is a logical grouping of types and code, such as a .dll or .exe). The second is by using the LoadFrom method of the Assembly class to load a specific assembly for a named module (such as myapp.exe).

 

using System.Reflection;

 

class CMain

{

          static void Main(string[] args)

          {

                   //step 1 load an assembly

                   Assembly asm = Assembly.LoadFrom("c:\\dotnet\\MathLibrary.dll");

 

                   //step 2 get the modules

                   Module[] modules = asm.GetModules();

 

                   foreach(Module mod in modules)

                   {

                             Console.WriteLine("module {0}", mod.Name); 

 

                             //step 3 get types

                             Type[] types = mod.GetTypes();

 

                             foreach(Type t in types)

                             {

                                      Console.WriteLine("Type {0}", t.Name); 

 

                                      //step 4 get methods

                                      MethodInfo[] methods = t.GetMethods();

 

                                      foreach(MethodInfo method in methods)

                                      {

                                       Console.WriteLine("method : {0} ",method.Name); 

                                      }

 

                                      FieldInfo[] fields = t.GetFields();

 

                                      foreach(FieldInfo field in fields)

                                      {

                                      Console.WriteLine("field : {0} ",field.Name);

                                      }

                             }

                   }

 

          }

}

 

How Do I...Create a assembly On the fly?

 

using System;

using System.Reflection;

using System.Reflection.Emit;

 

class CMain

{

          static void Main(string[] args)

          {

                   //step 0 get domain ref in which asm will be created

                   AppDomain domain = AppDomain.CurrentDomain;

 

                   //step 1 create a name for the asm

                   AssemblyName asmname = new AssemblyName();

                   asmname.Name = "MyFirstAssembly";

 

                   //step 2 build a asm

AssemblyBuilder asmbuilder =

domain.DefineDynamicAssembly(asmname,AssemblyBuilderAccess.Save); 

                  

//step 3 build a module

                   ModuleBuilder modbuilder =

asmbuilder.DefineDynamicModule("mymodule","mymodule.netmodule");

 

                   //step 4 create a type

                   TypeBuilder typebuilder =

modbuilder.DefineType("CA",TypeAttributes.Public); 

 

                   //step 5 create a field

                   FieldBuilder field1 = typebuilder.DefineField

          ("empno", Type.GetType("System.String"),FieldAttributes.Private);  

 

                   //step 6 create a method

                   MethodBuilder method1 = typebuilder.DefineMethod

                                      ("fun",MethodAttributes.Public,null,new Type[]{});

 

                   //step 7 write code in the method

                   ILGenerator il = method1.GetILGenerator();

 

          il.Emit(OpCodes.Ret);

 

                   //step 8 save

                   typebuilder.CreateType();

                   asmbuilder.Save("myasm.dll");

                   }

          }

}

 

 

 

 

How Do I...Invoke methods?

 

In many coding scenarios, you know the task that you want to carry out before you want to do it. Therefore, you can specify the methods that you need to invoke, and the parameters you need to pass them. However, there are also situations where you might want to dynamically invoke methods, based upon specific scenarios, or user actions. This capability is available through the Reflection namespace, by using the InvokeMember method on the Type object.

 

You can also take other actions, such as getting or setting the value of a specified property. These actions are available through the BindingFlags enumeration. The second parameter of InvokeMethod is a combination of the BindingFlags actions you specify. For example, if you want to invoke a static method on a class, you would include the static element in BindingFlags, and the InvokeMethod BindingFlag. The following example demonstrates how to invoke a hypothetical method

 

 

// calling a static method, receiving no arguments

 

// don't forget that we are using object in the reflection namespace...

using System;

using System.Reflection;

 

public class Invoke {

 

public static void Main (String [] cmdargs) {

 

// Declare a type object, used to call our InvokeMember method...

Type t = typeof (TestClass);

 

// BindingFlags has three bitor'ed elements. Default indicates

// that default binding rules should be applied.

 

t.InvokeMember ("SayHello",

                BindingFlags.Default | BindingFlags.InvokeMethod

                | BindingFlags.Static, null,

                null, new object [] {});

        }

}

 

 

Take a quick look at the rest of the parameters that were passed to the Invoke method. The first null argument passed is requesting that the default binder be used to bind the method you are invoking. When you invoke the default binder, include the default BindingFlags. Instead of null as the third parameter, you can specify a Binder object that defines a set of properties and enables binding, which may involve selection of an overloaded method or coercion of argument types. The second null argument is the object on which to invoke the method you chose. Finally, pass an object array of the arguments that the member receives.

 

 

 

 

Named arguments

 

You can also use named arguments, in which case you need to use a different overloaded version of the InvokeMember method. Create the array of object arguments as you have been doing so far, and also create a string array of the names of the parameters being passed. The overloaded method you want to use accepts the list of parameter names as the last parameter, and the list of values you want to set as the fifth parameter

 

 

// Calling a method using named arguments

 

// the argument array, and the parameter name array.

// to determine the names of the parameters in advance

 

object[] argValues = new object [] {"Mouse", "Micky"};

String [] argNames = new String [] {"lastName", "firstName"};

 

 

t.InvokeMember ("PrintName",

                BindingFlags.Default | BindingFlags.InvokeMethod,

                null, null, argValues, null, null, argNames);

 

 

 

The final example uses a slightly different process to invoke a method. Rather than using the Type object directly, create a separate MethodInfo object directly to represent the method you will be invoking. Then, call the Invoke method on your MethodInfo object, passing an instance of the object you need to invoke your method on (if you are invoking an instance method, but null if your method is static). As before, an object array of the parameters is required.

 

// Invoking a ByRef member

MethodInfo m = t.GetMethod("Swap");

 

args = new object[2];

 

args[0] = 1; args[1] = 2;

 

m.Invoke(new TestClass(),args);

 

Console.WriteLine ("{0}, {1}", args[0], args[1]);

 

 

How do I Serialize using XmlSerializer

 

Serializes and deserializes objects into and from XML documents. The XmlSerializer enables you to control how objects are encoded into XML. XML serialization is the process of converting an object's public properties and fields to a serial format for storage or transport. Deserialization re-creates the object in its original state from the XML output. You can thus think of serialization as a way of saving the state of an object into a stream or buffer

 

 

 

using System;

using System.IO;

using System.Xml.Serialization;

 

public class Dept

{

          public long m_code;

private string m_name;

 

          public Dept(long code,string name)

          {

                   m_code = code; m_name = name;

          }

                  

          public void Display()

          {

          Console.WriteLine("dept code: {0}  name: {1} ",m_code,m_name);

          }

}

 

class CMain

{

         

          static void Main ()

          {

MainXmlSerialize();

MainXmlDeserialize();

 

}

 

          static void MainXmlDeserialize ()

          {

                   Dept obj;

 

                   //step 1 create        a serializer

                   XmlSerializer sr = new XmlSerializer(typeof(Dept));

         

                   //step 2 create a file

                   StreamReader file = new StreamReader("c:\\dotnet\\abc.xml");

 

                   //step 3

                   obj = (Dept) sr.Deserialize(file);

 

                   //step 4 close the file

                   file.Close();

 

                   obj.Display();

          }

                  

          static void MainXmlSerialize ()

          {

                   Dept obj = new Dept (101,"Purchase");

 

                   //step 1 create        a serializer

                   XmlSerializer sr = new XmlSerializer(obj.GetType());

         

                   //step 2 create a file

                   StreamWriter file = new StreamWriter("c:\\dotnet\\abc.xml");

 

                   //step 3 serialize

                   sr.Serialize(file,obj);

 

                   //step 4 close the file

                   file.Close();

          }

}

 

 

How do I Serialize using SoapSerializer

 

using System;

using System.IO;

using System.Runtime.Serialization.Formatters.Soap;    

 

[Serializable]

public class Dept

{

          public long m_code;

private string m_name;

 

          public Dept(long code,string name)

          {

                   m_code = code; m_name = name;

          }

                  

          public void Display()

          {

          Console.WriteLine("dept code: {0}  name: {1} ",m_code,m_name);

          }

}

 

class CMain

{

          static void MainSoapDeserialize()

          {

                   Dept obj;

 

                   //step 1 create        a serializer

                   SoapFormatter fm = new SoapFormatter();

 

                   //step 2 open a file

                   FileStream file = File.Open("c:\\dotnet\\abc.xml",FileMode.Open);

 

                   //step 3

                   obj = (Dept) fm.Deserialize(file);

                            

                   //step 4 close the file

                   file.Close();

                  

                   obj.Display();

          }

 

          static void MainSoapSerialize()

          {

                   Dept obj = new Emp(101,"Purchase");

 

                   //step 1 create        a serializer

                   SoapFormatter fm = new SoapFormatter();

 

                   //step 2 create a file

                   FileStream file = File.Create("c:\\dotnet\\abc.xml");

 

                   //step 3

                   fm.Serialize(file,obj);

                            

                   //step 4 close the file

                   file.Close();

          }

 

}

 

 

How do I Serialize using BinarSerializer

 

using System;

using System.IO;

using System.Runtime.Serialization.Formatters.Soap;    

 

 

[Serializable]

public class Dept

{

          public long m_code;

private string m_name;

 

          public Dept(long code,string name)

          {

                   m_code = code; m_name = name;

          }

                  

          public void Display()

          {

          Console.WriteLine("dept code: {0}  name: {1} ",m_code,m_name);

          }

}

         

class CMain

{

          static void Main()

          {

          }

 

          static void MainSoapDeserialize()

          {

                   Dept obj;

 

                   //step 1 create        a serializer

                   BinaryFormatter fm = new BinaryFormatter();

 

                   //step 2 open a file

                   FileStream file = File.Open("c:\\dotnet\\abc.xml",FileMode.Open);

 

                   //step 3

                   obj = (Dept) fm.Deserialize(file);

                            

                   //step 4 close the file

                   file.Close();

                  

                   obj.Display();

          }

 

          static void MainBinarySerialize()

          {

                   Dept obj = new Dept (10,"jack",101,"Purchase");

 

                   //step 1 create        a serializer

                   BinaryFormatter fm = new BinaryFormatter();

 

                   //step 2 create a file

                   FileStream file = File.Create("c:\\dotnet\\abc.dat");

 

                   //step 3

                   fm.Serialize(file,obj);

                            

                   //step 4 close the file

                   file.Close();

          }

}

 

 

Domain

 

Historically, process boundaries have been used to isolate applications running on the same computer. Each application is loaded into a separate process, which isolates the application from other applications running on the same computer.

 

The applications are isolated because memory addresses are process-relative; a memory pointer passed from one process to another cannot be used in any meaningful way in the target process. In addition, you cannot make direct calls between two processes. Instead, you must use proxies, which provide a level of indirection.

 

Managed code must be passed through a verification process before it can be run. The verification process determines whether the code can attempt to access invalid memory addresses or perform some other action that could cause the process in which it is running to fail to operate properly. Code that passes the verification test is said to be type-safe. The ability to verify code as type-safe enables the common language runtime to provide as great a level of isolation as the process boundary, at a much lower performance cost.

 

Application domains provide a secure and versatile unit of processing that the common language runtime can use to provide isolation between applications. You can run several application domains in a single process with the same level of isolation that would exist in separate processes, but without incurring the additional overhead of making cross-process calls or switching between processes. The ability to run multiple applications within a single process dramatically increases server scalability.

 

Isolating applications is also important for application security. For example, you can run controls from several Web applications in a single browser process in such a way that the controls cannot access each other's data and resources.

The isolation provided by application domains has the following benefits:

·         Faults in one application cannot affect other applications. Because type-safe code cannot cause memory faults, using application domains ensures that code running in one domain cannot affect other applications in the process.

·         Individual applications can be stopped without stopping the entire process. Using application domains enables you to unload the code running in a single application.

Note You cannot unload individual assemblies or types. Only a complete domain can be unloaded.

·         Code running in one application cannot directly access code or resources from another application. The common language runtime enforces this isolation by preventing direct calls between objects in different application domains. Objects that pass between domains are either copied or accessed by proxy.

·         The behavior of code is scoped by the application in which it runs. In other words, the application domain provides configuration settings such as application version policies, the location of any remote assemblies it accesses, and information about where to locate assemblies that are loaded into the domain.

·         Permissions granted to code can be controlled by the application domain in which the code is running.

All objects created in a remote domain are returned by reference and have to derive from MarshallByRefObject. Objects passed as parameters to a remote method call can be forwarded by value or by reference. The default behavior is pass by value provided the object in question is marked by the custom attribute [serializable]. Additionally, the object could implement the ISerializable interface, which provides flexibility in how the object should be serialized and deserialized. Objects that are not marshal by reference or marshal by value cannot be accessed across domains.

using System;

using System.Runtime.Remoting;

 

namespace BULibrary

{

            [Serializable]

          public class CBank

          {

                   public CBank()

                   {

                             Console.WriteLine(AppDomain.CurrentDomain.FriendlyName);  

                   }

                   public void Credit()

                   {

                             Console.WriteLine(AppDomain.CurrentDomain.FriendlyName);  

                             Console.WriteLine("credit");

                   }

          }

 

          public class CBankEx : MarshalByRefObject

          {

                   CBank m_bank = new CBank();

 

                   public CBankEx()

                   {

                             Console.WriteLine(AppDomain.CurrentDomain.FriendlyName);  

                   }

                   public void Debit()

                   {

                             Console.WriteLine(AppDomain.CurrentDomain.FriendlyName);  

                             Console.WriteLine("debit");

                   }

                   public CBank GetBank()

                   {

                             return m_bank;

                   }

          }

}

 

While a common language runtime host creates application domains automatically when they are needed, you can create your own application domains and load into them assemblies you want to personally manage. You can also create application domains from which you execute code.You create a new application domain using one of the overloaded CreateDomain methods in the System.AppDomain class. You can give the application domain a name and reference it by that name.

using System;

using System.Reflection;

 

namespace TestinterDomain

{

          class Class1

          {

                   static void Main(string[] args)

                   {

                   //step 1 create a domain

                   AppDomain domain = AppDomain.CreateDomain("MyDomain");

 

 

                   //step 2 load the assembly in the new domain

                   //step 3 create a instance of CBajnk

                   //step 4 get a serialized object in current domain

object obj =domain.CreateInstanceAndUnwrap("BULibrary","BULibrary.CBankEx");

 

                   //step 5 get the type

                   Type t = obj.GetType();

 

                   //step 6 call the method

                   t.InvokeMember("Debit",BindingFlags.InvokeMethod,null, obj, null);

 

                   //step 7 unload the domain

                   AppDomain.Unload(domain);

                   }

          }

}

 

 

 

 

 

 

 

 

 

 

Satellite Assembly

 

One time in .NET that you need to know about satellite assemblies is when you are dealing with localization. For localizing text, one doesn't hard code text on a page, but uses a key for that text. The text equivalent for the key is retrieved from a file called a resource file. A resource file is essentially a dictionary of associations between the keys and their textual values. You will have this resource file duplicated once for each language that you support. .NET will retrieve values from these multiple language-resource files based on the chosen language context.

 

 

String.txt

 

name=jack

key=value

 

Step 1: Use resgen to create a .resources file from a .resx file.

 

Resgen MyText.resx

The above command will create a file called:

 

MyText.resources

Step 2: Use al.exe to create the satellite assembly:

 

Al.exe

     /t:lib

     /embed:MyText.en-gb.Resources,MyApplication.MyText.en-gb.Resources

     /culture:hi-gb

     /out:MyApplication.resources.dll

There are a couple of things worth noting here:

/t:lib: Says you are interested in a .dll.

/embed:MyText.en-gb.Resources,MyApplication.MyText.en-gb.Resources : Embeds and renames the resource to a target name to match the Visual Studio IDE naming structure.

/culture:hi-gb : Identifies the culture in which you are interested.

/out:MyApplication.resources.dll : Name of the DLL in which you are interested.

The generated .dll has to have that naming convention for .NET to find it. Also notice that you have to specify the culture setting, even though the culture is available in the name of the resource files. So it has to be mentioned in both places.

 

Place the Satellite Assembly in the Appropriate Directory

Once the satellite assembly is created, physically copy the .dll to the following directory:

 

\MyApplication\bin\en-gb\MyApplication.Resources.DLL

 

 

 

 

c:/> resgen string.txt

 

c:/> al /t:library /embed:string.resource /out:string.resource.dll

 

 

 

using System;

using System.Resources;

 

namespace testResource

{

          class CMain

          {

                   static void Main(string[] args)

                   {

ResourceManager rm =

ResourceManager.CreateFileBasedResourceManager("mystring","c:\\dotnet",null);

 

                   Console.WriteLine(rm.GetString("name")); 

                   }

          }

}

 

 

Place the Satellite Assembly in the Appropriate Directory

Once the satellite assembly is created, physically copy the .dll to the following directory:

 

\MyApplication\bin\en-gb\MyApplication.Resources.DLL

This would have been identical if Visual Studio IDE had generated this file. Repeat this process for each languagein which you are interested.

 

Regards,

Sasikumar




----------------------------------------------------------------DISCLAIMER---------------------------------------------------------
Information transmitted by this EMAIL is proprietary to iGATE Group of Companies and is intended for use only by the individual 
or entity to whom it is addressed and may contain information that is privileged, confidential, or exempt from disclosure under 
applicable law. If you are not the intended recipient of this EMAIL immediately notify the sender at iGATE or mailadmin@igate.com 
and delete this EMAIL including any attachments