Pages

Wednesday, 3 April 2013

Difference between Const and Readonly with Example in C#.Net

Const:

      1.    Const can only be initialized at the time of declaration of the field.
      2.    Const values will evaluate at compile time only.
      3.    Const value can’t be changed these will be same at all the time.
      4.    This type of fields are required when one of the field values remains constant throughout the system like Pi will remain same in your Maths Class.

Read-only:

     1.    The value will be initialized either declaration time or the constructor of the class allowing you to pass the value at run time.
      2.    Read only values will evaluate at runtime only.

Example
public class Const_VS_Readonly
{
public const int I_CONST_VALUE = 2;
public readonly int I_RO_VALUE;
public Const_VS_Readonly()
{
I_RO_VALUE = 3;
}
}

Explain Encapsulation with an Example

What is Encapsulation?

  • Encapsulation is one of the fundamental principles of object-oriented programming.
  • Encapsulation is a process of hiding all the internal details of an object from the outside world
  • Encapsulation is the ability to hide its data and methods from outside the world and only expose data and methods that are required
  • Encapsulation is a protective barrier that prevents the code and data being randomly accessed by other code or by outside the class
  • Encapsulation gives us maintainability, flexibility and extensibility to our code.
  • Encapsulation makes implementation inaccessible to other parts of the program and protect from whatever actions might be taken outside the function or class.
  • Encapsulation provides a way to protect data from accidental corruption
  • Encapsulation hides information within an object
  • Encapsulation is the technique or process of making the fields in a class private and providing access to the fields using public methods
  • Encapsulation gives you the ability to validate the values before the object user change or obtain the value
  • Encapsulation allows us to create a "black box" and protects an objects internal state from corruption by its clients.
  • Encapsulation is a procedure of covering up of the data & functions into a single unit called as class 

Two ways to create a validation process.

  • Using Accessors and Mutators
  • Using properties
In this example _employeeid and _salary is private fields and providing access to the fields using public methods (SetEmployeeID,GetEmployeeID,SetSalary,GetSalary)
In this example _employeeid and _salary is private fields and providing access to the fields using public methods (EmployeeID,Salary)

Benefits of Encapsulation

  • In Encapsulation fields of a class can be read-only or can be write-only
  • A class can have control over in its fields
  • A class can change data type of its fields anytime but users of this class do not need to change any code

What is the Difference between Overriding and overloading?

Overloading is defining functions that have similar signatures, yet have different parameters.
Overriding is only pertinent to derived classes, where the parent class has defined a method and the derived class wishes to override that function.
Overriding
Overloading
Methods name and signatures must be same.
Having same method name with different
Signatures.
Overriding is the concept of runtime polymorphism
Overloading is the concept of compile time polymorphism
When a function of base class is re-defined in the derived class called as Overriding
Two functions having same name and return type, but with different type and/or number of arguments is called as Overloading
It needs inheritance.
It doesn't need inheritance.
Method should have same data type.
Method can have different data types
Method should be public.
Method can be different access specifies
e.g.
Overriding
public class MyBaseClass
{
public virtual void MyMethod()
{
Console.Write("My BaseClass Method");
}
}
public class MyDerivedClass:MyBaseClass
{
public override void MyMethod()
{
Console.Write("My DerivedClass Method");
}
}
Overloading
int add(int a, int b)
int add(float a , float b)

ASP.NET Page Life Cycle with example

In this article, we are going to discuss the different methods and order they are executed during the load of an .aspx web page.
Methods
Description
Page_PreInit
Before page Initialization
Page_Init
Page Initialization
LoadViewState
View State Loading
LoadPostData
Postback Data Processing
Page_Load
Page Loading
RaisePostDataChangedEvent
PostBack Change Notification
RaisePostBackEvent
PostBack Event Handling
Page_PreRender
Page Pre Rendering Phase
SaveViewState
View State Saving
Page_Render
Page Rendering
Page_Unload
Page Unloading
PreInit : The entry point of the page life cycle is the pre-initialization phase called “PreInit”. You can dynamically set the values of master pages and themes in this event. You can also dynamically create controls in this event. 
Init : This event fires after each control has been initialized, each control's UniqueID is set and any skin settings have been applied. You can use this event to change initialization values for controls. The “Init” event is fired first for the most bottom control in the hierarchy, and then fired up the hierarchy until it is fired for the page itself. 
InitComplete: Raised once all initializations of the page and its controls have been completed. Till now the viewstate values are not yet loaded, hence you can use this event to make changes to view state that you want to make sure are persisted after the next postback
PreLoad : Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance
(1)Loads ViewState : ViewState data are loaded to controls
(2)Loads Postback data : postback data are now handed to the page
Load: The important thing to note about this event is the fact that by now, the page has been restored to its previous state in case of postbacks. Code inside the page load event typically checks for PostBack and then sets control properties appropriately. This method is typically used for most code, since this is the first place in the page lifecycle that all values are restored. Most code checks the value of IsPostBack to avoid unnecessarily resetting state. You may also wish to call Validate and check the value of IsValid in this method. You can also create dynamic controls in this method.
Control (PostBack) event(s) :ASP.NET now calls any events on the page or its controls that caused the PostBack to occur. This might be a button’s click event or a dropdown's selectedindexchange event.
LoadComplete :This event signals the end of Load.
 
PreRender : Allows final changes to the page or its control. This event takes place after all regular PostBack events have taken place. This event takes place before saving ViewState, so any changes made here are saved. For example : After this event, you cannot change any property of a button or change any viewstate value. Because, after this event, SaveStateComplete and Render events are called.
SaveStateComplete :Prior to this event the view state for the page and its controls is set. Any changes to the page’s controls at this point or beyond are ignored. 
Render : This is a method of the page object and its controls (and not an event). At this point, ASP.NET calls this method on each of the page’s controls to get its output. The Render method generates the client-side HTML, Dynamic Hypertext Markup Language (DHTML), and script that are necessary to properly display a control at the browser.
UnLoad : This event is used for cleanup code. After the page's HTML is rendered, the objects are disposed of. During this event, you should destroy any objects or references you have created in building the page. At this point, all processing has occurred and it is safe to dispose of any remaining objects, including the Page object. Cleanup can be performed on-
(a)Instances of classes i.e. objects
(b)Closing opened files
(c)Closing database connections
Below is example of the ASP.Net Life Cycle
HTML Default.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Page Button" />
</div>
</form>
</body>
</html>
Code Default.aspx
using System;
public partial class _Default : System.Web.UI.Page
{
int i = 0;
protected void Page_PreInit(object sender, EventArgs e)
{
Response.Write( "" + (++i).ToString() + " Page Pre-Init");

}
protected override void OnInit(EventArgs e)
{
Response.Write("" + (++i).ToString() + " Page Init");

}
protected void Page_InitComplete(object sender, EventArgs e)
{
Response.Write("" + (++i).ToString() + " Page Init Completed");

}
protected void Page_Load(object sender, EventArgs e)
{
ViewState["test"] = "Test";
Response.Write("" + (++i).ToString() + " Page Load");

}
protected override void OnPreRender(EventArgs e)
{
Response.Write("" + (++i).ToString() + " Page Pre Render");

}
//protected override void Render(HtmlTextWriter writer)
//{
// //Response.Write("" + (++i).ToString() + " Render");

//}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("" + (++i).ToString() + " Page Button Click");

}
protected override void OnUnload(EventArgs e)
{
// Response.Write("" + (++i).ToString() + " Unload");

}
public override void Dispose()
{
// Response.Write("" + (++i).ToString() + " Dispose");

}
protected override object SaveViewState()
{
Response.Write("" + (++i).ToString() + " Page Save View State");
return base.SaveViewState();
}
public void RaisePostBackEvent(string eventArgument)
{
Response.Write("" + (++i).ToString() + " Page Raise Post Back Event");

}
public void RaisePostDataChangedEvent()
{
Response.Write("" + (++i).ToString() + " Page Raise Post Data Change Event");

}
protected override void LoadViewState(object o)
{
Response.Write("" + (++i).ToString() + " Page Load View State");
base.LoadViewState(o);

}
private void Page_LoadComplete(object sender, System.EventArgs e)
{
Response.Write("" + (++i).ToString() + " Page Load Completed");
}
}
OUTPUT
When a page request is sent to the Web server, the page is run through a series of events during its creation and disposal as below only Page_Unload and Dispose are not shown here.
Suppose the Button event get fire then it will create event as below (again Page_Unload and Dispose are not shown here because page already load when these event occurs)

Thursday, 28 March 2013

Parser Error Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately. Parser Error Message: The file '/Account/Site.master' does not exist.

 

Server Error in '/Account' Application.

Parser Error

Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message: The file '/Account/Site.master' does not exist.

Source Error:

Line 1:  <%@ Page Title="Register" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"Line 2:      CodeBehind="Register.aspx.cs" Inherits="Tranzhop.Account.Register" %>
Line 3:  

Source File: /account/register.aspx    Line: 1


Solution: However, this issue turned out to be an IIS7 issue. The error message I described arose out of the distinction made in IIS7 between a "virtual directory" and an "application" (I don't know if such a distinction existed in IIS6). To fix this error, I opened IIS7, right-clicked on the virtual directory folder for this site, and selected "Convert to Application." I then refreshed the browser, and the error went away.

Wednesday, 20 March 2013

Handling Empty Data in an ASP.NET Repeater control

The GridView has an EmptyDataText property or the <EmptyDataTemplate> that lets us handle EmptyData. However the Repeater has no such property or template. In this short article, we will see how to adopt a simple technique to handle empty data in an ASP.NET Repeater control without creating a custom control.
Drag and drop a Repeater and a SQLDataSource control to the page. Bind the Repeater to the SQLDataSource as you usually do
<div>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1"            
    onitemdatabound="Repeater1_ItemDataBound">
 <HeaderTemplate>
    <table border="1" cellpadding="3" cellspacing="3">
    <tr bgcolor="blue">
    <td><b>CustomerID</b>
    </td>
    <td><b>CompanyName</b>
    </td>
    <td><b>ContactName</b>
    </td>
    <td><b>ContactTitle</b></td>
    </tr>
</HeaderTemplate>
 <ItemTemplate>
     <tr>
     <td>
        <%#DataBinder.Eval(Container.DataItem, "CustomerID")%>
     </td>
     <td>
        <%#DataBinder.Eval(Container.DataItem, "CompanyName")%>   
     </td>
     <td>
        <%#DataBinder.Eval(Container.DataItem, "ContactName")%>   
     </td>
     <td>
        <%#DataBinder.Eval(Container.DataItem, "ContactTitle")%>   
     </td>
     </tr>
 </ItemTemplate>
 <FooterTemplate>
 </table>           
 </FooterTemplate>
 
</asp:Repeater>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
    ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
    SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName],
    [ContactTitle], [Address] FROM [Customers] " >
</asp:SqlDataSource>
</div>
In your web.config, add a connection string as shown below:
 
      <connectionStrings>
            <add name="NorthwindConnectionString" connectionString="Data Source =(local);Integrated Security = SSPI; Initial Catalog=Northwind;"/>
      </connectionStrings>
 
If you run the application, the repeater would display the data from the database. Now change the query so that it returns empty data.
SELECT [CustomerID], [CompanyName], [ContactName], [ContactTitle], [Address] FROM [Customers] WHERE CUSTOMERID=’XYZ’
 
On running the application, you would see the following:
Empty Data
Now this display is not elegant enough to inform the user that there is no data, right? So let us see how to display a message in the Repeater control when there is no data present.
In the <FooterTemplate>, add a Label with some empty data text and set its visible property to false.
<FooterTemplate>
 <tr>
 <td>
 <asp:Label ID="lblEmptyData"
        Text="No Data To Display" runat="server" Visible="false">
 </asp:Label>
 </td>
 </tr>
 </table>           
 </FooterTemplate>
Now add an ItemDataBound event to the Repeater
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1"            
    onitemdatabound="Repeater1_ItemDataBound">
In the code behind, write the following code:
C#
    protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (Repeater1.Items.Count < 1)
        {
            if (e.Item.ItemType == ListItemType.Footer)
            {
                Label lblFooter = (Label)e.Item.FindControl("lblEmptyData");
                lblFooter.Visible = true;
            }
        }
    }
VB.NET
      Protected Sub Repeater1_ItemDataBound(ByVal sender As Object, ByVal e As RepeaterItemEventArgs)
            If Repeater1.Items.Count < 1 Then
                  If e.Item.ItemType = ListItemType.Footer Then
                        Dim lblFooter As Label = CType(e.Item.FindControl("lblEmptyData"), Label)
                        lblFooter.Visible = True
                  End If
            End If
      End Sub
The code checks if the Repeater has items in it. If the items count is less than 1, the code uses the FindControl() to locate the label and set it to visible.
On running the application again, you get to see the message 'No Data To Display' as shown in the screenshot below. This is certainly more user friendly than letting the user wonder why the data was not displayed at the first place.
Empty Data Message

Wednesday, 13 March 2013

To remove or replace multiple special character from string using sql queries.

CREATE FUNCTION [FN_REMOVE_SPECIAL_CHARACTER] (  
 @INPUT_STRING varchar(300))
RETURNS VARCHAR(300)
AS 
BEGIN
 
--declare @testString varchar(100),
DECLARE @NEWSTRING VARCHAR(100) 
-- set @teststring = '@san?poojari(darsh)'
 SET @NEWSTRING = @INPUT_STRING ; 
With SPECIAL_CHARACTER as
(
SELECT '>' as item
UNION ALL 
SELECT '<' as item
UNION ALL 
SELECT '(' as item
UNION ALL 
SELECT ')' as item
UNION ALL 
SELECT '!' as item
UNION ALL 
SELECT '?' as item
UNION ALL 
SELECT '@' as item
UNION ALL 
SELECT '*' as item
UNION ALL 
SELECT '%' as item
UNION ALL 
SELECT '$' as item
 )
SELECT @NEWSTRING = Replace(@NEWSTRING, ITEM, '') FROM SPECIAL_CHARACTER  
return @NEWSTRING 
END 
 
select dbo.[FN_REMOVE_SPECIAL_CHARACTER] ('@s()antosh')
 
 
CREATE FUNCTION [dbo].[udfGetCharacters](@inputString VARCHAR(MAX), @validChars VARCHAR(100))
RETURNS VARCHAR(500) AS
BEGIN
 
 WHILE @inputString like '%[^' + @validChars + ']%'
  SELECT @inputString = REPLACE(@inputString,SUBSTRING(@inputString,PATINDEX('%[^' + @validChars + ']%',@inputString),1),'')

 RETURN @inputString
END
 
--Usage of the function
select [dbo].udfGetCharacters('utkarsh puranik`s blog' ,'0-9a-z ')

--output
utkarsh puraniks blog