21 September, 2009

.Net Framework 3.0 FAQ

What is an operation contract?
An operation contract defines the parameters and return type of an operation. When creating an interface that defines the service contract, you signify an operation contract by applying the OperationContractAttribute attribute to each method definition that is part of the contract. The operations can be modeled as taking a single message and returning a single message, or as taking a set of types and returning a type. In the latter case, the system will determine the format for the messages that need to be exchanged for that operation.


What is a message contract?
A message contact describes the format of a message. For example, it declares whether message elements should go in headers versus the body, what level of security should be applied to what elements of the message, and so on.


What is a fault contract?
A fault contract can be associated with a service operation to denote errors that can be returned to the caller. An operation can have zero or more faults associated with it. These errors are SOAP faults that are modeled as exceptions in the programming model.


In Terms of WCF, what do you understand by metadata of a service
The metadata of a service describes the characteristics of the service that an external entity needs to understand to communicate with the service. Metadata can be consumed by the Service Model Metadata Utility Tool ( Svcutil.exe) to generate a WCF client and accompanying configuration that a client application can use to interact with the service.

The metadata exposed by the service includes XML schema documents, which define the data contract of the service, and WSDL documents, which describe the methods of the service.


What is password fatigue?
As the use of internet increases, as increases the danger of online identity theft, fraud, and privacy. Users must track a growing number of accounts and passwords. This burden results in "password fatigue," and that results in less secure practices, such as reusing the same account names and passwords at many sites.


What are activities in WWF?
Activities are the elemental unit of a workflow. They are added to a workflow programmatically in a manner similar to adding XML DOM child nodes to a root node. When all the activities in a given flow path are finished running, the workflow instance is completed.

An activity can perform a single action, such as writing a value to a database, or it can be a composite activity and consist of a set of activities. Activities have two types of behavior: runtime and design time. The runtime behavior specifies the actions upon execution. The design time behavior controls the appearance of the activity and its interaction while being displayed within the designer.

.Net Framework 3.0 FAQ

What is a service contract ( In WCF) ?
In every service oriented architecture, services share schemas and contracts, not classes and types. What this means is that you don't share class definitions neither any implementation details about your service to consumers.

Everything your consumer has to know is your service interface, and how to talk to it. In order to know this, both parts (service and consumer) have to share something that is called a Contract.

In WCF, there are 3 kinds of contracts: Service Contract, Data Contract and Message Contract.

A Service Contract describes what the service can do. It defines some properties about the service, and a set of actions called Operation Contracts. Operation Contracts are equivalent to web methods in ASMX technology


In terms of WCF, What is a message?
A message is a self-contained unit of data that may consist of several parts, including a body and headers.


In terms of WCF, What is a service?
A service is a construct that exposes one or more endpoints, with each endpoint exposing one or more service operations.


In terms of WCF, What is an endpoint?
An endpoint is a construct at which messages are sent or received (or both). It comprises a location (an address) that defines where messages can be sent, a specification of the communication mechanism (a binding) that described how messages should be sent, and a definition for a set of messages that can be sent or received (or both) at that location (a service contract) that describes what message can be sent.

An WCF service is exposed to the world as a collection of endpoints.


In terms of WCF, What is an application endpoint?
An endpoint exposed by the application and that corresponds to a service contract implemented by the application.


In terms of WCF, What is an infrastructure endpoint?
An endpoint that is exposed by the infrastructure to facilitate functionality that is needed or provided by the service that does not relate to a service contract. For example, a service might have an infrastructure endpoint that provides metadata information.


In terms of WCF, What is an address?
An address specifies the location where messages are received. It is specified as a Uniform Resource Identifier (URI). The schema part of the URI names the transport mechanism to be used to reach the address, such as "HTTP" and "TCP", and the hierarchical part of the URI contains a unique location whose format is dependent on the transport mechanism.


In terms of WCF, What is binding?
A binding defines how an endpoint communicates to the world. It is constructed of a set of components called binding elements that "stack" one on top of the other to create the communication infrastructure. At the very least, a binding defines the transport (such as HTTP or TCP) and the encoding being used (such as text or binary). A binding can contain binding elements that specify details like the security mechanisms used to secure messages, or the message pattern used by an endpoint.

20 September, 2009

.Net Framework 3.0 FAQ

What is XAML ?
WPF relies on the eXtensible Application Markup Language (XAML). An XML-based language, XAML allows specifying a user interface declaratively rather than in code. This makes it much easier for user interface design tools like MS Expression Blend to generate and work with an interface specification based on the visual representation created by a designer. Designers will be able to use such tools to create the look of an interface and then have a XAML definition of that interface generated for them. The developer imports this definition into Visual Studio, then creates the logic the interface requires.


What is XBAP?
XAML browser application (XBAP) can be used to create a remote client that runs inside a Web browser. Built on the same foundation as a stand-alone WPF application, an XBAP allows presenting the same style of user interface within a downloadable browser application. The best part is that the same code can potentially be used for both kinds of applications, which means that developers no longer need different skill sets for desktop and browser clients. The downloaded XBAP from the internet runs in a secure sandbox (like Java applets), and thus it limits what the downloaded application can do.

.Net Framework 3.0 FAQ

What contemporary computing problems WCS solves?
WCS provides an entirely new approach to managing digital identities. It helps people keep track of their digital identities as distinct information cards. If a web Site accepts WCS logins, users attempting to log in to that site will see a WCS selection. By choosing a card, users also choose a digital identity that will be used to access this site. Rather than remembering a plethora of usernames and passwords, users need only recognize the card they wish to use. The identities represented by these cards are created by one or more identity providers. These identities will typically use stronger cryptographic mechanisms to allow users to prove their identity. With this provider, users can create their own identities that don't rely on passwords for authentication.


What contemporary computing problems WPF solves?

user interface




needs to display video, run animations, use 2/3D graphics, and work with different document formats. So far, all of these aspects of the user interface have been provided in different ways on Windows. For example, a developer needs to use Windows Forms to build a Windows GUI, or HTML/ASPX/Applets/JavaScript etc. to build a web interface, Windows Media Player or software such as Adobe's Flash Player for displaying video etc. The challenge for developers is to build a coherent user interface for different kinds of clients using diverse technologies isn't a simple job.

A primary goal of WPF is to address this challenge! By offering a consistent platform for these entire user interface aspects, WPF makes life simpler for developers. By providing a common foundation for desktop clients and browser clients, WPF makes it easier to build applications.

.Net Framework 3.0 FAQ

What Improvements does WCF offers over its earlier counterparts?
A lot of communication approaches exist in the .NET Framework 2.0 such as ASP.NET Web Services, .NET Remoting, System.Messaging supporting queued messaging through MSMQ, Web Services Enhancements (WSE) - an extension to ASP.NET Web Services that supports WS-Security etc. However, instead of requiring developers to use a different technology with a different application programming interface for each kind of communication, WCF provides a common approach and API.


What are WCF features and what communication problems it solves?
WCF provides strong support for interoperable communication through SOAP. This includes support for several specifications, including WS-Security, WS-ReliableMessaging, and WS-AtomicTransaction. WCF doesn't itself require SOAP, so other approaches can also be used, including optimized binary protocol and queued messaging using MSMQ. WCF also takes an explicit service-oriented approach to communication, and loosens some of the tight couplings that can exist in distributed object systems, making interaction less error-prone and easier to change. Thus, WCF addresses a range of communication problems for applications. Three of its most important aspects that clearly stand out are:

Unification of Microsoft's communication technologies.
Support for cross-vendor interoperability, including reliability, security, and transactions.
Rich support for service orientation development.

.Net Framework 3.0 FAQ

System Requirements for Installing .NET Framework 3.0
Processor
Minimum: 400 megahertz (MHz) Pentium processor
Recommended: 1 gigahertz (GHz) Pentium processor

Operating System
.NET Framework 3.0 can be installed on any of the following systems:
Microsoft Windows 2003 Server Service Pack 1 (SP1)
Windows XP SP2
Windows Vista *

*Windows Vista comes with .NET Framework 3.0. There is no separate installation package required. The standalone .NET Framework 3.0 packages are not supported on Vista.

RAM
Minimum: 96 megabytes (MB)
Recommended:256 MB

Hard Disk
Up to 500 MB of available space may be required.
CD or DVD Drive Not required.

Display Minimum: 800 x 600, 256 colors
Recommended:1024 x 768 high color, 32-bit

Mouse Not required

19 September, 2009

.Net Framework 3.0 FAQ

What happens to the WinFX technologies?
The WinFX technologies will now be released under the name .NET Framework 3.0. There are no changes to the WinFX technologies or ship schedule — the same technologies you're familiar with now simply have a new name.


What is the .NET Framework 3.0 (formerly WinFX)?
The .NET Framework 3.0 is Microsoft's managed code programming model. It is a superset of the .NET Framework 2.0, combining .NET Framework 2.0 components with new technologies for building applications that have visually stunning user experiences, seamless and secure communication, and the ability to model a range of business processes. In addition to the .NET Framework 2.0, it includes Windows Presentation Foundation (WPF), Windows Workflow Foundation (WF), Windows Communication Foundation (WCF), and Windows CardSpace.

.Net Framework 3.0 FAQ

Will the name change be reflected in any of the existing .NET Framework 2.0 APIs, assemblies, or namespaces?
There will be no changes to any of the existing .NET Framework 2.0 APIs, assemblies, or namespaces. The applications that you've built on .NET Framework 2.0 will continue to run on the .NET Framework 3.0 just as they have before.


How does the .NET Framework 3.0 relate to the .NET Framework 2.0?
The .NET Framework 3.0 is an additive release to the .NET Framework 2.0. The .NET Framework 3.0 adds four new technologies to the .NET Framework 2.0: Windows Presentation Foundation (WPF), Windows Workflow Foundation (WF), Windows Communication Foundation (WCF), and Windows CardSpace. There are no changes to the version of the .NET Framework 2.0 components included in the .NET Framework 3.0. This means that the millions of developers who use .NET today can use the skills they already have to start building .NET Framework 3.0 applications. It also means that applications that run on the .NET Framework 2.0 today will continue to run on the .NET Framework 3.0.

.Net Framework 3.0 FAQ

Why is the .NET Framework 3.0 a major version number of the .NET Framework if it uses the .NET Framework 2.0 runtime a Compiler ?

The new technologies delivered in the .NET Framework 3.0, including WCF, WF, WPF, and CardSpace, offer tremendous functionality and innovation, and we wanted to signal that with a major release number.Which version of the Common Language Runtime (CLR) does the .NET Framework 3.0 use?The .NET Framework 3.0 uses the 2.0 version of the CLR. With this release, the overall developer platform version has been decoupled from the core CLR engine version. We expect the lower level components of the .NET Framework such as the engine to change less than higher level APIs, and this decoupling helps retain customers' investments in the technology.

.Net Framework 3.0 FAQ

What is .Net Framework 3.0

The Microsoft .NET Framework 3.0 (formerly WinFX), is the new managed code programming model for Windows.

It combines the power of the .NET Framework 2.0 with four new technologies: Windows Presentation Foundation (WPF), Windows Communication Foundation (WCF), Windows Workflow Foundation (WF), and Windows CardSpace (WCS, formerly "InfoCard").

Use the .NET Framework 3.0 today to build applications that have visually compelling user experiences, seamless communication across technology boundaries, the ability to support a wide range of business processes, and an easier way to manage your personal information online. Now the same great WinFX technology you know and love has a new name that identifies it for exactly what it is – the next version of Microsoft’s development framework. This change does not affect the release schedule of the .NET Framework 3.0 or the technologies included as a part of the package.

18 September, 2009

ASP.NET Interview Questions

ASP.NET Interview Questions

This is a list of questions I have gathered and created over a period of time from my experience, many of which I felt where incomplete or simply wrong. I have finally taken the time to go through each question and correct them to the best of my ability. However, please feel free to post feedback to challenge, improve, or suggest new questions. I want to thank those of you that have contributed quality questions and corrections thus far.

There are some questions in this list that I do not consider to be good questions for an interview. However, they do exist on other lists available on the Internet so I felt compelled to keep them here for easy access.

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()?
Response.Output.Write() allows you to write formatted output.

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

4. When during the page processing cycle is ViewState available?
After the Init() and before the Page_Load(), or OnLoad() for a control.

5. What namespace does the Web page belong in the .NET Framework class hierarchy?
System.Web.UI.Page

6. Where do you store the information about the user’s locale?
System.Web.UI.Page.Culture

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

8. 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 constituents.

9. Suppose you want a certain ASP.NET function executed on MouseOver for a certain button. Where do you add an event handler?
Add an OnMouseOver attribute to the button. Example: btnSubmit.Attributes.Add("onmouseover","someClientCodeHere();");

10. What data types do the RangeValidator control support?
Integer, String, and Date.

11. Explain the differences between Server-side and Client-side code?
Server-side code executes on the server. Client-side code executes in the client's browser.

12. What type of code (server or client) is found in a Code-Behind class?
The answer is server-side code since code-behind is executed on the server. However, during the code-behind's execution on the server, it can render client-side code such as JavaScript to be processed in the clients browser. But just to be clear, code-behind executes on the server, thus making it server-side code.

13. Should user input data validation occur server-side or client-side? Why?
All user input data validation should occur on the server at a minimum. Additionally, client-side validation can be performed where deemed appropriate and feasable to provide a richer, more responsive experience for the user.

14. What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other?
Server.Transfer transfers page processing from one page directly to the next page without making a round-trip back to the client's browser. This provides a faster response with a little less overhead on the server. Server.Transfer does not update the clients url history list or current url. Response.Redirect is used to redirect the user's browser to another page or site. This performas a trip back to the client where the client's browser is redirected to the new page. The user's browser history list is updated to reflect the new address.

15. Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?
Valid answers are:
· 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. What is the Global.asax used for?
The Global.asax (including the Global.asax.cs file) is used to implement application and session level events.

17. What are the Application_Start and Session_Start subroutines used for?
This is where you can set the specific variables for the Application and Session objects.

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. Example: With a base class named 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. A good use is 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. MSIL also allows the .NET Framework to JIT compile the assembly on the installed computer.

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 a 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. 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.

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

32. How many classes can a single .NET DLL contain?
It can contain many classes.


Web Service Questions

1. What is the transport protocol you use to call a Web service?
SOAP (Simple Object Access Protocol) is the preferred protocol.

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

3. What does WSDL stand for?
Web Services Description Language.

4. Where on the Internet would you look for Web services?
http://www.uddi.org

5. True or False: To test a Web service you must create a Windows application or Web application to consume this service?
False, the web service comes with a test page and it provides HTTP-GET method to test.


State Management Questions

1. What is ViewState?
ViewState allows the state of objects (serializable) to be stored in a hidden field on the page. ViewState is transported to the client and back to the server, and is not stored on the server or any other external source. ViewState is used the retain the state of server-side objects between postabacks.

2. What is the lifespan for items stored in ViewState?
Item stored in ViewState exist for the life of the current page. This includes postbacks (to the same page).

3. What does the "EnableViewState" property do? Why would I want it on or off?
It allows the page to save the users input on a form across postbacks. It saves the server-side values for a given control into ViewState, which is stored as a hidden value on the page before sending the page to the clients browser. When the page is posted back to the server the server control is recreated with the state stored in viewstate.

4. What are the different types of Session state management options available with ASP.NET?
ASP.NET provides In-Process and Out-of-Process state management. In-Process stores the session in memory on the web server. This requires the a "sticky-server" (or no load-balancing) so that the user is always reconnected to the same web server. Out-of-Process Session state management stores data in an external data source. The external data source may be either a SQL Server or a State Server service. Out-of-Process state management requires that all objects stored in session are serializable.

17 September, 2009

Menu with MultiView


Menu with MultiView



<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<script runat="server">



    protected void menuTabs_MenuItemClick(object sender, MenuEventArgs e)

    {

        multiTabs.ActiveViewIndex = Int32.Parse(menuTabs.SelectedValue);

    }

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head id="Head1" runat="server">

    <style type="text/css">

        html

        {

            background-color:silver;

        }

        .menuTabs

        {

            position:relative;

            top:1px;

            left:10px;

        }

        .tab

        {

            border:Solid 1px black;

            border-bottom:none;

            padding:0px 10px;

            background-color:#eeeeee;

        }

        .selectedTab

        {

            border:Solid 1px black;

            border-bottom:Solid 1px white;

            padding:0px 10px;

            background-color:white;

        }

        .tabBody

        {

            border:Solid 1px black;

            padding:20px;

            background-color:white;

        }

    </style>

    <title>Menu Tab Strip</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    

    <asp:Menu

        id="menuTabs"

        CssClass="menuTabs"

        StaticMenuItemStyle-CssClass="tab"

        StaticSelectedStyle-CssClass="selectedTab"

        Orientation="Horizontal"

        OnMenuItemClick="menuTabs_MenuItemClick"

        Runat="server">

        <Items>

        <asp:MenuItem

            Text="Tab 1"

            Value="0"

            Selected="true" />

        <asp:MenuItem

            Text="Tab 2"

            Value="1"/>

        <asp:MenuItem

            Text="Tab 3"

            Value="2" />

            

        </Items>

    </asp:Menu>    

    

    

    <div class="tabBody">

    <asp:MultiView

        id="multiTabs"

        ActiveViewIndex="0"

        Runat="server">

        <asp:View ID="view1" runat="server">

        

        Contents of first tab

        

        </asp:View>

        <asp:View ID="view2" runat="server">

        

        Contents of second tab

        

        </asp:View>

        <asp:View ID="view3" runat="server">

        

        Contents of third tab

        

        </asp:View>

    </asp:MultiView>    

    </div>

    

    </div>

    </form>

</body>

</html>




16 September, 2009

Code with Log File

In this article, we will adopt a simple mechanism to log errors and exceptions in website,
The error will get logged in a text file on the server.
The error file will be created on a daily basis, whenever the error is encountered

Public Shared Sub WriteErrorLog(ByVal errorMessage As String, ByVal errorStack As String, ByVal methodName As String)
Dim path As String = "~/LOG/" & DateTime.Today.ToString("dd-MM-yy") & ".txt"
If (Not File.Exists(System.Web.HttpContext.Current.Server.MapPath(path))) Then
File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close()
End If
Using w As StreamWriter = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path))
w.WriteLine(Constants.vbCrLf & "Log DateTime : " & DateTime.Now.ToString(System.Globalization.CultureInfo.InvariantCulture))
w.WriteLine("Page :- " & System.Web.HttpContext.Current.Request.Url.AbsolutePath.ToString.Trim)
w.WriteLine("Function Name :- " & methodName)
w.WriteLine("Message :- " & errorMessage)
w.WriteLine("Stack Trace :- " & errorStack)
w.WriteLine("__________________________")
w.Flush()
w.Close()
End Using
End Sub
Protected Sub btnTest_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Try
Dim i As Integer = 1
Dim j As Integer = 0
Response.Write(i \ j)
Catch ex As Exception
WriteErrorLog(ex.Message, ex.StackTrace.ToString.Trim, ex.TargetSite.Name)
End Try
End Sub

OutPut
__________________________

Log DateTime : 07/15/2009 15:25:20
Page :- /Default.aspx
Function Name :- btnTest_Click
Message :- Attempted to divide by zero.
Stack Trace :- at Default.aspx.btnTest_Click(Object sender, EventArgs e) in D:\Test\Default.aspx.vb:line 107
__________________________


Same thing you can do in Globa.asax, at Application_Error event. You can get an Server last error by Server.GetLastError()

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when an unhandled error occurs
Dim objErr As Exception = Server.GetLastError().GetBaseException()

'Function Name not be correct at application level error
WriteErrorLog(objErr .Message, objErr .StackTrace.ToString.Trim, "")

'IF you want you can redirect to user after log into log file here
' Response.Redirect("Error.aspx")
End Sub

Getting week of the month from a Date

Getting week of the month from a DateTime variable
// ---- GetWeekOfMonth ---------------------------
//
// Assuming Sunday starts a new week, get the ordinal
// week a date is in...of the date's month
// using Microsoft.VisualBasic;

int GetWeekOfMonth(DateTime Date)
{
long Week;

// get first day of month
DateTime BaseDate = new DateTime(Date.Year, Date.Month, 1);

// get difference, in weeks, between the date and first day of month
Week = DateAndTime.DateDiff(DateInterval.WeekOfYear,
BaseDate,
Date,
Microsoft.VisualBasic.FirstDayOfWeek.Sunday,
FirstWeekOfYear.Jan1);

// want it one, not zero based
return (int)Week + 1;
}

// test it
protected void Button1_Click(object sender, EventArgs e)
{
DateTime Date = new DateTime(2007, 3, 1);

while (Date.Month == 3)
{
int Week = GetWeekOfMonth(Date);

Response.Write(String.Format("{0:d} : {1}
", Date, Week));
Date = Date.AddDays(1);
}
}

RequiredFiledValidator For CheckBoxList


RequiredFiledValidator For CheckBoxList

function checkTemp(sender,args)

{

     for(var i=0;i<=document.getElementById("CheckBoxList1").firstChild.children.length-1;i++)

     {

          if(document.getElementById("CheckBoxList1").firstChild.children(i).cells(0).children(0).checked)=='true'

          args.IsValid=true

          return                    

     }

     args.IsValid=false

}

<asp:CustomValidator id="valcheckBoxTemp" runat="server" ClientValidationFunction="checkTemp"

ErrorMessage="This is required control "></asp:CustomValidator>  

15 September, 2009

Disable Copy Command

Disable Copy Command

oncopy="return false;" onpaste="return false;" oncut="return false;"

Alternate image when the orginal image is missing


How to provide an alternate image when the orginal image is missing?



<img border=0 src='<%# (Eval("Image").ToString() != null) ? "http://www.mynewsite.com/Images/thumb/" + Eval("Image") : "path_of_dummy_image" %>' />

Finding Particular Controls in Page

Finding Particular Controls in Page
private Control FindNestedControl(Control parent, string controlid)
{
Control c = parent.FindControl(controlid);
if (c != null)
return c;
else
{
foreach (Control child in parent.Controls)
{
c = FindNestedControl(child, controlid);
if (c != null)
return c;
}
}
return null;
}
Eg :- DropDownList ddlMyList = FindNestedControl(this.Page," ddlMyList") as DropDownList;

14 September, 2009

EncryptString & DecryptString

private string EnryptString (string strEncrypted)

{
byte[] b = System.Text.ASCIIEncoding.ASCII.GetBytes(strEncrypted);
string encryptedConnectionString = Convert.ToBase64String(b);
return encryptedConnectionString;
}

DecryptString

private string DecryptString (string encrString)

{
byte[] b = Convert.FromBase64String(encrString);
string decryptedConnectionString = System.Text.ASCIIEncoding.ASCII.GetString(b);
return decryptedConnectionString;
}

Customer Validator


<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="CustomField must be an even number!"

ControlToValidate="CustomField" ClientValidationFunction="ValidateEvent"

OnServerValidate="ValidateEvent">

  </asp:CustomValidator>



  <script type="text/javascript">



   function ValidateEvent(oSrc, args)

     {



args.IsValid = ((args.Value % 2) == 0);

      }



  </script>





   protected void ValidateEvent(object source, ServerValidateEventArgs args)

  {



    if ((Convert.ToInt32(args.Value) % 2) == 0)

            args.IsValid = true;

    else

            args.IsValid = false;



  }

13 September, 2009

DisableControlWithUpdateProgress


How to disable other controls when postback occur. Just add this below line of code into JavaScript in page header section.



<script language="javascript" type="text/javascript">

// Get a reference to the PageRequestManager.

              var prm = Sys.WebForms.PageRequestManager.getInstance();            

            

              // Using that prm reference, hook _initializeRequest

              // and _endRequest, to run our code at the begin and end

              // of any async postbacks that occur.

              prm.add_initializeRequest(InitializeRequest);

              prm.add_endRequest(EndRequest);

            

              // Executed anytime an async postback occurs.

              function InitializeRequest(sender, args)

              {      

                // Get a reference to the element that raised the postback,

                //   and disables it.

                $get(args._postBackElement.id).disabled = true;

              }

              // Executed when the async postback completes.

              function EndRequest(sender, args)

              {  

                // Get a reference to the element that raised the postback

                //   which is completing, and enable it.

                $get(args._postBackElement.id).disabled = false;

              }

            

</script>

12 September, 2009

Export CSV File


protected void btnExport_Click(object sender, EventArgs e)

  {

      ExportCSV(CreateData(),"Test")

  }



  public void ExportCSV(DataTable data, string fileName)

  {



    HttpContext context = HttpContext.Current;



    context.Response.Clear();

    context.Response.ContentType = "text/csv";

    context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".csv");



    //rite column header names

    for (int i = 0; i < data.Columns.Count - 1; i++)

    {

      if (i > 0)

      {

        context.Response.Write(",");

      }

      context.Response.Write(data.Columns[i].ColumnName);

    }

    context.Response.Write(Environment.NewLine);



    //Write data

    foreach (DataRow row in data.Rows)

    {



      for (int i = 0; i < data.Columns.Count - 1; i++)

      {

        if (i > 0)

        {

          context.Response.Write(",");

        }

        context.Response.Write(data.Columns[i].ColumnName);

      }

      context.Response.Write(Environment.NewLine);

    }

    context.Response.End();



  }



  private DataTable CreateData()

  {



    DataTable table1;

    table1 = new DataTable("Customers");



    DataRow row1, row2, row3;



    DataColumn colName = new DataColumn("CustomerName", System.Type.GetType("System.String"));

    DataColumn colCity = new DataColumn("City", System.Type.GetType("System.String"));

    table1.Columns.Add(colName);

    table1.Columns.Add(colCity);



    row1 = table1.NewRow();

    row1["CustomerName"] = "Microsoft";

    row1["City"] = "Redmond";

    table1.Rows.Add(row1);



    row2 = table1.NewRow();

    row2["CustomerName"] = "Amazon.com";

    row2["City"] = "Seattle";

    table1.Rows.Add(row2);



    row3 = table1.NewRow();

    row3["CustomerName"] = "IBM";

    row3["City"] = "Armonk";

    table1.Rows.Add(row3);



    return table1;



  }


FileUpload


<body>

   <form id="formFileUpload" method="post"  enctype="Multipart/Form-Data" runat="Server">

   <b>File Upload In ASP.Net</b>

   <hr />

   <br />

   Choose Your File  To Upload : <br />

   <input id="FileField" type="File" runat="server" size="60" /><br />

   <br />

   <asp:Button ID="UploadButton" runat="server" Text="Go"

       onclick="UploadButton_Click" /><br />    

    <div id="UploadDetails" visible="false" runat="server">

        File Name: <span id="FileName" runat="server"/> <br />

        File Content: <span id="FileContent" runat="server"/><br />

        File Size: <span id="FileSize" runat="server"/>bytes<br />

   </div>    

   <span ID="Span1" style="Color:Red" runat="Server"/>



   </form>

  

</body>







protected void Page_Load(object sender, EventArgs e)

    {

        string UpPath;

        UpPath = "C:\\UploadedUserFiles";

        if (! Directory.Exists(UpPath))

        {

            Directory.CreateDirectory("C:\\UploadedUserFiles\\");    

        }

    }

    protected void UploadButton_Click(object sender, EventArgs e)

    {

        FileName.InnerHtml = FileField.PostedFile.FileName;

        FileContent.InnerHtml = FileField.PostedFile.ContentType;

        FileSize.InnerHtml = FileField.PostedFile.ContentLength.ToString();

        UploadDetails.Visible = true;



        string strFileName;

        strFileName = FileField.PostedFile.FileName;

        string c = System.IO.Path.GetFileName(strFileName);

        try

        {

        FileField.PostedFile.SaveAs("C:\\UploadedUserFiles\\" + c);

        Span1.InnerHtml = "File Uploaded Sucessfully.";

        }

        catch(Exception exp)

        {

            Span1.InnerHtml = "Some Error occured.";

            UploadDetails.Visible = false;

        }

    }

11 September, 2009

MasterPagePropertiesAccess




<div style="height: 40px; background: Yellow;">

      Header<br />

      <div runat="server" id="hotProductsContentContainer">Hot Products</div>

      <div>Menu</div>

      </div>

    <div>

      <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">

      </asp:ContentPlaceHolder>

    </div>

    <div style="height: 40px; background: blue;">

      Footer</div>

    </div>





public string HotProductsContent

  {

    get { return hotProductsContentContainer.InnerHtml; }

    set { hotProductsContentContainer.InnerHtml = value; }

  }











//In Content page

protected void Page_Load(object sender, EventArgs e)

{

Master.HotProductsContent = "New Hot Products for Furniture";

}





Source ASP.NET Videos

MultiView


<form id="form1" runat="server">

        <br />

        <strong>MultiView<br />

            <asp:RadioButtonList ID="RadioButtonList1" runat="server" AutoPostBack="True" RepeatDirection="Horizontal" OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">

                <asp:ListItem Value="0">Bulleted List</asp:ListItem>

                <asp:ListItem Value="1">File Upload</asp:ListItem>

                <asp:ListItem Value="2">URL Mapping</asp:ListItem>

            </asp:RadioButtonList><br />

            <br />

        </strong>

        <br />

        <asp:MultiView ID="MultiView1" runat="server">

            <asp:View ID="View1" runat="server">

        Bulleted List Control<br />

        <br />

        <asp:BulletedList ID="BulletedList1" runat="server" DataSourceID="XmlDataSource1"

            DataTextField="text" DataValueField="url" DisplayMode="HyperLink">

            <asp:ListItem Value="http://www.microsoft.com">Microsoft</asp:ListItem>

        </asp:BulletedList>

        <asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/hyperlinks.xml"></asp:XmlDataSource>

            </asp:View>

            <asp:View ID="View2" runat="server">

        File Upload Control<br />

        <br />

        <asp:FileUpload ID="FileUpload1" runat="server" /><br />

        <asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" /><br />

        <asp:HyperLink ID="HyperLink1" runat="server">HyperLink</asp:HyperLink></asp:View>

            <asp:View ID="View3" runat="server">

                URL mapping<br />

                <br />

        <a href="guid_{492f3e0b-848e-11da-9550-00e08161165f}.htm">guid_{492f3e0b-848e-11da-9550-00e08161165f}.htm</a><br />

        <br />

        <a href="guid.htm">guid.htm</a>

                <br />

            </asp:View>

        </asp:MultiView>

    </form>



//cODE





protected void Button1_Click(object sender, EventArgs e)

    {

        if (FileUpload1.HasFile)

        {

            FileUpload1.SaveAs(("c:\\websites\\tricks\\upload\\" + FileUpload1.FileName));

            HyperLink1.Text = FileUpload1.FileName;

            HyperLink1.NavigateUrl = ("upload\\" + FileUpload1.FileName);

        }

    }

    protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)

    {

        MultiView1.ActiveViewIndex = Convert.ToInt32(RadioButtonList1.SelectedValue);

    }

10 September, 2009

PopUpInJavaScript


<script type="text/javascript">

<!--

var updated="";



function wopen(url, name, w, h)

{

  // Fudge factors for window decoration space.

  // In my tests these work well on all platforms & browsers.

  w += 32;

  h += 96;

  wleft = (screen.width - w) / 2;

  wtop = (screen.height - h) / 2;

  // IE5 and other old browsers might allow a window that is

  // partially offscreen or wider than the screen. Fix that.

  // (Newer browsers fix this for us, but let's be thorough.)

  if (wleft < 0) {

    w = screen.width;

    wleft = 0;

  }

  if (wtop < 0) {

    h = screen.height;

    wtop = 0;

  }

  var win = window.open(url,

    name,

    'width=' + w + ', height=' + h + ', ' +

    'left=' + wleft + ', top=' + wtop + ', ' +

    'location=no, menubar=no, modal=yes' +

    'status=no, toolbar=no, scrollbars=no, resizable=no', 'tite=no', 'resizable=no', 'directories=no', 'status=no');

  // Just in case width and height are ignored

  win.resizeTo(w, h);

  // Just in case left and top are ignored

  win.moveTo(wleft, wtop);

  win.focus();

}

// -->

</script>

</head>

<body style="text-align: center">

    Click the Button to Upload Some Files<br />

    <br />

    <input id="AddFileButton" type="button" value="Add File" onclick="wopen('FileUpload.aspx', 'popup', 500, 300); return false;"/>


SendingMails

Protected Sub btnSend_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSend.Click

'Create instance of main mail message class.
Dim mailMessage As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage()

'Configure mail mesage
'Set the From address with user input
' mailMessage.From = New System.Net.Mail.MailAddress(txtFromAddress.Text.Trim())
'Get From address in web.config
mailMessage.From = New System.Net.Mail.MailAddress(System.Configuration.ConfigurationManager.AppSettings("fromEmailAddress"))
'Another option is the "from" attirbute in the element in the web.config.

'Set additinal addresses
mailMessage.To.Add(New System.Net.Mail.MailAddress(txtToAddress.Text.Trim()))
'mailMessage.CC
'mailMessage.Bcc
'mailMessage.ReplyTo

'Set additional options
mailMessage.Priority = Net.Mail.MailPriority.High
'Text/HTML
mailMessage.IsBodyHtml = False

'Set the subjet and body text
mailMessage.Subject = txtSubject.Text.Trim()
mailMessage.Body = txtBody.Text.Trim()

'Add one to many attachments
'mailMessage.Attachments.Add(New System.Net.Mail.Attachment("c:\temp.txt")

'Create an instance of the SmtpClient class for sending the email
Dim smtpClient As System.Net.Mail.SmtpClient = New System.Net.Mail.SmtpClient()

'Use a Try/Catch block to trap sending errors
'Especially useful when looping through multiple sends
Try
smtpClient.Send(mailMessage)
Catch smtpExc As System.Net.Mail.SmtpException
'Log error information on which email failed.
Catch ex As Exception
'Log general errors
End Try

End Sub

//aspdotnetways.blogspot.com

and in Web.Config

<appSettings>

    <add key="fromEmailAddress" value="YOUR EMAIL ADDRESS HERE"/>

  </appSettings>





<!--Mail settings-->

  <system.net>

    <mailSettings>

      <smtp>

        <network host="YOUR HOST HERE"/>

      </smtp>

    </mailSettings>

  </system.net>

  <!--Mail settings-->


08 September, 2009

Update Progress Bar Dynamic Change Label

Use UpdateProgress control, set the label text is Please wait while processing...

put the below code at script tag

var prm = Sys.WebForms.PageRequestManager.getInstance();

prm.add_initializeRequest(InitializeRequest);

function InitializeRequest(sender, args)
{

// Get a reference to the element that raised the postback,

// and disables it.

$get(args._postBackElement.id).disabled = true;$get('LblHolder).innerHTML= = "This is a test";


}

07 September, 2009

Deploying a SQL Database to a Remote Host by using ASP.NET 2.0 callbacks (vb code behind)

Imports System.Data.SqlClient

Partial Class _Default
Inherits System.Web.UI.Page
Implements System.Web.UI.ICallbackEventHandler

' Get the connection string named "DB" from "web.config" file.
' Replace the "DB" with the name of the your datyabase connection.
Private strConnectionString As String = _
ConfigurationManager.ConnectionStrings("DB").ConnectionString

' Declare shared connection var. The connection must remain the same for all the callbacks.
Shared conn As SqlConnection = Nothing
Shared cmd As SqlCommand

' ASP.NET 2.0 callbacks related stuff. Google with "ASP.NET 2.0 callbacks" to find out how it works.
Private cs As ClientScriptManager = Page.ClientScript
Private _callbackArg As String


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim CallbackRef As String = _
Page.ClientScript.GetCallbackEventReference(Me, "arg", "ProcessCallBack", "context")
End Sub


Public Sub RaiseCallbackEvent(ByVal eventArgument As String) Implements ICallbackEventHandler.RaiseCallbackEvent
_callbackArg = eventArgument
End Sub


Function GetCallbackResult() As String Implements ICallbackEventHandler.GetCallbackResult
'
Dim strCallbackCommand As String = Left(_callbackArg, 2)
Dim strCallbackCommandText As String = Mid(_callbackArg, 3)

Select Case strCallbackCommand

Case Is = "01" ' Open the connection
Dim strCallbackMsg As String = "11 Connection opened; need the same shared connection through all the requests of the batch; we are creating the database, not using it."
Try
conn = New SqlConnection(strConnectionString)
conn.Open()
cmd = conn.CreateCommand
Catch ex As Exception
strCallbackMsg = String.Format("21 Could not open the connection. Error was {0}", ex.ToString())
End Try
Return strCallbackMsg

Case Is = "02" ' Close out the connection
If (conn IsNot Nothing) Then
Try
conn.Close()
conn.Dispose()
Catch ex As Exception
Me.Response.Write(String.Format("Could not close the connection. Error was {0}", ex.ToString()))
End Try
End If
Return "12 Connection closed"

Case Is = "03" ' Execute T-SQL against the target database
cmd.CommandText = strCallbackCommandText
cmd.CommandTimeout = 600
Try
cmd.ExecuteNonQuery()
Catch e As SqlException
' Handle exception.
Return "14 " & e.Message
Finally
End Try
Return "13 Succeded"

Case Else
Return "00_Unrecognized command"
End Select
End Function

End Class

Deploying a SQL Database to a Remote Host by using ASP.NET 2.0 callbacks (web.config)




connectionString="Data Source=.\SQLEXPRESS;
AttachDbFilename=|DataDirectory|\DB.mdf;
Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />






06 September, 2009

Deploying a SQL Database to a Remote Host by using ASP.NET 2.0 callbacks (screen shot)

Deploying a SQL Database to a Remote Host by using ASP.NET 2.0 callbacks

Though The Database Publishing Wizard can provide separate scripts for diferent objects and current PCs are pretty powerful, the copy / paste approach is unlikely to handle more than tenths of megabytes of script. But for many developers it would be okay in many cases. In next versions I hope I'll overcome the limitation.

You are uploading an .aspx page to a remote host and pointing Internet Explore to the page; then the application creates the database.

The difference to http://www.codeplex.com/sqlhost is that you need no uploading a SQL script to the host; you are supplying the .aspx page with the SQL script through the ASP.NET 2.0 Callbacks mechanism.

The drawback is that you can’t paste big SQL scripts into the text box; the advantage is that you can track the process of Script execution. Also when you upload a content of a table, you may not repeat the lengthy

INSERT [dbo].[SomeLengthyName] ([ApplicationGuidId], [UserGuidId], [SomeOtherGuidId], [YetAnotherGuidId], [index], SomeIntValue VALUES ('497705fc-6bb3-4f9d-90d8-d1a067c47348', [OtherGuid], [OtherGuid], [OtherGuid], [OtherGuid], 33, 7)

It’s a bit overkill to send two hundred bytes to just populate a field with, say number one 7. The command could be kind of “repeat previous” – two bytes plus two bytes - number of chars; this gives 4 bytes instead of 200 and plus the rest of a string. But that’s yet to be implemented.

So, have a look at a screen shot in a previous this blog’s message and if you decided to give a try to the idea, try it with you local database first:
- create some ASP.NET 2.0 project on your PC using VS.NET 2.0.
- create SQL database; I named it “DB”;
- edit connectionString in your “web.config” file to point to the database;
- copy Default.aspx code from one of the previous messages of this blog; replace your Default.aspx code with it;
- copy Default.aspx.vb code-behind from one of the previous messages of this blog; replace your Default.aspx.vb code-behind with it;
- launch the application;
- get The Database Publishing Wizard’s .sql file to some text editor, copy it to clipboard;
- paste the SQL script into the application’s textbox;
- click “Process” button.

The rest you can discover on you own, examining the controls and the code. Good Luck.

http://aspdotnetway.blogspot.com/

05 September, 2009

Interview Questions - Part 9

Interview Questions
--------------------------
86. What is caching?
a ) This allows a way to keep most frequently used data in memory to increase the performance of the application.

87. What are the types of page output cache?
a ) This is used to store the contents of a processed page in memory.
It is devided in to 2 types
1. full page caching
it stores the entire contents of a page
2. partial page caching
it stores the parts of a page.

88. What do you mean by post-cache substitution?
a ) This is one type of partial page caching. It allows you to cache the entire page but parts of a page are not cached means they will be created dynamically.

89. When the items will be removed from the cache?
a ) Items from cache are removed
1. when memory runs low
2. when an item expires
3. when items dependency changes

90. What is Sliding expiration?
a ) Suppose an item is placed in cache and its sliding expiration is 10 minutes. Then this sliding expiration policy specifies that the item stored in cache will be removed after 10 min from the time it is last used/accessed.

91. What is Absolute expiration?
a ) Suppose an item is placed in cache and its absolute expiration is 5 pm. Then this absolute expiration policy specifies that the item will be removed from the cache after 5 pm.

92. What is the directive used to implement caching in a page?
a ) It is @OutputCache

93. What is the attribute used to set the expiration of an item in the cache?
a ) It is “Duration” attribute

94. What are the attributes of outputcache used to store multiple versions of a page?
a )
1. VaryByParam
Using querystring it enables you to cache multiple versions of a page
2. varyByControl
Using a control value it enables you to cache multiple versions of a page
3. VaryByHeader
Using requests http header it enables you to cache multiple versions of a page
4. VaryByCustom
Using custom string or browser type it enables you to cache multiple versions of a page

95. what is sql dependency in caching?
a ) Means an item in the cache depends on the changes in a table in sql Database.

Interview Questions - Part 8

Interview Questions
---------------------------

76. What is the life time of the data stored in viewstate?
a ) Data stored in viewstate exists for the life of the current page.

77. Can a masterpage contain multiple content areas?
a ) Yes

78. What does the merge method of dataset do?
a ) It merges the dataset with another dataset.

79. What is the maximum length of the char datatype?
a ) Char – max of 8000 characters

80. What is the method used to kill a session explicitly?
a ) Session.abandon method.

81. What is the extension of the resource files?
a ) .resx

82. What is the attribute used to apply theme to a specific page?
a ) That is ‘Theme’ attribute.

83. How many types of configuration files are there?
a ) 2 types
Machine.config: This is a server or machine wide configuration file
Web.config : This is a application configuration file.

84. What are the advantages of web.config file?
a )
1. This contains application specific configuration settings whichis same for all the pages in that application.
2. This is xml file which is easily readble and understandable.
3. This applies changes to the asp.net application with out need for the administrator to stop and start the webserver.
4. It provides more security as data is encrypted.

85. Is it possible for an application to have more than one web.config file?
a ) Yes. An application can support more than one web.config file.

Interview Questions - Part 10

96. What is a TreeView Server control ?
a ) This is a site navigation control. It displays the data in hierarchical order. Generally is is used to display Menu items for an application. It contains a number of prebuilt styles.

97. What are the differences between viewstate and hidden fields?
a ) Viewstate :
1. This is used for pages that will postback to itself
2. This is a built in structure for maintaining state of a page
3. Security is more as data is hashed, compressed and encoded.
Hiddenfield :
1. This is used for pages that will postback to itself or to another page
2. This is not an inbuilt structure
3. Security is less when compared to viewstate

98. Examples of Navigation controls?
a ) They are
1. TreeView Control
2. Menu
3. SiteMapPath

99. What is the namespace used for web page
a ) System.Web.UI.Page

100. What is the use of IsPostBack method?
a ) This method is to determine whether request is new request or postback request.

101. What are the advantages of DataGrid Control?
a )
1. Inbuilt support for paging and sorting
2. Inbuilt support for user selection and editing
3. Contains its default display

04 September, 2009

Interview Questions - Part 7

Interview Question
--------------------------

66. What are the types of Serialization?
a ) 4 types
1. XML Serialization
2. Binary Serialization
3. SOAP Serialization
4. Custom Serialization

67. What is xml serialization?
a. ) Xml serialization can convert only the public properties and fields of an object in to an xml stream that confirms to a specific xml schema defination language document. Xml serialization is also known as shallow serialization. Xml serialization is used when you nedd the data in the object to stored in xml format. Xml stream can be processed by any application as needed regardless of platform.

68. What are the 2 methods of xmlserializer class?
a ) 1. serialize
2. deserialize

69. What is binary serialization?
a ) This is used to convert both public and private properties and fields of an object. This serialization is useful when data needs to travel electronically over wire. Disadvantage of this serialization is it is not easily portable to another platform.

70. What is SOAP Serialization?
a ) Similar to binary serialization this also convert the public and private properties and fields of an object in to a stream of bytes. This serialization is useful when you need interoperability.

71. what is satellite assembly?
a) An assembly which contains language specific resouces means culture information is known as satellite assembly.

72. what are the parts of version number of an assembly?
a) They are major, minor, revision, build.

73. what are the commands used to insert and remove assemblies in/from global assembly cache?
a) gacutil -I assemblyname /to insert
gacutil -u assemblyname /to uninstall

74. In which suituations we use gacutil tool?
a) We use it in development scenarios.

75. what is side-by-side execution?
a) This provides a way to keep multiple versions of an application on the same machine at the same time.

03 September, 2009

Interview Questions - Part 6

Interview Questions
-----------------------------

56. How can we customise columns in datagrid?
a ) Using the Template column.

57. What is the character/size limit in query string?
a ) Some browsers impose a 2083 character limit on the length of the URL.

58. How do you separate business logic while creating on asp.net application?
a ) By using code behind model

59. How many classes can a single .net dll contain?
a ) It can contain unlimitesd classes.

60. What is the maximum length of varchar and nchar datatypes?
a ) Varchar - max of 8000 characters
Nchar - max of 4000 characters

61. What is Portable Executable?
a ) It is a file format defining the structure that all executable files and dynamic link libraries must use to allow them to be loaded and executed by windows.

62. What is the use of Application Domain?
a ) This provides a way to isolate an application from other applications.

63. In which folder we store Local Resouce files?
a ) They are specific to a single page. They are stored in App_LocalResorces

64. What is serialization? What are its advantages?
a ) It provides a way to save the state of an object by converting it into a stream of bytes.
Advantages:
1. It provides a way to transportation of an object through a network
2. It provides a way to re create the same object by saving the its state.

65. What are the disadvantages of serialization?
a )
1. It requires more resources (to convert an object into a stream of bytes)
2. Serialization is a slow process.
3. It involves latency issues for transmitting the data over network.

Interview Questions - Part 5

Interview Questions
------------------------

46. What is a command object?
a.) This is used to perform the required operations on the database. A command object contains 2 arguments. First argument specifies the sql statement or stored procedure to be executed on the database and second argument specifies the connection object. First argument, if it is a sql statement, it can be a select, update, insert or delete. If we want to use a stored procedure we should specify its name as the first argument of the command object. Command object is generally used along with the Data Reader.

47. Why we use ExecuteNonQuery method?
a.) This is the method of the connection object. This is used when you use a stored procedure. This won’t return any data from database, simply executes the procedure.

48. What is a DataAdapter?
a.) Dataset can’t communicate directly with the database. So, in order to communicate with the database it makes use of DataAdapter. This acts as a bridge between dataset and database. It contains 2 arguments. First argument specifies the sql statement , and 2 argument specifies the connection object. It can perform all the DML operations.

49. What is the method used by dataadapter to fill the dataset?
a.) It uses Fill() method to fill the dataset with data from database.

50. what are the differences between datareader and data adapter?
a.) DataReader:
1.It supports connected model
2.It is used to retrive a forward only read only stream of data from data source.
3.performance is more
4.It can not perform insert, delete or update operations
DataAdapter:
1.It supports Disconnected model
2.It acts as a bridge between dataset and database
3.performance is less when compared to datareader
4.It can perform insert, delete and update operations

51. How many templates are there in Repeater control?
a) 5 Templates are there
1. ItemTemplate
2. AlternatingItemTemplate
3. HeaderTemplate
4. FooterTemplate
5. SeparatorTemplate

52. What are the disadvantages of Repeater Control?
a )
1. It does not contain predefined layout.
2. It produces readonly output
3. It does not support user selection and editing of data
4. No inbuilt support for paging and sorting

53. How many templates are there in DataList Control
a ) 7 Templates
1. ItemTemplate
2. AlternatingItemTemplate
3. HeaderTemplate
4. FooterTemplate
5. SeparatorTemplate
6. SelectedItemTemplate
7. EditItemTemplate

54. What is the use of alternatingItem Template?
a ) This is used to apply alternate color scheme in Datareader and DataList server controls.

55. How many columns are there in DataGrid Control
a ) 5 columns
1. Bound Column
2. Button Column
3. Edit command column
4. Hyperlink Column
5. Templated Column

02 September, 2009

Interview Questions - Part 4

Interview Questions
--------------------------------

36. what are the differences between Ado and Ado.net
a.) Ado:
1. It supports connected model
2. xml support is less
3. It uses record set
Ado.net
1. It supports disconnected model
2. xml support is more
3. it uses data set

37. What are the basic objects needed for Ado.Net
a.) There are 5 main objects.
1. Connection object: used to open a connection to the database
2. command object: used to perform operations on database
3. datareader object: used to read data in forward only read only manner from database
4. DataAdapter: Acts as a bridge between Dataset and Dataset
5. Dtaset: In-Memory container for all your data.

38. What are the arguments of a connection object?
a.) 1. server : this is used to specify the server name.
2. InitialCatalog: This is used to specify the database name
3. usedID: specifies the user id
4. password: specifies the user password.

39. Which method is used to release resources on connection object?
a.) Dispose() method.

40. What are the namespaces required to use Ado.net
a.) System
System.Data
System.Data.SqlClient (or) System.Data.OleDb (OR) system.Data.Odbc (OR) system.Data.OracleClient.

41. What is a Dataset?
a.) Dataset is a simple, in-memory data store for your data. It contains data, constraints on data, and relationships between data. It supports disconnected model, means connection is opened when the request is made and it closes when request is served with response. It can contain data from more than one table or database.

42. Why we use AcceptChanges method ?
a.) This is the method used by Dataset to commit the changes done by DML statements.

43. What is Getchanges method?
a.) This is used to get only those rows which have been modified. This can be used on a datatable or dataset.

44. What is a DataReader?
a.) DataReader is used to read data in forward only and read only manner.
Read() method is used to read data from database using datareader. They support connected model. Performance is more as they read data in forward only and read only manner. It can’t read data from more than one table at any point of time.

45. What are the methods we can apply on dataReader?
a.) 1.Read(): used to read
2.Close(): Used to close datareader
3.IsClosed(): used to check whether datareader is closed or not
4.HasRows(): used to check whether there are rows or not
5.NextResult(): with this we can execute a set of sql statements

01 September, 2009

Interview Questions - Part 3

26. How many types of assemblies are there?
a. 2 Types.
1. Private assemblies: which are used by only one application and are placed in the application's directory
2. shared assemblies: which are shared by many applications and are placed in machine wide code cache called global assembly cache.

27. What are main contents of an assembly
a. They are 4 contents
1. assembly manifest
2. Type metadata
3. msil that implements types
4. list of resouces

28. What is an assembly manifest?
a. Assembly manifest is main part of an assembly. it is used to store information about metadata like version information, security information, types info, scope of assembly etc.

29. What are the contents of an assembly manifest?
a. It contains name of the assembly,version information, culture information, strongname information, type reference information, list of files in assembly, and list of other assemblies

30. What is a global assembly cache?
a. Using this you can place assemblies at one common place. this common place is known as global assembly cache. the advantage of this global assembly cache is that the assemblies placed in this common place can be shared by many applications. they are not restricted to a particular application. they can be shared by any application. when you place an assembly in to global assembly cache that assembly should have a strong name. Global assembly cache is placed in the subdirectory of the systemroot directory.

31. What are the ways to keep assemblies in to global assemby cache?
a. 3 ways.
1. using windows installer
2. using global assembly cache tool
3. using windows explorer

32. what is advantage of windows installer ?
a. This should be used in the deployment time. this provides reference counting of an assembly.

33. what is a strong name?
a. when you want to place assembly in global assembly cache you should give strong name to that assembly. It contains assembly name, its version, public key and digital signature.This is used to uniquely identify an assembly, and to perform integrity checks on assembly. It ensures that no one can create a subsequent version of an assembly.

34. what are the advantages of global assembly cache?
a. 1. assemblies placed in GAC can be shared by multiple applications.
2. It provides security.
3. It provides a way to keep multiple versions of same assembly on the same machine.

35. can we place the contents of an assembly into different files?
a. Yes.