Thursday 26 December 2013

Write Error into Log File in VB

Create a general Class:
================
Imports Microsoft.VisualBasic
Imports System.IO
Imports System.Globalization
Imports System.Net

Public Class clsErrHandler

    ''' Handles error by accepting the error message
    ''' Displays the page on which the error occured

    Public Sub WriteError(ex As Exception)
        'VARIABLE DECLARATION
        Dim strErrorIn As String, strFileName As String, strErrorMethodName As String, strErrorMessage As String, _
       strLineNo As String, strException As String, strDllInfo As String, strLocationInfo As String

        Dim strFileCheck As String
        Dim arrFileCheck As String()
        Try
            strException = ex.StackTrace.Trim().Remove(0, 3)

            If strException.Contains(":") AndAlso strException.Contains(".") AndAlso strException.Contains("\") Then
                strDllInfo = strException.Substring(0, strException.IndexOf("("c))
                strLocationInfo = strException.Substring(strException.IndexOf(")"c), (strException.LastIndexOf(":"c)) - strException.IndexOf(")"c)).Remove(0, 5)


                'Get the File Type & Name
                strFileCheck = strLocationInfo.Substring(strLocationInfo.LastIndexOf("\"c)).Remove(0, 1)
                arrFileCheck = strFileCheck.Split("."c)

                If arrFileCheck.Length > 2 Then
                    strErrorIn = "Page File"
                Else
                    strErrorIn = "Class File"
                End If
                strFileName = strFileCheck


                'Get the Error Method Name
                strErrorMethodName = strDllInfo.Substring(strDllInfo.LastIndexOf("."c)).Remove(0, 1)

                'Get the Error Meassage
                strErrorMessage = ex.Message

                'Get the Error Line No.
                strLineNo = strException.Substring(strException.LastIndexOf(":"c), (strException.Length - strException.LastIndexOf(":"c))).Remove(0, 6)
            Else
                strFileName = "-"
                strErrorMethodName = ex.ToString()
                strErrorIn = "Application Error"
                strLineNo = "-"
                strErrorMessage = ex.Message
            End If

            'Write the Error In ErroLog File
            WriteToErrorLog(strErrorIn, strFileName, strErrorMethodName, strErrorMessage, strLineNo)

        Catch exp As Exception
            WriteError(exp)
        End Try
    End Sub

    Public Sub WriteToErrorLog(strErrorIn As String, strFileName As String, strErrMethodName As String, strErrMessage As String, _
     strLineNo As String)
        'IP TRACKING START HERE
        Dim strHostName As String = ""
        Dim ipEntry As IPHostEntry = System.Net.Dns.GetHostEntry(strHostName)
        Dim addr As IPAddress() = ipEntry.AddressList
        Dim path As String = "~/ErrorLog/" & DateTime.Today.ToString("dd-MM-yyyy") & ".txt"

        Try
            strHostName = System.Net.Dns.GetHostName()
            'IP TRACKING END HERE

            'LOG FILE CREATE IF NOT EXISTS
            If (Not File.Exists(System.Web.HttpContext.Current.Server.MapPath(path))) Then
                File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close()
            End If

            Using w As StreamWriter = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path))
                w.WriteLine(Constants.vbCrLf & "Log Entry : ")

                Dim err As String = "Error Path: " & System.Web.HttpContext.Current.Request.Url.ToString()
                err = err & Environment.NewLine
                err = err & "Error Date Time: " & DateTime.Now.ToString(CultureInfo.InvariantCulture)
                err = err & Environment.NewLine
                err = err & "Error Type: " & strErrorIn
                err = err & Environment.NewLine
                err = err & "File Name : " & strFileName
                err = err & Environment.NewLine
                err = err & "Error Method: " & strErrMethodName
                err = err & Environment.NewLine
                err = err & "Error Line: " & strLineNo
                err = err & Environment.NewLine
                err = err & "Error Message: " & strErrMessage
                err = err & Environment.NewLine
                err = err & "Host Name : " & strHostName & ". IP Address : " & addr(addr.Length - 1).ToString()

                w.WriteLine(err)
                w.WriteLine("__________________________________________________")
                w.Flush()
                w.Close()
            End Using
        Catch ex As Exception
            WriteError(ex)
        End Try
       
    End Sub

End Class

Write in Catch
=========
Dim objErrHandler = New clsErrHandler()
            Try
                objErrHandler.WriteError(ex)
            Catch exp As Exception
                objErrHandler.WriteError(exp)           
            End Try

Wednesday 4 December 2013

List of SP or Function containing specific text

SELECT ROUTINE_NAME, ROUTINE_DEFINITION
    FROM INFORMATION_SCHEMA.ROUTINES
    WHERE ROUTINE_DEFINITION LIKE '%searchtext%'
   -- AND ROUTINE_TYPE='PROCEDURE'

How do I find what stored procedures contain a table in SQL

SELECT DISTINCT so.name  
FROM syscomments sc  
INNER JOIN sysobjects so ON sc.id=so.id  
WHERE sc.TEXT LIKE '%tablename%' 

Tuesday 3 December 2013

SQL Server STR Function and SPACE Function


STR() Function
This function returns character data converted from numeric data.
It takes 3 arguments. First argument as float data,second argument
as integer value specifying the length of the string including decimal
that is to be retrieved and third argument as integer specifying the
number of places to the right of the decimal point.

e.g: SELECT STR(123.45, 6, 1)

SPACE() Function
This function returns a string of repeated spaces.

e.g:select 'Hello'+Space(2)+'World'

Character Count using jQuery

<%@ 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 id="Head1" runat="server">
    <title></title>
    <script src="jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        var characterLimit = 140;
        $(document).ready(function () {
            $("#lblremaingCharacters").html(characterLimit);
            $("#meTextarea").bind("keyup", function () {
                var characterInserted = $(this).val().length;
                if (characterInserted > characterLimit) {
                    $(this).val($(this).val().substr(0, characterLimit));
                }
                var characterRemaining = characterLimit - characterInserted;
                $("#lblremaingCharacters").html(characterRemaining);
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <label id="lblremaingCharacters" style="color:Red;font-weight:bold"></label><label> characters remaining.</label><br />
        <asp:TextBox ID="meTextarea" runat="server" TextMode="MultiLine"></asp:TextBox>
 
    </div>
    </form>
</body>
</html>

Thursday 14 November 2013

jQuery Datepicker

<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Datepicker</title>

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

<script>
$(function() {
$( "#datepicker" ).datepicker({
changeMonth: true,
changeYear: true
});
});
</script>

<style type="text/css">
div.ui-datepicker{
 font-size:10px;
}
</style>

</head>
<body>

<p>Date: <input type="text" id="datepicker" /></p>


</body>
</html>

Abstract vs Interface

What is an Abstract Class?

An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.

What is an Interface?

An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn’t support multiple inheritance, interfaces are used to implement multiple inheritance.

Both Together

When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.
When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.
There are some similarities and differences between an interface and an abstract class that I have arranged in a table for easier comparison:
Feature Interface Abstract class
Multiple inheritance A class may inherit several interfaces. A class may inherit only one abstract class.
Default implementation An interface cannot provide any code, just the signature. An abstract class can provide complete, default code and/or just the details that have to be overridden.
Access Modfiers An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public An abstract class can contain access modifiers for the subs, functions, properties
Core VS Peripheral Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface. An abstract class defines the core identity of a class and there it is used for objects of the same type.
Homogeneity If various implementations only share method signatures then it is better to use Interfaces. If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.
Speed Requires more time to find the actual method in the corresponding classes. Fast
Adding functionality (Versioning) If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method. If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
Fields and Constants No fields can be defined in interfaces An abstract class can have fields and constrants defined

Using the Code

Let me explain the code to make it a bit easier. There is an Employee abstract class and an IEmployee interface. Within the Abstract class and the Interface entity I am commenting on the differences between the artifacts.
I am testing both the Abstract class and the Interface by implementing objects from them. From the Employee abstract class, we have inherited one object: Emp_Fulltime. Similarly from IEmployee we have inherited one object: Emp_Fulltime2.
In the test code under the GUI, I am creating instances of both Emp_Fulltime and Emp_Fulltime2 and then setting their attributes and finally calling the calculateWage method of the objects.

Abstract Class Employee

using System;

namespace AbstractsANDInterfaces
{
    /// 


    /// Summary description for Employee.

    /// 

    
    public abstract class Employee
    {
        //we can have fields and properties 


        //in the Abstract class

        protected String id;
        protected String lname;
        protected String fname;

        //properties


        public abstract String ID
        {
            get;
            set;
        }

        public abstract String FirstName
        {
            get;
            set;
        }
        
        public abstract String LastName
        {
            get;
            set;
        }
        //completed methods


        public String Update()
        {
            return "Employee " + id + " " + 
                      lname + " " + fname + 
                      " updated";
        }
        //completed methods


        public String Add()
        {
            return "Employee " + id + " " + 
                      lname + " " + fname + 
                      " added";
        }
        //completed methods


        public String Delete()
        {
            return "Employee " + id + " " + 
                      lname + " " + fname + 
                      " deleted";
        }
        //completed methods


        public String Search()
        {
            return "Employee " + id + " " + 
                      lname + " " + fname + 
                      " found";
        }

        //abstract method that is different 


        //from Fulltime and Contractor

        //therefore i keep it uncompleted and 

        //let each implementation 

        //complete it the way they calculate the wage.


        public abstract String CalculateWage();
        
    }
}

Interface Employee

using System;


namespace AbstractsANDInterfaces
{
    /// <span class="code-SummaryComment"><summary></span>


    /// Summary description for IEmployee.

    /// <span class="code-SummaryComment"></summary></span>

    public interface IEmployee
    {
        //cannot have fields. uncommenting 


        //will raise error!
        //        protected String id;
        //        protected String lname;
        //        protected String fname;


        //just signature of the properties 

        //and methods.

        //setting a rule or contract to be 

        //followed by implementations.


        String ID
        {
            get;
            set;
        }

        String FirstName
        {
            get;
            set;
        }
        
        String LastName
        {
            get;
            set;
        }
        
        // cannot have implementation


        // cannot have modifiers public 

        // etc all are assumed public

        // cannot have virtual


        String Update();

        String Add();

        String Delete();

        String Search();

        String CalculateWage();
    }
}

Inherited Objects

Emp_Fulltime:
using System;

namespace AbstractsANDInterfaces
{
    /// 


    /// Summary description for Emp_Fulltime.

    /// 

     
    //Inheriting from the Abstract class

    public class Emp_Fulltime : Employee
    {
        //uses all the properties of the 


        //Abstract class therefore no 

        //properties or fields here!


        public Emp_Fulltime()
        {
        }


        public override String ID
        {
            get

            {
                return id;
            }
            set
            {
                id = value;
            }
        }
        
        public override String FirstName
        {
            get

            {
                return fname;
            }
            set
            {
                fname = value;
            }
        }

        public override String LastName
        {
            get

            {
                return lname;
            }
            set
            {
                lname = value;
            }
        }

        //common methods that are 

        //implemented in the abstract class

        public new String Add()
        {
            return base.Add();
        }
        //common methods that are implemented 


        //in the abstract class

        public new String Delete()
        {
            return base.Delete();
        }
        //common methods that are implemented 


        //in the abstract class

        public new String Search()
        {
            return base.Search();
        }
        //common methods that are implemented 


        //in the abstract class

        public new String Update()
        {
            return base.Update();
        }
        
        //abstract method that is different 


        //from Fulltime and Contractor

        //therefore I override it here.

        public override String CalculateWage()
        {
            return "Full time employee " + 
                  base.fname + " is calculated " + 
                  "using the Abstract class...";
        }
    }
}
Emp_Fulltime2:
using System;

namespace AbstractsANDInterfaces
{
    /// 

    /// Summary description for Emp_fulltime2.


    /// 

    
    //Implementing the interface

    public class Emp_fulltime2 : IEmployee
    {
        //All the properties and 


        //fields are defined here!

        protected String id;
        protected String lname;
        protected String fname;

        public Emp_fulltime2()
        {
            //


            // TODO: Add constructor logic here

            //

        }

        public String ID
        {
            get

            {
                return id;
            }
            set
            {
                id = value;
            }
        }
        
        public String FirstName
        {
            get
            {
                return fname;
            }
            set

            {
                fname = value;
            }
        }

        public String LastName
        {
            get
            {
                return lname;
            }
            set
            {
                lname = value;
            }
        }

        //all the manipulations including Add,Delete, 


        //Search, Update, Calculate are done

        //within the object as there are not 

        //implementation in the Interface entity.

        public String Add()
        {
            return "Fulltime Employee " + 
                          fname + " added.";
        }

        public String Delete()
        {
            return "Fulltime Employee " + 
                        fname + " deleted.";
        }

        public String Search()
        {
            return "Fulltime Employee " + 
                       fname + " searched.";
        }

        public String Update()
        {
            return "Fulltime Employee " + 
                        fname + " updated.";
        }
        
        //if you change to Calculatewage(). 


        //Just small 'w' it will raise 

        //error as in interface

        //it is CalculateWage() with capital 'W'.

        public String CalculateWage()
        {
            return "Full time employee " + 
                  fname + " caluculated using " + 
                  "Interface.";
        }
    }
}

Code for Testing

//This is the sub that tests both 

//implementations using Interface and Abstract

private void InterfaceExample_Click(object sender, 
                                System.EventArgs e)
{
    try

    {

        IEmployee emp;

        Emp_fulltime2 emp1 = new Emp_fulltime2();

        emp =  emp1;
        emp.ID = "2234";
        emp.FirstName= "Rahman" ;
        emp.LastName = "Mahmoodi" ;
        //call add method od the object


        MessageBox.Show(emp.Add().ToString());
        
        //call the CalculateWage method

        MessageBox.Show(emp.CalculateWage().ToString());


    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

}

private void cmdAbstractExample_Click(object sender, 
                                   System.EventArgs e)
{

    Employee emp;

    emp = new Emp_Fulltime();
    

    emp.ID = "2244";
    emp.FirstName= "Maria" ;
    emp.LastName = "Robinlius" ;
    MessageBox.Show(emp.Add().ToString());

    //call the CalculateWage method


    MessageBox.Show(emp.CalculateWage().ToString());

}

Conclusion

In the above examples, I have explained the differences between an abstract class and an interface. I have also implemented a demo project which uses both abstract class and interface and shows the differences in their implementation.

Monday 28 October 2013

Getting List of all the foreign keys and there details with table and field name

SELECT tabs.name AS [Reference Table],
   (SELECT name FROM sys.tables AS ctab
       WHERE (object_id = fk.parent_object_id)) AS [Parent Table],
       fk.name AS [Key Name],
        ac.name AS [Column Name]
FROM sys.tables AS tabs INNER JOIN            
sys.foreign_keys AS fk ON fk.referenced_object_id = tabs.object_id inner join            
sys.foreign_key_columns as fkc on fk.object_id = fkc.constraint_object_id inner join            
sys.all_columns as ac on ac.column_id = fkc.parent_column_id
             and ac.object_id = fkc.parent_object_id
ORDER BY tabs.name, 2

Thursday 17 October 2013

Response.Flush() vs Response.End

Response.Flush() vs Response.End:
Response.Flush

Forces all currently buffered output to be sent to the client.
The Flush method can be called multiple times during request processing.

Response.End

Sends all currently buffered output to the client,
stops execution of the page, and raises the EndRequest event.

Null checking in Editor

<script language="javascript" type="text/javascript">
            function test() {              
                var a = $find("<%=Editor1.ClientID%>");
                var value = a.get_content();              
                //alert(value);
                value = value.replace(/<br \/>/gi, '');
                value = value.replace(/&nbsp;/gi, '');
                value = value.replace(/^\s+|\s+$/g, '')
                //alert(value);
                //alert((value).replace(/<br \/>/gi, ''));
            if (value == "") {
                alert("Editor's content is empty");
                return false;
            }
        }
    </script>

Monday 30 September 2013

Difference between Close() and Dispose()

Close() Vs Dispose Method

The basic difference between Close() and Dispose() is :
 when a Close() method is called, any managed resource can be temporarily closed and can be opened once again. It means that, with the same object the resource can be reopened or used.
 Where as Dispose() method permanently removes any resource (unmanaged) from memory for cleanup and the resource no longer exists for any further processing.

Example :

using System;
using System.Data;
using System.Data.SqlClient;
public class Test
{
private string connString = "Data Source=COMP3;Initial Catalog=Northwind;User Id=sa;Password=pass";
private SqlConnection connection;
public Test()
{
connection = new SqlConnection(connString);
}
private static void Main()
{
Test t = new Test();
t.ConnectionStatus();
Console.ReadLine();
}
public void ConnectionStatus()
{
try
{
if(connection.State == ConnectionState.Closed)
{
connection.Open();
Console.WriteLine("Connection opened..");
}

if(connection.State == ConnectionState.Open)
{
connection.Close();
Console.WriteLine("Connection closed..");
}
// connection.Dispose();

if(connection.State == ConnectionState.Closed)
{
connection.Open();
Console.WriteLine("Connection again opened..");
}
}
catch(SqlException ex)
{
Console.WriteLine(ex.Message+"\n"+ex.StackTrace);
}
catch(Exception ey)
{
Console.WriteLine(ey.Message+"\n"+ey.StackTrace);
}
finally
{
Console.WriteLine("Connection closed and disposed..");
connection.Dispose();
}
}
}

In the above example if you uncomment the "connection.Dispose()" method and execute, you will get an exception as, "The ConnectionString property has not been initialized.".This is the difference between Close() and Dispose().

Friday 27 September 2013

PRIMARY KEY AND UNIQUE KEY

PRIMARY KEY AND UNIQUE KEY are similar except it has different functions. Primary key makes the table row unique (i.e, there cannot be 2 row with the exact same key). You can only have 1 primary key in a database table.

Unique key makes the table column in a table row unique (i.e., no 2 table row may have the same exact value). You can have more than 1 unique key table column (unlike primary key which means only 1 table column in the table is unique).



Primary Key
Unique Key
It will not accept null values
One and only one Null values are accepted.
There will be only one primary key in a table
More than one unique key will be there in a table.
Clustered index is created in Primary key
Non-Clustered index is created in unique key.
Primary key allows each row in a table to be uniquely identified and ensures that no duplicate rows exist.
Unique key constraint is used to prevent the duplication of key values within the rows of a table and allow null values.

Wednesday 4 September 2013

Get value from popup page Javascript

sample1.html:
 
<html>
<head>
    <title>Sample 1</title>
</head>
<body>
<script language="JavaScript">
    function windowOpen() {
        var myWindow=window.open('sample2.html','windowRef','width=200,height=200');
       if (!myWindow.opener) myWindow.opener = self;
    }
</script>
<form name="frmMain" method="post" action="">
    <input type="text" value="" name="txtVol" id="txtVol">
    <input name="openPopup" type="button" id="openPopup" onClick="Javascript:windowOpen();" value="Get Value">
</form>
</body>
</html>
 
 
sample2.html:
 
<html>
<head>
   <title>Sample 2</title>
</head>
<body>
<script language="JavaScript">
    function updateOpener() {
        window.opener.document.frmMain.txtVol.value = document.frmMain.txtInput.value;
        window.close();
    }
</script>
Value :<form name="frmMain" method="post" action="">
    <input type="text" name="txtInput" value="">    
     <input name="Close" type="submit" id="Close"onClick="Javascript:updateOpener()" value="Close">
</form>
</body>
</html>

Get the column values as comma separated values in SQL

Get the column values as comma separated values

Table citymaster
cityid cityname
1       A
2       B
3       C
4       D
SELECT DISTINCT STUFF((SELECT ',' + cast(s.cityid as varchar)FROM citymaster s
 FOR XML PATH('')),1,1,'') AS CSV
FROM citymaster AS t

output
1,2,3,4
=========================================================
 Table CompanyMaster
Company Location
A Chennai
A Pune
B Delhi
B Mumbai
A Bangalore
B Hyderabad
B Kolkata

SELECT t.Company, STUFF((SELECT ',' + s.Location FROM CompanyMaster s 
WHERE s.Company = t.Company FOR XML PATH('')),1,1,'') AS Locations
FROM CompanyMaster AS t GROUP BY t.Company

output:

Company  Locations
A        Chennai,Pune,Bangalore
B        Delhi,Mumbai,Hydrabad,Kolkata

Get Last 10 Database name in SQL Server

Last 10 database name:

Select top 10 name,database_id,create_date FROM sys.databases ORDER BY database_id desc

Get List of Stored Procedures Where a Table Name is Used in SQL Server


Following code will  get procedures name which contains particular table name

SELECT Name FROM sys.procedures WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%TableName%'

Sunday 25 August 2013

Radiobutton validation using JQuery


This example for Radiobutton validation using JQuery

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Validate asp.net radiobuttonlist in JQuery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#btnSubmit').click(function() {
if ($('#rdbtnGender :radio:checked').length > 0) {
return true;
}
else {
alert('Please select Gender')
return false;
}
})
})
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td> <b>Select Gender:</b></td>
<td>
<asp:RadioButtonList ID="rdbtnGender" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Value="1" Text="Male" />
<asp:ListItem Value="2" Text="Female" />
</asp:RadioButtonList>
</td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="btnSubmit" Text="Submit" runat="server" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>