This is default featured post 1 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured post 2 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured post 3 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured post 4 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured post 5 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

Showing posts with label .net traning. Show all posts
Showing posts with label .net traning. Show all posts

UN Mannaged Code

At the time .NET Framework is firstly introduced by Microsoft, the concept of managed code and unmanaged code as two different programming models is introduced as well.
Microsoft defines that managed code is the code generated by the .NET Framework and could be executed by the common language runtime (CLR). At the other hand the unmanaged code is any other code that doesn't match the pervious definition. As a result, all the code created and generated before the .NET Framework is released considered unmanaged code. This unmanaged code contains WIN32 APIs, valuable external libraries, COM components, and COM+ services, and all of these are so useful and important.

The dilemma now is: the .NET Framework which is the current development environment only accepts managed code. We have already made valuable libraries and components but all are unmanaged code. We need to use this valuable unmanaged code while we are working under the .NET Framework environment. What is the solution of this dilemma ???

To solve this problem and for backward compatibility Microsoft fires another concept and calls it "Interoperating with unmanaged code". Which is how to call or use unmanaged code form within managed code and vice versa. Then it divided this process into two categories which are:

  1. - How to call WIN APIs and DLLs (unmanaged code) form within the .NET Framework (managed code) using the Platform Invoke (PInvoke) technique.
  2. - How to use COM components (unmanaged code) from within the .NET Framework (managed code) using the COM Interop technique.

The first item in the pervious list is the subject of this tutorial. We will try to highlight the main differences between unmanaged and managed code. Then we will create an example showing how to call unmanaged DLL function from within the .NET Framework managed code using the platform invoke technique.

To download the example created in this tutorial just click here.

Dissimilarities Between managed and unmanaged Programming Models

Managed and unmanaged programming models are dissimilar in many aspects. The following paragraphs highlight some of those aspects with a brief description about each of them.

Type definition or information is mandatory for all types in the managed programming model while it is optional for only public types in the unmanaged programming model. Managed model use metadata for type definition while unmanaged model use type libraries. Interoperating services tools convert type libraries to metadata in assemblies and metadata to type libraries to overcome the interoperation process.

Type safety is highly achieved in managed code rather than unmanaged code. The unmanaged programming model is not type safe while the managed one is optionally type safe. In unmanaged model compilers provide no type checking on pointer types which may lead to potentially harmful activity. You can still use pointers in managed code but this will put restrictions on that code due to its unsafe behavior. It will be marked as untrusted code. Interoperation services prevent untrusted managed code form accessing unmanaged code.

Type compatibility is not achieved between managed and unmanaged code. Types differ between the two models and also among different programming languages.

Coding models are differ. The unmanaged objects always communicate via interfaces, while managed objects can pass data directly without implementing interfaces. Interoperating services especially COM interop generates interfaces to the managed objects to expose their functionalities to COM objects.

Identity used in unmanaged model is GUID, while managed model uses strong names. Unmanaged model uses the GUID to identify a specific type. Managed model uses strong name consists of a unique assembly name and a type name for the same purpose. Interoperating services generate GUIDs and strong names as required.

Error handling mechanism in managed code is exceptions. COM methods return an HRESULT as a result to indicate wither the call succeeded or failed. COM interop maps managed exceptions to failure HRESULT.

Consuming Unmanaged DLL Functions Using PInvoke:

Consuming unmanaged DLL function means that we need to call a function located in an unmanaged DLL library from with in the .Net framework. Platform invoke or PInvoke is the technique used to make this happens. When Platform invoke calls an unmanaged function it firstly locates the DLL containing the function and then loads it into memory. It searches for the function in memory and locates its memory address. After that it pushes the function artuments in to the stake and marshaling data as required. Finally the control is transferred tot he unmanaged function. Platform invoke throws exeception generated by the unmanaged function to the managed caller.

To call a specific function within a specific DLL you have to follow the following steps:

  1. - First you have to locate this DLL, know its name, and know the function name you need to call.
  2. - After that you have to create a class to hold that DLL function. You can use an existing class, create a new class for each DLL function, or collect related DLL functions in one class.
  3. - After creating the class (or module in Visual Basic) you have to create a new managed prototype for that unmanaged function declared inside the created class.
  4. - Finally you are ready to call that DLL function from within your application.

Let us create a real example to examine the above four steps in more details.

PInvoke Example:

This example aims to call an unmanaged DLL function exists in the WIN32 APIs library from within a new created Visual Basic application. We will use the Visual Studio 2005 as the development environment for our example. So, open up your Visual Studio 2005 and create a new Visual Basic project. Add a new class for your project and name it "Unmanged". At the top of the class file add the following imports statement to import the interoperating services capabilities to our class.

	Imports System.Runtime.InteropServices

Now to step1.

Function and DLL identification

There are three commonly used WIN32 APIs "GDI32.dll" for graphics device interface (GDI), "Kernel32.dll" for low level operating system functions, and "User32.dll" for windows management functions for message handling, menus, timers, and communications. Of course you are free to make use of any other APIs. You will find them in the "System32" directory under your windows directory.

For our example we will select the "User32.dll", so the DLL name is now identified. What about the function?, we have to know functions inside that DLL to select from. Many tools both command line and visual are existed to do this task, among them we prefer the visual tool shipped with the Visual Studio 2005 and called Microsoft dependancy walker "Depends.exe". You can run this tool from "\Common7\Tools\Bin" directory under your Visual Studio directory. The following figure shows this tool opening the "User32.dll" library in its left pane, while the right pane listing all functions located in this library.

PInvoke-Dependency-Walker.jpg
Figure 1 - Depends.exe" tool lists the functions located at the "User32.dll" library

As the above figure implies we choose the "MessageBox" function. WIN32 APIs may contain two versions for each function that handles characters and strings. One for the ANSI version (MessageBoxA), and the other for the Unicode version (MessageBoxW). By choosing the "MessageBox" as our function the identification process is completed.

Create a class to hold the DLL function

We already made this step when we add a new class to our created project and called it "Unmanged". This process is called wrapping. Wrapping the unmanaged DLL functions in a managed class allows the platform invoke to handle the underlying exported functions automatically. You have to define a static method for each DLL function you want to call.

Create prototypes in managed code

In this step we will define the function prototype under our class using managed model rather than the unmanaged definition exists at the DLL library. To get the unmanaged prototype of the "MessageBox" function, search the MSDN library under the "win32 and COM development" section, or enter the function name in he search box then filter the result to the "Windows platform" section only. The unmanaged prototype of the "MessageBox" function is as followes.

int MessageBox(HWND hWnd,
    LPCTSTR lpText,
    LPCTSTR lpCaption,
    UINT uType
  );

To set the new managed declaration in our new visual basic project we will use the "Declare" statement to define the function and the "Lib" keyword to identify its library name as in the following line of code.

    Declare Auto Function MessageBox Lib "User32.dll"

The "Auto" keyword is set to let the target platform determines the suitable character width (ANSI or Unicode).

Now to complete the declaration process you need to convert the unmanaged types of the function parameters to their managed counterparts. MSDN library provides a table that resolve each WIN32 API type into its managed type. You can get this table from the following link http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconplatforminvokedatatypes.asp

Now convert each unmanaged type into its managed counterpart using the above table.

Public Class Unmanged
 
    Declare Auto Function MessageBox Lib "User32.dll" _
     (ByVal Hwnd As Integer, ByVal Text As String, _
     ByVal Caption As String, ByVal Type As Integer) _
        As Integer
 
End Class

That's it. The DLL function now is ready to be called from within the current project.

Calling the DLL function

To examine the DLL function we will call it from within the "Form1" class as following.

Public Class Form1
    Private Sub Form1_Load(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles MyBase.Load
 
        Unmanged.MessageBox(0, "Hello every one", _
         "PInvoke Example", 0)
 
    End Sub
End Class

Now run the program and get the results.

PInvoke-Example.jpg
Figure 2 - The unmanaged "MessageBox" function called from within a managed code

As figure2 implies, the function is called and a message box with the caption and text input parameters is displayed.
 
To download the example created in this tutorial just click here.

Using SQL Server to maintain session state


Maintaining data between server calls is a common dilemma in Web development. You may need to maintain information for the application or for particular user sessions. Storing such data is called state management, and ASP.NET provides the means to accomplish the task via various avenues. This includes storing the data in memory, on a state server, or via Microsoft SQL Server. This article focuses on session state management (user session data) using SQL Server.

Why is state management necessary?
Before we dive into SQL Server setup and usage, you may wonder why it's necessary. One of the more distressing aspects of Web development is the fact that HTTP is a stateless protocol. It works in a disconnected fashion with each Web request serviced as it's received. After the request is processed, all of the data utilised is discarded. The server doesn't remember anything between calls. That is, it doesn't remember unless it has explicit instructions to do so.

Session variables
Session variables are utilised with the following format:

C#: Session["variable_name"] = value;
VB.NET: Session("variable_name") = value

Once this value is stored, it's available throughout the user's session. The variable is discarded when the session ends. You may circumvent the discarding of the value by utilising persistent state management (which is a topic for another day).

ASP.NET state management
ASP.NET allows you to store session data in memory, via a state server, or in SQL Server. The determination of the storage location is the application's Web.config file. The sessionState element within the system.web element is where the state management option is configured. The following example shows SQL Server utilised:

<sessionState
mode="SQLServer"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;user id=username;password=password"
cookieless="false"
timeout="20" />

Remember that the element names and attributes are case-sensitive. The following are possible values for the mode attribute:

  • InProc--store in memory. This is the fastest for performance, but all data is lost when the ASP.NET process recycles.
  • SQLServer--store data on SQL Server. This is the most reliable since it's disconnected from the Web server. This option uses the sqlConnectionString option. The connection string follows the normal syntax for connecting to a SQL Server database.
  • StateServer--store data on a separate Web server (IIS). This option uses the stateConnectionString attribute.

All options use the remaining. The cookieless attributes signal whether cookies are stored in memory (false) or maintained in the QueryString/URL (true). The timeout attribute signals the length of time (without activity) that session variables are stored. Now let's turn our attention to SQL Server setup.

SQL Server setup
SQL Server requires a special database to handle state management. Thankfully, the .NET Framework installation includes the necessary files to get this up and running in no time. The following scripts are installed:

  • InstallPersistSqlState.sql--contains scripts to set up database for persistent state management
  • InstallSqlState.sql--Contains scripts to set up database for state management
  • UninstallPersistSqlState.sql--Contains scripts for uninstalling persistent state management
  • UninstallSqlState.sql--Contains scripts for uninstalling state management

These scripts may be run from Query Analyzer or via the isql.exe command-line utility. To set up state management, we run InstallSqlState.sql. The result of the script is the creation of a database named ASPState. This handles the storage and maintaining of session variables. You can easily test the functionality with a simple example.

The following C# sample includes one Web form that populates session variables and redirects to another Web form that displays the values:

<%@ Page language="c#" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML><HEAD>
<title>WebForm1</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
</HEAD>
<body MS_POSITIONING="GridLayout">
<script language="C#" runat="server">
private void Page_Load(object sender, System.EventArgs e) {
Session["FirstName"] = "Tony";
Session["LastName"] = "Patton";
Session["Site"] = "Builder.com";
Response.Redirect("WebForm2.aspx", true);
}
</script></body></HTML>

Here's the second Web form:

<%@ Page language="c#" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML><HEAD><title>WebForm2</title></HEAD>
<body>
<script language="C#" runat="server">
private readonly string newLine = "<br>";
private void Page_Load(object sender, System.EventArgs e) {
Response.Write(Session["FirstName"].ToString() + " ");
Response.Write(Session["LastName"].ToString() + newLine);
Response.Write(Session["Site"].ToString() + newLine);
}
</script></body></HTML>

If you're a VB.NET developer, the pages have the following format:

<%@ Page Language="vb" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html><head>
<title>WebForm1</title></head><body>
<script language="vb" runat="server">
Private Sub Page_Load(sender As Object, e As System.EventArgs)
Session("FirstName") = "Tony"
Session("LastName") = "Patton"
Session("Site") = "Builder.com"
Response.Redirect("WebForm2.aspx", true)
End Sub
</script></body></html>

Here's the Page_Load event on the second form:

<%@ Page Language="vb" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html><head>
<title>WebForm2</title></head><body>
<script language="vb" runat="server">
Private ReadOnly newLine As String = "<br>"
Private Sub Page_Load(sender As Object, e As System.EventArgs)
Response.Write(Session("FirstName").ToString() + " ")
Response.Write(Session("LastName").ToString() + newLine)
Response.Write(Session("Site").ToString() + newLine)
End Sub
</script></body></html> 

One note on uninstalling the state management feature: Microsoft recommends stopping the World Wide Web Publishing service before executing the uninstall script. You can accomplish this with the net stop w3svc command from a command line. You can restart it with net start w3svc.

You can easily see the session management feature in action by examining the tempdb database on the SQL Server. It will contain two temporary tables used for session management: ASPStateTempApplications and ASPStateTempSessions.

A viable option
SQL Server provides an alternative if you worry about losing session state data due to Web server downtime. There is a performance hit since database interaction is involved, but it's the most reliable method available.
 
 
--By Tony Patton

difference between const and static readonly

The difference is that the value of a static readonly field is set at run time, and can thus be modified by the containing class, whereas the value of a const field is set to a compile time constant.

In the static readonly case, the containing class is allowed to modify it only

  • in the variable declaration (through a variable initializer)
  • in the static constructor (instance constructors, if it's not static)

static readonly is typically used if the type of the field is not allowed in a const declaration, or when the value is not known at compile time.

Instance readonly fields are also allowed. 

Remember that for reference types, in both cases (static and instance) the readonly modifier only prevents you from assigning a new reference to the field.  It specifically does not make immutable the object pointed to by the reference.

    class Program

    {

        public static readonly Test test = new Test();

 

        static void Main(string[] args)

        {

            test.Name = "Program";

 

            test = new Test();  // Error:      A static readonly field cannot be assigned to (except in a static constructor or a variable initializer) 

 

        }

    }

 

    class Test

    {

        public string Name;

    }

 

On the other hand, if Test were a value type, then assignment to test.Name would be an error.

ASP.Net Interview Questions


1.

Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading process.
inetinfo.exe is theMicrosoft IIS server running, handling ASP.NET requests among other things.When an ASP.NET request is received (usually a file with .aspx extension),the ISAPI filter aspnet_isapi.dll takes care of it by passing the request tothe actual worker process aspnet_wp.exe.

2. What's the difference between Response.Write() andResponse.Output.Write()?

 The latter one allows you to write formattedoutput.

3. What methods are fired during the page load?
 
 Init() - when the pageis instantiated, Load() - when the page is loaded into server memory,PreRender() - the brief moment before the page is displayed to the user asHTML, Unload() - when page finishes loading.

4. Where does the Web page belong in the .NET Framework class hierarchy?

System.Web.UI.Page

5. Where do you store the information about the user's locale?

System.Web.UI.Page.Culture

6.
What's the difference between Codebehind="MyCode.aspx.cs" andSrc="MyCode.aspx.cs"?
 
 CodeBehind is relevant to Visual Studio.NET only.

7. What's a bubbled event?

 When you have a complex control, like DataGrid, writing an event processing routine for each object (cell, button, row, etc.) is quite tedious. The controls can bubble up their eventhandlers, allowing the main DataGrid event handler to take care of its onstituents.

8. Suppose you want a certain ASP.NET function executed on MouseOver overa certain button. Where do you add an event handler?
 
It's the Attributesproperty, the Add function inside that property. So btnSubmit.Attributes.Add("onMouseOver","someClientCode();")
 
9.
What data type does the RangeValidator control support?
 
 Integer,String and Date.

10. Explain the differences between Server-side and Client-side code?

Serverside code runs on the server. Client-side code runs in the clients' browser.
 
11. What type of code (server or client) is found in a Code-Behind class?

Server-side code.

12.
Should validation (did the user enter a real date) occur server-side or client-side? Why?
 
Client-side. This reduces an additional request to the server to validate the users input.

13. What does the "EnableViewState" property do? Why would I want it on or off?

It enables the viewstate on the page. It allows the page to save the users input on a form.

14. What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other?

Server.Transfer is used to post a form to another page. Response.Redirect is used to redirect the user to another page or site.

15. Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?

·

A DataSet can represent an entire relational database in memory, complete with tables, relations, and views.

·

A DataSet is designed to work without any continuing connection to the original data source.

·

Data in a DataSet is bulk-loaded, rather than being loaded on demand.
·
There's no concept of cursor types in a DataSet.
 
· DataSets have no current record pointer You can use For Each loops to move through the data.

·

You can store many edits in a DataSet, and write them to the original data source in a single operation.

·

Though the DataSet is universal, other objects in ADO.NET come in different versions for different data sources.
16.
Can you give an example of what might be best suited to place in the Application_Start and Session_Start       subroutines?
 
This is where you can set the specific variables for the Application and Session objects.

17. If I'm developing an application that must accommodate multiple security levels though secure login and my ASP.NET web application is spanned across three web-servers (using round-robin load balancing) what would bethe best approach to maintain login-in state for the users? Maintain the login

state security through a database.

18. Can you explain what inheritance is and an example of when you might use it?

When you want to inherit (use the functionality of) another class. Base Class Employee. A Manager class could be derived from the Employee base class.

19. Whats an assembly?

Assemblies are the building blocks of the .NET framework. Overview of assemblies from MSDN
 
20.
Describe the difference between inline and code behind.
 
Inline code written along side the html in a page. Code-behind is code written in a separate file and referenced by the .aspx page.

21. Explain what a diffgram is, and a good use for one?

The DiffGram is one of the two XML formats that you can use to render DataSet object contents to XML. For reading database data to an XML file to be sent to a Web Service.

22. Whats MSIL, and why should my developers need an appreciation of it if at all?

MSIL is the Microsoft Intermediate Language. All .NET compatible languages will get converted to MSIL.

23. Which method do you invoke on the DataAdapter control to load your generated dataset with data?

The .Fill() method

24. Can you edit data in the Repeater control?

No, it just reads the information from its data source

25. Which template must you provide, in order to display data in a Repeater control?

ItemTemplate

26. How can you provide an alternating color scheme in a Repeater control?

Use the AlternatingItemTemplate

27.

What property must you set, and what method must you call in your code, in order to bind the data from some data source to the Repeater control?

You must set the DataSource property and call the DataBind method.

28.
What base class do all Web Forms inherit from?
 
The Page class.

29. Name two properties common in every validation control?

ControlToValidate property and Text property.

30.
What tags do you need to add within the asp:datagrid tags to bind columns manually?
 
Set AutoGenerateColumns Property to false on the datagrid tag

31.

What tag do you use to add a hyperlink column to the DataGrid?

<asp:HyperLinkColumn>

32.
What is the transport protocol you use to call a Web service?
 
SOAP is the preferred protocol.

33. True or False: A Web service can only be written in .NET?

False

34. What does WSDL stand for?

(Web Services Description Language)

35. Where on the Internet would you look for Web services?

(

http://www.uddi.org)
36.
Which property on a Combo Box do you set with a column name, prior to setting the DataSource, to display data in the combo box?
 
DataTextField property

37. Which control would you use if you needed to make sure the values in two different controls matched?

CompareValidator Control

38. True or False: To test a Web service you must create a windows application or Web application to consume this service?

False, the webservice comes with a test page and it provides HTTP-GET method to test.
 
39.
How many classes can a single .NET DLL contain?
 
It can contain many classes.

Uploading Files using FileUpload control in Update Panel in ASP.Net AJAX

By default, FileUpload control will not work inside an UpdatePanel control for uploading files using Asynchronous postback. This is because, the file uploading and file manipulations is restricted by default in client side for security reasons. Hence it is not possible to upload files using asynchronous postback in UpdatePanel.

 

To upload files inside UpdatePanel control we need to rely upon a standard postback i.e. we need to set the button that is uploading the file to be PostBack trigger instead of AsyncPostBack trigger. This will initiate a normal postback whenever we click the upload button and it is possible to upload the file.

 

Refer the below code for clear understanding,

 

<asp:UpdatePanel ID="UpdatePanel1" runat="server">

            <ContentTemplate>              

                <asp:FileUpload ID="fuUpload" runat="server" />

                <asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Upload" />

            </ContentTemplate>

            <Triggers>

                <asp:PostBackTrigger ControlID="btnUpload" />               

            </Triggers>

        </asp:UpdatePanel>

 

 

 protected void btnUpload_Click(object sender, EventArgs e)

    {

        string filename = System.IO.Path.GetFileName(fuUpload.FileName);

        fuUpload.SaveAs("C:\temp" + filename);

    }

 

To simulate an AJAX file upload we can use iframes. In this approach, the page that is contained in the iframe will contain the FileUpload control and it will be posted with a normal postback to the server and hence provides a feeling like AJAX request. We will see about this in future code snippets.

events & workshops

.

Upcoming Events & Workshops Schedule

Event Name Event Type Date Venue URL to know more Agenda Presenter(s)
Hyderabad UG Event Free Community Event 12 Dec 2009 Saturday Microsoft Corporation (I) Pvt. Ltd.,
4th Floor, Usha Jubilee Town 36,
Plot No.8-2-293/82/A/1130/A,
Road No.36, Jubilee Hills,
Hyderabad 500 033
(near Chutney’s restaurant)

Click here

Maximizing Query Optimizer using Query & Table hints by Amit Bansal (MVP)

VS 2010 and ASP.NET 4.0 Features at a Glance by Hima Bindu Vejella (MVP)

Amit Bansal

Hima Bindu Vejell

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites