Sunday, November 18, 2012

Exporting and Importing Sites and App Pools

When using multiple IIS server in a Load Balanced Environment it will  be alot of work to create all you’re website twice with the same settings on each webserver. Therefor it is possible to export and import you’re configuration from one webserver to the other.

To Export the Application Pools on IIS 7 :
%windir%\system32\inetsrv\appcmd list apppool /config /xml > c:\apppools.xml
This will export all the application pools on you’re webserver, therefor you need to edit the apppools.xml and remove the application that you do not need to import for example:
  • DefaultAppPool
  • Classic .NET AppPool
  • SecurityTokenServiceApplicationPool
To import the Application Pools:
%windir%\system32\inetsrv\appcmd add apppool /in < c:\apppools.xml
All the AppPools in the xml will be created on you’re second webserver.



Command Line code for export and import site configuration

To export/import a single application pool:
%windir%\system32\inetsrv\appcmd list apppool “MyAppPool” /config /xml > c:\myapppool.xml

Import:
%windir%\system32\inetsrv\appcmd add apppool /in < c:\myapppool.xml

To export/import a single website:



C:\Windows\System32\inetsrv>appcmd list site "SmithersColombiaAnalytics" /config /xml > c:\soColmbAlty.XML


Import:



C:\Windows\System32\inetsrv>appcmd.exe add site /in < d:\import\soAustAlty.xml

 

Tuesday, September 4, 2012

Installing dlls to GAC with .net Framework 4.0



I recently faced to an issue with installing dlls to GAC with .net Framework 4.0.

It was my local development machine and .net Framework 4.0. I wanted to install a dll to GAC. But gacutil.exe was not there.

.net 4.0 GAC location C:\Windows\Microsoft.NET\assembly\GAC_MSIL


I copied gacutil.exe from my  staging server to my machine. The exe was located in “C:\Windows\Microsoft.NET\Framework\v1.1.4322”.  Then I tried to install the dll. but it returned an error saying version mismatch.

When I search for the issue, I found that gacutil.exe come with the “Microsoft Windows SDK for Windows 7 and .NET Framework 4”. I downloaded SDK from here and installed in my development server. Then copied these files from development server (C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools ) to production server. Then Tried to run gacutil –i.
    gacutil.exe
    gacutil.exe.config
    1033\gacutlrc.dll

These files can be placed any location in the machine, but need to run the gacutil - command from that location.

Remember to put gacutlrc.dll in to the same folder, otherwise your command will run wiout giving any errors, but dll won’t be in GAC.

Saturday, August 25, 2012

Get last index position of character


The function is used to find the last index position of the character in the given string

Create FUNCTION [dbo].[CharLastIndex](@SeekChars nvarchar(max),@String nvarchar(max))
RETURNS int
AS 
BEGIN   
    Declare @Index int,@startPosition int
    SET  @startPosition=0
    Select @Index= charindex(@SeekChars,@String,@startPosition)
    SET @startPosition = @Index
    While(@startPosition!=0)
    BEGIN
        SET @Index =@startPosition
        Select @startPosition = charIndex(@SeekChars,@String,@startPosition+1)
    END

RETURN @Index
END

Check given string is integer or not



Create FUNCTION [dbo].[CheckIsInt](@String nvarchar(255)) 
RETURNS bit
AS 
BEGIN   
Declare @Count int,@char nchar(1),@result bit
SET @Count=1
SET @result =0
While (@Count<=len(@String))
BEGIN
    Set @char =substring(@String,@Count,1)
    if(charindex(@char,'0123456789')=0)
        return 0
    else
        SET @result=1   
    SET    @Count =@Count + 1
END
return @result

END

Get Distinct String using SQL Server

Get distinct string between given two string

ALTER function [dbo].[GetDistinctString](@string1 varchar(max),@string2 varchar(max))
returns varchar(max)
as
begin
Set @string2 = ',' + @string2 + ','
Declare @count int,@index int,@s1Len int,@nextIndex int
Set @index=0
Set @nextIndex =1
Set @s1Len=len(@string1)
Declare @part varchar(4)

While(len(@string2)>0 and @index <= @s1Len and @nextIndex <> 0)
begin
    Set @nextIndex = charindex(',',@string1,@index)
    if @nextIndex !=0
    begin
        Set @part = substring(@string1,@index,@nextIndex - @index )
       
    end
    else
    begin
        Set @part = substring(@string1,@index,@s1Len - @index + 1)
       
    end
    --Set @string2 = replace(@string2,@part,'')
    Set @string2 = replace(@string2,','+@part+',',',')
   
    Set @index =@nextIndex+1

end
Set @string1 = @string1 + @string2
Set @s1Len =len(@string1)
return substring(@string1,0,@s1Len)

end

Get Empty Guid using SQL Function


Get Empty Guid using SQL Server

Create FUNCTION [dbo].[GetEmptyGUID]()
RETURNS UNIQUEIDENTIFIER
AS
BEGIN
RETURN SELECT CAST(CAST(0 as BINARY) AS UNIQUEIDENTIFIER)
END

Truncate Time

Function to truncate the time from the given date using SQL Server

ALTER FUNCTION [dbo].[TruncateTime]
(
@dateToConvert datetime
)
RETURNS datetime
AS
BEGIN
RETURN convert(datetime, convert(varchar(10), @dateToConvert, 101))
END

Decode URL using SQL Server



Create FUNCTION [dbo].[UrlDecode](@url varchar(max))
RETURNS varchar(MAX)
AS
BEGIN
    DECLARE @count int, @c char(1), @cenc char(2), @i int, @urlReturn varchar(MAX)
    SET @count = Len(@url)
    SET @i = 1
    SET @urlReturn = ''
    WHILE (@i <= @count)
     BEGIN
        SET @c = substring(@url, @i, 1)
        IF @c LIKE '[!%]' ESCAPE '!'
         BEGIN
            SET @cenc = substring(@url, @i + 1, 2)
            SET @c = CHAR(CASE WHEN SUBSTRING(@cenc, 1, 1) LIKE '[0-9]'
                                THEN CAST(SUBSTRING(@cenc, 1, 1) as int)
                                ELSE CAST(ASCII(UPPER(SUBSTRING(@cenc, 1, 1)))-55 as int)
                            END * 16 +
                            CASE WHEN SUBSTRING(@cenc, 2, 1) LIKE '[0-9]'
                                THEN CAST(SUBSTRING(@cenc, 2, 1) as int)
                                ELSE CAST(ASCII(UPPER(SUBSTRING(@cenc, 2, 1)))-55 as int)
                            END)
            SET @urlReturn = @urlReturn + @c
            SET @i = @i + 2
         END
        ELSE
         BEGIN
            SET @urlReturn = @urlReturn + @c
         END
        SET @i = @i +1
     END
    RETURN @urlReturn
END

Check given string is Guid or not in SQL Server



Below function is used to find whether given string is Valid Guid or not.


Create function [dbo].[IsGuid] ( @testString varchar(38))
returns int
as
begin
    declare @ret int
    select  @ret = 0,
            @testString = replace(replace(@testString, '{', ''), '}', '')
    if len(isnull(@testString, '')) = 36 and
       @testString NOT LIKE '%[^0-9A-Fa-f-]%' and
       -- check for proper positions of hyphens (-) 
       charindex('-', @testString) = 9 and
       charindex('-', @testString, 10) = 14 and
       charindex('-', @testString, 15) = 19 and
       charindex('-', @testString, 20) = 24 and
       charindex('-', @testString, 25) = 0
          set @ret = 1
   
    return @ret
end



Usage

select  dbo.isGuid('some string')


Wednesday, August 15, 2012

Get Number of Records count based on the search string

The following Store procedure can be used for following purpose. you can modified based on your requirement.

1.Get number of records based on the search string
2.Execute the SQL Query inside the store procedure.
3.Using the view inside the Store procedure.

Create PROCEDURE [dbo].[GetCount]
(
    @Id uniqueidentifier=null,
    @SearchCriteria nvarchar(max) = null,
    @ApplicationId uniqueidentifier
)
as
Begin
DECLARE @nparam NVARCHAR(40)
DECLARE @Query nvarchar(max)
SELECT @Query = '
      SELECT
      Count(Id)
    From [vwGetAllQuestion] WHERE ID = isnull(@Id,Id)' + isnull(@SearchCriteria,'')
    set @nparam = '@Id uniqueidentifier'

--select @Query
EXEC sp_executesql @Query, @nparam, @Id

end

Export Data Table to CSV file with comma values

public void WriteCSVToResponse(DataTable dt, string fileName, string delimiter)
    {
        //prepare the output stream
        Response.Clear();
        Response.ContentType = "text/csv";
        Response.AppendHeader("Content-Disposition",
            string.Format("attachment; filename={0}", fileName));
      
        //write the csv column headers
        if (dt != null && dt.Rows.Count > 0)
        {
           
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                if (dt.Columns[i].ColumnName != "FormsResponseXML")
                {
                    Response.Write(dt.Columns[i].ColumnName);
                    Response.Write((i < dt.Columns.Count - 1) ? delimiter : Environment.NewLine);
                }
            }

            //write the data
            foreach (DataRow row in dt.Rows)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    if (dt.Columns[i].ColumnName != "FormsResponseXML")
                    {                       
                        var append = row[i].ToString().Contains(",")? string.Format("\"{0}\"", row[i].ToString()): row[i].ToString();
                        Response.Write(append);
                        Response.Write((i < dt.Columns.Count - 1) ? delimiter : Environment.NewLine);
                    }
                }
            }
        }

        Response.End();
    }

Sunday, August 12, 2012

Convert DataTable to CSV file


 public void WriteCSVToResponse(DataTable dt, string fileName, string delimiter)
    {
        //prepare the output stream
        Response.Clear();
        Response.ContentType = "text/csv";
        Response.AppendHeader("Content-Disposition",
            string.Format("attachment; filename={0}", fileName));

        //write the csv column headers
        if (dt != null && dt.Rows.Count > 0)
        {
           
            for (int i = 0; i < dt.Columns.Count; i++)
            {
               
                    Response.Write(dt.Columns[i].ColumnName);
                    Response.Write((i < dt.Columns.Count - 1) ? delimiter : Environment.NewLine);
               
            }

            //write the data
            foreach (DataRow row in dt.Rows)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                   
                        Response.Write(row[i].ToString());
                        Response.Write((i < dt.Columns.Count - 1) ? delimiter : Environment.NewLine);
                   
                }
            }
        }

        Response.End();
    }

Saturday, October 29, 2011

What is an application object and where we use application object in asp.net | application object sample using asp.net


What is an application object?

Application object is used to store the information and access variables from any page in application. Application object is same as session object only the difference is session object is used to maintain the session for particular user. If one user enters in to the application then session id will create for that particular user if he leaves from the application then the session id will deleted.  they will get different session id but application object is same for all users once application object is created that application object is used throughout the application regardless of user. The information stored in application object accessed throughout all the pages in application (like database connection information) and we can change the application object in one place those changes automatically reflected in all the pages.

Thursday, April 29, 2010

How to Make by pressing Enter Key ASP Button fires Click Event using JQUERY

<div class="headerSearch formPanel" formButtonId="<%=SearchButton1.ClientID %>">

<label for="txtSearch">
Product Search:</label>
<input type="text" id="TextBox1" class="text" value="Enter Keyword" runat="server"
onfocus="clearText(this.id)" />
<div class="button buttonBlack">
<asp:LinkButton ID="SearchButton1" runat="server" OnClientClick="return ProductSearch();"
OnClick="SearchButton1_Click" Text="<span></span>Go" />
</div>
</div >


Include this JQUERY in your ASPX page


$(function(){
$("div.formPanel").each(function()
{
if($(this).attr("formButtonId"))
{
$(this).bind("keypress", function(e){
if (e.keyCode == 13)
{
e.returnValue = false;
e.cancel = true;
var button = $("#" + $(this).attr("formButtonId"));

var retValue = button.triggerHandler("click");
if(retValue == undefined || retValue == true)
eval(button.attr("href"));

return false;
}
});
}
});
});

Tuesday, March 2, 2010

Creating Log File

actually keep this piece of code in a class called util. so I'm just going to paste the function and also the setting in the config file.

Setting in Config File

<add key="FilePath" value="D:\logFile.txt"/>

public static void function in util.cs

public static void writeToLogFile(string logMessage)
{
string strLogMessage = string.Empty;
string strLogFile = System.Configuration.ConfigurationManager.AppSettings["logFilePath"].ToString();
StreamWriter swLog;

strLogMessage = string.Format("{0}: {1}", DateTime.Now, logMessage);

if (!File.Exists(strLogFile))
{
swLog = new StreamWriter(strLogFile);
}
else
{
swLog = File.AppendText(strLogFile);
}

swLog.WriteLine(strLogMessage);
swLog.WriteLine();

swLog.Close();

}

Wednesday, February 24, 2010

Introduction


OOPS or Object Oriented Programming Concepts but some of the concepts have been always used in one or the other programming languages. For example you must have used structs in C which is a good example of encapsulation. There are four major pillar of OOPS. Let’s try to understand each one of them by taking some examples also:-
1.) Encapsulation
2.) Abstraction
3.) Polymorphism
4.) Inheritance

Encapsulation:-

Interview Definition:- Binding data and member functions together inside a single unit.
How to Encapsulate:- By creating types e.g Classes and Struct
Bu using encapsulation we can create out own custom types by reusing the existing or primitive types.

Abstraction:-

Abstraction defines way to abstract or hide your data and members from outside world. Simply speaking Abstraction is hiding the complexities of your class or struct or in a generic term Type from outer world. This is achieved by means of access specifiers.
Interview Definition: - Hiding the complexities of your type from outside world.

How to Abstract: - By using Access Specifiers
.Net has five access specifiers:-
Public -- Accessible outside the class through object reference.
Private -- Accessible inside the class only through member functions.
Protected -- Just like private but Accessible in derived classes also through member functions.
Internal -- Visible inside the assembly. Accessible through objects.
Protected Internal -- Visible inside the assembly through objects and in derived classes outside the assembly through member functions.
Let’s try to understand by a practical example:-
Interview Tip:-
The default access specifier for a class in internal. Mind it I mean class not class’s data members.

public class Class1
{
int i; //No Access specifier means private
public int j; // Public
protected int k; //Protected data
internal int m; // Internal means visible inside assembly
protected internal int n; //inside assembly as well as to derived classes outside assembly
static int x; // This is also private
public static int y; //Static means shared across objects
[DllImport("MyDll.dll")]
public static extern int MyFoo(); //extern means declared in this assembly defined in some other assembly
public void myFoo2()
{
//Within a class if you create an object of same class then you can access all data members through object reference even private data too
Class1 obj = new Class1();
obj.i =10; //Error can’t access private data through object.But here it is accessible.:)
obj.j =10;
obj.k=10;
obj.m=10;
obj.n=10;
// obj.s =10; //Errror Static data can be accessed by class names only
Class1.x = 10;
// obj.y = 10; //Errror Static data can be accessed by class names only
Class1.y = 10;
}
}

//Now lets try to copy the same code inside Main method and try to compile
[STAThread]
static void Main()
{
//Access specifiers comes into picture only when you create object of class outside the class
Class1 obj = new Class1();
// obj.i =10; //Error can’t access private data through object.
obj.j =10;
// obj.k=10; //Error can’t access protected data through object.
obj.m=10;
obj.n=10;
// obj.s =10; //Errror Static data can be accessed by class names only
Class1.x = 10; //Error can’t access private data outside class
// obj.y = 10; //Errror Static data can be accessed by class names only
Class1.y = 10;
}
//What if Main is inside another assembly
[STAThread]
static void Main()
{
//Access specifiers comes into picture only when you create object of class outside the class
Class1 obj = new Class1();
// obj.i =10; //Error can’t access private data through object.
obj.j =10;
// obj.k=10; //Error can’t access protected data through object.
// obj.m=10; // Error can’t access internal data outside assembly
// obj.n=10; // Error can’t access internal data outside assembly

// obj.s =10; //Errror Static data can be accessed by class names only
Class1.x = 10; //Error can’t access private data outside class
// obj.y = 10; //Errror Static data can be accessed by class names only
Class1.y = 10;
}

Tuesday, February 9, 2010

Thursday, February 4, 2010

Page Refresh Problem

A common problem that Web Application developers encounter is how to stop the user from refreshing the page. The problem arises, if the previous request to the server was a PostBack, which, for example, inserts the WebForm's data into a database. This will result in the addition of duplicate rows in the database. But we have a constraint that we can't stop the user by refreshing the page. So, what to do? Although we can't stop the user from refreshing the page, but we can determine if this event has already occurred and then take appropriate action.

My strategy will make use of the ViewState feature. As we are using ViewState, it would seem logical to perform the operation in the LoadViewState and SaveViewState methods. Using these two methods, instead of the OnLoad method, has more benefits in that it eliminates the potential problems of sub-classes implementing Page_Load. methods follows:

public class Refresh : System.Web.UI.Page

{
private bool _refreshState;
private bool _isRefresh;
public bool IsRefresh

{

get

{

return _isRefresh;

}

}

protected override void LoadViewState(object savedState)

{

object[] allStates = (object[])savedState;

base.LoadViewState(allStates[0]);

_refreshState = (bool)allStates[1];

_isRefresh = _refreshState == (bool)Session["__ISREFRESH"];


}



protected override object SaveViewState()

{

Session["__ISREFRESH"] = _refreshState;

object[] allStates = new object[2];

allStates[0] = base.SaveViewState();

allStates[1] = !_refreshState;

return allStates;

}

}

Thursday, September 24, 2009

Reverse Data Table

This Method is used the Reverse the given input DataTable

For Eample,

Input Data Table has the following Records,

NAME TITLE DEV_IN SCOST DCOST SOLD
-------- -------------------- -------- ---------- ---------- ----------
RAMESH HOTEL MANAGEMENT DBASE 12000 35000 4
RAMESH DEAD LEE PASCAL 99.95 4500 73

public static DataTable ReverseDataTable(DataTable dataTable)
{
DataTable table = new DataTable();
DataRow[] rowArray = dataTable.Select();
table = dataTable.Clone();
for (int i = rowArray.Length - 1; i >= 0; i--)
{
table.ImportRow(rowArray[i]);
}
return table;
}

OutPut

NAME TITLE DEV_IN SCOST DCOST SOLD
-------- -------------------- -------- ---------- ---------- ----------
RAMESH DEAD LEE PASCAL 99.95 4500 73
RAMESH HOTEL MANAGEMENT DBASE 12000 35000 4

Wednesday, September 23, 2009

Filter DataTable and Sort

public static DataTable FilterDataTable(DataTable dataTable, string filterQuery, string sortQuery)
{
DataTable table = new DataTable();
try
{
DataRow[] rowArray = dataTable.Select(filterQuery, sortQuery);
table = dataTable.Clone();
foreach (DataRow row in rowArray)
{
table.ImportRow(row);
}
}
catch
{
table = dataTable.Clone();
}
return table;
}