Pages

Saturday 20 April 2013

What are the various steps to make a simple Silverlight application?

This sample we are making using VS 2008 Web Express edition and .NET 3.5. It’s a six step procedure to run our first Silverlight application. So let’s go through it step by step.
  • Step 1: The first thing we need to do is install the Silverlight SDK kit from http://www.microsoft.com/downloads/details.aspx?familyid=FB7900DB-4380-4B0F-BB95-0BAEC714EE17&displaylang=en.
  • Step 2: Once you install the Silverlight SDK, you should be able to use the Silverlight template. So when you go to create a new project, you will see a ‘SilverLight Application’ template as shown in the below figure.

  • Step 3: Once you click OK, you will see a dialog box as shown below, which has three options:

    • Add an ASP.NET web project to the solution to host Silverlight: This option is the default option, and it will create a new Web Application project that is configured to host and run your Silverlight application. If you are creating a new Silverlight application, then this is the option to go.
    • Automatically generate a test page to host Silverlight at build time: This option will create a new page at runtime every time you try to debug and test your application. If you want to only concentrate on your Silverlight application, then this option is worth looking at.
    • Link this Silverlight control into an existing website: If you have an existing Silverlight application, then this option helps to link the Silverlight application with the existing web application project. You will not see this option enabled in new projects, you need to have an existing web application.
    For this example, we have selected the first option. Once you click OK, you should see the full IDE environment for Silverlight.

    So let’s run through some basic points regarding the IDE view that we see. You will see there are two projects: your web application and the Silverlight application. In the Silverlight application, we have two XAML files: App.XAML and Page.XAML. App.XAML has the global level information.
  • Step 4: Now for simplicity's sake, we just use the TextBlock tag to display a text. You can see that as we type in Page.XAML, it is displayed in the viewer.

  • Step 5: Now we need to consume the Silverlight application in an ASPX page. So in the HTML / ASPX page, we need to first refer to the Silverlight namespace using the Register attribute.
  • <%@Register Assembly="System.Web.Silverlight" 
       Namespace="System.Web.UI.SilverlightControls" TagPrefix="asp" %>
    We also need to refer to the ScriptManager from the Silverlight name space. The ScriptManager control is a functionality from AJAX. The main purpose of this control is to manage the download and referencing of JavaScript libraries.
    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    Finally, we need to refer to the Silverlight application. You can see that in the source we have referred to the XAP file. The XAP file is nothing but a compiled Silverlight application which is compressed and zipped. It basically has all the files that are needed for the application in a compressed format. If you rename the file to a ZIP extension, you can open it using WinZIP.
    <asp:Silverlight ID="Xaml1" runat="server" 
       Source="~/ClientBin/MyFirstSilverLightApplication.xap"
       MinimumVersion="2.0.31005.0" Width="100%" Height="100%" />
    So your final ASPX / HTML code consuming the Silverlight application looks something as shown below:
    <%@ Page Language="C#" AutoEventWireup="true" %>
    <%@ Register Assembly="System.Web.Silverlight" Namespace="System.Web.UI.SilverlightControls"
    TagPrefix="asp" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" style="height:100%;">
    <head runat="server">
    <title>MyFirstSilverLightApplication</title>
    </head>
    <body style="height:100%;margin:0;">
    <form id="form1" runat="server" style="height:100%;">
    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    <div style="height:100%;">
    <asp:Silverlight ID="Xaml1" runat="server" 
       Source="~/ClientBin/MyFirstSilverLightApplication.xap" 
       MinimumVersion="2.0.31005.0" Width="100%" Height="100%" />
    </div>
    </form>
    </body>
    </html>
  • Step 6: So finally set the web application as Start up and also set this page as Start up and run it. You should be pleased to see your first Silver light application running.

Function Overloading in Web Services

Overloading Web Services

While trying to overload Web Methods in Web Services and after doing the build, it will work successfully. But when we try to run or consume, it will show an error message. We can show this using an example.
namespace TestOverloadingWebService
{ 
    [WebService(Namespace = "http://tempuri.org/", Description=" <b> Function 
    overloading in Web Services </b>")] 
public class OverloadingInWebService : System.Web.Services.WebService 
{ 
    [WebMethod()] 
    public int Add(int a, int b) 
    { 
        return (a + b); 
    } 
    [WebMethod()] 
    public float Add(float a, float b) 
    { 
        return (a + b); 
    } 
} 
}
In the above example, we made one web service having class OverloadingInWebService. In the Web Service, we have added attribute Description, which is used to describe the web service purpose to client. In the above Web Service, we have two overloaded WebMethods:
public int Add(int a, int b) 
and
public float Add(float a, float b)
While running this Web service, it will show the following runtime error.
ViewError.JPG

Solution for the Above Error

The procedure to solve this problem is very easy. Start each method with a Web Method attribute. Add Description property to add a description of web method and MessageName property to change web method name.
[WebMethod(MessageName = "<name>", Description = "<description>")]
namespace TestOverloadingWebService 
{ 
    [WebService(Namespace = "http://tempuri.org/", Description=" <b> Function 
    overloading in Web Services </b>")] 
public class OverloadingInWebService : System.Web.Services.WebService 
{ 
    [WebMethod(MessageName = "AddInt", Description = "Add two integer 
        Value", EnableSession = true)] 
    public int Add(int a, int b) 
    { 
        return (a + b); 
    } 
    [WebMethod(MessageName = "AddFloat", Description = "Add two Float  
        Value", EnableSession = true)] 
    public float Add(float a, float b) 
    { 
        return (a + b); 
    } 
} 
}

Reason for the Above Error

The Overloading is supported by web services. But when WSDL (Web Service Description Language) is generated, it will not be able to make the difference between methods because WSDL does not deal on the base of parameters. By passing web methods –‘MessageName Property’, it changes the method name in WSDL. See the WSDL given below, the operation name is Add but the input method name is AddInt as well as output method name is also same (AddInt). The same will apply for Float also.
<wsdl:operation name="Add"> 
            <wsdl:documentation xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">Add 
            two integer Value</wsdl:documentation> 
            <wsdl:input name="AddInt" message="tns:AddIntSoapIn" /> 
            <wsdl:output name="AddInt" message="tns:AddIntSoapOut" /> 
</wsdl:operation> 
<wsdl:operation name="Add"> 
            <wsdl:documentation xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">Add     
            two Float Value</wsdl:documentation> 
            <wsdl:input name="AddFloat" message="tns:AddFloatSoapIn" /> 
            <wsdl:output name="AddFloat" message="tns:AddFloatSoapOut" /> 
</wsdl:operation>
 
Other Example 
 
Creating XML Web Service in .Net
Use the following steps to create a web service.
  • Go to Visual Studio 2010 and create a New Project.
img1.gif
  • Select .NET Framework 3.5.
  • Create an ASP.NET Web Service Application.
  • Give it a name and click ok button.
img2.gif
Add the following method in the Service.cs file.
[WebMethod] public int AddNumber(int a, int b) {     return (a + b); } [WebMethod] public int AddNumber(int a, int b, int c) {     return (a + b + c); }
The complete Service.cs file is:
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Services;namespace WebMethodOverlodding {     /// <summary>    /// Summary description for Service1    /// </summary>    [WebService(Namespace = "http://tempuri.org/")]     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]     [System.ComponentModel.ToolboxItem(false)]     // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.     // [System.Web.Script.Services.ScriptService]    public class Service1 : System.Web.Services.WebService    {         [WebMethod]         public int AddNumber(int a, int b)         {            return (a + b);         }         [WebMethod]         public int AddNumber(int a, int b, int c)         {            return (a + b + c);         }     } }
In the above Web Service, we have two overloaded WebMethods. This Web Service would compile fine. Run the WebService in the browser. That should give an error saying that the AddNumbers() methods use the same message name 'AddNumbers' and asking to use the MessageName property of the WebMethod. like as.
img3.gif
Solution for the Above Error
The procedure to solve this problem is very easy. Start each method with a Web Method attribute. Add the MessageName property to the WebMethod attribute as shown below.
[WebMethod] public int AddNumber(int a, int b) {      return (a + b); } [WebMethod (MessageName="AddThreeNumbers")] public int AddNumber(int a, int b, int c) {      return (a + b + c); }
The complete Service.cs file is look like as.
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Services;namespace WebMethodOverlodding {     /// <summary>    /// Summary description for Service1    /// </summary>    [WebService(Namespace = "http://tempuri.org/")]     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]     [System.ComponentModel.ToolboxItem(false)]     // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.     // [System.Web.Script.Services.ScriptService]    public class Service1 : System.Web.Services.WebService    {       [WebMethod]       public int AddNumber(int a, int b)         {            return (a + b);         }      [WebMethod (MessageName="AddThreeNumbers")]      public int AddNumber(int a, int b, int c)         {            return (a + b + c);         }     } }
Now again run the above web service by pressing the F5 key; we will then see:
IMG4.gif
img5.gif
Reason for the Above Error
The Overloading is supported by web services. But when WSDL (Web Service Description Language) is generated, it will not be able to make the difference between methods because WSDL does not deal on the base of parameters. By passing web methods 'MessageName Property', it changes the method name in WSDL. See the WSDL given below, the operation name is AddNumber but the input method name and output method name is different. The same will apply for second method also.
<wsdl:operation name="AddNumber">     <wsdl:input message="tns:AddNumberSoapIn"/>     <wsdl:output message="tns:AddNumberSoapOut"/>  </wsdl:operation>  <wsdl:operation name="AddNumber">      <wsdl:input name="AddThreeNumbers" message="tns:AddThreeNumbersSoapIn"/>      <wsdl:output name="AddThreeNumbers" message="tns:AddThreeNumbersSoapOut"/>  </wsdl:operation>
 

Interview Questions Answers for Silverlight

Q1. What is Silverlight?
- Silverlight is  a powerful technology used to build rich browser, desktop and mobile user experience (UX) applications with the support for Media, multithreading, data binding, 2-D and 3-D graphics. Powered by the .NET framework, Silveright is a free plug-in and compatible with multiple browsers, devices and operating systems
- It has its own CLR (coreclr.dll) and exists as a browser plug-In (npctrl.dll).
- For Silverlight development, you can either install Silverlight using the
Web Platform Installer or use Silverlight 4 Tools for Visual Studio 2010.
- The latest version is Silverlight 4.0 and a plan has been laid out for Silverlight 5.0
Q2. Is Silverlight a replacement for ASP.NET?
Absolutely not. ASP.NET provides its own power of server side programming, with more enhanced security. Silverlight plugin executes inside the browser sandbox (client side) and needs to be configured explicitly for security using WCF services for authorization and authentication. A mix of ASP.NET and Silverlight is used in most applications.
Q3. Can we develop Client-server applications or Intranet applications using Silverlight?
This totally depends on the architecture and application requirements. One important thing to note here is that Silverlight applications cannot ‘directly’ connect to the database server. So thinking of a client-server application development using Silverlight might require some thinking on your part. WindowsForm or WPF can be a good choice in this scenario.
Q4. What type of applications can be developed using Silverlight?
You can think of developing browser or mobile applications using Silverlight, where you need to represent output in a graphical form, a rich UX. For E.g. In case of a healthcare application, you can think of using Silverlight for simulating ECG of the patient, as shown below:
Silverlight Health Care
The above output makes use of Polyline 2-D graphical element of Silverlight. Likewise various types of Line-of-Business (LOB) applications, for various domains can be developed. Some example are :
- Healthcare.
- Insurance
- Logistic
and any other domains you can think of.
Q5. How then the data be made available to Silverlight applications?
- For developing Line-Of-Business (LOB) applications, Silverlight supports Data-Binding features with OneWay, TwoWay binding mechanism.
- Using Windows Communication Foundation (WCF), data from the remote server can be made available to Silverlight applications.
- The communication between Silverlight and WCF service is possible using ‘basicHttpBinding’. This is the binding provided in WCF service for HTTP protocol with plain text communication from Silverlight to WCF.
Q6. What types of security measures are provided with Silverlight?
- For secure communication, Silverlight makes use of WCF service and uses the security features of WCF.
- You can also make use of Secure Socket Layer (SSL) transport security mechanism from Silverlight to WCF.
Q7. Can the Silverlight application be deployed on the desktop?
- Yes, Absolutely possible. With Silverlight 3.0 version and onwards, the Out-Of-Browser (OOB) facility has been provided. Using this feature, the Silverlight application can be physically deployed on local machine.
- In Silverlight 4.0 the OOB facility has been enhanced with elevated rights, which allows a Silverlight application to do the following:
        -Communicate with Word, Excel type applications by using COM enhancements, provided in Silverlight 4.0.
         -Communicate with local database e.g. MS-Access, Sql Server etc.
Q8. Where is the Silverlight application present, is it on the Web server or on the Client?
- The Silverlight application in most cases is hosted in an ASP.NET webpage, although it can be hosted on HTML pages too. The extension of the SL plugin is .xap.
- When the end-user makes an HTTP request to this ASP.NET page (.aspx), the Silverlight application is made available to the browser and the result is displayed.
Q9. What are the controls provided in Silverlight for Line-of-Business (LOB) applications?
You can make use of following controls:
- DataGrid.
- DataForm.
- Chart controls etc.
Q10. Can the Silverlight application communicate with ASP.NET?
This can be possible using:
- Cookies.
- QueryString.
- You can use JavaScript on the ASP.NET page and it can be called in Silverlight.
Q11. What is the real advantage of using Excel/Word files or local database in Silverlight?
- This can be required when the end-user is using Silverlight application in OOB (Out-Of-Browser) and for storing and fetching the frequently required data, instead of relying on WCF service for data communication, the data can be fetched and stored in Excel sheet on the local database
- In case of the Excel/Word files communication, they are recommended to be stored in ‘MyDocuments’ special folder.
Q12.What are the advantages of Extensible Application Markup Language (XAML) over C# or VB.NET
- One important thing note here is that C#/VB.NET (code-behind files) have their own important roles to play.
- XAML provides lots of features like code-less development, creating complex UI controls E.g. creating image list by using ListBox and Image control used together.
- The XAML file can define an instance of the class created using C# and VB.NET and all public properties declared in this class can be directly bound in XAML elements.
Q13. Can we use any specific Patterns in Silverlight programming?
- Yes. In Silverlight, Model-View-View-Model (MVVM) can be used for loosely coupled application development where code can be completed isolated from the XAML.
- We can also use Prism in Silverlight which is a set of classes provided for developing next generation loosely coupled, flexible LOB applications. 


What is XAP file?

XAP (pronounced as ZAP) is the compressed output of the Silverlight Application which includes application manifest file, compiled output assembly and other resources used by your silverlight application. This uses the normal ZIP compression method to reduce the total download size. When you build your Silverlight application, it actually generates this .XAP file & puts in the output folder which the .aspx page refers as source to load the application.

Once you build your project, it will create the XAP file (in our case: SilverlightApps.HelloSilverlight.xap) and put it into the ClientBin directory of the web project. When the page loads it will pickup from the same location as the source you specified inside the aspx/html page. 


What is MainPage.xaml file?

When you create the Silverlight project, Visual Studio IDE will automatically add a default “MainPage.xaml” file which is actually a startpage for your Silverlight application. You can modify this page as per your need or can create a new one. So, what’s there inside the file? Lets look at it: 

 
Lets walk-through each lines of the code. It contains a UserControl as root of the file which may contain all other controls inside it. The following line tells the compiler to use the specified class to use:


The next couple of lines beginning with xmlns tells the compiler to import some namespaces which can be used by the Silverlight XAML page.

The following line speaks about the design time Height & Width of the Silverlight page:


If you want to specify actual Height & Width of your Silverlight application, you can manually append the following line inside that:


Next comes the Grid control which is used as a layout panel and that can include more other controls. Though the default XAML file uses the Grid as the layout panel, you can change it to any other panel as per your need. I will discuss about the various panel later in this tutorial.


“MainPage.xaml” has also it’s code behind file like App.xaml & you can use this to write code to develop your functionalities. By default, it comes empty with a call to Initialize() method inside the Constructor of the MainPage class. The implementation of this method is also available in a different partial class of MainPage inside “MainPage.g.i.cs” like “App” class. Whenever you add some controls inside the XAML page, it will be loaded here. 


How can I host a Silverlight Application?

When you create a Silverlight project, it asks you to create a Web Application project. This project is responsible for hosting your XAP file. Generally Silverlight application doesn’t require any server to host it to run, but if you are planning to host it in web you must need a web server for that.
Once you publish your Web Application to host in IIS, you may need to add three MIME types in your IIS Server. This is require to host it in earlier versions of IIS. Latest version of IIS comes with that configuration by default. Followings are the list of MIME Types those you need to add in your IIS Properties:

.xap application/x-silverlight-app
.xaml application/xaml+xml
.xbap application/x-ms-xbap

Silverlight Application (XAP) generally loads inside the ASPX or HTML pages pointing to the path to load the XAP. The aspx/html page uses <object /> tag to load the Silverlight application.

Here is the code present inside the aspx/html pages for loading the Silverlight XAP:



Let us go line by line to learn the basics of it.
  • In the first line <object> tag tells the browser to load the Silverlight plug-in.
  • Next couple of lines uses <param> tag.
    • The first param “source” has the value to the location of the .xap file.
    • Second param “onError” tells the plug-in to call the javascript method mentioned in the value, if any application error occurs.
    • The third param “background” specifies the color of the Silverlight application background.
    • The next param “minRuntimeVersion” specifies the minimum required plug-in version to load your Silverlight application.
    • If “autoUpgrade” is set as true in the next param, it will automatically upgrade the runtime.
  • The next lines are very interesting. Whatever you design there, will not be visible in the browser in normal scenarios. If the user doesn’t have Silverlight runtime installed in his PC or the Silverlight plug-in is disabled this section will visible to the user. This part is well known as “Silverlight Installation Experience panel”. By default, it shows a Silverlight image to download the runtime from Microsoft site. When the user clicks on it, this starts the installation. I will discuss about the Silverlight Experience later in depth. 
  • What is XAML?

    XAML stands for eXtended Application Markup Language. It is nothing but an XML file which is used to declaratively create the User Interface of the Silverlight or WPF applications. This XAML file generally rendered by the Silverlight plugin and displayed inside the browser window. When you compile your projects which includes XAML pages, those first converts into BAML (Binary Application Markup Language) and then rendered in the web browser window. Let use see a simple example of XAML here:


    The above XAML is a typical example where I am creating a text using the TextBlock control by specifying different properties as attributes to the control for name, font-family, weight, text etc. 

What is Silverlight?

Silverlight is a powerful cross-browser & cross-platform technology for building the next generation web experience & rich internet applications for the web. You can run Silverlight in most of all the popular browsers like Internet Explorer, Firefox, Chrome, Safari etc. Silverlight can run in various devices and operating systems like Windows, Apple Mac OS-X and Windows Phone 7. Using Silverlight you can create rich, visually stunning web applications like flash. Also you can create smooth animations using Storyboards; you can stream media over the net etc.
Silverlight web browser plug-in comes as free to install (approximately 4-5 MB in size). You can download the required plug-in from Microsoft Silverlight Site. 

What is App.xaml file?

App.xaml file is the loader of your Silverlight Application. You can declare your shared/global resources, styles, templates, different brushes inside this file which will be accessible by your application.

A typical App.xaml file looks like: 



It has a code behind file too named as “App.xaml.cs”. This file is used to handle global application level events which you can use as per your need. Visual Studio creates these two files at the time of project creation. The three events inside the App.xaml.cs are:
  • Application_Startup
  • Application_Exit
  • Application_UnhandledException.
These three events are registered in the constructor of your App.xaml.cs file. Here is the code snippet of the same: 



Let us do a brief discussion on each part of the code file.
Overview of App Constructor: Inside the constructor of the App class you will find that all the three event has been registered. Also, there is a call to InitializeComponent() method. If you look around the whole class you will not find the method implementation. Strange!!! Where is the method?

The method has been implemented inside the partial class of the App class. If you go to the definition or just press F12 on top of the method, Visual Studio will open up the actual file named “App.g.i.cs” which contains the partial implementation of the same class. There you will find the method implementation.

What this method does: This method is responsible to load the XAML using the LoadComponent() method into the memory which can be used by your application.

What can we do inside the App.g.i.cs file: App.g.i.cs file is auto generated by the compiler and hence if you modify something there will be overwritten by the compiler itself on next build.

Why this file is not available inside my solution: As this is an compiler generated file, it has been placed inside the temporary directory named “obj”. If you go to the solution directory you will see the “obj” folder. Open it and browse through it’s subfolder (either debug or release) and you will see the file placed there. If you are unable to find it there, just do a rebuild of your solution and immediately it will be created there.

Overview of Application_Startup Event:
Application_Startup event is the root of your application. In this event you can create the instance of your initial page and set it as the RootVisual. Also, if you want to create some global objects or want to write some app initialization code, then this Application_Startup event will be the best part for you to implement it.

Overview of Application_Exit Event:
Similarly, you can write code to cleanup objects or do something when closing the application inside the Application_Exit event.

Overview of Application_UnhandledException Event:
If any exception comes while running and you didn’t handle that in the actual place, you can write some code in Application_UnhandledException to log the error details into database or show some message to the user. This will allow the application to continue running after an exception has been thrown. By default, if the app is running outside of the debugger then report the exception using the Browser DOM & the error will be visible in the status bar of Internet Explorer.

What are the Prerequisite to create a new Silverlight Application?

Before starting with the Silverlight application development be sure you have all the necessary softwares installed in your PC. If you don’t have then follow the steps mentioned in Microsoft Silverlight Site (http://silverlight.net/getstarted/) to download & install the following items in your development environment:
  • Visual Studio 2008 SP1 for Silverlight 3 application development or Visual Studio 2010 for Silverlight 3 & Silverlight 4 application development
  • Silverlight 3 Tools for Visual Studio 2008 SP1 or Silverlight 4 Tools for Visual Studio 2010
  • Expression Blend 3 for Silverlight 3 or Expression Blend 4 Preview for Silverlight 4 (optional)
  • WCF RIA Services for Silverlight (optional)
  • Silverlight 3 Toolkit or Silverlight 4 Toolkit based on your earlier version of Silverlight (optional)
Remember that, Silverlight 3 comes preinstalled with Visual Studio 2010 and hence if you are using Visual Studio 2010, you don’t need to install the Silverlight 3 Tools for it. Using Visual Studio 2010 you can develop both Silverlight 3 and Silverlight 4 applications but Visual Studio 2008 SP1 only supports Silverlight 3.

If you have proper development environment ready for Silverlight application you can proceed to the next chapter for creating our first simple Silverlight project. I am using Visual Studio 2010 RC and Silverlight 4 RC while writing these applications. Hence, the attached samples will not open in Visual Studio 2008.

Can Silverlight run in other platforms other than Windows?

Yes, animations made in Silverlight can run in other platforms other than Windows. In whatever platform you want to run, you just need the Silverlight plug-in.

Page Life cycle of Silverlight Application

As we know Silverlight application running at client side and it’s not stateless like asp.net pages. so as such you will find there is no page life cycle in silverlight application. Apart from it we can consider the following steps which executed at client end


  1. First the App constructor in the App.xaml file.
  2. The App's Applicaiton_Startup event which will be executed every time you open your Silverlight app.
  3. The Main page's Constructor..  It will be the constructor of the page assigned to the RootVisual properly within the App's Application_Startup event.
  4. InitializeCompnent, only to make sure the components are singed to variables so you can use them. I hope this one will be removed in the future and be handled elsewhere.
  5. If you have hooked up to the Loaded event within the Main Page Constructor, that event will then be executed, same with the rest event listen in the order they will be executed if you have hooked up to them.
  6. Then the SizeChanged event.
  7. Then the LayoutUpdated event.
  8. Then GotFocus if you mark the Silverlight app.
  9. If you navigate from your Silverlight app or close the Browser the App's Application_Exit event will be executed.

Thursday 18 April 2013

Interview Questions in ASP .Net?

1. What is ASP.Net?
It is a framework developed by Microsoft on which we can develop new generation web sites using web forms(aspx), MVC, HTML, Javascript, CSS etc. Its successor of Microsoft Active Server Pages(ASP). Currently there is ASP.NET 4.0, which is used to develop web sites. There are various page extensions provided by Microsoft that are being used for web site development. Eg: aspx, asmx, ascx, ashx, cs, vb, html, xml etc.
2. What’s the use of Response.Output.Write()?
 We can write formatted output  using Response.Output.Write().
3. In which event of page cycle is the ViewState available?
   After the Init() and before the Page_Load().
4. What is the difference between Server.Transfer and Response.Redirect?  
In Server.Transfer page processing transfers from one page to the other 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.  The clients url history list or current url Server does not update in case of Server.Transfer.
Response.Redirect is used to redirect the user’s browser to another page or site.  It performs 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.
5. From which base class all Web Forms are inherited?
Page class. 
6. What are the different validators in ASP.NET?
  1. Required field Validator
  2. Range  Validator
  3. Compare Validator
  4. Custom Validator
  5. Regular expression Validator
  6. Summary Validator
7. Which validator control you use if you need to make sure the values in two different controls matched?
Compare Validator control.
8. What is ViewState?
ViewState is used to retain the state of server-side objects between page post backs.
9. Where the viewstate is stored after the page postback?
ViewState is stored in a hidden field on the page at client side.  ViewState is transported to the client and back to the server, and is not stored on the server or any other external source.
10. How long the items in ViewState exists?
They exist for the life of the current page.
11. What are the different Session state management options available in ASP.NET?

  1. In-Process
  2. Out-of-Process.
In-Process stores the session in memory on the web server.
Out-of-Process Session state management stores data in an external server.  The external server may be either a SQL Server or a State Server.  All objects stored in session are required to be serializable for Out-of-Process state management.
12. How you can add an event handler?
 Using the Attributes property of server side control.
e.g.
?
1
btnSubmit.Attributes.Add("onMouseOver","JavascriptCode();")
13. What is caching?
Caching is a technique used to increase performance by keeping frequently accessed data or files in memory. The request for a cached file/data will be accessed from cache instead of actual location of that file.
14. What are the different types of caching?
ASP.NET has 3 kinds of caching :
  1. Output Caching,
  2. Fragment Caching,
  3. Data Caching.
15. Which type if caching will be used if we want to cache the portion of a page instead of whole page?
Fragment Caching: It caches the portion of the page generated by the request. For that, we can create user controls with the below code:
?
1
<%@ OutputCache Duration="120" VaryByParam="CategoryID;SelectedID"%>
16. List the events in page life cycle.
  1) Page_PreInit
2) Page_Init
3) Page_InitComplete
4) Page_PreLoad
5) Page_Load
6) Page_LoadComplete
7) Page_PreRender
8)Render
17. Can we have a web application running without web.Config file?
  Yes
18. Is it possible to create web application with both webforms and mvc?
Yes. We have to include below mvc assembly references in the web forms application to create hybrid application.
?
1
2
3
4
5
System.Web.Mvc
 
System.Web.Razor
 
System.ComponentModel.DataAnnotations
19. Can we add code files of different languages in App_Code folder?
  No. The code files must be in same language to be kept in App_code folder.
20. What is Protected Configuration?
It is a feature used to secure connection string information.
21. Write code to send e-mail from an ASP.NET application?
?
1
2
3
4
5
6
7
        MailMessage mailMess = new MailMessage ();
        mailMess.From = "abc@gmail.com";
        mailMess.To = "xyz@gmail.com";
        mailMess.Subject = "Test email";
        mailMess.Body = "Hi This is a test mail.";
        SmtpMail.SmtpServer = "localhost";
        SmtpMail.Send (mailMess);
MailMessage and SmtpMail are classes defined System.Web.Mail namespace.
 22. How can we prevent browser from caching an ASPX page?
  We can SetNoStore on HttpCachePolicy object exposed by the Response object’s Cache property:
?
1
2
3
Response.Cache.SetNoStore ();
 Response.Write (DateTime.Now.ToLongTimeString ());
   
23. What is the good practice to implement validations in aspx page?
Client-side validation is the best way to validate data of a web page. It reduces the network traffic and saves server resources.
24. What are the event handlers that we can have in Global.asax file?

Application Events: Application_Start , Application_End, Application_AcquireRequestState, Application_AuthenticateRequest, Application_AuthorizeRequest, Application_BeginRequest, Application_Disposed,  Application_EndRequest, Application_Error, Application_PostRequestHandlerExecute, Application_PreRequestHandlerExecute,
Application_PreSendRequestContent, Application_PreSendRequestHeaders, Application_ReleaseRequestState, Application_ResolveRequestCache, Application_UpdateRequestCache
Session Events: Session_Start,Session_End
25. Which protocol is used to call a Web service?
HTTP Protocol
26. Can we have multiple web config files for an asp.net application?
Yes.
27. What is the difference between web config and machine config?
Web config file is specific to a web application where as machine config is specific to a machine or server. There can be multiple web config files into an application where as we can have only one machine config file on a server.

28.  Explain role based security ?
  Role Based Security used to implement security based on roles assigned to user groups in the organization.
Then we can allow or deny users based on their role in the organization. Windows defines several built-in groups, including Administrators, Users, and Guests.
?
1
2
3
4
<AUTHORIZATION>< authorization >
    < allow roles="Domain_Name\Administrators" / >   < !-- Allow Administrators in domain. -- >
    < deny users="*"  / >                            < !-- Deny anyone else. -- >
 < /authorization >
29. What is Cross Page Posting?
When we click submit button on a web page, the page post the data to the same page. The technique in which we post the data to different pages is called Cross Page posting. This can be achieved by setting POSTBACKURL property of  the button that causes the postback. Findcontrol method of PreviousPage can be used to get the posted values on the page to which the page has been posted.
30. How can we apply Themes to an asp.net application?
We can specify the theme in web.config file. Below is the code example to apply theme:
?
1
2
3
4
5
6
7
8
9
<configuration>
 
<system.web>
 
<pages theme="Windows7" />
 
</system.web>
 
</configuration>
31: What is RedirectPermanent in ASP.Net?
  RedirectPermanent Performs a permanent redirection from the requested URL to the specified URL. Once the redirection is done, it also returns 301 Moved Permanently responses.
32: What is MVC?
MVC is a framework used to create web applications. The web application base builds on  Model-View-Controller pattern which separates the application logic from UI, and the input and events from the user will be controlled by the Controller.

33. Explain the working of passport authentication.
First of all it checks passport authentication cookie. If the cookie is not available then the application redirects the user to Passport Sign on page. Passport service authenticates the user details on sign on page and if valid then stores the authenticated cookie on client machine and then redirect the user to requested page
34. What are the advantages of Passport authentication?
All the websites can be accessed using single login credentials. So no need to remember login credentials for each web site.
Users can maintain his/ her information in a single location.
35. What are the asp.net Security Controls?
  • <asp:Login>: Provides a standard login capability that allows the users to enter their credentials
  • <asp:LoginName>: Allows you to display the name of the logged-in user
  • <asp:LoginStatus>: Displays whether the user is authenticated or not
  • <asp:LoginView>: Provides various login views depending on the selected template
  • <asp:PasswordRecovery>:  email the users their lost password
36: How do you register JavaScript for webcontrols ?
We can register javascript for controls using <CONTROL -name>Attribtues.Add(scriptname,scripttext) method.
37. In which event are the controls fully loaded?
Page load event.
38: what is boxing and unboxing?
Boxing is assigning a value type to reference type variable.
Unboxing is reverse of boxing ie. Assigning reference type variable to value type variable.
39. Differentiate strong typing and weak typing
In strong typing, the data types of variable are checked at compile time. On the other hand, in case of weak typing the variable data types are checked at runtime. In case of strong typing, there is no chance of compilation error. Scripts use weak typing and hence issues arises at runtime.
40. How we can force all the validation controls to run?
The Page.Validate() method is used to force all the validation controls to run and to perform validation.
41. List all templates of the Repeater control.
  • ItemTemplate
  • AlternatingltemTemplate
  • SeparatorTemplate
  • HeaderTemplate
  • FooterTemplate
42. List the major built-in objects in ASP.NET? 
  • Application
  • Request
  • Response
  • Server
  • Session
  • Context
  • Trace
43. What is the appSettings Section in the web.config file?
The appSettings block in web config file sets the user-defined values for the whole application.
For example, in the following code snippet, the specified ConnectionString section is used throughout the project for database connection:
?
1
2
3
4
<em><configuration>
<appSettings>
<add key="ConnectionString" value="server=local; pwd=password; database=default" />
</appSettings></em>
44.      Which data type does the RangeValidator control support?
The data types supported by the RangeValidator control are Integer, Double, String, Currency, and Date.
45. What is the difference between an HtmlInputCheckBox control and an HtmlInputRadioButton control?
In HtmlInputCheckBoxcontrol, multiple item selection is possible whereas in HtmlInputRadioButton controls, we can select only single item from the group of items.
46. Which namespaces are necessary to create a localized application?
System.Globalization
System.Resources
47. What are the different types of cookies in ASP.NET?
Session Cookie – Resides on the client machine for a single session until the user does not log out.
Persistent Cookie – Resides on a user’s machine for a period specified for its expiry, such as 10 days, one month, and never.
48. What is the file extension of web service?
Web services have file extension .asmx..
49. What are the components of ADO.NET?
The components of ADO.Net are Dataset, Data Reader, Data Adaptor, Command, connection.
50. What is the difference between ExecuteScalar and ExecuteNonQuery?
ExecuteScalar returns output value where as ExecuteNonQuery does not return any value but the number of rows affected by the query. ExecuteScalar used for fetching a single value and ExecuteNonQuery used to execute Insert and Update statements.

Differentiate between Early binding and late binding

Early binding means calling a non-virtual method that is decided at a compile time while Late binding refers to calling a virtual method that is decided at a runtime.

The polymorphism is achieved by early binding and late binding

Early Binding:

Compiler bind the objects to methods at the compile time.This is called early binding or static binding.Function overloading is example for early binding.

Late Binding:

Compiler bind the objects to methods at the runtime.This is called late binding or dynamic binding.Function overriding is example for late binding.


What is Dynamic Binding and static binding ?
Ans: Well Dynamic binding is objects are binded to the reference object on runtime where as static binding is the binding in which the compiler is straight away aware of which object is binded before runtime.
dynamic binding is also called late binding.
I have shown an example below which uses two classes  DynamicBinding and DBInherit  which inherits the DynamicBinding and overrides an method of the above class , so what happens if create a base class reference and initialise it with junior class object , then I will get the junior class method and not the base class method as it is overridden and the compiler knows it only at runtime.
Hence the output will show the junior class method output (DBInherit  is the junior class referred here) and not the base class.

DynamicBinding.cs class source code:

01. 
02. 
03.using System;
04.using System.Collections.Generic;
05.using System.Linq;
06.using System.Text;
07. 
08.namespace TestCsharp
09.{
10.class DynamicBinding
11.{
12.public virtual void abcd()
13.{
14.Console.Write("In base class\n");
15.}
16.}
17. 
18.class DBInherit : DynamicBinding // this is the junior class
19.{
20.public override void  abcd()
21.{
22.Console.Write("In junior class\n");
23.}
24. 
25.public void abcd2()
26.{
27.Console.Write("In junior class\n");
28.}
29.}
30.}
31. 
32. 
33. 



Program.cs class source code:
01.using System;
02.using System.Collections.Generic;
03.using System.Linq;
04.using System.Text;
05. 
06. 
07. 
08.namespace TestCsharp
09.{
10.class Program : InterfaceTest
11.{
12.static void Main(string[] args)
13.{
14.#region This code is used to show the dynamic binding
15. 
16.DynamicBinding _objDB = new DynamicBinding();
17._objDB.abcd();
18. 
19.DynamicBinding _objDB2 = new DBInherit(); ///this is an example of dynamic binding as the compiler did'nt knew if there is a method overriding the base class method
20._objDB2.abcd();
21. 
22. 
23.#endregion
24. 
25. 
26.}
27.}
28.}

The output will look like as shown below :