Monday 7 May 2012

Sql Server 2008 Interview Questions And Answers

Which are new data types introduced in SQL SERVER 2008?

GEOMETRY Type : The GEOMETRY data type is a system .NET common language runtime (CLR) data type in SQL Server. This type represent data in a two‐dimensional Euclidean coordinate system.
GEOGRAPHY Type: The GEOGRAPHY datatype’s functions are the same as with GEOMETRY. The difference between the two is that when you specify GEOGRAPHY, you are usually specifying points in terms of latitude and longitude.
New Date and Time Datatypes: SQL Server 2008 introduces four new datatypes related to date and time: DATE, TIME, DATETIMEOFFSET, and DATETIME2
DATE: The new DATE type just stores the date itself. It is based on the Gregorian calendar and handles years from 1 to 9999.

TIME: The new TIME (n) type stores time with a range of 00:00:00.0000000 through 23:59:59.9999999. The precision is allowed with this type. TIME supports seconds down to 100 nanoseconds. The n in TIME (n) defines this level of fractional second precision, from 0 to 7 digits of precision.

The DATETIMEOFFSET Type: DATETIMEOFFSET (n) is the time‐zone‐aware version of a datetime datatype. The name will appear less odd when you consider what it really
is: a date + a time + a time‐zone offset. The offset is based on how far behind or ahead you are from Coordinated Universal Time (UTC) time.

The DATETIME2 Type: It is an extension of the datetime type in earlier versions of SQL Server. This new datatype has a date range covering dates from January 1 of year 1 through December 31 of year 9999. This is a definite improvement over the 1753 lower boundary of the datetime datatype. DATETIME2 not only includes the larger date range, but also has a timestamp and the same fractional precision that TIME type provides


What is MERGE Statement?

MERGE is a new feature that provides an efficient way to perform multiple DML operations. In previous versions of SQL Server, we had to write separate statements to INSERT, UPDATE, or DELETE data based on certain conditions, but now, using MERGE statement we can include the logic of such data modifications in one statement that even checks when the data is matched then just update it and when unmatched then insert it. One of the most important advantages of MERGE statement is all the data is read and processed only once.

What is CLR?

In SQL Server 2008, SQL Server objects such as user‐defined functions can be created using such CLR languages. This CLR language support extends not only to user‐defined functions, but also to stored procedures and triggers. You can develop such CLR add‐ons to SQL Server using Visual Studio 2008.

How would you handle error in Sql Server 2008.
SQL Server now supports the use of TRY...CATCH for handling errors. TRY...CATCH lets us build error handling at the level we need, by setting a region where if any error occurs, it will break out of the region and head to an error handler. The basic structure is as follows:

BEGIN TRY
<code>
END TRY
BEGIN CATCH
<code>
End CATCH

So, If any error occurs in the try block, execution is diverted to the catch block, and the error can be dealt.

What are Sparse Columns?
A sparse column is another tool used to reduce the amount of physical storage used in a database. They are the ordinary columns that have an optimized storage for null values. Sparse columns reduce the space requirements for null values at the cost of more overhead to retrieve nonnull values.

What is CTE?

CTE is an abbreviation Common Table Expression. A Common Table Expression (CTE) is an expression that can be thought of as a temporary result set which is defined within the execution of a single SQL statement. A CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query.

What does TOP Operator Do?

The TOP operator is used to specify the number of rows to be returned by a query. The TOP operator has new addition in SQL SERVER 2008 that it accepts variables as well as literal values and can be used with INSERT, UPDATE, and DELETES statements.


Asp.Net 4.0 Interview Questions And Answers

1. What is main focus in Microsoft’s Latest ASP.NET 4.0?
 
Ans.The focus of Microsoft’s latest ASP.NET 4.0 has mainly been on improving the performance and Search-engine Optimization (SEO).

2. What are the improvements Microsoft has done in AJAX Library for ASP.NET 4.0?

Ans.
Following are some major improvements in the AJAX Library in ASP.NET 4.0.

Script Loader: The new script loader control enable developers to load all the required scripts only once, thereby eliminating the unnecessary subsequent requests to the server. It supports the ‘lazy load’ pattern which loads scripts only when necessary, and loads scripts in combination, in order to increase the performance of loading a page. It also supports the jQuery script and custom scripts.
JQuery Integration: ASP.NET 4.0 extensively supports the integration for jQuery by mixing the jQuery and Ajax plug-ins seamlessly.
Client Data Access: By using predefined client controls inside the Ajax Library, developers can easily build asynchronous data-driven applications. For example client DataView control will display one or more records by consuming a WCF service. All the relevant time-consuming operations will be handled by the Ajax library asynchronously.

3. What is Web.config File Refactoring provided in ASP.NET 4.0?

Ans.
The Web.config file that contains configuration information for a Web application has grown considerably over the past few releases of the .NET Framework as new features have been added.
In .the .NET Framework 4, the major configuration elements have been moved to the machine.config file, and applications now inherit these settings. This allows the Web.config file in ASP.NET 4 applications to be empty or to specify only which version of the framework the application is targeting, as shown in the following example:
<?xml version="1.0"?>
    <configuration>
        <system.web>
           <compilation targetFramework="4.0" />
        </system.web>
    </configuration>
4. What is Output Cache Extensibility in ASP.NET 4.0?

Ans.
The main limitation in Output Cache feature in previous versions of ASP.NET is that cached content always had to be stored in-memory. With ASP.NET 4.0 we can extend caching by using Output Cache Providers. We can create ‘Output Cache Providers’ that store the cache content to any persistence mechanism such as databases, disk, cloud storage and distributed cache engines.
To create a custom output-cache provider, a class which derived from System.Web.Caching.OutputCacheProvider has to be created in ASP.NET 4.0. There are four public methods which you have to override in order to provide your own implementation for add, remove, retrieve and update functionality. Also, the output-cache provider has to be registered in theweb.config.
<?xml version="1.0"?>
    <configuration>
        <system.web>
           <outputCache defaultProvider="DemoCache">
               <providers>
                    <add name="DemoCache" type="DemoCacheNamespace, DemoCacheClass" />
                </providers>
            </outputCache>
        </system.web>
    </configuration>
When you use OutputCache like following it will automatically take the default cache provider that is defined in the configuration file.
<%@ OutputCache Duration="60" VaryByParam="None" %>
Or you can also give provider at the time of using OutputCache like following.
<%@ OutputCache Duration="60" VaryByParam="None" providerName="DemoCache" %>
5. How Auto-Start Web Application is achieved in ASP.NET 4.0?

Ans. Scenario in Previous Versions of ASP.NET:
Most application requires initial data load or caching operations to be done before serving the client requests. Typical this happens only when the first user request a page. However, often developers and web administrators write fake requests to keep the application alive to increase the response time.
Resolution: To address this issue in ASP.NET 4.0 we can configure “Application Pool” worker process by setting the startMode attribute to “AlwaysRunning” in the applicationHost.config file which is normally situated at “C:\Windows\System32\inetsrv\config\” as shown in following sample code.
<applicatioPools>
     <add name="appProc" managedRuntimeVersion="v4.0" startMode="AlwaysRunning" />
</applicatioPools>
6. What is advantage of Response.RedirectPermanent over Response.Redirect?

Ans.
For old URLs in previous versions of ASP.NET we can use Response.Redirect method to redirect user to new URL. The problem with it is causing extra round-trip to server to access old URLs and thus decreasing page rank in search engines.
Respnse.RedirectPermanent is using HTTP 301(Moved Permanently) internally to handle requests. This will enable search-engines to index URLs and content efficiently and thus improve the page rankings.
7. How we can use mechanism “Session State Compression” in ASP.NET 4.0?
Ans.
When we store session data in “OutProc” mode that is in state server or SQL server or anywhere else except in memory, we need to serialize our data before storing and deserialize data before retrieving, which will take significant time if the data that we are storing grows and also increase latency of the application.
In ASP.NET 4.0 we can compress data before serializing and decompress before deserializing the data. For defining the compression we need to set compressionEnable attribute to true while setting sessionState properties in web.config configuration file as shown in following demo code.
<sessionState mode="SqlServer" sqlConnectionSting="Your connection string for sql server"
allowCustomSqlDatabase="true" compressionEnable="true" />
Here the session state data will be serialized/deserialized using Session.IO.Compression.GZipStream.

8. In ASP.NET 4.0 how you can expand the range of allowable URLs?

Ans.
Upto foreversions of ASP.NET URLs are limited to 260 characters in length, based on NTFS file path limit. You can now increase(or decrease) this limit according to your requirement using two new attributes of the httpRuntime configuration element.
<httpRuntime maxRequestPathLength="260" maxQueryStringLength="2048" />
9. How you can restrict following characters in URLs of your web application?
<&*%;:\?>

Ans.
In ASP.NET 4.0 you can customize the set of valid characters using new requestPathInvalidChars attribute of the httpRuntime configuration element.
<httpRuntime requestPathInvalidChars="&lt;,&gt;,*,%,&amp;,:,;,\,?" />
10. What is new syntax for encoding string, which is in previous versions like following.
<strong><% =Server.HtmlEncode(content) %>
</strong>

Ans. We can use colon(:) after opening code segment in view as shown below.
<%: content %>
11. Is it possible to set ViewState for individual control in ASP.NET 4.0? If yes then how you could achieve it?
 
Ans. Yes, it is possible to set ViewState for individual control in ASP.NET 4.0. In each web control new attribute ViewStateMode property included. You can set Enabled, Disabled or Inherits to this property.

12. Which are the two properties given by ASP.NET 4.0 to give meta information at page level?
Ans.
ASP.NET introduces MetaKeywords and MetaDescription property to Page object, which you can use in code behind to define the meta information at page level as shown in below sample.
void Page_Load(Object sender, EventArgs e)
{
     Page.MetaDescription = "ASP.NET 4.0 New Features Interview Questions";
     Page.MetaKeywords = "ASP.NET 4.0 New Features, Interview Questions";
}

13. What is the feature that is supported by ASP.NET 4.0 for user friendly and meaningful URLs?
 
Ans. ASP.NET 4.0 supports built in support for URL Routing. This can make site more user friendly and site content more discoverable by search engines. It is also easy to remember and while bookmarking.
Following example shows URL without using Routing mechanism of ASP.NET 4.0.
http://website/products.aspx?categoryid=12
After using Routing mechanism of ASP.NET 4.0, above URL becomes as follow.
http://website/products/software
For mapping above URL to the list of products based on category, we need to map our route using new method MapPageRoute of class Route as shown in following examples.
Application_Start(object sender, EventArgs e)   {
     RouteTable.Routes.MapPageRoute("ProductsRoute",
         "product/{prodId}", "~/products.aspx");
}

14. How predictable cliend IDs generated in ASP.NET 4.0 server controls?
 
Ans. ASP.NET 4 now supports a new ClientIDMode property for server control.
This property indicates how the Client ID should be generated to a particular control
when they render. Client ID has been an important property of the server controls
recently—especially with the success of jQuery and other Ajax scripting technologies.
The ClientIDMode property has four values;
* AutoID – This renders the output as it was before (example: ctl00_ContentPlaceholder1_ListView1_ctrl0_Label1)
* Predictable (Default)– Trims all “ctl00” strings in the Client Id property.
* Static – Full control over the Client ID (developer can set the Client Id and it will not be changed after the control renders)
* Inherit – Allow control to inherit the behavior from its parent control

15. What are the different ways you can set Client ID property in ASP.NET 4.0?
 
Ans. There are four different ways you can set Client ID in ASP.NET 4.0 which are as
follows.
* Directly on individual control (On the container control. (All the child controls will inherit the settings from parent/container control)
* Page or User Control level using <%@ Page%> or <%@ Control %> directives.
* Directly in the web.config file. All the controls within the web application will inherit the settings.

16. What is role of ClientIDRowSuffix for data bound controls in ASP.NET 4.0?
 
Ans. Once we set the relevant databound property to ClientIDRowSuffix, the value will be added as a suffix to individual row elements. The example of which is as follow.
<asp:DataList ID="DataList1" ClientIDRowSuffix="State" runat="server">
</asp:DataList>
The state value will be added as suffix to each data row element as follows.
<ul>
     <li ID="John_NY">
          John
     </li>
     <li ID="Brian_CA">
          Brian
     </li>
</ul>

Thursday 3 May 2012

Master Page In Silverlight

There is no MasterPage in Silverlight, so we have to create something similiar to that.

Lets Begin :)

Step 1.
//MainPage.xaml


There are 3 Grids inside main Grid, first Grid is for Header, second Grid act as a Container for other Silverlight UserControls [like Home, AboutUs] and third Grid is for Footer.

<Grid x:Name="LayoutRoot" Background="White"  Height="500" Width="700" >
        <Grid.RowDefinitions>
            <RowDefinition Height="30" />
            <RowDefinition/>
            <RowDefinition Height="30" />
        </Grid.RowDefinitions>

        <Grid x:Name="GridHeader" Grid.Row="0">
            <Grid.Background>
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="Blue" Offset="0"/>
                    <GradientStop Color="#FFFBF5F5" Offset="1"/>
                </LinearGradientBrush>
            </Grid.Background>

            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="128*" />
                <ColumnDefinition Width="158*" />
                <ColumnDefinition Width="152*" />
                <ColumnDefinition Width="128*" />
                <ColumnDefinition Width="134*" />
            </Grid.ColumnDefinitions>

            <HyperlinkButton x:Name="hlbhome" Foreground="White" Grid.Column="0" Content="Home" FontSize="12" FontFamily="Arial" FontWeight="Bold" Margin="26,8,13,0" Click="hlbhome_Click" Height="18" VerticalAlignment="Top" />
            <HyperlinkButton x:Name="hlbAboutUs" Foreground="White" Grid.Column="1"  Content="About Us" FontSize="12" FontFamily="Arial" FontWeight="Bold" Margin="26,8,13,0" Click="hlbAboutUs_Click" Height="18" VerticalAlignment="Top" />
            <HyperlinkButton x:Name="hlbLogin" Foreground="White" Grid.Column="2"  Content="Login" FontSize="12" FontFamily="Arial" FontWeight="Bold" Margin="26,8,13,0" Click="hlbLogin_Click" Height="18" VerticalAlignment="Top" />
            <HyperlinkButton x:Name="hlbRegister" Foreground="White" Grid.Column="3"  Content="Register" FontSize="12" FontFamily="Arial" FontWeight="Bold" Margin="26,8,13,0" Click="hlbRegister_Click" Height="18" VerticalAlignment="Top" />
            <HyperlinkButton x:Name="hlbContactUs" Foreground="White" Grid.Column="4"  Content="Contact Us" FontSize="12" FontFamily="Arial" FontWeight="Bold" Margin="26,8,13,0" Click="hlbContactUs_Click" Height="18" VerticalAlignment="Top" />

        </Grid>
        <Grid x:Name="GridContainer" Grid.Row="1">
            <Grid.Background>
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="Blue" Offset="0"/>
                    <GradientStop Color="#FFEBD0D0" Offset="0"/>
                </LinearGradientBrush>
            </Grid.Background>
        </Grid>

        <Grid Grid.Row="2" >
            <Grid.Background>
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="Blue" Offset="0"/>
                    <GradientStop Color="#FFFBF5F5" Offset="1"/>
                </LinearGradientBrush>
            </Grid.Background>
            <TextBlock x:Name="footer" Text="Created by...." VerticalAlignment="Center" HorizontalAlignment="Center" />
        </Grid>
    </Grid>

On click of Hyperlinks corresponding UserControls will appear inside GridContainer.

Note :- Here we are using 'LinearGradientBrush' for giving some background color to Grids.

Step 2.
//MainPage.xaml.cs

  Home home;
  AboutUs aboutUs;
  Login login;
  Register register;
  ContactUs contactUs;

   public MasterPage()
   {
           InitializeComponent();
            home = new Home();
            aboutUs = new AboutUs();
            login = new Login();
            register = new Register();
            contactUs = new ContactUs();

            //Setting Home page as a default page.

            GridContainer.Children.Clear();
            GridContainer.Children.Add(home);
        }

        private void hlbhome_Click(object sender, RoutedEventArgs e)
        {
            GridContainer.Children.Clear();
            GridContainer.Children.Add(home);
        }

        private void hlbAboutUs_Click(object sender, RoutedEventArgs e)
        {
            GridContainer.Children.Clear();
            GridContainer.Children.Add(aboutUs);
        }

        private void hlbLogin_Click(object sender, RoutedEventArgs e)
        {
            GridContainer.Children.Clear();
            GridContainer.Children.Add(login);
        }

        private void hlbRegister_Click(object sender, RoutedEventArgs e)
        {
            GridContainer.Children.Clear();
            GridContainer.Children.Add(register);
        }

        private void hlbContactUs_Click(object sender, RoutedEventArgs e)
        {
            GridContainer.Children.Clear();
            GridContainer.Children.Add(contactUs);
        }


Step 3.
On click of  Hyperlink Home and AboutUs, Header and Footer remain same as it will be appear in real MasterPage -





 





Wednesday 2 May 2012

Upload File In Silverlight

Silverlight doesn't have upload control, here we are uploading a file using OpenFileDialog from silverlight client to server location using wcf.

Step 1.
In Silverlight Web application -> Add -> Add New Item -> Silverlight-enabled wcf -> Add.

Step 2.
In WCF,
[OperationContract]
public void SaveFile(UploadFile uploadfile)
{
            FileStream filestream = new FileStream("E:\\Uploaded\\" + uploadfile.FileName, FileMode.Create);
            filestream.Write(uploadfile.File, 0, uploadfile.File.Length);
            filestream.Close();
            filestream.Dispose();
  }

        
[DataContract]
public class UploadFile
{
            [DataMember]
            public string FileName;
            [DataMember]
            public byte[] File;
}

Step 3.

Add service reference -




















Step 4.
//MainPage.xaml
















Step 5.
//MainPage.xaml.cs

public OpenFileDialog fileDialog = null;
        
public MainPage()
{
         InitializeComponent();
 }

 private void btnUploadFile_Click(object sender, RoutedEventArgs e)
 {
         ServiceReference1.Service1Client service = new ServiceReference1.Service1Client();
         fileDialog = new OpenFileDialog();
         fileDialog.Filter = "All Files|*.*";
         bool? result = fileDialog.ShowDialog();
         if (result != null && result == true)
         {
                Stream strm = fileDialog.File.OpenRead();
                byte[] Buffer = new byte[strm.Length]; strm.Read(Buffer, 0, (int)strm.Length);
                strm.Dispose();
                strm.Close();

                //Accessing DataContract...

                ServiceReference1.Service1UploadFile file = new ServiceReference1.Service1UploadFile();
                file.FileName = fileDialog.File.Name;
                file.File = Buffer;
                service.SaveFileAsync(file);
                service.SaveFileCompleted += new EventHandler                 <System.ComponentModel.AsyncCompletedEventArgs>(service_SaveFileCompleted);
        }
        else
        {
                txtMsg.Text = "Plz Select File !!! ";
         }

    }

  public void service_SaveFileCompleted(object sender,    System.ComponentModel.AsyncCompletedEventArgs e)
 {
        if (e.Error == null)
             txtMsg.Text = fileDialog.File.Name + "Successfully Saved";
  }