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";
  }




Sunday, 29 April 2012

Validation In Silverlight


By default silverlight doesn't give any visual feedback when the data binding system encounters error relating to incorrect input. But internally it rejects data and user is thinking that data has been saved. Silverlight data binding engine has to notify or alert us through visual appearance when there is a violation of rule.

Lets begin :)

1. Create a silverlight application and add the following Student class to your project

public class Student
{
public string Name{get; set;}
public int Age{get; set;}
}

2.//MainPage.xaml.cs

public MainPage()
{
initializeComponent();
Student std= new Student();
LayoutRoot.DataContext =std;
}

3.//MainPage.xaml
Run the application and type string in the age field . Internal validation has happened by rejecting the  invalid input but no visual feedback.

4.ValidatesOnExceptions = True, by doing that, it will makes sure silverlight will provide visual feedback for the validation error.
<TextBox Name="txtName" Text="{Binding Name,ValidatesOnExceptions=True}"
<TextBox Name="txtAge" Text="{Binding Age,ValidatesOnExceptions=True}"

5. Again type string value in Age textbox, this appearance will come :)




Friday, 27 April 2012

Silverlight Deep Zooming

The idea behind Deep Zoom is to present a “zoom-able” interface for huge images. The typical Deep Zoom image is far too large to be shown on screen at once at its native resolution.

It’s easy to create a Silverlight application that uses Deep Zoom, provided you have the  right tools. The most important is the free Deep Zoom Composer tool. The Deep Zoom Composer allows you to convert a large image into the tiled groups of images that Deep Zoom needs for its zooming interface. It also lets youtile together smaller images to create a large image that’s suitable for Deep Zoom, and it can even stitch overlapping images together automatically.

To get started, load Deep Zoom Composer, and click New Project. You’ll need to choose a project name and a project location.One folder, named Source Images, holds the original versions of all the pictures you import. The second folder, named Working Data, holds the dozens of image files that are generated when you lay these pictures out into a Deep Zoom image set.

Note : Deep Zoom project can only be opened in Deep Zoom composer. You must export the image set to generate a Silverlight project.

1.To get the pictures you want, click the Import button in the panel at right, browse to the correct file, and click OK. Importing large pictures can be slow, so be prepared to wait.

2.until you’ve imported all the pictures you need.

3.Click the Compose button. and lay out your pictures.
 
4.To add, drag picture  from the panel at the bottom.
 
5.Click the Export button. Deep Zoom Composer gives several export options The two most useful are to export your image set to DeepZoomPix or to create a Silverlight project.

6.To create a Silverlight project, click the Custom tab in the panel at the right. In the“Output type” box, choose Silverlight Deep Zoom

7. In the Name text box, enter a name for your project. If you want to export the project to a different folder, change the path in the Location text box.

8.Choose “Export as a collection” to create a Deep Zoom image set.
 
9.In the “Image settings” box , choose either PNG or JPEG.
 
10.Click Export to create the image set and Silverlight project.

Showing a Deep Zoom image in a Silverlight application is fairly easy. In fact, all you need is the MultiScaleImage element, as shown here:

<MultiScaleImage x:Name="msi" Height="600" Width="800"/>

Wednesday, 25 April 2012

Silverlight Video Support

When it comes to video, Silverlight supports the follow standards:

• Windows Media Video 7 (WMV1)
• Windows Media Video 8 (WMV2)
• Windows Media Video 9 (WMV3)
• Windows Media Video Advanced Profile, non-VC-1 (WMVA)
• Windows Media Video Advanced Profile, VC-1 (WMVC1)
• H.264 video and AAC audio (also known as MPEG-4 Part 10 or MPEG-4 AVC)

First, create a MediaElement for the file you want to play :

<MediaElement x:Name="fireMovie" Source="fire.wmv" Height="200" Width="200"></MediaElement>

Often, you can recognize Windows Media Video by the file extension .wmv. Other video formats – for example, MPEG and QuickTime–need not apply. The last two formats in this list–VC-1 and H.264–are widely supported.

WMV files you use in your Silverlight application will be a final product based on larger, higher-quality original video files. Often, the original files will be in a non-WMV format.

To get the right results when preparing video for the Web, you need the right tool. Expression Encoder is a remarkably polished and powerful tool.

Key features:

Simple video editing : You can cut out sections of video, insert a lead-in, and perform other minor edits.

Overlays : You can watermark videos with a still or animated logo that stays superimposed over the video for as long as you want it to.

Silverlight-ready : allows you to create a fully skinned Silverlight video player.

To encode a video file in Expression Encoder, follow these steps :

1.To specify the source file, choose File Import. Browse to the appropriate media file, select it, and click Open.

2.To specify the destination file, look at the group of tabs on the right side of the window, and select the Output tab. In the Job Output section, you can specify the directory where the new file will be placed, and its name.

3.To choose the bit rate, look in the Presets tab (in the top-right corner of the window) and expand the Encoding for Silverlight section. If you’re using progressive downloads, you need to select a format from the Variable bitrate group.

4.After you choose an encoding, the relevant information appears in the Video section of the Encode tab.

5.To encode your video, click the Encode button at the bottom of the window, in the Media Content panel.

Tuesday, 24 April 2012

Silverlight Audio Support

Adding audio to a Silverlight application is fairly easy, because you can throw in just about any MP3 file. Using a video file is more work. Not only must you make sure you’re using one of the supported WMV formats, but you also need to carefully consider the quality you need and the bandwidth your visitors can support.

For audio, Silverlight supports the following :

• Windows Media Audio (WMA) [versions 7, 8, and 9]
• MP3

All the audio and video functionality is built into a single class: MediaElement. A simple MediaElement tag is all you need to play a sound. For example, add this markup to your user interface :

<MediaElement Source="test.mp3"></MediaElement>

The startup behavior of the MediaElement is determined by its AutoPlay property. If this property is set to false, the audio file is loaded, but your code takes responsibility for starting the playback at the right time :

<MediaElement x:Name="media" Source="test.mp3" AutoPlay="False"></MediaElement>

When using this approach, you must make sure to give the MediaElement a name so that you can interact with it in code. Generally, interaction consists of calling the Play(), Pause(), and Stop() methods.
We can change the Position property to move through the audio.
Here’s a simple event handler that seeks to the beginning of the current audio file and then starts playback : 

private void cmdPlay_Click(object sender, RoutedEventArgs e)
{
media.Position = TimeSpan.Zero;
media.Play();
}

The two check boxes on the page are the last ingredient in this media player and one of the simplest details. The Mute check box sets the corresponding IsMuted property of the MediaElement :
private void chkMute_Click(object sender, RoutedEventArgs e)
{
media.IsMuted = (bool)chkMute.IsChecked;
}

Handling errors :
MediaElement doesn’t throw an exception if it can’t find or load a file. Instead, it’s up to you to handle the MediaFailed event. Fortunately, this task is easy. First, tweak your MediaElement tag as shown here :
<MediaElement ... MediaFailed="media_MediaFailed"></MediaElement>
Then, in the event handler, you can use the
ExceptionRoutedEventArgs.ErrorException property to get an exception object that describes
the problem. Here’s an example that displays the appropriate error message:
private void media_MediaFailed(object sender, ExceptionRoutedEventArgs e)
{
lblErrorText.Text = e.ErrorException.Message;
}

The MediaElement exposes a number of properties that allow you to control your playback.
Volume : Sets the volume as a number from 0 (completely muted) to 1 (full volume). The default value is 0.5.set IsMuted to true for temporarily muting.

Balance : Sets the balance between the left and right speaker as a number from -1 (left speaker only), 1(right speaker only) and 0 by default.

Position : Provides a TimeSpan object that indicates the current location in the media file.

<Slider Grid.Column="1" x:Name="sliderVolume" Minimum="0" Maximum="1" Value="0.5"
ValueChanged="sliderVolume_ValueChanged" ></Slider>

<Slider Grid.Row="1" Grid.Column="1" x:Name="sliderBalance" Minimum="-1" Maximum="1"
ValueChanged="sliderBalance_ValueChanged"></Slider>

When the user drags the thumb in the slider, the change is applied to the MediaElement :
private void sliderVolume_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
media.Volume = sliderVolume.Value;
}

private void sliderBalance_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
media.Balance = sliderBalance.Value;
}

The Mute check box sets the corresponding IsMuted property of the MediaElement :
private void chkMute_Click(object sender, RoutedEventArgs e)
{
media.IsMuted = (bool)chkMute.IsChecked;
}

Linq To Sql

LINQ to Sql  interact and provides query capability to relational database.

Architecture of LINQ to sql consists of :

Object Model - It consists of Data Context and Data Entities. Data entities are the partial classes generated by Linq to sql. Data context define connection to the database.It maps data entities with databae tables and
fills the objects into generic collection type called Table<>. It also maps Stored Procedures and user defined functions.
 
Object Relational Designer  

Runtime
 
Key Features of Linq to sql :-

1)Generating Object Model From db -  Linq to Sql connects to sql server db and creates ObjectModel by dragging  and dropping tables from the server explorer.

2)Stored Procedures and user defined functions support - linq to sql supports stored procedures and user-defined functions by generating corresponding methods in DataContext.

3)Framework compatibilities - linq to sql is part of .Net framework 3.5 and higher.

Strengths :-

1)Linq to sql queries are well-integrated with programming lang. this helps in avoiding Sql Injection attacks.

2)Uniform syntax for working with various data sources like xml, relational datastores like sql server.

3)Improve app. dev by proving Intellisense, compile time syntax checking and debugging support.

4)Support compiled queries and stored procedure to enhance the overall performance of db operations.

Weakness:-

1)Linq to Sql only works with Sql Server Db.

2)From main object, navigation to foreign key, reference object is not possible.

3)It supports only bottom-up design i.e database to object oriented and not the other way.

Summary :-

It overcome several drawbacks of Ado.Net by providing single uniform type query language to query relational and non relational datastores in obj oriented manner. User friendly object oriented syntax, highly
optimized for MS sql server.




Tuesday, 10 January 2012

Navigation In Silverlight

Navigation in Silverlight can be achieved by managing Root Visual in App.xaml. We can use layout container as Silverlight application's root visual, this container may be border or Grid. In root visual, we can change user control that represents first page with different user control that represents other page. This technique is simple and requires less codes. It also has ability of state management and animation.

//App.xaml.cs
   
       // This Grid will host pages.
        private Grid rootGrid = new Grid();

        private void Application_Startup(object sender, StartupEventArgs e)
        {
           // Load the first page.
            this.RootVisual = rootGrid;
            rootGrid.Children.Add(new Register());
        }

        public static void Navigate(UserControl newPage)
        {
            App currentApp = (App)Application.Current;
            // Change the currently displayed page.
            currentApp.rootGrid.Children.Clear();
            currentApp.rootGrid.Children.Add(newPage);
        }

Note : Navigate method is static for making process straightforward.

Now, In Silverlight application navigation can be performed by using this code :)

App.Navigate(new confirm());