Tuesday, April 20, 2010

Errors and Solution

Error 1:
string isEmpty = string.Empty;
DateTime dt = isEmpty == string.Empty ? BNull.Value : DateTime.Now;
Error
Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DBNull' and 'System.DateTime'

Solution
Cast it to object.
string isEmpty = string.Empty;
DateTime dt = Convert.ToDateTime(isEmpty == string.Empty ? (object)DBNull.Value : (object)DateTime.Now);

Thursday, April 15, 2010

User Defined Functions

Types of User Defined Functions
I. Scalar Functions
II. In-Line Table Functions
III. Multistatement Table Functions

Accept parameters of any scalar data type except rowversion


Scalar Functions

In-Line Table Functions

Multistatement Table Functions

Returns only scalar value.

Return a table variable that was created by a single select statement.

Returns a table variable. No multi result set.

This type of function is used when we want to apply more logic except we can express
in a single query.

I.e. like stored procedure we can manipulate with more statements.

Support multiple T-SQL statements.

Supports only sing T-SQL Statement.

Support multiple T-SQL statements.

Return type is fixed.

No need to specify the table column names and its type.

We have to specify the table columns.
CREATE FUNCTION Testscalar(@ID INT) 
RETURNS INT 
AS 
  BEGIN 
      SELECT @ID = 10 
      SELECT @ID = @ID + 1 
      SELECT @ID = @ID + 1 
      RETURN @ID 
  END 
CREATE FUNCTION [dbo].[Testinline]
                           (
                                   Params
                           )
RETURNS TABLE AS
RETURN
	SELECT *
	FROM   dbo.treeview 
CREATE FUNCTION [dbo].[Testinline](@i INT) RETURNS TABLE AS
RETURN
SELECT @i AS [ColName]

CREATE FUNCTION [dbo].[Testmultiline]
                              (
                                      @ID INT
                              )
RETURNS @TableVariable TABLE ( I INT,
                              J  VARCHAR(10)) AS
BEGIN
        INSERT
        INTO   @TableVariable
        SELECT 1, '10' UNION ALL
        SELECT 2, '20' UNION ALL
        SELECT 3, '30'
        
        RETURN
END

The last statement included within a function must be a return statement

RETURN statements in scalar valued functions must include an argument.

Simply retrun statemet is wrong.

The last statement included within a function must be a return statement.

Return @I is wrong

Return @I as a is wrong

The last statement included within a function must be a return statement.

return @TableVariable is wrong.


Original Link : 15seconds

Valid

· Control-flow statements
· Assignment statements
· Variable declarations
· SELECT statements that modify local variables
· Cursor operations that fetch into local variables
· INSERT, UPDATE, DELETE statement that act upon local table variables
Invalid:

· Built-in, nondeterministic functions such as GetDate()
· Statements that update, insert, or delete tables or views
· Cursor fetch operations that return data to the client
. can’t able to execute a stored procedure.

How to Call Scalar-valued Functions
SELECT ColNames, dbo.ScalarValuedFunction(starttime,endtime) AS ColName FROM TableName
WHERE BankerID = dbo.ScalarValuedFunction('IBM')

How to Call Table-valued Functions
SELECT * FROM dbo.TableValuedFunctions('key1|key2|key3|key4|key5', '|')
-- For converting arrays to table

SELECT * FROM Department D 
CROSS APPLY dbo.fn_GetAllEmployeeOfADepartment(D.DepartmentID) 

SELECT * FROM Department D 
OUTER APPLY dbo.fn_GetAllEmployeeOfADepartment(D.DepartmentID) 

Tuesday, April 13, 2010

Handlers Module

HttpContext
- Request
- Response

HttpApplication
- maintaining application-scope methods
- data
- events
- After the HttpApplication object massages the request, it pushes the request through one or more HttpModule objects.

HttpModule

- When an HttpModule is hooked into the pipeline (via an entry in web.config), the ASP.NET runtime calls the module's Init and Dispose methods.
- Init is called when the module attaches itself to the HttpApplication object
- Dispose is called when the module is detached from HttpApplication.
































































Event

Occurs

AcquireRequestState

When ASP.NET acquires the current state (for example, session state) associated
with the current request

AuthenticateRequest

When a security module has established the identity of the user

AuthorizeRequest

When a security module has verified user authorization

BeginRequest

When the first event in the HTTP pipeline chain of execution responds to a request

Disposed

When ASP.NET completes the chain of execution when responding to a request

EndRequest

When the last event in the HTTP pipeline chain of execution responds to a request

Error

When an unhandled exception is thrown

PostRequestHandlerExecute

When the ASP.NET handler (page, XML Web Service) finishes execution

PreRequestHandlerExecute

Just before ASP.NET begins executing a handler such as a page or XML Web Service

PreSendRequestContent

Just before ASP.NET sends content to the client

PreSendRequestHeaders

Just before ASP.NET sends HTTP headers to the client

ReleaseRequestState

After ASP.NET finishes executing all request handlers; also causes state modules
to save the current state data

ResolveRequestCache

When ASP.NET completes an authorization event to let the caching modules serve requests
from the cache, bypassing execution of the handler (the page or XML Web Service,
for example)

UpdateRequestCache

When ASP.NET finishes executing a handler in order to let caching modules store
responses that will be used to serve subsequent requests from the cache


<httpmodules>
<add name="MyHttpModule" type="name of the class which implement the interface IHttpModule, path where the class is present, Culture=neutral">

<httpmodules>
<add type="[Namespace.]SeoUrls, [AssemblyName], [Version=x.x.x.x, Culture=neutral, PublicKeyToken=933d439bb833333a]" name="SeoUrls">
</add>

<httpmodules>
<add name="MyHttpModule" type="Secure, App_Code, Culture=neutral">
</add>


<httphandlers>
<add verb="*" path="*.data" type="namespace.classname, assemblyname(I.E. DLL Name)">

<add verb="*" path="xyz.aspx" type="test.MyFactory,HandlerFactoryTest">
</add>

</add></httphandlers></httpmodules></httpmodules></add></httpmodules>

ISNULL() vs COALESCE()


ISNULL()

COALESCE()

Specifc to SQL SERVER

ANSI standard.

The query can be used in another RDBMS which follows the ANSI standard.

SELECT ISNULL(NULL, NULL)

--O/P null

SELECT COALESCE(NULL, NULL)

Error: None of the result expressions in a CASE specification

can be NULL.

In coalesce atleast one parameter should not be null.

DECLARE @a VARCHAR(10)
DECLARE @b VARCHAR(10)
SELECT ISNULL(@a, @b)

--O/P null

DECLARE @a VARCHAR(10)
DECLARE @b VARCHAR(10)
SELECT COALESCE (@a, @b)

--O/P null

Required 2 parameters

Requires atleast 2 parameters

Accepts only 2 parameters.

But we can nest like this if we want more than 2 parameter.

ISNULL(ISNULL(Col1,Col2), Col3)


I tried 18600 parameters.

If it reaches more than that or with this count itself

the SQL SERVER throws "System.OutOfMemoryException".

So I think this blongs to hardware specification.

Consider 2nd parameter data type as first datatype.
(i.e. It uses as the first parameter datatype.)

If the length of the second parameter is greater than the first parameter
it will be truncated to first parameter size.

Eg.1

DECLARE @a VARCHAR(10)
DECLARE @b DATETIME
SET @b = GETDATE()

SELECT CONVERT(VARCHAR(11), @b, 100)
SELECT ISNULL(@a, @b)

--O/P Apr 13 201

--It took the format 100 and varchar size to 10.

--Change the varchar size of below query and you will understand.

SELECT ISNULL(@a, CONVERT(VARCHAR(11), @b, 100))
SELECT ISNULL(CAST(@a as varchar(11)), @b)
--O/P Apr 13 201
--O/P Apr 13 2010

Eg.2

DECLARE @a VARCHAR(5)
DECLARE @b VARCHAR(8)
SET @b = 'SQL SERVER'
SELECT ISNULL(@a, @b)

--O/P SQL S

It truncates to first parameter size.

Eg.3

DECLARE @a VARCHAR(5)
DECLARE @b VARCHAR(8)
DECLARE @c INT
SET @c = 123456
SELECT ISNULL(@a, @c)

--O/P *

If SET @c = 12345--O/P 12345

Since @a size is 5 which is the first parameter.

Multiple datatype is allowed.

It took highest data type in the expression list.

If we are having int and double. It took double.

Eg.1

DECLARE @a VARCHAR(10)
DECLARE @b DATETIME
SET @b = GETDATE()
SELECT COALESCE(@a, @b)

--O/P 2010-04-13 17:21:12.330

Eg.2
DECLARE @a VARCHAR(5)
DECLARE @b VARCHAR(8)
SET @b = 'SQL SERVER'
SELECT COALESCE(@a, @b)

--O/P SQL SERV

It tooks the datatype of the parameter which is not null.

Eg.3

DECLARE @a VARCHAR(5)
DECLARE @b VARCHAR(8)
DECLARE @c INT
SET @c = 123456
SELECT COALESCE(@a, @b, @c)

--O/P 123456
DECLARE @a INT
DECLARE @b DATETIME
SET @a = 2
SET @b = GETDATE()
SELECT COALESCE (@a, @b)

--O/P 1900-01-03 00:00:00.000

if we set
SET @a = 0
--O/P 1900-01-01 00:00:00.000

if we set, it increments month and date
SET @a = 35
--O/P 1900-02-05 00:00:00.000


Reference: sqlserver-qa.net
Deciding between COALESCE and ISNULL

Thursday, April 8, 2010

Brute force protect your website



<head runat="server">
    <title></title>
    <style type="text/css">
        .table
        {
            background-image: url('Images/buttonbg.png');
            background-repeat: repeat;
        }
        .buttonBg
        {
            background-color: Silver;
            background-image: none;
            border-style: solid;
            border-width: 1;
            border-color: #c63 #930 #930 #c63;
        }
        .textbox_username
        {
            background: #ffffff url('images/icon_username.png') no-repeat;
            background-position: 1 1;
            padding-left: 19px;
            border: 1px solid #999999;
            border-top-color: #CCCCCC;
            border-left-color: #CCCCCC;
            color: #333333;
            font: 90% Verdana, Helvetica, Arial, sans-serif;
            font-size: 12px;
            height: 20px;
        }
        .textbox_password
        {
            background: #ffffff url('images/icon_password.png') no-repeat;
            background-position: 1 1;
            padding-left: 19px;
            border: 1px solid #999999;
            border-top-color: #CCCCCC;
            border-left-color: #CCCCCC;
            color: #333333;
            font: 90% Verdana, Helvetica, Arial, sans-serif;
            font-size: 12px;
            height: 20px;
        }
        .button
        {
            border: 1px solid #999999;
            border-top-color: #CCCCCC;
            border-left-color: #CCCCCC;
            background-color: white;
            color: #333333;
            font: 90% Verdana, Helvetica, Arial, sans-serif;
            font-size: 11px;
            -moz-border-radius: 3px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table class="table">
            <tr>
                <td colspan="4">
                    <asp:Label ID="lblUserLogOn" runat="server" Text="User Log On" Style="font-size: smaller;
                        font-family: Verdana; font-weight: bolder;"></asp:Label>
                </td>
            </tr>
            <tr>
                <td rowspan="3">
                    <img src="Images/Security.PNG" style="width: 80px; height: 80px;" alt="" />
                </td>
                <td>
                    <asp:Label ID="lblUserName" runat="server" Text="User Name" Style="font-size: x-small;
                        font-family: Verdana; font-weight: bold;"></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="txtUserName" runat="server" CssClass="textbox_username" TabIndex = "1" ></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Label ID="lblPassword" runat="server" Text="Password" Style="font-size: x-small;
                        font-family: Verdana; font-weight: bold;"></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="txtPassword" runat="server" CssClass="textbox_password" TabIndex = "2"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td colspan="2" style="text-align:right; padding-right:2px;">
                    <asp:Button ID="btnLogOn" runat="server" Text="LogOn" CssClass="buttonBg" 
                        TabIndex = "3" onclick="btnLogOn_Click"/>
                </td>
            </tr>
            <tr>
            <td colspan="3" style="text-align:right; padding-right:2px;">
                <asp:Label ID="lblInvalid" runat="server" Text="Incorrect username or password." style="color:#FF0000;"></asp:Label>
            </td>
            </tr>
        </table>
    </div>
    
    </form>
</body>
</html>

public partial class SimpleLoginTemplate_LogOn : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        //ClearLogonCounter();

        switch (btnLogOn.Enabled)
        {
            case false:
                break;
            case true:
                btnLogOn.Enabled = NumberOfLogonAttemps() <= 5 ? true : false;
                break;
        }
    }

    protected void btnLogOn_Click(object sender, EventArgs e)
    {
        AddOrCountLogonAttempt();

        if (NumberOfLogonAttemps() > 5)
        {
            if (!lblInvalid.Text.Trim().Equals("User has been locked for 5 minutes."))
                //If the attempt is > 5 Lock the user for 5 min
                //After that the userName cleared from the cache
                Cache.Insert(txtUserName.Text.Trim(), (int)Cache[txtUserName.Text.Trim()], null, DateTime.Now.AddMinutes(5), TimeSpan.Zero);

            lblInvalid.Text = "User has been locked for 5 minutes.";
            btnLogOn.Enabled = false;
        }
        else
        {
            btnLogOn.Enabled = true;
            switch (LogOn())
            {
                //Clear the count if user logon correctly
                case true:
                    ClearLogonCounter();
                    break;
                case false:
                    break;
            }
        }
    }

    private bool LogOn()
    {
        lblInvalid.Text = "Incorrect username or password.";
        return false;
    }

    #region "Brute force protect"
    //http://madskristensen.net/post/Brute-force-protect-your-website.aspx
    private int NumberOfLogonAttemps()
    {
        if (Cache[txtUserName.Text.Trim()] == null)
           return 0;
        //txtNoOfTries.Text = Convert.ToString( Cache[txtUserName.Text.Trim()]);
        return (int)Cache[txtUserName.Text.Trim()];
    }

    private void ClearLogonCounter()
    {
        if (Cache[txtUserName.Text.Trim()] != null)
        {
            Cache.Remove(txtUserName.Text.Trim());
        }
    }

    private void AddOrCountLogonAttempt()
    {
        if (Cache[txtUserName.Text.Trim()] == null)
        {
            //NoAbsoluteExpiration -- item should never expire
            // Sliding expiration means we reset the X seconds after each request.
            //http://wiki.asp.net/page.aspx/655/caching-in-aspnet/

            Cache.Insert(txtUserName.Text.Trim(), 1, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(1));
        }
        else
        {
            int tries = (int)Cache[txtUserName.Text.Trim()];
            Cache[txtUserName.Text.Trim()] = tries + 1;
        }
    }

    #endregion
}

Reference:madskristensen.net
All credits goes to him.

Tuesday, March 23, 2010

Struct


  1. Within a struct declaration, fields cannot be initialized unless they are declared as const or static.
     
    //public int UserId = 10; //Error

  2. A struct may not declare a default constructor (a constructor without parameters) or a destructor. Any private or otherwise inaccessible members can be initialized only in a constructor.
  3. Copy a struct to struct.
    If you copy a struct, C# creates a new copy of the object and assigns the copy of the object to a separate struct instance.
    Structs are copied on assignment. When a struct is assigned to a new variable, all the data is copied, and any modification to the new copy does not change the data for the original copy. This is important to remember when working with collections of value types such as Dictionary.
     
    Student s1 = new Student();
    Student s2;
    s1 = s2;
    Response.Write(s1.PUserId);
    Response.Write(s2.PUserId);

    Here all the values of s1 will be copied to s2.
  4. Structs are value types and classes are reference types.
  5. Unlike classes, structs can be instantiated without using a new operator.
     
    Student s1;
    s1.Address = "Savadipalayam";

  6. Initialize the fields through properties. Use of unassigned local variable 's1'.
     
    Student s1;
    Response.Write(s1.PUserId)

    In fact, when instantiating a struct without the new keyword, we must first initialize its fields explicitly.
     
    Student s1;
    s1.PUserId = 10;
    Response.Write(s1.PUserId)

  7. Structs can declare constructors that have parameters. But all the field variables should be fully initialzed.
     
    public Student(int UserId, int ZipCode, double Salary, string Address)
    {
    this.UserId = UserId;
    this.ZipCode = ZipCode;
    this.Salary = Salary;
    //this.Address = Address;
    }

    This will produce an error Field 'StructTest.Student.Address' must be fully assigned before control is returned to the caller". Since Address is not initialized.
  8. A struct cannot inherit from another struct or class, and it cannot be the base of a class. All structs inherit directly from System.ValueType, which inherits from System.Object.
  9. A struct can implement interfaces, and it does that exactly as classes do.
  10. Cannot convert null to 'StructTest.Student'

    Student s2 = null;

    DateTime is struct. We can't assign null to DateTime.
    Cannot convert null to 'System.DateTime' because it is a non-nullable value type.
    eg.

    DateTime dt = null;

  11. A struct can be used as a nullable type and can be assigned a null value.
    Working with Nullable Types in struct.
  12. If a field is not initialized whether it is a primitive data type it produce the error "Use of possibly unassigned field 'i'" when we didn’t create instance for the struct.

    Student1 s3;
    Response.Write(s3.i);


  13. When we create an instance for the struct but we don’t have any constructor to assing value, it will asign the default value for premitive datatype and for others it will assing null(null for string).


    public struct Student1
    {
    public int i;
    public string j;
    }

    Student1 s3 = new Student1();
    Response.Write(s3.i); //O/P = 0
    Response.Write(s3.j); //O/P = null


  14. struct can also have copy constructor but have to be fully initialzed.

    public Student(Student stud)
    {
    this.UserId = stud.UserId;
    this.ZipCode = stud.ZipCode;
    this.Salary = stud.Salary;

    //Field 'StructTest.Student.Address' must be fully assigned before control is returned to the caller
    //this.Address = stud.Address;

    this.Address = stud.Address;
    }

  15. Struct can contain methods. It may be static, and a static method can call only another static methods.

    public void sub()
    {

    }

    public static string multiply()
    {
    return Send();
    }

    public static string Send()
    {
    //An object reference is required for the non-static field, method, or property 'StructTest.Student.Address'
    //Address = "Mottur Road";
    //return Address;

    Street = "Mottur Road";
    return Street;
    }

  16. //The allowed modifiers are new, static, virtual, override, and a valid combination of the four access modifiers (public, internal and private).

    // Override the ToString method so the value appears in text
    public override string ToString()
    {
    return String.Format("({0},{1})", Street, Address);
    }

  17. Support access modifiers, constructors, indexers, methods, fields, nested types, operators, and properties.

    public int PUserId
    {
    get { return UserId; }
    set { UserId = value; }
    }

  18. Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal.. If we declare a struct inside a namespace with any of the access specifier as private, protected, or protected internal, we will get this error.
    So it is always public when we declare a struct inside a namespace.
  19. Abstract and sealed modifiers are not permitted in a struct declaration since it is always implicitly sealed.
    Since it is implicitly sealed, struct members may not be declared protected.
    So we can't able to inherit another struct.
    Since it is not abstract, struct can't be a base to a class or another structure.



struct Student : IOne, ITwo
{
int UserId;
//public int UserId = 10; //Within a struct declaration, fields cannot be initialized unless they are declared as const or static.

public static string Street = "Savadipalayam";

int ZipCode;
double Salary;
public string Address;

//Structs cannot contain explicit parameterless constructors(Default constructor)
/* public Student()
{
this.UserId = 10;
this.ZipCode = 637101;
this.Salary = 2000;
this.Address = "Idappadi";
}
*/

// all the members of the struct has to be initialized in this way
public Student(int UserId, int ZipCode, double Salary, string Address)
{
this.UserId = UserId;
this.ZipCode = ZipCode;
this.Salary = Salary;
this.Address = Address;
}

// struct can also have copy constructor but have to be fully initialzed
public Student(Student stud)
{
this.UserId = stud.UserId;
this.ZipCode = stud.ZipCode;
this.Salary = stud.Salary;

//Field 'StructTest.Student.Address' must be fully assigned before control is returned to the caller
//this.Address = stud.Address;

this.Address = stud.Address;
}

public int PUserId
{
get { return UserId; }
set { UserId = value; }
}

//new protected member declared in struct
//protected void add()
//{
//}

//Struct can contain methods. It may be static, and can call only another static methods.
public void sub()
{

}

public static string multiply()
{
return Send();
}

public static string Send()
{
//An object reference is required for the non-static field, method, or property 'StructTest.Student.Address'
//Address = "Mottur Road";
//return Address;

Street = "Mottur Road";
return Street;
}

//The modifier 'abstract' is not valid for this item
//public abstract void Return() { }

#region ITwo Members

void ITwo.add()
{
throw new System.NotImplementedException();
}

public void sum()
{
throw new System.NotImplementedException();
}

#endregion

#region IOne Members

void IOne.add()
{
throw new System.NotImplementedException();
}

void IOne.sum()
{
throw new System.NotImplementedException();
}

#endregion
}

//Nested Structures


public struct outer
{
public int i;
public struct inner
{
public int j;
}
}


How to call?.


outer.inner inn = new outer.inner();
inn.j = 10;


References
C# School
vijaymukhi
C# Online.net
codeproject
csharp-station

Can't access App_Code class in Code Behind file

I had created a struct in file in the App_Code. But I can't able to access the namespace.
 
namespace StructTest
{
public struct Student
{
int id;
int zipcode;
double salary;
}
}

Solution
Right click on the file and select properties then change the Build Action to Compile.