Wednesday, 23 January 2013

List all Primary and Foreign Key in a Table


List all Primary and Foreign Key in a Table


Method 1:

SELECT

DISTINCT

Constraint_Name AS [Constraint],

Table_Schema AS [Schema],

Table_Name AS [TableName]

FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE



Method 2:

SELECT OBJECT_NAME(OBJECT_ID) AS NameofConstraint,

SCHEMA_NAME(schema_id) AS SchemaName,

OBJECT_NAME(parent_object_id) AS TableName,

type_desc AS ConstraintType

FROM sys.objects

WHERE type_desc IN ('FOREIGN_KEY_CONSTRAINT','PRIMARY_KEY_CONSTRAINT')

Find the Name of all Tables alongwith the Column Names in a Database


Find the Name of all Tables alongwith the Column Names in a Database


As the name suggest, You can achieve the same using the following Query:


SELECT TOP 100 PERCENT WITH TIES c.TABLE_NAME , COUNT(*) NumColumns

FROM INFORMATION_SCHEMA.[COLUMNS ] c

inner join INFORMATION_SCHEMA.[TABLES] t

ON C.TABLE_SCHEMA = t.TABLE_SCHEMA

and c.TABLE_NAME = T.TABLE_NAME

GROUP BY c.TABLE_NAME

ORDER BY c.TABLE_NAME

Joining 3 or more Tables in SQL Server


Joining 3 or more Tables in SQL Server


Here is a sample SQL Query which would let you join Three or more Tables and display data from them using simple Select Statement:



SELECT p.Name, v.Name

FROM Production.Product p

JOIN Purchasing.ProductVendor pv

ON p.ProductID = pv.ProductID

JOIN Purchasing.Vendor v

ON pv.BusinessEntityID = v.BusinessEntityID

WHERE ProductSubcategoryID = 15

ORDER BY v.Name;

Modify the field names and Table Names according to your requirement...

Display the Content of Multiline Textbox Line By Line after Retrieval


Display the Content of Multiline Textbox Line By Line after Retrieval


While saving multiline text box values to database and then retrieving it, the line feed character is not displayed on retrieval. For instance, we use a multiline text box to enter address and as often the address consists of multiple lines which are created using the Enter key (carraige return character). Now if we save a multiline address to the database and later retrieve it and display the value on a label, we would find the address shown as a single line and not multiple lines.

However, the carriage return information is saved in the database but it is saved as a square symbol. The square symbol actually represents "\r\n" character -  \r  represents carriage return; \n represents new line. 

So while displaying the data to the label we simply replace the '\r\n' character with '<br />' .


txtAddress.Text = dtCompanyInfo.Rows[0]["ADDRESS"].ToString().Replace("\r\n", "<br />");


Where "dtCompanyInfo" is the instance of the DataTable and "txtAddress" is the instance of a TextBox 

This way we can format the retrieved data so that it can be displayed in the same manner as it was entered, especially when the data contains line feed / carriage return characters.

Tuesday, 22 January 2013

Access all Control Panel Options in One Place


Access all Control Panel Options in One Place

Well Its always a headache to find the correct option/functionality out of numerous Options available in Control Panel. It would be great to have all the options in expanded form in one place so the end User should not get confused about the correct Feature...

So Here I am with the solution of the Problem.. Its very simple and a single step solution...

All You have to do is to create a folder by the following name and you could access this functionality:

Create a Folder By the Name:

Vishal.{ED7BA470-8E54-465E-825C-99712043E01C}

Monday, 21 January 2013

Fire Events in Dynamically Created Gridview


Fire Events in Dynamically Created Gridview


Most of us have used Dynamic Gridviews in our project.. If you are not familiar with dynamic gridview; then please refer these links first:


But the problem arises when we are asked to handle the events inside the dynamic Gridview..

In this case what to do???

So Here I am with the solution and relevant links:

For Binding Events we could do like this:

 GridView gv = new GridView();
 gv.RowDataBound += new GridViewRowEventHandler(gv_RowDataBound);

 Then We could handle the events like this: 
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
  // your code
}

 For More Details refer these links:


http://forums.asp.net/t/1276555.aspx/1?Dynamic+Gridview+Event+Handler+not+fire+RowCommand+RowDeleting+SelectedindexChanging+

http://stackoverflow.com/questions/4757058/how-to-create-gridview-updating-event-dynamically

http://stackoverflow.com/questions/2021580/selectedindexchanged-on-dynamically-created-gridview
  

Saturday, 19 January 2013

Remove Selected Item from Dropdownlist inside Gridview Using Javascript


Remove Selected Item from Dropdownlist inside Gridview Using Javascript


Sometime when we use Dropdown inside a gridview there is this requirement of removing the item already selected in a row from the list item of the dropdownlist present in other row..

For Example if we have aaa,bbb,ccc,ddd in a dropdown inside a gridview and we have selected aaa in row1 of the gridview.. Then only bbb,ccc,ddd should display in the dropdown of the other rows..

It can be achieved using foreach loop by finding the selected item in other rows and removing the same..

But Today I am discussing about doing the same using Javascript:


<script language="Javascript">
function checkDuplicate(objID)
{
//after gridbind put total row count in hidden field
iRowCnt = new Number(document.getElementById("hdnRowCount").value);
var iCheckedIndex; 
var dropDownVal;
   
//get selectedvalue in variable
var szSelVal = objID.value;

for(i = 1; i <= iRowCnt; i++)
{
  dropDownVal = document.getElementById("gvPack_ctl0" + (i + 1) + "_ddl1").value;

  //compare values
  if (szSelVal == dropDownVal)
  {
    alert("Please, given value alreay selected");
    return false;
  }
}
</script>


Friday, 18 January 2013

Mobile APN Settings for Various Service Provider in India


Mobile APN Settings for Various Service Provider in India


I always have problem regarding configuring the 2G/3G settings in my mobile device for Internet..
At this point you dont know whom to call/contact.. So Here I am with a brief list of APN Settings for most of the Service Provider in India.. Hope It helps:

Aircel APN for 2G/3G/GPRS

You can get the settings for Aircel 2G/3G , automatically delivered on your phone by sending an SMS with PI to 121
You can also manually set the Aircel 2G/3G/GPRS settings on your phone by using the following information.

Setting Name    Value
Operator    AIRCEL
APN (preapaid)    aircelgprs.pr
APN (postpaid)    aircelgprs.po
Access Number    *99***1#
Username    [blank]
Password    [blank]
Authentication Type    normal
Proxy    Enable
Proxy address    192.168.035.201
Port    8081
Data Bearer    PACKET DATA

Applies to : APN for Aircel -TamilNadu,  Karnataka, New Delhi, NCR, Andhara Pradesh, Assam, Bihar and Jharkand,
Chennai, Gujarat,  Haryana, Himachal Pradesh, Jammu Kashmir, Kerala, Kolkatta, Madhya Pradesh, Maharashtra, Mumbai,
North East, Orissa, Punjab.Rajasthan, UP East, UP West, West Bengal.


Airtel APN For 3G / 2G / GPRS

To access 2G / 3G internet through Airtel, use the APN : airtelgprs.com

To get the settings automatically on your phone, Send an SMS with content “MO” to 54321 and the settings will be
sent to you auomatically

Setting Name    Value
Operator    AIRTEL
APN-Access Point Names    airtelgprs.com
Access number    *99***1#
Username    [blank]
Password    [blank]
Authentication type    normal
Proxy    Disable
Proxy address    0.0.0.0
Port    8080
Data Bearer    GPRS or PACKET DATA
DNS1    0.0.0.0
DNS2    0.0.0.0

Applies to : APN for Airtel – TamilNadu,   Karnataka,  New Delhi,  NCR,  Andhara Pradesh,  Assam,  Bihar and
Jharkand,  Chennai,  Gujarat,   Haryana,  Himachal Pradesh,  Jammu Kashmir,  Kerala,  Kolkatta,  Madhya Pradesh,
Maharashtra,  Mumbai,  North East,  Orissa,  Punjab.  Rajasthan,  UP East,  UP West,  West Bengal.



BSNL APN 2G/3G/GPRS

You can get internet settings  for BSNL 2G/3G , delivered on your mobile by sending an SMS GPRS to 53733
You can also manually type the BSNL internet settings on your mobile by using the following information.

Setting Name    Value
Operator    BSNL
APN- GPRS    bsnlnet
APN- WAP    bsnlwap
Access Number    *99# or *99***1#
Username    [blank]
Password    [blank]
Authentication Type    normal
Proxy    Enable
Proxy address    10.220.67.131
Port    9201 for Wap 1.0 device 8080 for Wap 2.0 device

The internet settings are available in :
North Zone: Haryana, Punjab, UP(East), UP(West), Himachal Pradesh, Rajasthan, Jammu & Kashmir
East Zone: Jharkhand, Bihar, Kolkata, West Bengal, Orissa, Assam, North East, Adman Nicobar
West Zone: Maharashtra, Gujrat, Madhya Pradesh, Chattishgarh
South Zone: Karnatka, Andhra Pradesh, Chennai, Tamil Nadu, Kerala

Applies to:  BSNL APN for- TamilNadu,  Karnataka, New Delhi, NCR, Andhara Pradesh, Assam, Bihar and Jharkand,
Chennai, Gujarat,  Haryana, Himachal Pradesh, Jammu Kashmir, Kerala, Kolkatta, Madhya Pradesh, Maharashtra,
Mumbai, North East, Orissa, Punjab. Rajasthan, UP East, UP West, West Bengal, Chhattisgarh.




Idea APN for 2G/3G/GPRS

You can get internet settings  for IDEA Cellular 2G/3G , delivered on your mobile by sending an SMS SET to 54671
You can also manually type the IDEA internet settings on your mobile by using the following information.
Setting Name    Value
Operator    IDEA
APN    imis/internet
Access Number    *99# or *99***#
Username    [blank]
Password    [blank]
Authentication Type    normal
Proxy    Enable
Proxy address    10.4.42.45
Port    8080
Data Bearer    GPRS/PACKET DATA
 
Applies to : Idea APN for -Tamil Nadu,  Karnataka, New Delhi, NCR, Andhara Pradesh, Assam, Bihar and Jharkand,
Chennai, Gujarat,  Haryana, Himachal Pradesh, Jammu Kashmir, Kerala, Kolkatta, Madhya Pradesh, Maharashtra,
Mumbai, North East, Orissa, Punjab. Rajasthan, UP East, UP West, West Bengal.



Reliance GSM APN for 2G/3G/GPRS.

You can get internet settings  for  Reliance GSM 2G/3G , delivered on your mobile by sending an SMS ALL to 55100
You can also manually type the Reliance internet settings on your mobile by using the following information.


Setting Name    Value
Operator    Reliance GSM
APN    rcomnet or smartnet
Access Number    #777
Username    [blank]
Password    [blank]
Authentication Type    none
Proxy    Disable
Proxy address    [blank]
Port    [blank]
Data Bearer    GPRS/PACKET DATA
DNS1    [blank]
DNS2    [blank]

Use “rcomnet” for the following circles: Andhra Pradesh, Delhi, Gujarat, Haryana, J&K, Karnataka, Kerala, Maharashtra,
Mumbai, Punjab, Rajasthan, Tamil Nadu (including Chennai), UP(E), UP(W)

Use “smartnet” for the following circles: Assam, Bihar, Himachal Pradesh, Kolkatta, Madhya Pradesh,
North-East, Orissa, West Bengal
Applies to : Reliance APN for – TamilNadu,  Karnataka, New Delhi, NCR, Andhara Pradesh, Assam, Bihar and Jharkhand,
 Chennai, Gujarat,  Haryana, Himachal Pradesh, Jammu Kashmir, Kerala, Kolkatta, Madhya Pradesh, Maharashtra, Mumbai,
North East, Orissa, Punjab. Rajasthan, UP East, UP West, West Bengal.




TATA DOCOMO APN for 2G/3G/GPRS

You can get internet settings  for Tata Docomo 2G/3G , delivered on your mobile by sending an SMS INTERNET to 52270
You can also manually type the Tata Docomo internet settings on your mobile by using the following information.

Setting Name    Value
Operator    TATA DOCOMO
APN    TATA.DOCOMO.INTERNET
Access Number    *99#
Username    [blank]
Password    [blank]
Authentication Type    normal
Proxy    off/Disable
Proxy address    0.0.0.0
Port    8080
Data Bearer    GPRS/PACKET DATA
DNS1    0.0.0.0
DNS2    0.0.0.0


Applies To : Tata Docomo APN for -TamilNadu,  Karnataka, New Delhi, NCR, Andhara Pradesh, Assam, Bihar and Jharkhand,
 Chennai, Gujarat,  Haryana, Himachal Pradesh, Jammu Kashmir, Kerala, Kolkatta, Madhya Pradesh, Maharashtra, Mumbai,
North East, Orissa, Punjab. Rajasthan, UP East, UP West, West Bengal.




Vodafone APN for 2G/3G/GPRS

You can get internet settings  for Vodafone 2G/3G , delivered on your mobile by sending an SMS VMC  to 52586
You can also manually type the Vodafone internet settings on your mobile by using the following information.

Setting Name    Value
Operator    Vodafone
APN    www
Access Number    *99***1#
Username    [blank]
Password    [blank]
Authentication Type    normal
Proxy    off/Disable
Proxy address    [blank]
Port    [blank]
Data Bearer    PACKET DATA
DNS1    [blank]
DNS2    [blank]
Applies To :  Vodafone APN for – TamilNadu,  Karnataka, New Delhi, NCR, Andhra Pradesh, Assam, Bihar and Jharkhand,
 Chennai, Gujarat,  Haryana, Himachal Pradesh, Jammu Kashmir, Kerala, Kolkatta, Madhya Pradesh, Maharashtra, Mumbai,
North East, Orissa, Punjab. Rajasthan, UP East, UP West, West Bengal.



Uninor APN for 2G/3G/GPRS

You can get the settings for Uninor 2G/3G , automatically delivered on your phone by sending an SMS ALL to 58355
You can also manually set the Uninor 2G/3G/GPRS settings on your phone by using the following information.


Setting Name    Value
Operator    Uninor
APN    uninor
Access Number    *99#
Username    [blank]
Password    [blank]
Authentication Type    normal
Proxy    Enable
Proxy address    10.58.10.58
Port    8080
Data Bearer    GPRS
DNS1    Not Enabled
DNS2    Not enabled

The above internet settings are available in Andhara Pradesh, Assam, Bihar and Jharkand, Chennai, Delhi, Gujarat, Haryana,
Himachal pradesh, Jammu kashmir,Karnataka, Kerala, Kolkatta, Madhya Pradesh,Maharashtra, Mumbai, North East, Orissa,
Punjab, Rajasthan, Tamil Nadu, UP East, UP West, West Bengal


Applies To : Uninor APN for – TamilNadu,  Karnataka, New Delhi, NCR, Andhra Pradesh, Assam, Bihar and Jharkhand,
Chennai, Gujarat,  Haryana, Himachal Pradesh, Jammu Kashmir, Kerala, Kolkatta, Madhya Pradesh, Maharashtra, Mumbai,
North East, Orissa, Punjab. Rajasthan, UP East, UP West, West Bengal, Chhattisgarh.

Contact Us

Thursday, 17 January 2013

Prevent User from Entering HTML tags in Textbox/TextArea


Prevent User from Entering HTML tags in Textbox/TextArea


In ASP.net this is integrated by default in the page directives:

<%@ Page Language="C#" ValidateRequest="true" AutoEventWireup="true" CodeFile="Default1.aspx.cs" Inherits="Default1" %>



If ValidateRequest is true, the code will trow exeption like:

potentially dangerous Request.Form value was detected from the client (TextBox1="<div>").


Use the following Javascript to prevent the User from Entering HTML Tags in the Textbox/TextArea:


function checkHTMLtags(sender, args)
    {
       var trgtId = document.getElementById("<%=txt1.ClientID%>");
       var str=trgtId.value
       //convert to lowercase
        str=str.toLowerCase()
        //split the string by taking <br> as reference
        var strArray=str.split('<br>');
         if (strArray.length > 0)
          {
            for(k=0;k<strArray.length;k++)
            {
       for(i=0;i<strArray[k].length;i++)
        {
         //check for the presence of < and if available check the following char
         //condition added to include > symbol as well
         if((strArray[k].charAt(i)=='<') || (strArray[k].charAt(i)=='>'))
            {
                        var j=i+1;
                        var str1=strArray[k].charAt(j);
                        var myRegxp=/^[0-9]*$/ ;
                        if(myRegxp.test(str1) == false)
                        {
                           //alert("No HTML Tags allowed in the textarea");
                           trgtId.focus();
                           args.IsValid = false;
                           return;
                        }
                    }
                }
            }
          }
                         
       args.IsValid = true;
       return;
    }
 
Refer This link for more Details:
 
http://msdn.microsoft.com/en-us/library/ff649310.aspx 

Using Google Translate in Your Website Easy Way

Using Google Translate in Your Website Easy Way


There are times when you have been asked for creating a Multi-lingual Website... I am not going to discuss how we can create one but Today I will be discussing a simple way to achieve the same functionality using Google Translate Widget in your website..

Here is the Code Snippet to achieve the same:


<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Google Iframe</title>

</head>

<body>

<form id="form1" runat="server">

<td valign="top">

<div id="google_translate_element" style="text-align: left">
</div>

<script>
function googleTranslateElementInit()

{
  new google.translate.TranslateElement({pageLanguage: 'en'},'google_translate_element');

}
</script>

<script src="http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit">

</script>

</td>

Hello World.

</form>

</body>

</html>

Wednesday, 16 January 2013

Zip and Unzip File Using C# ASP.Net

Zip and Unzip File Using C# ASP.Net


To achieve this we have reference to J# class library..It resides in a file name "vjslib.dll"..

Right click your project in Server Explorer and click on "Add Reference" -> Select the .Net tab -> Scroll down and select "vjslib" -> Click OK and you are there. Now you can refer the Java library classes within your application. 

Include the following Namespaces:


using java.util;

using java.util.zip;

using java.io;

Then Use the following codes to achieve the functionality:


public string ZipFile(string savePath, string[] attachFiles)

    {

        string sFlag = "Error";

        try

        {

            FileOutputStream fileOutput = new FileOutputStream(savePath);

            ZipOutputStream zipOutput = new ZipOutputStream(fileOutput);

            FileInputStream fileInput = null;

            foreach (string file in attachFiles)

            {

                fileInput = new FileInputStream(file);

                ZipEntry zipEntry = new ZipEntry(Path.GetFileName(file));

                zipOutput.putNextEntry(zipEntry);

                sbyte[] buffer = new sbyte[1024];

                int len = 0;

                while ((len = fileInput.read(buffer)) &gt;= 0)

                {

                    zipOutput.write(buffer, 0, len);

                }

            }

            zipOutput.closeEntry();

            fileInput.close();

            zipOutput.close();

            fileOutput.close();

            return sFlag = "Success";

        }

        catch (Exception)

        {

            return sFlag;

        }

    }

    private List<zipentry> GetZipFiles(ZipFile zipfill)

    {

        List listZip = new List();

        Enumeration zipEnum = zipfill.entries();

        while (zipEnum.hasMoreElements())

        {

            ZipEntry zipEntry = (ZipEntry)zipEnum.nextElement();

            listZip.Add(zipEntry);

        }

        return listZip;

    }

    public string UnZipFile(string zippedFile, string destPath)

    {

        string sFlag = "Error";

        try

        {

            ZipFile zipfile = new ZipFile(zippedFile);

            List zipFiles = GetZipFiles(zipfile);

            foreach (ZipEntry zipFile in zipFiles)

            {

                if (!zipFile.isDirectory())

                {

                    InputStream s = zipfile.getInputStream(zipFile);

                    try

                    {

                        Directory.CreateDirectory(destPath + "\\" + Path.GetDirectoryName(zipFile.getName()));

                        FileOutputStream dest = new FileOutputStream(Path.Combine(destPath + "\\" + Path.GetDirectoryName(zipFile.getName()), Path.GetFileName(zipFile.getName())));

                        try

                        {

                            int len = 0;

                            sbyte[] buffer = new sbyte[7168];

                            while ((len = s.read(buffer)) &gt;= 0)

                            {

                                dest.write(buffer, 0, len);

                            }

                        }

                        finally

                        {

                            dest.close();

                        }

                    }

                    finally

                    {

                        s.close();

                    }

                }

                sFlag = "Success";

            }

            return sFlag;

        }

        catch (Exception)

        {

            return sFlag;

        }

    }


Refer:

http://www.codeproject.com/Articles/18495/Simple-Application-to-Zip-and-UnZip-files-in-C-usi

Friday, 11 January 2013

Get URL of the Referring Page Dynamically


Get URL of the Referring Page Dynamically


Here is the Code Snippet to get the Url of the Referring Page:


System.Uri url = Context.Request.UrlReferrer;
   
string RefURL = url.AbsoluteUri.ToString();

lblURL.Text = RefURL;


Note: InCase If the Referring Page is using  URL Rewriting to alter the structure of the URL; Even then we can get the original Url as follows:


string url= Request.Url.GetLeftPart(UriPartial.Authority)+Request.RawUrl;

lblURL.Text =url;

Refer this for more details:

http://msdn.microsoft.com/en-us/library/system.uri.aspx

Find Whether the String is Present in a Particular WebPage or Not


Find Whether the String is Present in a Particular WebPage(URL) or Not


Use the following Method to achieve this:

Note: You have to pass the URL address and the string variable to this method...


private bool SearchPage(string URL, string StrToLocate)

{

StreamReader SR;

WebResponse Resp ;

WebRequest MyWebRequest;

string PageStr;

MyWebRequest = WebRequest.Create(URL) ;

MyWebRequest.Timeout = 10000 ;

try

{

Resp = MyWebRequest.GetResponse() ;

SR = new StreamReader(Resp.GetResponseStream()) ;

PageStr = SR.ReadToEnd() ;

SR.Close() ;

PageStr = PageStr.ToUpper();

if ( PageStr.IndexOf(StrToLocate.ToUpper(), 0, PageStr.Length) != -1 )

return true;

else

return false;

}

catch ( WebException wex )

{

if (wex.Status == WebExceptionStatus.Timeout)

Response.Write("The request has timed out!") ;

else

Response.Write("There was some exception: " + wex.Message) ;

return false;

}

} 

Extract all Number from String


Extract all Number from String


There are some time when we need to get the numbers present in a particular string.. The following example will help you to achieve the same.. 

Have a look at the code-snippet below:


private string ExtractNumbers(string Expression)

{

string result = null;

char Letter;

for (int i = 0; i < Expression.Length; i++)

{

Letter = Convert.ToChar(Expression.Substring(i, 1));

if (Char.IsNumber(Letter))

{

result += Letter.ToString();

}

}

lblNum.Text=result;

}  

Moving All Files from One Folder to Another


Moving All Files from One Folder to Another


Use the following Code Snippet to Move (Cut) all files in a folder to another Folder:


Suppose there are two folders Folder1 and Folder2.. We will move all contents of  Folder1 to Folder2:


DirectoryInfo dir1= new DirectoryInfo("F:\Folder1");

          DirectoryInfo dir2 = new DirectoryInfo("F:\Folder2");

          FileInfo[] Folder1Files = dir1.GetFiles();

          if(Folder1Files.Length > 0)

          {

               foreach(FileInfo aFile in Folder1Files)

               {

                   if(File.Exists("F:\Folder2" + aFile.Name))

                   {

                      File.Delete("F:\Folder2" + aFile.Name);

                   }

                  aFile.MoveTo("F:\Folder2" + aFile.Name);

               }

          }

Copy All files from One Folder to Another Dynamically

Copy All files from One Folder to Another Dynamically


Use the following Code-Snippet to Copy all files from One Folder to Another:


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.IO;

public partial class Sample : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

DirectoryInfo sourcedinfo = new DirectoryInfo(@”E:\Copy);

DirectoryInfo destinfo = new DirectoryInfo(@”E:\Paste);

CopyAll(sourcedinfo, destinfo);

Console.Read();

}

public void CopyAll(DirectoryInfo source, DirectoryInfo target)

{

try

{

//check if the target directory exists

if (Directory.Exists(target.FullName) == false)

{

Directory.CreateDirectory(target.FullName);

}

//copy all the files into the new directory

foreach (FileInfo fi in source.GetFiles())

{

Console.WriteLine(@”Copying {0}\{1}, target.FullName, fi.Name);

fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);

}

//copy all the sub directories using recursion

foreach (DirectoryInfo diSourceDir in source.GetDirectories())

{

DirectoryInfo nextTargetDir = target.CreateSubdirectory(diSourceDir.Name);

CopyAll(diSourceDir, nextTargetDir);

}

Console.WriteLine(Success);

}

catch (IOException ie)

{

Console.WriteLine(ie.Message);

}

}

}

Get the Online Visitors Count in Your Website Dynamically


Get the Online Visitors Count in Your Website Dynamically


Write the following Code Snippet in your Global.asax file:

void Application_Start(object Sender, EventArgs E)

{

// Set our user count to 0 when we start the server

Application["ActiveUsers"] = 0;

}

void Session_Start(object Sender, EventArgs E)

{

Session["Start"] = DateTime.Now;

Session.Timeout = 1;

Application.Lock();

Application["ActiveUsers"] = (int)Application["ActiveUsers"] + 1;

Application.UnLock();

}

void Session_End(object Sender, EventArgs E)

{

Application.Lock();

Application["ActiveUsers"] = (int)Application["ActiveUsers"] - 1;

Application.UnLock();

Session.Clear();

Session.Remove("Start");

}

Now in the Design Part you can get this number by calling Application["ActiveUsers"] in the .aspx file...

For Example if you want to display the number of visitors online in a label, then do like this:


lblCount.Text=Application["ActiveUsers"].ToString(); 



Download Files from Remote FTP Server to Local


Download Files from Remote FTP Server to Local


For being able to download all files from a FTP directory to a local folder, you will have to list 

all files in the remote directory and then download them one by one. You can use the 

following code to do the same:


Call this inside an Event for Example Button Click:


string[] files = GetFileList();

foreach (string file in files)


{


Download(file);


}


public string[] GetFileList()


{


string[] downloadFiles;


StringBuilder result = new StringBuilder();


WebResponse response = null;


StreamReader reader = null;


try


{


FtpWebRequest reqFTP;


reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/"));


reqFTP.UseBinary = true;


reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);


reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;


reqFTP.Proxy = null;


reqFTP.KeepAlive = false;


reqFTP.UsePassive = false;


response = reqFTP.GetResponse();


reader = new StreamReader(response.GetResponseStream());


string line = reader.ReadLine();


while (line != null)


{


result.Append(line);


result.Append("\n");


line = reader.ReadLine();


}


// to remove the trailing '\n'


result.Remove(result.ToString().LastIndexOf('\n'), 1);


return result.ToString().Split('\n');


}


catch (Exception ex)


{


if (reader != null)


{


reader.Close();


}


if (response != null)


{


response.Close();


}


downloadFiles = null;


return downloadFiles;


}


}



Method Used to achieve Downloading:


private void Download(string file)


{


try


{


string uri = "ftp://" + ftpServerIP + "/" + remoteDir + "/" + file;


Uri serverUri = new Uri(uri);


if (serverUri.Scheme != Uri.UriSchemeFtp)


{


return;


}


FtpWebRequest reqFTP;


reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" +

remoteDir + "/" + file));


reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);


reqFTP.KeepAlive = false;


reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;


reqFTP.UseBinary = true;


reqFTP.Proxy = null;


reqFTP.UsePassive = false;


FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();


Stream responseStream = response.GetResponseStream();


FileStream writeStream = new FileStream(localDestnDir + "\" + file, FileMode.Create);


int Length = 2048;


Byte[] buffer = new Byte[Length];


int bytesRead = responseStream.Read(buffer, 0, Length);


while (bytesRead > 0)


{


writeStream.Write(buffer, 0, bytesRead);


bytesRead = responseStream.Read(buffer, 0, Length);


}


writeStream.Close();


response.Close();


}


catch (WebException wEx)


{


MessageBox.Show(wEx.Message, "Download Error");


}


catch (Exception ex)


{


MessageBox.Show(ex.Message, "Download Error");


}


}

List All Directory Contents in FTP Dynamically


List All Directory Contents in FTP Dynamically


This code snippet will display the lists of files inside a directory in FTP.. 


using System;

using System.IO;

using System.Net;

using System.Text;

namespace Examples.System.Net

{

public class WebRequestGetExample

{

public static void Main ()

{

// Get the object used to communicate with the server. 

FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/");

request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

// This example assumes the FTP site uses anonymous logon. 

request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");

FtpWebResponse response = (FtpWebResponse)request.GetResponse();

Stream responseStream = response.GetResponseStream();

StreamReader reader = new StreamReader(responseStream);

Console.WriteLine(reader.ReadToEnd());

Console.WriteLine("Directory List Complete, status {0}", response.StatusDescription);

reader.Close();

response.Close();

}

}

}

Refer this link for more details:

Set Focus over a Control on Postback/PageLoad


Set Focus over a Control on Postback/PageLoad


In this code snippet, you will see how you can set the focus to an textbox either after the page loads for the first time or after postback. In asp.net there is no direct way for setting focus after post back, you need to use client side script only.
  
For example to set the focus for an textbox:

 document.forms[0].Textbox1.focus();
          
Note: This method uses the name property of the textbox.
To use the id, you would use:

document.getElementById("Textbox1").focus();

For injecting client side script using code behind, you can either use registerstartupscript method or registerclientsidescript. In our case we need to use registerstartupscript, since we need to set the focus immediately after page loads. Registerstartupscript method will place the script just before form end tag. 
So this script will be executed after page loads. 
To set focus we need to write following code:


Page.RegisterStartupScript("SetFocus", "<script language=""Jscript"" > document.getElementById(""Textbox1"").focus(); </Script>");

Close Current Browser Tab Using Javascript


Close Current Browser Tab Using Javascript


Mozilla browsers will not allow you to close the window using window.close() unless the script opened the window. This is a little annoying sometimes. But there is a workaround to resolve this issue. If you observe the error message that is thrown by Mozilla Firefox, "Scripts may not close windows that were not opened by the script", it clearly says that if the script didn't open the window, you can't close that. But we open a blank page in the same window using "_self" as the target window and close the same window. In that way, the script opens the window (which is a blank one) and closes the window too.

So, to put this in the code:


< script >

function closeMe()

{

var win = window.open("","_self"); /* url = "" or "about:blank"; target="_self" */

win.close();

}

< /script >

< input type="button" name="CloseMe" value="Close Me" onclick="closeMe()" />

In mozilla, if there are more than one tabs open, then only the tab where this script is being executed, will be closed, not the whole window. But if there is only one tab open where this script is executing then the window will be closed.

Reference:

Tuesday, 8 January 2013

Disable Button Double Click in ASP.NET


Disable Button Double Click in ASP.NET


Add following code to Page_load. This code prevents button double-click on client-side but still executes code at server-side: 

C#

btnNew.Attributes.Add("onclick", " this.disabled = true; " + ClientScript.GetPostBackEventReference(btnNew, null) + ";");   

VB.Net

btnNew.Attributes.Add("onclick", " this.disabled = true; " + ClientScript.GetPostBackEventReference(btnNew, Nothing) + ";") 

Monday, 7 January 2013

Proper Guidelines for Posting in Asp.Net Forums


Proper Guidelines for Posting in Asp.Net Forums


There are times when most of the People are unaware of the guidelines that is being followed while Posting in MICROSOFT ASP.NET FORUMS(http://forums.asp.net/)

Today I will discuss the guidelines and associated links which should be followed strictly while posting in the forums:





And here are the some associated Cases:

http://forums.asp.net/t/904780.aspx/1?I+have+been+put+under+moderation+

http://forums.asp.net/t/1794945.aspx/1?Account

Two kinds of abusers have their accounts deactivated without notice - spammers and those who attempt to game the community recognition programme. 

Other than that, Moderators usually deactivate accounts of those who repeatedly infringe the Terms of Use, and only then after the individual has been warned that if they continue to act in a manner which is contrary to the Terms Of Use, their account will be deactivated.

**Here the link to the original thread:

 http://forums.asp.net/t/1867455.aspx/1?Proper+Guidelines+for+the+Forum

Execute Batch File in ASP.Net C#


Execute Batch File in ASP.Net C#


You can run Batch file (*.bat) in your ASP.Net Application.. Here is how we can achieve this:

Include the Namespace:

Using System.Diagnostics;

Then:

The path below indicate that batch file location is on root directory:


string str_Path = Server.MapPath(".") + "\\execute.bat";

Use the Code Snippet Below to achieve the goal:


        string str_Path = Server.MapPath(".") + "\\execute.bat";
        ProcessStartInfo processInfo = new ProcessStartInfo(str_Path);
        processInfo.UseShellExecute = false;
        Process batchProcess = new Process();
        batchProcess.StartInfo = processInfo;
        batchProcess.Start();

Wednesday, 2 January 2013

Extract All Email Address from a String


Extract All Email Address from a String


Make Use of the Following Function to achieve this:


public static void emas(string text)
{
 const string MatchEmailPattern =
 @"(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
 + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.

([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
 + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.

([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
 + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})";

Regex rx = new Regex(MatchEmailPattern,  RegexOptions.Compiled |RegexOptions.IgnoreCase);
            // Find matches.
            MatchCollection matches = rx.Matches(text);
            // Report the number of matches found.
            int noOfMatches = matches.Count;
            // Report on each match.
            foreach (Match match in matches)
            {
                Console.WriteLine(match.Value.ToString());
            }
   }

  

Alternatively,You can Use this fuction as well:
 


using System.IO;
using System.Text.RegularExpressions;
using System.Text;

class MailExtracter
{

    public static void ExtractEmails(string inFilePath, string outFilePath)
    {
        string data = File.ReadAllText(inFilePath); //read File 
        //instantiate with this pattern 
      Regex emailRegex = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",
            RegexOptions.IgnoreCase);
        //find items that matches with our pattern
        MatchCollection emailMatches = emailRegex.Matches(data);

        StringBuilder sb = new StringBuilder();

        foreach (Match emailMatch in emailMatches)
        {
            sb.AppendLine(emailMatch.Value);
        }
        //store to file
        File.WriteAllText(outFilePath, sb.ToString());
    }
}

Refresh Parent Page from Iframe


Refresh Parent Page from Iframe


You might have in the situation when you need to refresh the Parent from the Iframe on any event..
Here is the code to achieve this:

In Iframe aspx page, add this script function:


    <script language="javascript">
    function RefreshParent()
    {
    window.parent.location.href = window.parent.location.href;
    }
    </script>


Then Call this Javascript Function from the Code-Behind:


Page.RegisterStartupScript("RefreshParent","<script language='javascript'>RefreshParent()</script>");

back to top