Wednesday, July 25, 2012

Mobile Apps in C#

Hello World. The First Windows Mobile Application.

Now we are going to start develop our first windows mobile application :D.
Follow the step:

1. Open your visual studio.
2. Press project from create section.




3. New Project wizard will open. Please rename the app as HelloWorld. Note the Location for farther use.Then press OK.




4. For viewing Solution Explorer Select View->Solution Explorer.
5. For viewing Properties Window Select View->Properties Window.
6. From the Solution Explorer Select the Form1.  And double click on it if you are not seeing from window on the project window.
7. For viewing Toolbox Select View->Toolbox .
8. From the Toolbox please select a Lable control and double click on it. It will appear on the Form1.



9. Position the Label Control in center by drag and drop.

















10. Now open the Properties Window.

















11. On the Text Property there is a text label1. Select this text and remove it by pressing delete key. Type here the HELLO WORLD Text. And Save the Application.

Believe it or not we have just finished to develop our first windows mobile application without write a single line of code  :D.

Executing The HELLO WORLD:

For executing this application please select The Start Debugging From the Debug menu. Or press F5 key.


 After doing that there is the Deploy Wizard Window appeared. Please select the Windows Mobile 5.0 Smartphone Emulator the press the Deploy button.



















Please wait some time Visual Studio will deploy the application before run.
When it finished the deployment you will see the result.

This is the very basic level of tutorial. But it might be helpful for those who are not yet familiar with the windows mobile device application development.

I am using the Windows mobile 5.0 Smartphone SDK for this tutorial. But you can use other version of sdk as well.

Tuesday, July 24, 2012

.NET Assemblies

What is an assembly?
Assemblies are the basic building blocks required for any application to function in the .NET realm. They are partially compiled code libraries that form the fundamental unit of deployment, versioning, activation scoping, reuse, and security. Typically, assemblies provide a collection of types and resources that work together to form a logical unit of functionality. They are the smallest deployable units of code in .NET. Compared to the executable files assemblies are far more reliable, more secure, and easy to manage. An assembly contains a lot more than the Microsoft Intermediate Language (MSIL) code that is compiled and run by the Common Language Runtime (CLR). In other words, you can say that an assembly is a set of one or more modules and classes compiled in MSIL, and metadata that describes the assembly itself, as well as the functionalities of the assembly classes.
2. Name the different components of an assembly.
An assembly is a logical unit that is made up of the following four different types of components:

  • Assembly manifest
  • MSIL source code
  • Type metadata
  • Resources
3. What are the different types of assemblies? Explain them in detail.
The following are the two types of assemblies:

  • Private Assembly - Refers to the assembly that is used by a single application. Private assemblies are kept in a local folder in which the client application has been installed.
  • Public or Shared Assembly - Refers to the assembly that is allowed to be shared by multiple applications. A shared assembly must reside in Global Assembly Cache (GAC) with a strong name assigned to it.
For example, imagine that you have created a DLL containing information about your business logic. This DLL can be used by your client application. In order to run the client application, the DLL must be included in the same folder in which the client application has been installed. This makes the assembly private to your application. Now suppose that the DLL needs to be reused in different applications. Therefore, instead of copying the DLL in every client application folder, it can be placed in the global assembly cache using the GAC tool. These assemblies are called shared assemblies.
4. Can one DLL file contain the compiled code of more than one .NET language?
No, a DLL file can contain the compiled code of only one programming language.
5. What is the maximum number of classes that can be contained in a DLL file?
There is no limit to the maximum number of classes that can be contained in a DLL file.
6. What is a satellite assembly?
Satellite assemblies are assemblies that are used to deploy language and culture specific resources for an application. In an application, a separate product ID is assigned to each language and a satellite assembly is installed in a language specific sub-directory.
7. Is versioning applicable to private assemblies?
No, versioning is not applicable to private assemblies as these assemblies reside in their individual folders. Versioning can be applied to GAC only.
8. What is metadata?
An assembly metadata describes every data type and member defined in the code. It stores the description of an assembly, such as name, version, culture, public key of an assembly along with the types exported, other assemblies dependent on this assembly, and security permissions needed to run the application. In addition, it stores the description of types, such as the name, visibility, base class, interfaces implemented, and members, such as methods, fields, properties, events, and nested types.

It also stores attributes. Metadata is stored in binary format. Therefore, metadata of an assembly is sharable among applications that execute on various platforms. It can also be exported to other applications to give information about the services and various features of an application.
9. What is Assembly Manifest?
Assemblies maintain all their information in a special unit called the manifest. Every assembly has a manifest.

The followings are the contents of an Assembly Manifest:

  • Assembly name - Represents a text string that specifies the assembly's name.
  • Version number - Represents a major and minor version number, as well as a revision and build number. The CL.R makes use of these numbers to enforce version policy.
  • Culture - Represents information of the culture or language, which the assembly supports. An assembly is a container of only resources containing culture- or language-specific information.
  • Strong name information - Represents the public key from the publisher, if a strong name is assigned to an assembly.
  • List of all files in the assembly - Represents a hash of each file contained in the assembly and a file name.
  • Type reference information - Represents the information used at the runtime to map a type reference to the file that contains its declaration and implementation.
  • Information on referenced assemblies - Represents a list of other assemblies that are statically referenced by the assembly. Each reference includes the names of dependent assemblies, assembly metadata (version, culture, operating system, and so on), and public key, if the assembly is strong named.
10. What is the value of the Copy Local property when you add an assembly in the GAC?
False.
11. What is Native Image Generator?
The Native Image Generator (Ngen.exe) is a tool that creates a native image from an assembly and stores that image to native image cache on the computer. Whenever, an assembly is run, this native image is automatically used to compile the original assembly. In this way, this tool improves the performance of the managed application by loading and executing an assembly faster.

Note that native images are files that consist of compiled processor-specific machine code. The Ngen.exe tool installs these files on to the local computer.

Background

The Windows Communication Foundation (WCF) is an application programming interface in the .NET Framework for building connected, service-oriented applications. A WCF client has two ways to access the functions provided by WCF services. They are synchronous and asynchronous WCF calls.
This article is an example to show you how to access WCF services in both ways, synchronously as well as asynchronously. This article assumes that the readers have some basic understandings of the WCF services. If you are not familiar with WCF services, this link is a good place to get you started. In this article, I will first build a WCF service. I will then show you how to access this service. The following is a screen shot of this example Visual Studio solution in the solution explorer:
VisualStudio.jpg This Visual Studio solution has three .NET projects:
  • The "WCFServiceImplementation" project is a class library that implements the WCF service.
  • The "WCFServiceHost" project is an ASP.NET web application that hosts the WCF service implemented in the "WCFServiceImplementation" project.
  • The "WCFCallExample" project is a WPF application, where I will demonstrate the two ways to access the WCF service.
This Visual Studio solution is developed in C# in Visual Studio 2008. We will take a look at how the WCF service is implemented first.

The Implementation of the WCF Service

VisualStudioImplementation.jpg The .NET project "WCFServiceImplementation" is a class library. The entire WCF service is implemented in this project in the "StudentService.cs" file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
 
namespace WCFServiceImplementation
{
    [ServiceContract]
    public interface IStudentService
    {
        [OperationContract]
        List<Student> GetStudents(int NoOfStudents);
    }
 
    [DataContract]
    public class Student
    {
 
        [DataMember(Order = 1)]
        public int StudentID { get; set; }
 
        [DataMember(Order = 2)]
        public string StudentName { get; set; }
 
        [DataMember(Order = 3)]
        public int Score { get; set; }
 
        [DataMember(Order = 4)]
        public DateTime EvaluationTime { get; set; }
    }
 
    public class StudentService : IStudentService
    {
        public List<Student> GetStudents(int NoOfRecords)
        {
            List<Student> studentList = new List<Student>();
 
            Random rd = new Random();
            for (int Idex = 1; Idex <= NoOfRecords; Idex++)
            {
                Student student = new Student();
                student.StudentID = Idex;
                student.StudentName = "Student Name No." + Idex.ToString();
                student.Score = (int)(60 + rd.NextDouble() * 40);
                student.EvaluationTime = System.DateTime.Now;
 
                studentList.Add(student);
            }
 
            System.Threading.Thread.Sleep(10000);
 
            return studentList;
        }
    }
}
This class library defines the following:
The "service contract" "IStudentService" is implemented in the "StudentService" class. When accessing the WCF service, a WCF client can make a WCF call to the "GetStudents" method by passing the number of the student records to the proxy method at the client side. The "GetStudents" method then randomly generates a List of "Student" objects and sends the List of these objects to the caller. You may notice that "System.Threading.Thread.Sleep(10000)" is added to the "GetStudents" method to artificially delay the response of the WCF service, so we can see the difference between the synchronous and asynchronous WCF calls at the client side.

The WCF Service Host Application "WCFServiceHost"

The WCF service is hosted in the ASP.NET application project "WCFServiceHost", which is shown as the following in the solution explorer:
VisualStudioHost.jpg In this project, the WCF service is hosted in the "StudentService.svc" file. Since the entire implementation of the WCF service is completed in the "WCFServiceImplementation" class library, the "StudentService.svc" file is as simple as the following:
 <%@ ServiceHost Language="C#" Debug="true" 
    Service="WCFServiceImplementation.StudentService" %>
The configuration of the WCF service in the "Web.config" file is the following:
<system.serviceModel>
    <services>
      <service behaviorConfiguration="WCFServiceHost.ServiceBehavior"
        name="WCFServiceImplementation.StudentService">
        <endpoint address="" binding="basicHttpBinding" 
  contract="WCFServiceImplementation.IStudentService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
      
    </services>
    
    <behaviors>
      <serviceBehaviors>
        <behavior name="WCFServiceHost.ServiceBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
</system.serviceModel>
If we now right-click on the file "StudentService.svc" and select "View in Browser" in the solution explorer, a web browser window is open showing that the WCF service is functioning. The end-point address of the WCF service is shown in the address bar of the browser:
ViewInBrowser.jpg

The Example WCF Client Application "WCFCallExample"

The following is the simple WPF application "WCFCallExample" shown in the solution explorer. This application is the example client application to access the WCF service built before.
VisualStudioWPFApplicationFull.jpg The "Service Reference" "StudentService" is added to the project using the "Adding service reference" utility provided by the Visual Studio. After adding the "StudentService" reference, the Visual Studio will generate all the client proxies for accessing the WCF service. When adding this reference, you will need to click the "Advanced ..." button and open the "Service Reference Settings" window. You need to make sure that the "Generate asynchronous operations" checkbox is checked:
ProxyGenerateAsync.jpg By checking this checkbox, Visual Studio will generate the proxies to support both synchronous and asynchronous calls to the WCF service.
The "WPF user control" "WCFCallExample" implemented in the "WCFCallExample.xaml" and its code-behind file will be used to demonstrate both synchronous and asynchronous calls to the WCF service using the proxies generated. The "WCFCallExample.xaml" file is shown as the following:
<UserControl x:Class="WFCCallExample.WCFCallExample"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:Toolkit="http://schemas.microsoft.com/wpf/2008/toolkit"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    
    <Grid VerticalAlignment="Stretch"
          HorizontalAlignment="Stretch" Margin="10,10,10,10">
        
        <Grid.RowDefinitions>
            <RowDefinition Height="23" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        
        <StackPanel Grid.Row="0" Orientation="Horizontal" HorizontalAlignment="Right">
            <TextBlock Style="{StaticResource SmallBold}">
                Select the number of the students:
            </TextBlock>
            
            <ComboBox Margin="10,0,0,0" Name="cmbNumberOfStudents" Width="80"
                      SelectionChanged="cmbNumberOfStudents_SelectionChanged" />
            
            <Button Margin="10,0,0,0" Width="150" Click="WCFServiceCall_Click">
                Make WCF service call</Button>
            
            <Button Margin="10,0,0,0" Width="150" Click="ClickMe_Click">
                Click me!</Button>
        </StackPanel>
        
        <Toolkit:DataGrid Margin="0,10,0,10" AutoGenerateColumns="False"
                          Grid.Row="1" Name="DGStudent" IsReadOnly="True">
            <Toolkit:DataGrid.Columns>
                <Toolkit:DataGridTextColumn Header="StudentID" 
   Binding="{Binding StudentID}" />
                <Toolkit:DataGridTextColumn Header="StudentName" 
   Binding="{Binding StudentName}" />
                <Toolkit:DataGridTextColumn Header="Score" Binding="{Binding Score}" />
                <Toolkit:DataGridTextColumn Header="EvaluationTime" 
   Binding="{Binding EvaluationTime}" />
            </Toolkit:DataGrid.Columns>
        </Toolkit:DataGrid>
    </Grid>
</UserControl>
This "XAML" file defines the following major functional "UI elements":
  • A "ComboBox" to select the number of the students to retrieve from the WCF service.
  • A "DataGrid" to display the information of the students obtained from the WCF service.
  • A "Button" labeled as "Make WCF service call" to issue the WCF calls.
  • A "Button" labeled as "Click me!" to pop up a simple "Messagebox". This button is used to show if the UI thread is blocked by the WCF call.
The code-behind file of the "WCFCallExample.xaml" file is the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ServiceModel;
 
namespace WFCCallExample
{
    /// <summary>
    /// Interaction logic for WCFCallExample.xaml
    /// </summary>
    public partial class WCFCallExample : UserControl
    {
        private bool AsynchronousCall = false;
 
        public WCFCallExample(bool AsynchronousCall)
        {
            InitializeComponent();
            this.AsynchronousCall = AsynchronousCall;
 
            cmbNumberOfStudents.Items.Add("****");
            cmbNumberOfStudents.SelectedIndex = 0;
            for (int Idex = 5; Idex <= 30; Idex = Idex + 5)
            {
                cmbNumberOfStudents.Items.Add(Idex);
            }
        }
 
        private void ClickMe_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("OK, I am clicked ...");
        }
 
        private void WCFServiceCall_Click(object sender, RoutedEventArgs e)
        {
            if (cmbNumberOfStudents.SelectedValue.ToString() == "****")
            {
                MessageBox.Show("Please select the number of the students to retrieve");
                return;
            }        
 
            DGStudent.ItemsSource = null;
 
            int NumberOfStudents =
                System.Convert.ToInt16(cmbNumberOfStudents.SelectedValue);
 
            if (AsynchronousCall) { MakeAsynchronousCall(NumberOfStudents); }
            else { MakeSynchronousCall(NumberOfStudents); }
        }
 
        private void cmbNumberOfStudents_SelectionChanged(object sender,
            SelectionChangedEventArgs e)
        {
            DGStudent.ItemsSource = null;
        }
 
        private void MakeSynchronousCall(int NumberOfStudents)
        {
            StudentService.StudentServiceClient WCFClient =
                new WFCCallExample.StudentService.StudentServiceClient();
            
            try
            {
                WCFClient.Open();
                List<StudentService.Student>  Students =
                    WCFClient.GetStudents(NumberOfStudents);
 
                DGStudent.ItemsSource = Students;
            }
            catch (Exception ex){ MessageBox.Show(ex.Message); }
            finally
            {
                if (WCFClient.State ==
                    System.ServiceModel.CommunicationState.Opened)
                {
                    WCFClient.Close();
                }
            }
        }
 
        private void MakeAsynchronousCall(int NumberOfStudents)
        {
            BasicHttpBinding basicHttpBinding = new BasicHttpBinding();
            StudentService.StudentServiceClient c =
                new WFCCallExample.StudentService.StudentServiceClient();
            EndpointAddress endpointAddress = c.Endpoint.Address;
 
            StudentService.IStudentService iStudentService =
                new ChannelFactory<StudentService.IStudentService>
                (basicHttpBinding, endpointAddress).CreateChannel();
 
            AsyncCallback aSyncCallBack =
                delegate(IAsyncResult result)
            {
                try
                {
                    List<StudentService.Student> Students =
                        iStudentService.EndGetStudents(result);
 
                    this.Dispatcher.BeginInvoke((Action)delegate
                    { DGStudent.ItemsSource = Students; });
                }
                catch (Exception ex)
                {
                    this.Dispatcher.BeginInvoke((Action)delegate
                    { MessageBox.Show(ex.Message); });
                }
            };
 
            try
            {
                iStudentService.BeginGetStudents(NumberOfStudents,
                    aSyncCallBack, iStudentService);
            } catch (Exception ex) { MessageBox.Show(ex.Message); }
        }
    }
}
This code-behind file does the following:
  • It defines a private boolean type instance variable "AsynchronousCall", which will be initiated in the constructor of the class. This boolean variable will be used by the event handling method "WCFServiceCall_Click" to decide if a synchronous call or an asynchronous call should be made to the WCF service when the "Make WCF service call" button is clicked.
  • If a synchronous call should be made, the method "MakeSynchronousCall" is used. It will issue a synchronous WCF call and bind the list of the student information from the WCF service to the "DataGrid".
  • If an asynchronous call should be made, the method "MakeAsynchronousCall" is used. It will issue an asynchronous call and bind the list of the student information from the WCF service to the "DataGrid" in the "AsyncCallback" "delegate".
Both synchronous and asynchronous calls to the WCF service are pretty simple by using the proxies generated by the Visual Studio. When making a synchronous call, the UI thread that issues the call will be blocked until the WCF service sends the results back to the client. When an asynchronous call is made, the UI thread sends the WCF request and forks a worker thread to wait for the response from the WCF service. The UI thread is not blocked and remains responsive to other user interactions. When the response from the WCF service comes back, the "AsyncCallback" "delegate" is executed to process the WCF service response.
This "user control" "WCFCallExample" is hosted in the application's main window "MainWnd.xaml":
 <Window x:Class="WFCCallExample.MainWnd"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Style="{StaticResource WindowDefault}"
    Title="{Binding Path=ApplicationName, Mode=OneTime}"
        WindowStartupLocation="CenterScreen"
        WindowState="Maximized"
        Icon="Images/Rubik-Cube.ico">
    
    <Grid VerticalAlignment="Stretch"
          HorizontalAlignment="Stretch" Margin="5,20,5,5">
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="20" />
        </Grid.RowDefinitions>
        
        <Grid Grid.Row="0">
            <Grid.RowDefinitions>
                <RowDefinition Height="60" />
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>
            
            <Grid Grid.Row="0" HorizontalAlignment="Stretch">
                <Grid.RowDefinitions>
                    <RowDefinition Height="20" />
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
                
                <TextBlock Grid.Row="0" Style="{StaticResource AppHeader}"
                           HorizontalAlignment="Center"
                           Text="{Binding Path=ApplicationName, Mode=OneTime}" />
                
                <StackPanel Grid.Row="1" Orientation="Horizontal" 
    HorizontalAlignment="Center">
                    <TextBlock xml:space="preserve"
                               Style="{StaticResource AuthorInformation}">
      Developed by </TextBlock>
                    <TextBlock xml:space="preserve" 
   Style="{StaticResource AuthorInformation}"
                               Text="{Binding Path=Author, Mode=OneTime}"></TextBlock>
                    <TextBlock xml:space="preserve"
                               Style="{StaticResource AuthorInformation}"> on </TextBlock>
                    <TextBlock xml:space="preserve" 
   Style="{StaticResource AuthorInformation}"
                               Text="{Binding Path=DevelopentDate, Mode=OneTime}">
    </TextBlock>
                    <TextBlock xml:space="preserve"
                               Style="{StaticResource AuthorInformation}"> Version 
    </TextBlock>
                    <TextBlock xml:space="preserve" 
   Style="{StaticResource AuthorInformation}"
                               Text="{Binding Path=Version, Mode=OneTime}"></TextBlock>
                </StackPanel>
            </Grid>
             
            <Grid Grid.Row="1" x:Name="MainContent" HorizontalAlignment="Stretch" 
              VerticalAlignment="Stretch" Margin="5, 2, 5, 10">
                <TabControl FontSize="12" x:Name="ApplicationMainTab">
                    <TabItem
                    HeaderTemplate="{StaticResource TabItemHeaderTemplate}">
                        <TabItem.Header>
                            Call WCF Services Synchronously
                        </TabItem.Header>
                    </TabItem>
  
                    <TabItem
                    HeaderTemplate="{StaticResource TabItemHeaderTemplate}">
                        <TabItem.Header>
                            Call WCF Services Asynchronously
                        </TabItem.Header>
                    </TabItem>
                </TabControl>
  
            </Grid>
        </Grid>
  
        <TextBlock Grid.Row="1" Text="{Binding Path=Copyright, Mode=OneTime}"
                   HorizontalAlignment="Center" Style="{StaticResource SmallBold}"
                   Foreground="Silver" />
    </Grid>
</Window>
The above "XAML" file defines two "tab items" in a "TabControl". Each of the "tab items" will host an instance of the "user control" created in the "WCFCallExample.xaml" file. One instance will be initiated to make synchronous WCF calls and the other will be initiated to make asynchronous WCF calls by setting the boolean instance variable "AsynchronousCall" accordingly.
The code-behind file of the "MainWnd.xaml" file is the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WFCCallExample.Properties;
 
namespace WFCCallExample
{
    /// <summary>
    /// Interaction logic for MainWnd.xaml
    /// </summary>
    public partial class MainWnd : Window
    {
        public MainWnd()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainWnd_Loaded);
        }
 
        void MainWnd_Loaded(object sender, RoutedEventArgs e)
        {
            DataContext = Settings.Default;
 
            ((TabItem)ApplicationMainTab.Items[0]).Content
                = new WCFCallExample(false);
 
            ((TabItem)ApplicationMainTab.Items[1]).Content
                = new WCFCallExample(true);
        }
    }
}
The "MainWnd_Loaded" event handler initiates two instances of the "WCFCallExample" "user control" objects and associates each of them to the appropriate "tab item". One instance of the "user control" object is initiated to make synchronous calls, and the other is initiated to make asynchronous calls.

Run the Application

Now, we finish the development of this example application. Set the "WCFCallExample" project as the "startup project" and press "F5", you can debug run the application. Let us first take a look at the "Call WCF Services Synchronously" tab:
WCFCallSynchronized.jpg Select the number of the students to retrieve from the WCF service and click the "Make WCF service call" button, a synchronous WCF call is made and the student list is retrieved from the WCF service. During the time when you wait for the WCF service to respond to your call, you can click on the "Click me!" button, you will notice that the UI thread of the WPF application is blocked, and the application will not respond to your button click until the WCF call is finished.
Let us now take a look at the "Call WCF Services Asynchronously" tab:
WCFCallAsynchronized.jpg After selecting the number of the students to retrieve and clicking the "Make WCF service call" button, an asynchronous WCF call is made. If you can click on the "Click me!" button, you will notice that the UI thread is not blocked and the "MessageBox" telling you the button is clicked shows up immediately even before the WCF service responds back to the WCF call.

Points of Interest

  • This article is an example to show you how to build a WCF service and how to call the WCF service synchronously and asynchronously as well.
  • When building the WCF service, I separated the implementation and the host of the service. This is not always necessary. This article only shows you that you can separate the concerns of the implementation and the hosting, if you want do it.
  • To call a WCF service synchronously, you can simply use the proxy method created by the Visual Studio, similar to calling a local method.
  • To call a WCF service asynchronously, you will need to first create an "AsyncCallback" "delegate" and pass this delegate to the asynchronous proxy method generated by the Visual Studio. Since the "AsyncCallback" "delegate" is executed in a worker thread different from the UI thread, any access to the "UI elements" needs to be "Dispatched".
  • From the application point of view, either way has its advantages and disadvantages. For most applications, after the calling of a WCF service, the application will be in an intermediate state until the response from the service is received. During this time, it may be ideal to block the UI thread to prevent user actions to get into any un-predictable results. In this case, a synchronous call may be appropriate. In some other scenarios, particularly when we work on some "SOA" applications, we may need to make multiple service calls at the same time and let the services to work in parallel. In this case, asynchronous WCF calls will be the ideal.
  • One thing just came to my mind. To make an asynchronous call, you probably do not need to have the asynchronous proxies. You can well fork a worker thread by yourself and let the thread to do a synchronous call. You will achieve the same effect as using the asynchronous proxies.
  • If you are not familiar with WCF services, this link is a good place to get you started.

Monday, July 23, 2012

ASP .NET Features

1.What’s the difference between Response.Write() andResponse.Output.Write()? 
Ans: Response.Output.Write() allows you to write formatted output.
2.What methods are fired during the page load?
Ans:
            Init() - when the page is instantiated
            Load() - when the page is loaded into server memory
            PreRender() - the brief moment before the page is displayed to the user as HTML
            Unload() - when page finishes loading.
   3.   When during the page processing cycle is ViewState available?
   Ans: After the Init() and before the Page_Load(), or OnLoad() for a control.

   4.   What namespace does the Web page belong in the .NET Framework class hierarchy?
   Ans: System.Web.UI.Page
   5.   Where do you store the information about the user’s locale?
   Ans: System.Web.UI.Page.Culture 
   6.   What’s a bubbled event?
   Ans:
        When you have a complex control, like DataGrid, writing an event processing routine for  
        each object (cell, button, row, etc.) is quite tedious. The controls can bubble up their 
        eventhandlers, allowing the main DataGrid event handler to take care of its constituents.
           
   7.   What data types do the RangeValidator control support?
   Ans. Integer, String, and Date.
   8. What is the difference between Server.Transfer and Response.Redirect? Why would I choose  one over the other?  
   Ans: 
          Server.Transfer transfers page processing from one page directly to the next page without making a  round-trip back to the client's browser. This provides a faster response with a little less overhead on the server. Server.Transfer does not update the clients url history list or current url. Response.Redirect is used to redirect the user's browser to another page or site. This performas a trip back to the client where the client's browser is redirected to the new page. The user's browser history list is updated to reflect the new address. 
  9. What base class do all Web Forms inherit from?
  Ans: The Page class.
  10. What is ViewState?
   Ans.
           ViewState allows the state of objects (serializable) to be stored in a hidden field on the page. ViewState is transported to the client and back to the server, and is not stored on the server or any other external source. ViewState is used the retain the state of server-side objects between postabacks.
 
  11. What does the "EnableViewState" property do? Why would I want it on or off?
  Ans.
          It allows the page to save the users input on a form across postbacks. It saves the server-side values for a given control into ViewState, which is stored as a hidden value on the page before sending the page to the clients browser. When the page is posted back to the server the server control is recreated with the state stored in viewstate.      

  12.  How to manage state in Asp.Net Web applications? 
  Ans.
     State management is done at client side and server side
Client Side: Client Side it can achieved with the help of View state, Cookies, Query String,hidden fields    and control state.
Server Side: with the help of Cache, Application,Session and Database. 
  13. What is smart navigation?  
   Ans:
         The cursor position is maintained when the page gets refreshed due to the server side validation and the page gets refreshed. 
   14. What is System.Web.Mail?
   Ans. 
         System.Web.Mail (SWM) is the .Net namespace used to send email in .Net Framework applications.  SWM contains three classes:

1. MailMessage - used for creating and manipulating the mail message contents.
2. MailAttachments - used for creating a mail attachment to be added to the mail message.
3. SmtpMail - used for sending email to the relay mail server. 
   15. How many objects does ADO.Net have and what are they?
   Ans.
          There are 5 objects in ADO.Net.
          They are Connection, Adapter, Command, Reader and Dataset.
   16.  How does ASP.Net page works?
    Ans.
        1. When a browser requests an HTML file, the server returns the file
        2. When a browser requests an ASP.Net file, IIS passes the request to the ASP.Net engine on the server.
       3. The ASP.Net engine reads the file, line by line, and executes the scripts in the file
       4. Finally, the ASP.Net file is returned to the browser as plain HTML.

     17.How do you debug an ASP.Net Web application?
     Ans.
          Attach the aspnet_wp.exe process to the DbgClr debugger. 

     18. In order to get assembly info which namespace we should have import?
     Ans. 
            System.Reflection Namespace

Wednesday, July 18, 2012

11g logo

Oracle Database 11g:
The Top Features for DBAs and Developers

by Arup Nanda Oracle ACE Director

In this multipart series, learn how important new features such as Database Replay, Flashback Data Archive, Edition-based Redefinition, and SecureFiles work via simple, actionable how-to's and sample code. (Updated for Release 2!)


Change, although constantly present, is seldom risk-free. Even if the change is relatively minor (creating an index for example), your goal is probably to predict its precise impact as accurately as possible and then take appropriate action.
Many new change assurance (or "Real Application Testing," as Oracle calls it) features in Oracle Database 11g bring that dream closer to reality. The Database Replay tool, for example, allows you to capture production database workload and replay it in a test (or even the same) database to assess the impact of change. Or consider SQL Performance Analyzer, which predicts the performance impact of changes to SQL before they are made. (In my opinion, this Real Application Testing functionality alone justifies the upgrade.) After this process, Edition-based Redefinition (introduced in Release 2) enables patching and updates of data objects while the application remains online.
Overall, Oracle Database 11g makes database infrastructure far more efficient, resilient, and manageable. For example, very compelling new features in the realm of partitioning ease the design and management of partitioned tables immensely.
In this series (as in the previous series focusing on Oracle Database 10g), you will learn how these new features work via simple, actionable how-to's and sample code.
Enjoy the series, and the release!

Database Replay

Explore Database Replay, the new tool that captures SQL statements and lets you replay them at will.

Partitioning

Learn about Referential, Internal, and Virtual Column partitioning; new sub-partitioning options; and more.

Edition-Based Redefinition

It's revolutionary: Patch or update your application's data objects while the application remains in uninterrupted use (in Release 2 only).

Schema Management

Add columns with a default value easily and explore invisible indexes, virtual columns, and read only tables.

Patching and Upgrades, RAC One Node, and Clusterware

Learn how to enable a single name for the cluster, enable HA for a single-instance database, place OCR and voting disks on ASM, and more (in Release 2 only).

Data Warehousing and OLAP

Get a tour of new features in these areas, including Cube Organized MVs, a new Analytic Workspace Manager, Query Rewrite extended to subqueries and remote tables, and more.

PL/SQL Performance

Explore in-lining of code, "real" native compilation, PLS timer, use of simple integer, and more.

PL/SQL: Efficient Coding

Triggers that fire several times at different events and ability to force triggers of the same type to follow a sequence are some new gems.

Transaction Management

Get an introduction to Flashback Data Archive and explore Enterprise Manager's LogMiner interface.

Security

Learn about Tablespace Encryption, case-sensitive passwords, data masking, and other features.

SQL Performance Analyzer & Real-Time SQL Monitoring

Learn how to accurately predict changes on the actual SQL statements issued against your database - plus, monitor SQL performance in real time.

Oracle Exadata Simulator

Predict how your statements will behave in Oracle Exadata Database Machine using any Oracle Database 11g Release 2 EE database (using SQL Performance Analyzer).

SQL Plan Management

Use bind variables that pick the right plan every time and ensure a new execution plan is perfect before it's used.

Manageability

Explore automatic memory management, multicolumn statistics, online patching, and more features.

SQL Access Advisor

Get advice about optimal table design based on actual use of the table, not just data.

SQL Operations: Pivot and Unpivot

Present information in a spreadsheet-type crosstab report from any relational table using simple SQL, and store any data from a crosstab table to a relational table.

Backup and Recovery

Explore Data Recovery Advisor, do parallel backup of the same file, create and manage virtual catalogs, and undrop tablespaces.

Resiliency

Explore Automatic Health Monitor, Automatic Diagnostic Repository, and other new resiliency features.

Automatic Storage Management

Learn about new SYSASM role, variable extent sizes, and other ASM improvements.

Compression

Support for data compression is nothing new in Oracle Database, but 11g takes the concept to a new level with Advanced and Hybrid Columnar Compression.

Caching and Pooling

Explore SQL Result Cache, PL/SQL Function Cache, and Database Resident Connection Pooling.

Data Guard

Query the physical standby database in real time without shutting down recovery, just for starters.

SecureFiles

Explore next-generation LOBs: LOB encryption, compression, deduplication, and asynchronicity.

And Don't Forget...

COPY command, Export/Imports, Data Pump and SQL*Plus improvements, Scheduler email notification, and more.