mobile ads

Tuesday 3 December 2013

Difference between Stored Procedures and Function in SQL

Stored Procedure 
A Stored Procedure is a program (or procedure) which is physically stored within a database. The advantage of a stored procedure is that when it is run, in response to a user request, it is run directly by the database engine, which usually runs on a separate database server. As such, it has direct access to the data it needs to manipulate and only needs to send its results back to the user, doing away with the overhead of communicating large amounts of data back and forth.
User-defined Function
A user-defined function is a routine that encapsulates useful logic for use in other queries. While views are limited to a single SELECT statement, user-defined functions can have multiple SELECT statements and provide more powerful logic than is possible with views.
Differences 
*. SP can return zero or n values whereas function can return one value which is mandatory. 
*. SP can have input/output parameters for it whereas functions can have only input parameters.
*. SP allows select as well as DML statement in it whereas function allows only select statement in it. 
*. Functions can be called from procedure whereas procedures cannot be called from function. 
*. Exception can be handled by try-catch block in a procedure whereas try-catch block cannot be used in a function. 
*. We can go for transaction management in procedure whereas we can't go in function. 
*. SP can not be utilized in a select statement whereas function can be embedded in a select statement.
 

Friday 29 November 2013

Constructors

A constructor is a method in the class which gets executed when its object is created. Whenever a class or struct is created, its constructor is called. Even if we don't write the constructor code, default constructor will be created and called first when object is instantiated and sets the default values to members of claas. A class or struct may have multiple constructors that take different arguments.
 Constructors enable the programmer to set default values, limit instantiation, and write code that is flexible and easy to read.Constructors have the same name as Class
Default constructor will no take parameters and will be invoked when instance is created.
We can prevent the class instantiation by declaring the constructor as private
class sample
{
      private sample()
     {
      }
}
Classes can define the constructors with parameter also and must be called by "new" keyword.
class sample
{
   public int y;
   public sample (int i)
   {
        y=i;
    }
}
constructor with parameters.
sample s= new sample(10);
A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only, and does not take access modifiers or have parameters.It is called automatically before the first instance is created or any static members are referenced.
It is called automatically to initialize the class before the first instance is created or any static members are referenced. The user has no control on when the static constructor is executed.
class SimpleClass
{
    // Static variable that must be initialized at run time.
    static readonly long baseline;
    // Static constructor is called at most one time, before any
    // instance constructor is invoked or member is accessed.
    static SimpleClass()
    {
        baseline = DateTime.Now.Ticks;
    }
}
A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.
It is mandatory to have the constructor in the class and that too should be accessible for the object i.e., it should have a proper access modifier. Say, for example, we have only private constructor(s) in the class and if we are interested in instantiating the class, i.e., want to create an object of
 the class, then having only private constructor will not be sufficient and in fact it will raise an error. So, proper access modifies should be provided to the constructors.

Monday 25 November 2013

Sending SMS from ASP.NET

Write a method in class file

public static void CreateRequestTOSENDSMS()
        {
            string url = "SMS gateway url, which will be provided by SMS people";//      HttpContext.Current.Request.Url.AbsoluteUri.ToString().Replace("AutoLogin", "Login");
            CookieContainer myCookieContainer = new CookieContainer();
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.CookieContainer = myCookieContainer;
            request.Method = "GET";
            request.KeepAlive = false;
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            System.IO.Stream responseStream = response.GetResponseStream();
            System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
            string srcString = reader.ReadToEnd();
             // Concat the string data which will be submit
            string formatString ="username={0}&pass={1}&senderid={2}&mtype=txt&tempid={3}&f1={4}&f2={5}&f3={6}&dest_mobileno={7}&response=Y";
            string postString = string.Format(formatString, "demo12", "demo123", "DEMOVL", "1018", "1234", "5673", "tyyty");
            byte[] postData = Encoding.ASCII.GetBytes(postString);

            // Set the request parameters
            request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "POST";
            request.Referer = url;
            request.KeepAlive = false;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; CIBA)";
            request.ContentType = "application/x-www-form-urlencoded";
            request.CookieContainer = myCookieContainer;
            System.Net.Cookie ck = new System.Net.Cookie("SMS", "Value of SMS cookie");
            ck.Domain = request.RequestUri.Host;
            request.CookieContainer.Add(ck);
            request.CookieContainer.Add(response.Cookies);
            // Submit the request data
            System.IO.Stream outputStream = request.GetRequestStream();
            request.AllowAutoRedirect = true;
            outputStream.Write(postData, 0, postData.Length);
            outputStream.Close();
            // Get the return data
            response = request.GetResponse() as HttpWebResponse;
            responseStream = response.GetResponseStream();
            reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
            srcString = reader.ReadToEnd();
            }

The parameters "url", "formatstring" may vary from one SMS provider to another. Add these namespaces.
using System.Text;
using System.IO;
using System.Net;

Why we use Static Keyword?

The static keyword defines, that the class or property or method we declare as static does not require a previous instance of an object. In the other hand, a static method for example cannot use any instance method / instance property of the own object.

Also static defined things will be optimized by the compiler, for example that a static object is only written once in the memory and everything accesses to the same object. When we use static keyword it means there is no need to create an instance of object . Static class including a static method can called by class name. Static class can have only static methods.

Friday 22 November 2013

Why .NET

Few points to answer why .NET
  1.   In .NET we have language choice to code with (C#,VB.NET, Java,Boo,Python e.t.c), producing the same type of compiled code.
  2.  .NET programs run at native speed while java is interpreted which makes java slower.Although java has Just In Time compilation but it stills run slower. With .NET you are not limited to JIT but have the option for AOT(Ahead of time) compilation if you want to eliminate startup delays.
  3. Calling native code in java is not a very clean process. You need to generate some stub files which makes the whole process cumbersome and dirty. In .NET you just declare that you are calling a native function from a specified library and just start calling it. 
  4. .NET languages are richer than Java. They have object oriented feature that are absent in java e.g properties,delegates,generics.
  5.  Java GUI programs look alien on the host operating system. Even if you use the OS's theme you still notice that the java widgets look out of place.
  6.  .NET in the form of Mono has brought a whole revolution on the linux desktop in form of great applications like beagle, tomboy, diva, iFolder, banshee e.t.c. This is something that java has failed to do despite the fact that it's been there long before .NET
  7. Many programs that would have been difficult to develop with java have been developed with .NET things like compilers (Mono's C# and VB.NET) 3D game engines (unity game engine) e.t.c
  8.  The CLI is an open standard maintained by an independent standards organization (E.C.M.A) while java is still governed by SUN microsystems.Even though java has recently been open-sourced, it's future will still be highly influenced by SUN.
  9. You can code on the .NET platform using Java but you cannot code on Java platform using any of the .NET languages.

Thursday 14 November 2013

How to use Ajax calendar in ASP.NET


Step 1: Register ajax dll

Add this line after @Page directive.
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxtoolkit" %>

Step 2 : Include scriptmanager in your code
 <asp:ScriptManager ID="scrp" runat="server">    </asp:ScriptManager>

Step 3 : Next
<asp:TextBox ID="txtDOB" runat="server" />
                                                        <asp:Image ID="imgDOB" runat="server" Height="22px" ImageUrl="~/images/calendar.JPG"
                                                            Width="26px" />
                                                        <ajaxtoolkit:CalendarExtender ID="calDOB" runat="server" PopupButtonID="imgDOB" TargetControlID="txtDOB">
                                                        </ajaxtoolkit:CalendarExtender>

Ajax calendar control has two main properties, PopupButtonID and TargetControlID.

When we click on the image button a calendar will be shown and selected date will be displayed in textbox.

For this to work you need to add AjaxControlToolKit dll.

Wednesday 6 November 2013

PageIndexChanging Vs PageIndexChanged


PageIndexChanging
- Occurs when one of the pager buttons is clicked, but before the GridView control handles the paging operation. This event is often used to cancel the paging operation. 

Ex:
protected void gvTeachers_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                gvTeachers.PageIndex = e.NewPageIndex;
               //bind the grid
            }
            catch (Exception ex)
            {
                lblErrorMessage.Visible = true;
                lblErrorMessage.Text = ex.Message;
                log.Error(ex.Message + " "+ex.StackTrace);
            }
        }


PageIndexChanged
- Occurs when one of the pager buttons is clicked, but after the GridView control handles the paging operation. This event is commonly used when you need to perform a task after the user navigates to a different page in the control.

PageIndexChanged is fired after the actual page index is changed, but before the GridView is databound again with the new page data.

PageIndexChanging fired prior to the change and the PageIndexChanged fired after the new data for the next page is displayed. 

Thursday 31 October 2013

Event Handling in ASP.NET


Event is an action or occurrence like mouse click, key press, mouse movements, or any system generated notification. The processes communicate through events. For example, Interrupts are system generated events. When events occur the application should be able to respond to it.
In ASP.Net an event is raised on the client, and handled in the server. For example, a user clicks a button displayed in the browser. A Click event is raised. The browser handles this client-side event by posting it to the server.
The server has a subroutine describing what to do when the event is raised; it is called the event-handler. Therefore, when the event message is transmitted to the server, it checks whether the Click event has an associated event handler, and if it has, the event handler is executed.

All ASP.Net controls are implemented as classes, and they have events which are fired when user performs certain action on them. For example, when a user clicks a button the 'Click' event is generated. For handling these events there are in-built attributes and event handlers. To respond to an event, the event handler is coded

The common control events.
EventAttributeControls
ClickOnClickButton, image button, link button, image map
CommandOnCommandButton, image button, link button
TextChangedOnTextChangedText box
SelectedIndexChangedOnSelectedIndexChangedDrop-down list, list box, radio button list, check box list.
CheckedChangedOnCheckedChangedCheck box, radio button

Some events cause the form to be posted back to the server immediately, these are called the postback events. For example, the click events like, Button.Click. Some events are not posted back to the server immediately, these are called non-postback events.For example, the change events or selection events, such as, TextBox.TextChanged or CheckBox.CheckedChanged, or DropDownList,SelectedIndexChanged.The nonpostback events could be made to post back immediately by setting their AutoPostBack property to true.

The default event for the Page object is the Load event. Similarly every control has a default event. For example, default event for the button control is the Click event.
The default event handler could be created in Visual Studio, just by double clicking the control in design view.

Common Page and Control Events

  • DataBinding . raised when a control bind to a data source
  • Disposed . when the page or the control is released
  • Error . it is an page event, occurs when an unhandled exception is thrown
  • Init . raised when the page or the control is initialized
  • Load . raised when the page or a control is loaded
  • PreRender . raised when the page or the control is to be rendered
  • Unload . raised when the page or control is unloaded from memory
Application and Session Events

The most important application events are:
  • Application_Start . it is raised when the application/website is started
  • Application_End . it is raised when the application/website is stopped
Similarly, the most used Session events are:
  • Session_Start . it is raised when a user first requests a page from the application
  • Session_End . it is raised when the session ends

Wednesday 30 October 2013

ASP.NET Page Validation Controls


  • RequiredFieldValidator—Enables you to require a user to enter a value in a form field.
  • RegularExpressionValidator—Enables you to compare a value against a regular expression.
  • RangeValidator—Enables you to check whether a value falls between a certain minimum and maximum value.
  • CompareValidator—Enables you to compare a value against another value or perform a data type check.
  • CustomValidator—Enables you to perform custom validation.
  • ValidationSummary—Enables you to display a summary of all validation errors in a page.
You can associate the validation controls with any form controls included in ASP.NET Framework. For example, if you want to require a user to enter a value into a TextBox control, you can associate a RequiredFieldValidator control with the TextBox control.

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <br />
        Name: <asp:TextBox ID="tbName" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator 
                ID="RequiredFieldValidator1" runat="server"
                ErrorMessage="You must enter your name" 
                ControlToValidate="tbName"  ForeColor="Red"/>
        <br />
        Date of birth: <asp:TextBox ID="tbDOB" runat="server" />
        <asp:RegularExpressionValidator
                ID="RegularExpressionValidator1" runat="server"
                ErrorMessage="Enter a date in the form MM/DD/YYYY"
                ControlToValidate="tbDOB"  ForeColor="Red"
                ValidationExpression="(0[1-9]|1[012])/([1-9]|0[1-9]|[12][0-9]|3[01])/\d{4}"
        />
        <br />
        Amount of candies you eat daily (< than 1000): 
        <asp:TextBox ID="tbCandy" runat="server" />
        <asp:CompareValidator 
            ID="CompareValidator1" runat="server"
            ErrorMessage="Number is not < 1000"
            ControlToValidate="tbCandy"
            Operator="LessThan"  ForeColor="Red"
            ValueToCompare="1000" Type="Integer" />
        <br />
        Number of Doctor visits (1 - 10):
        <asp:TextBox ID="tbDr" runat="server" />
        <asp:RangeValidator 
                ID="RangeValidator1" runat="server"
                ErrorMessage="Enter a value from 1 to 10"
                ControlToValidate="tbDr"  ForeColor="Red"
                MinimumValue="1" MaximumValue="10" />
        <br />
        

        <asp:ValidationSummary runat="server" 
            ID="validationSummary"  ForeColor="Blue"/>

        <br />
        <asp:Button runat="server" Text="Submit" ID="btnSubmit" />
    </div>
    </form>
</body>
</html>


For detailed description in MSDN, Click here

Tuesday 29 October 2013

WPF Introduction


Windows Presentation Foundation (WPF) is a next-generation presentation system for building Windows client applications with visually stunning user experiences. With WPF, you can create a wide range of both standalone and browser-hosted applications.
The core of WPF is a resolution-independent and vector-based rendering engine that is built to take advantage of modern graphics hardware. WPF extends the core with a comprehensive set of application-development features that include Extensible Application Markup Language (XAML), controls, data binding, layout, 2-D and 3-D graphics, animation, styles, templates, documents, media, text, and typography. WPF is included in the Microsoft .NET Framework, so you can build applications that incorporate other elements of the .NET Framework class library.

WPF can be used to develop the following types of applications:

1. Standalone Applications (traditional style Windows applications built as executable assemblies that are installed to and run from the client computer).
2. XAML browser applications (XBAPs) (applications composed of navigation pages that are built as executable assemblies and hosted by Web browsers such as Microsoft Internet Explorer or Mozilla Firefox).
3. Custom Control Libraries (non-executable assemblies containing reusable controls).
4. Class Libraries (non-executable assemblies that contain reusable classes).

WPF Architecture

For every new technology, it is very essential to have a clear idea about its architecture. So before beginning your application, you must grab a few concepts. If you would not like to know WPF in detail, please skip this section. As mentioned earlier, WPF is actually a set of assemblies that build up the entire framework. These assemblies can be categorized as:
  • Managed Layer
  • UnManaged Layer
  • Core API
Managed Layer: Managed layer of WPF is built using a number of assemblies. These assemblies build up the WPF framework, communicate with lower level unmanaged API to render its content. The few assemblies that comprise the WPF framework are:
  1. PresentationFramework.dll: Creates the top level elements like layout panels, controls, windows, styles, etc.
  2. PresentationCore.dll: It holds base types such as UIElement, Visual from which all shapes and controls are Derived in PresentationFramework.dll.
  3. WindowsBase.dll: They hold even more basic elements which are capable of being used outside the WPF environment like Dispatcher object, Dependency Objects. I will discuss each of them later.
Unmanaged Layer (milcore.dll): The unmanaged layer of WPF is called milcore or Media Integration Library Core. It basically translates the WPF higher level objects like layout panels, buttons, animation, etc. into textures that Direct3D expects. It is the main rendering engine of WPF.
WindowsCodecs.dll: This is another low level API which is used for imaging support in WPF applications. WindowsCodecs.dll comprises a number of codecs which encode / decode images into vector graphics that would be rendered into WPF screen.
Direct3D: It is the low level API in which the graphics of WPF is rendered.
User32: It is the primary core API which every program uses. It actually manages memory and process separation.
GDI & Device Drivers: GDI and Device Drivers are specific to the operating system which is also used from the application to access low level APIs.

For more information,Click here

Wednesday 16 October 2013

Difference between Response.Redirect and Server.Transfer

Response.Redirect involves an extra round-trip to the server whereas Server.Transfer conserves server resources by avoiding that extra round-trip. Server.Transfer just changes the focus of the page by directly communicating with server.
         Response.Redirect
  1. Response.Redirect() will send you to a new page, update the address bar and add it to the Browser History. On your browser you can click back.
  2. It redirects the request to some plain HTML pages on our server or to some other web server.
  3. It causes additional roundtrips to the server on each request.
  4. It doesn’t preserve Query String and Form Variables from the original request.
  5. It enables to see the new redirected URL where it is redirected in the browser (and be able to bookmark it if it’s necessary).
  6. Response. Redirect simply sends a message down to the (HTTP 302) browser. 


  1. Server.Transfer
  2. Server.Transfer() does not change the address bar, we cannot hit back.One should use Server.Transfer() when he/she doesn’t want the user to see where he is going. Sometime on a "loading" type page.
  3. It transfers current page request to another .aspx page on the same server.
  4. It preserves server resources and avoids the unnecessary roundtrips to the server.
  5. It preserves Query String and Form Variables (optionally).
  6. It doesn’t show the real URL where it redirects the request in the users Web Browser.
  7. Server.Transfer happens without the browser knowing anything, the browser request a page, but the server returns the content of another.

machine.config and web.config

Machine.Config file specifies the settings that are global to a particular machine.  It is specifically used to store machine and application settings global to all asp.net web sites running in IIS in a computer. A system can have only one machine.config computer. Each .NET Framework such as 1.1, 2.0, 4.0 will have its own machine.config in the %runtime install path%\Config folder.
 This file is located at the following path:
 [Windows Directory]\Microsoft.NET\Framework\[Framework Version]\CONFIG\machine.config
 As web.config file is used to configure one asp .net web application, same way Machine.config file is used to configure the application according to a particular machine. That is, configuration done in machine.config file is affected on any application that runs on a particular machine. Usually, this file is not altered and only web.config is used which configuring applications.
 You can override settings in the Machine.Config file for all the applications in a particular Web site by placing a Web.Config file in the root directory of the Web site as follows:
\InetPub\wwwroot\Web.Config
If you want to override a setting from machine.config for a particular asp.net web site, then you can re-write in web.config of that web site. An asp.net can have any number of web.config files.

Friday 11 October 2013

Difference between Convert.ToString() and .ToString()

We can convert the integer i using i.ToString () or Convert.ToString
The basic difference between them is the Convert function handles NULLS while i.ToString () does not; it will throw a NULL reference exception error. So as good coding practice using convert is always safe.


You can create a class and override the toString method to do anything you want.

The Convert.toString converts the specified value to its equivalent string representation.

Can we define a Private Constructor

Yes, In static classes.
A private constructor is a special instance constructor. It is commonly used in classes that contain static members only. If a class has one or more private constructors and no public constructors, then other classes (except nested classes) are not allowed to create instances of this class. For example:
class NLog
{
    // Private Constructor:
    private NLog() { }

    public static double e = System.Math.E;
}
The declaration of the empty constructor prevents the automatic generation of a default constructor. Note that if you don't use an access modifier with the constructor it will still be private by default. However, the private modifier is usually used explicitly to make it clear that the class cannot be instantiated.
Private constructors are used to prevent the creation of instances of a class when there are no instance fields or methods, such as the math class, or when a method is called to obtain an instance of a class. If all the methods in the class are static, consider making the entire class static.

What is Abstract Class and Interface? Why we use them and at What scenario we use?

AbstractClass: Abtract class cannot be instantiated, it can only be inherited.

When you have a requirement where your base class should provide default implementation of certain methods whereas other methods should be open to being overridden by child classes use abstract classes.

For e.g. again take the example of the Vehicle class above. If we want all classes deriving from Vehicle to implement the Drive() method in a fixed way whereas the other methods can be overridden by child classes. In such a scenario we implement the Vehicle class as an abstract class with an implementation of Drive while leave the other methods / properties as abstract so they could be overridden by child classes.

The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.

For example a class library may define an abstract class that is used as a parameter to many of its functions and require programmers using that library to provide their own implementation of the class by creating a derived class.


Interface: Interface is like contract between the base class and interface used. If your child classes should all implement a certain group of methods/functionalities but each of the child classes is free to provide its own implementation then use interfaces.

For e.g. if you are implementing a class hierarchy for vehicles implement an interface called Vehicle which has properties like Colour MaxSpeed etc. and methods like Drive(). All child classes like Car Scooter AirPlane SolarCar etc. should derive from this base interface but provide a seperate implementation of the methods and properties exposed by Vehicle.

 If you want your child classes to implement multiple unrelated functionalities in short multiple inheritance use interfaces.

For e.g. if you are implementing a class called SpaceShip that has to have functionalities from a Vehicle as well as that from a UFO then make both Vehicle and UFO as interfaces and then create a class SpaceShip that implements both Vehicle and UFO .


Use an abstract class

  • When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning. This is the practice used by the Microsoft team which developed the Base Class Library. ( COM was designed around interfaces.)

  • Use an abstract class to define a common base class for a family of types.

  • Use an abstract class to provide default behavior.

  • Subclass only a base class in a hierarchy to which the class logically belongs.

 Use an interface

  • When creating a standalone project which can be changed at will, use an interface in preference to an abstract class; because, it offers more design flexibility.

  • Use interfaces to introduce polymorphic behavior without subclassing and to model multiple inheritance—allowing a specific type to support numerous behaviors.

  • Use an interface to design a polymorphic hierarchy for value types.

  • Use an interface when an immutable contract is really intended.

  • A well-designed interface defines a very specific range of functionality. Split up interfaces that contain unrelated functionality.