Thursday, June 27, 2013

Developer Common Mistake

String Concatenation

They Used String to append , here each time when you add something , a new address is being allocated in the memory.
Whereas in String Builder same address is gets modified.

//INCORRECT
List values = new List(){"This ","is ","Sparta ","!"};
string outputValue = string.Empty;
foreach (var value in values)
{
   outputValue += value;
}


//CORRECT
StringBuilder outputValueBuilder = new StringBuilder();
foreach (var value in values)
{
   outputValueBuilder.Append(value);
}

Not using mapping for rewriting properties

Not Using powerful C# mapper : - http://automapper.org/ 

Using ‘foreach’ instead of ‘for’ for anything else than collections

IF it not a collection then use for loop  is much more efficient than using the ‘foreach’ loop.



Theme In C# asp.net


  1. Open Visual Studio File -->New--> Website (Create Website)
  2. Add App_Code Folder
  3. Inside App_Code Folder Add Class (ThemeClass.cs) 
  4. Add master Page
  5. Then Add Default .aspx Use Master Page
ThemeClass.Cs

public class themeclass : System.Web.UI.Page
{
   
    protected void Page_PreInit(object sender, EventArgs e)
    {
        if (Session["Theme"] != null)
        {
            Page.Theme = Session["Theme"].ToString();
        }
    }
   
}

I have Used inherited Class By Page



Default.aspx

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Title="Untitled Page" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

 <div>
        <table class="tablecss" align="center" width="30%">
            <tr>
                <td colspan="2" align="center">
                    <h3>
                        Registration Form</h3>
                </td>
            </tr>
            <tr>
                <td align="right">
                    UserName:
                </td>
                <td>
                    <asp:TextBox ID="txtUser" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td align="right">
                    Email:
                </td>
                <td>
                    <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td align="right">
                    Date of Birth:
                </td>
                <td>
                    <asp:TextBox ID="txtDOB" runat="server"></asp:TextBox>
                </td>
            </tr>           
            <tr>
                <td align="right">
                    Address:
                </td>
                <td>
                    <asp:TextBox ID="txtAddress" runat="server" Columns="17" Rows="8" TextMode="MultiLine"></asp:TextBox>
                </td>
            </tr>
        </table>
    </div>
</asp:Content>



Default.CS

public partial class _Default : themeclass
{
    protected void Page_Load(object sender, EventArgs e)
    {
       

    }
}

System.Web.UI.Page is replaced by Class Name

MasterPage

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

<!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>Untitled Page</title>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div id="header" runat="server" style="align: center">
            <asp:DropDownList ID="ddlchangecolor"  runat="server" OnSelectedIndexChanged="ddlchangecolor_SelectedIndexChanged"
                OnTextChanged="ddlchangecolor_TextChanged">
                <asp:ListItem Text="White" Value="White"></asp:ListItem>
                <asp:ListItem Text="Blue" Value="Blue"></asp:ListItem>
                <asp:ListItem Text="Red" Value="Red"></asp:ListItem>
                <asp:ListItem Text="Purple" Value="Purple"></asp:ListItem>
            </asp:DropDownList>
            <asp:Button ID="btnBlue" runat="server" Text="Change Theme" BackColor="Blue" Font-Bold="true"
                OnClick="btnBlue_Click" />
        </div>
        <%--   <asp:ScriptManager ID="ScriptManager1" runat="server" />--%>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>
        <div id="footer" runat="server">
        </div>
    </div>
    </form>
</body>
</html>


MasterPage.CS
using System;

public partial class MasterPage : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void ddlchangecolor_SelectedIndexChanged(object sender, EventArgs e)
    {      
    }
    protected void btnBlue_Click(object sender, EventArgs e)
    {
        Session["Theme"] = ddlchangecolor.SelectedItem.Value.ToString().Trim();
     
        Server.Transfer(Request.FilePath);
    }
    protected void ddlchangecolor_TextChanged(object sender, EventArgs e)
    {
      
    }
}

 In The App_Theme Folder 
Add Skin With Blue, Purple, Red , White
Add CSS With Every Skin
Blue.CSS Under Blue Folder
body
{
    background-color:Blue;
}


Purple.CSS Under PurpleFolder
body
{
    background-color:
Purple;
}




Red.CSS Under Red Folder
body
{
    background-color:
Red;
}


White.CSS Under White Folder
body
{
    background-color:
White;
}


Happy Coding



Wednesday, June 26, 2013

Try Catch in sql server Stored Procedure

As we all use try catch for exception handling in code  similarly we apply in stored procedure

Syntax:
BEGIN TRY
{ sql_statement
|
statement_block }
END TRY
BEGIN CATCH
{ sql_statement
|
statement_block }
END CATCH




Functions to be used in CATCH block are :
  • ERROR_NUMBER: returns the error number, and is the same value of @@ERROR.
  • ERROR_SEVERITY: returns the severity level of the error that invoked the CATCH block.
  • ERROR_STATE: returns the state number of the error.
  • ERROR_LINE: returns the line number where the error occurred.
  • ERROR_PROCEDURE: returns the name of the stored procedure or trigger for which the error occurred.
  • ERROR_MESSAGE: returns the full message text of the error. The text includes the values supplied for any substitutable parameters, such as lengths, object names, or times.

USE AdventureWorks;
GO
BEGIN TRY
-- Generate a divide-by-zero error.
SELECT 1/0;
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_STATE() AS ErrorState,
ERROR_PROCEDURE() AS ErrorProcedure,
ERROR_LINE() AS ErrorLine,
ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
GO

Wednesday, June 19, 2013

Table script With data- Database publishing Wizard

Table script With data- Database publishing Wizard
All you have to download the Database Publishing Wizard

  1. Install it

Server.mappath in C#

Server.MapPath specifies the relative or virtual path to map to a physical directory.
  • Server.MapPath(".") returns the current physical directory of the file (e.g. aspx) being executed
  • Server.MapPath("..") returns the parent directory
  • Server.MapPath("~") returns the physical path to the root of the application
  • Server.MapPath("/") returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)
An example:
Let's say you pointed a web site application (http://www.example.com/) to
C:\Inetpub\wwwroot
and installed your shop application (sub web as virtual directory in IIS, marked as application) in
D:\WebApps\shop
For example, if you call Server.MapPath in following request:
http://www.example.com/shop/products/GetProduct.aspx?id=2342
then:
  • Server.MapPath(".") returns D:\WebApps\shop\products
  • Server.MapPath("..") returns D:\WebApps\shop
  • Server.MapPath("~") returns D:\WebApps\shop
  • Server.MapPath("/") returns C:\Inetpub\wwwroot
  • Server.MapPath("/shop") returns D:\WebApps\shop
If Path starts with either a forward (/) or backward slash (\), the MapPath method returns a path as if Path were a full, virtual path.
If Path doesn't start with a slash, the MapPath method returns a path relative to the directory of the request being processed.
Note: in C#, @ is the verbatim literal string operator meaning that the string should be used "as is" and not be processed for escape sequences.

Delegates in C#

Delegates are pointer toward a function or method.It solved the decoupling problem.

For exampling : when you go to marriage the representative welcomes you and tells someone (References) to look after you. Due to this he easily manage all the guest.

Wouldn’t it be nice to have a delegate that could refer to more than one function at once and invoke them
simultaneously? This would allow the client application to have multiple “listeners” and notify the listeners all
at once when something happens.
In fact, delegates do have this functionality, but you’re more likely to see it in use with .NET events.
Events, which are described in the next chapter, are based on delegates but work at a slightly higher level.
In a typical ASP.NET program, you’ll use events extensively, but you’ll probably never work directly with
delegates.


There are four step to create delegates :-
  1. Declare
  2.  Create
  3. Pointer
  4. Invoke
   public delegate int Pointertoaddfun(int i, int y);
    private int add(int x,int y)
    {
        return x + y;
    }
    private int sub(int x, int y)
    {
        return x + y;
    }
 
    public Pointertoaddfun getpointer(int dir)
    {
        Pointertoaddfun objpoiter=null;
        if (dir == 1)
        { objpoiter = add; }
        if (dir == 2)
        { objpoiter = sub; }
    }

    To watch video : -http://www.youtube.com/watch?v=3ckXHImXMiU

Tuesday, June 18, 2013

Trigger in Sql Server

Trigger is a logic which executes on the tables after or before when the insertion, deletion and updation query executes. 

There are two type of trigger
  1. Instead of trigger
  2. After Trigger

Instead of trigger : - It fire before the insert/Update/Delete executes on table.

After Trigger : It fires After insert/delete/update command executes on table.

 Lets Start Understanding the use of trigger in sql server -
First we Create trigger : - this one is after trigger

 
CREATE Trigger tblUpdate   
On tblemp   
After Insert,Delete, Update   
As Begin   
   
Declare @Oldvalues nvarchar(50)   
Declare @newvalues nvarchar(50)   

   
--Fetch inserted value   
Select @newvalues=Customername from inserted   
--fetch deleted value   
   
Select @Oldvalues=Customername from deleted   
   
insert into tblaudit(LastUpdated,Oldvalues,newvalues)   
values(getdate(),@Oldvalues,@newvalues)   
   
End   


Description of Used word in trigger : -
tblUpdate - Trigger Name
tblemp     - Table name on which trigger will fire.
Inserted  - When any insert command executes it will store the current value.

Deleted   - When any delete command excutes it will store the deleted data.


Here i have created two table one is tblemp and tblaudit
Table tblaudit


CREATE TABLE [dbo].[tblaudit](
    [LastUpdated] [datetime] NULL,
    [Oldvalues] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [newvalues] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]


Table tblemp

CREATE TABLE [dbo].[tblemp](
    [CustomerID] [int] IDENTITY(1,1) NOT NULL,
    [Customername] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]


When any insert update delete command executes trigger will fire automatically..

Note : First create table then trigger.
Watch Video click here

Monday, June 17, 2013

405 - HTTP verb used to access this page is not allowed.

The HTTP verb POST used to access path '/html5demos/post.html' is not allowed.

When you tried to work on html page in Visual studio sometime it fire above error.

<!DOCTYPE html>
<html>
<head>
    <title>Untitled Page</title>
</head>
<body>
    <form name="form" id="form1" method="post" action="post.html" target=_self>
    <input type="text" id="text2" name="text2"  />
    <input type="text" id="Text1"  />
    <input type="submit" name="Submit" value="Submit" />
  
    </form>
</body>
</html>

Solution

Problem : File type is not registred in IIS amp setting. Http POST , HEAD are respond with 405 error.

1.GO to Control Panel "Administrative Tools" --> IIS
2.Select The Website and select handler mapping
3.Add Script map
Request Path Should Be " .Htm "
or ".html"
Select this Path  C:\Windows\System32\inetsrv\asp.dll

Name  what ever u can 

After this click on Request Restriction 
 Mapping  :  "Invoke handler only if request is mapped to :" 
check "file" 

Verbs :  "All Verbs"

In the last Click Okay OK

Hope it will work fine... 


Friday, June 14, 2013

Saturday, June 1, 2013

Upload Image through FCK Editor Asp.net

Upload Image through FCK Editor Asp.net it always throws the some issue :-
When trying to upload images through FCK Editor tool inside an aspx page it throws an  error[XML 403 path Error].
To Fix the issue we have to configure manually.

STEP-I :
File Path  :  fckeditor/fckconfig.js
Previously :
var _FileBrowserLanguage    = 'asp' ;  // asp | aspx | cfm | lasso | perl | php | py
var _QuickUploadLanguage    = 'asp' ;  // asp | aspx | cfm | lasso | perl | php | py

We have to change 'asp' to 'aspx'

STEP-II
File Path  :  fckeditor\editor\filemanager\connectors\aspx\config.ascx
Previously :
           Change-1 : Enabled = CheckAuthentication();
                       
                          Change-2 : UserFilesPath = "~/upload/";
           Change-3 : UserFilesAbsolutePath = "C:\\upload\\";
                            
Chnage -1 : change it to Enable = true;
Change -2 : change the folder name in which you want to store the uploaded image.
Change -3 : change the absolute path of the folder in which you want to store the uploaded image.

Best Code practice C#

Use int.TryParse( ) to keep away exception .
Convert.Int32 throws an exception of "System.FormatException" when the input parameter is wrong .

Example

If we are converting a QueryString value to integer and the QueryString value is "de8913jhjkdas", then -
int employeeID = 0;
employeeAge = Convert.ToInt32(Request.QueryString.Get("Userid")); //Here it will throw an Exception.

int employeeAge = 0;
int.TryParse(Request.QueryString.Get("Userid");, out employeeAge); //Here it will not throw any Exception.

You can also use bool.TryParse, float.TryParse, double.TryParse, etc for converting into other datatypes.



Convert.ToString() V/S obj.ToString()



Use Convert.ToString(), because if you are using obj.ToString() and the object(obj) value is null it will throw an excetion of type "System.NullReferenceException".
The cause of the exception is null doesn't have a method called ToString().
Response.Write("Name : " + Session["User_Name"].ToString());        //Here it will throw an Exception if Session["User_Name"] is null.
Response.Write("Name : " + Convert.ToString(Session["User_Name"])); //Here it will not throw any Exception.
 String.Empty V/S ""


If you want to check whether a string is empty or not then use String.Empty instead of "", because "" will create a new object in the memory for the checking while String.Empty will not create any object, because Empty is a read-only property of String class.
So its better to use if("Devi" == String.Empty) instead of if("Devi" == "").
You can also use if("Devi".Length == 0) for doing the same thing but if the string is null then it will throw an exception of type "System.NullReferenceException".
 
 String.IsNullorEmpry() V/S ("" || null)


Suppose you want to check a string for both its emptiness and nullability then its better to use String.IsNullOrEmpty() instead of ("" || null). Because "" will create a new object but String.IsNullOrEmpty() will not do so.
So its better to use if(String.IsNullOrEmpty("Devi")) instead of if("Devi" == "" || "Devi" == null)