Florence Blogspot about asp.net tutorials and web design and web development

Friday, May 29, 2009

Read the emailID from txt file

Read the emailID from txt file:
_____________________________________

Using Regular Expression, we can do this.

the textfile format may be in any format like

sdfsd

danasegarane@test.com,

test@test.com,

me@me.com

sdf

sdfs

dfsd


First Method:

string pattern = @"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?";

System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(pattern);

//Read file
string sFileContents =System.IO.File.ReadAllText(Server.MapPath("Email.txt"));

System.Text.RegularExpressions.MatchCollection mc = reg.Matches(sFileContents);

//string array for stroing
System.Collections.Generic.List str = new System.Collections.Generic.List();foreach (System.Text.RegularExpressions.Match m in mc)

{

str.Add(m.Value);

}

OR

Second Method:

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

try
{
//the file is in the root - you may need to change it
string filePath = MapPath("~") + "/EmailText.txt";

using (StreamReader sr = new StreamReader( filePath) )
{
string content = sr.ReadToEnd();
if (content.Length > 0)
{
//this pattern is taken from Asp.Net regular expression validators library
string pattern = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
MatchCollection mc = Regex.Matches(content, pattern);
for (int i = 0; i <>

Monday, May 25, 2009

Export Data To Excel using ADO.Net

Excel Workbook is just like database with sheets corresponding to tables. See the mapping below.



Database <—————> Excel Workbook


Sheet <—————-> Table



Connection String for Excel 97-2003 Format (.XLS)


For Excel 97-2003 format Microsoft Jet OLEDB Driver 4.0 is used. A sample connection string as follows.


"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Book1.xls;Extended Properties='Excel 8.0;HDR=Yes'"




Connection String for Excel 2007 Format (.XLSX)


For Excel 2007 format the new Microsoft Ace OLEDB Driver 12.0 is used. A sample connection string as follows.


"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Book1.xlsx;Extended Properties='Excel 8.0;HDR=Yes'"



Rest everything is same for both versions. One thing to note Microsoft Ace OLEDB Driver 12.0 works for both Excel 2003 and Excel 2007 format.



You can specify whether your Excel file has Headers or not using the HDR property.


When HDR is set to Yes the First Row is considered as the Header of the Excel file.





Establish a Connection



String strExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;"


+ "Data Source=Book1.xls;"


+ "Extended Properties='Excel 8.0;HDR=Yes'";



OleDbConnection connExcel = new OleDbConnection(strExcelConn);


OleDbCommand cmdExcel = new OleDbCommand();


cmdExcel.Connection = connExcel;





Accessing Sheets



connExcel.Open();


DataTable dtExcelSchema;


dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);


connExcel.Close();



The dtExcelSchema contains all the Sheets present in your Excel Workbook


You access them in the following way


string sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"];



This will give the name of the first sheet. i.e. Sheet1$



Create a new sheet


cmdExcel.CommandText = "CREATE TABLE [tblData]" +


"(ID varchar(10), Name varchar(50));";


connExcel.Open();


cmdExcel.ExecuteNonQuery();


connExcel.Close();



The above code creates a new Sheet in the Excel Workbook with the name tblData with two columns ID and Name.


Insert Record into Sheet


connExcel.Open();


cmdExcel.CommandText = "INSERT INTO [tblData] (ID, Name)" +


" values ('1', 'MAK')";


cmdExcel.ExecuteNonQuery();


connExcel.Close();





Update existing Record into Sheet


connExcel.Open();


cmdExcel.CommandText = "UPDATE [tblData] " +


"SET Name ='John' WHERE ID = '1'";


cmdExcel.ExecuteNonQuery();


connExcel.Close();

C# How to place an arraylist inside a Session Variable and Iterate through it

Question:

Hi,

In my web form, I want to store multiple IDs inside an arraylist and then store the arraylist in a Session Variable (e.g. Session["InstallationID"]) to use it in a different web form where I want to use every ID inside the arraylist.

How do I place the arraylist inside the Session Variable and then take each ID off of it to be used in a SELECT statement?

Answer:


Something like this:

1    protected void Page_Load(object sender, EventArgs e)
2 {
3 if (!IsPostBack)
4 {
5 List<int> ids = new List<int> {1, 2, 3, 4, 5};
6 Session["myIds"] = ids;
7 }
8 }
9
10 protected void buttonSubmit_Click(object sender, EventArgs e)
11 {
12 List<int> ids = Session["myIds"] != null ? (List<int>) Session["myIds"] : null;
13 if (ids != null)
14 {
15 foreach (int id in ids)
16 {
17 ListBox1.Items.Add(String.Format("select * from customer where id={0}", id));
18 }
19 }
20 }

OR


protected void Page_Load(object sender, EventArgs e)
{
//Save
ArrayList idList = new ArrayList();
idList.Add("1");
idList.Add("2");
idList.Add("3");
Session["InstallationId"] = idList;
}//Page2

protected void Page_Load(object sender, EventArgs e)

{

//Retreive

ArrayList idList = (ArrayList)Session["InstallationId"];

string id1 = idList[0].ToString() ;

string id2 = idList[1].ToString();

string id3 = idList[2].ToString();

}

Refer for references: http://forums.asp.net/t/1425975.aspx



Tuesday, May 19, 2009

Maintain Scroll Position after Asynchronous Postback

Maintain Scroll Position after Asynchronous Postback

Do you want to maintain the scroll position of a GridView, Div, Panel, or whatever that is inside of an UpdatePanel after an asynchronous postback? Normally, if the updatepanel posts back, the item will scroll back to the top because it has been reloaded. What you need to do is “remember” where the item was scrolled to and jump back to there after the postback. Place the following script after the ScriptManager on your page. And since the _endRequest event of the PageRequestManager happens before the page is rendered, you’ll never even see your item move!

<script type="text/javascript">
var xPos, yPos;
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(BeginRequestHandler);
prm.add_endRequest(EndRequestHandler);
function BeginRequestHandler(sender, args) {
xPos = $get('scrollDiv').scrollLeft;
yPos = $get('scrollDiv').scrollTop;
}
function EndRequestHandler(sender, args) {
$get('scrollDiv').scrollLeft = xPos;
$get('scrollDiv').scrollTop = yPos;
}
</script>

Tuesday, May 12, 2009

How to check the Status of the Internet connection from windows application in C#.net

How to check the Status of the Internet connection from windows application in C#.net


try this:
bool ConnectionExists()
{
try
{
System.Net.Sockets.TcpClient clnt=new System.Net.Sockets.TcpClient("www.google.com",80);
clnt.Close();
return true;
}
catch(System.Exception ex)
{
return false;
}
}



or this one

public static bool Test(string url)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "HEAD";
try {
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
resp.Close(); return true;
}
catch { return false; } }


or

In this tutorial, we'll create a class with a static function that returns true if connected and false if not, using our API function in private state.

Check this out :

using System ;
using System.Runtime ;
using System.Runtime.InteropServices ;

public class InternetCS
{

//Creating the extern function...
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState( int out Description, int ReservedValue ) ;

//Creating a function that uses the API function...
public static bool IsConnectedToInternet( )
{

int Desc ;
return InternetGetConnectedState( out Desc, 0 ) ;

}

}

Friday, May 1, 2009

Get the Checkboxlist values using javascript:

Get the Checkboxlist values using javascript:

We cannot get the value of the checkbox in the checkboxlist because it is rendered in the form of table , td, input and the text of the check is like label.

So we need to bind the value of checkbox in the tilte attribute and then we can read the title values using javascript.

<script type="text/javascript">

function IsCheck()

{

var UserID="";

var UserCode=""

var cblist = "ChkBoxListUsers";

var chkList1= document.getElementById(cblist);

var arrayOfCheckBoxes= chkList1.getElementsByTagName("input");

var arrayOfCheckBoxspans= chkList1.getElementsByTagName("span");

var arrayOfCheckBoxLabels= chkList1.getElementsByTagName("label");

var listcount = arrayOfCheckBoxes.length;

for(var i=0;i<arrayOfCheckBoxes.length;i++)

{

if(arrayOfCheckBoxes[i].checked)

{

UserCode += arrayOfCheckBoxspans[i].title + ",";

UserID += arrayOfCheckBoxLabels[i].innerHTML+ ", ";

}

}

window.opener.document.forms[0].HdnSelectedUsers.value=UserCode;

window.opener.document.forms[0].txtSelectedUsers.value=UserID;

window.close();

return false;

}

</script>

Frontend:

<body>

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

<div style="text-align: center">

<fieldset class="Fieldset" style="width: 95%" runat="server" id="fsToolDetails">

<legend class="Legend_Text"><strong>User Details</strong></legend>

<table border="0" cellpadding="0" cellspacing="0" style="width: 100%">

<tr>

<td align="center">

<asp:Label ID="Label1" runat="server" Text="SELECT USER" Width="240px" CssClass="Headlabel"></asp:Label></td>

</tr>

<tr>

<td align="left" style="height: 14px">

<asp:Label ID="lblError" runat="server" CssClass="Err_label"></asp:Label></td>

</tr>

<tr>

<td width="100%" align="left" height="150px">

<div align="left" style="width:300px; height: 159px; width: 100%; overflow: auto; padding-top: 1px;

padding-left: 1px">

<asp:CheckBoxList ID="ChkBoxListUsers" runat="server" CssClass="selectBox" Width="500px" RepeatColumns="2" RepeatDirection="Horizontal" OnDataBound="ChkBoxListUsers_DataBound">

</asp:CheckBoxList>

</div>

</td>

</tr>

<tr>

<td align="center">

<asp:Button ID="btnSubmit" Text="Order" runat="server" CssClass="buttons"

Width="57px" />

<asp:Button ID="btnClose" Text="Close" runat="server" CssClass="buttons" Width="54px"

OnClientClick="window.close();" />

</td>

</tr>

<tr>

<td align="center">

</td>

</tr>

</table>

</fieldset>

</div>

<script type="text/javascript">

function IsCheck()

{

var UserID="";

var UserCode=""

var cblist = "ChkBoxListUsers";

var chkList1= document.getElementById(cblist);

var arrayOfCheckBoxes= chkList1.getElementsByTagName("input");

var arrayOfCheckBoxspans= chkList1.getElementsByTagName("span");

var arrayOfCheckBoxLabels= chkList1.getElementsByTagName("label");

var listcount = arrayOfCheckBoxes.length;

for(var i=0;i<arrayOfCheckBoxes.length;i++)

{

if(arrayOfCheckBoxes[i].checked)

{

UserCode += arrayOfCheckBoxspans[i].title + ",";

UserID += arrayOfCheckBoxLabels[i].innerHTML+ ", ";

}

}

window.opener.document.forms[0].HdnSelectedUsers.value=UserCode;

window.opener.document.forms[0].txtSelectedUsers.value=UserID;

window.close();

return false;

}

</script>

</form>

</body>

Codebehind:

protected void Page_Load(object sender, EventArgs e)

{

if(!IsPostBack)

{

btnSubmit.Attributes.Add("onclick", "return IsCheck();");

if( Request.QueryString["CompanyId"] != null && Request.QueryString["CompanyId"] != "")

{

FillUsers(Request.QueryString["CompanyId"]);

}

}

}

private void FillUsers(string CompanyID)

{

BLLPopUpUser ObjPopUpUser = new BLLPopUpUser();

DataSet ds = new DataSet();

ds = ObjPopUpUser.GetUserListfromCompany(CompanyID);

ChkBoxListUsers.DataSource = ds;

ChkBoxListUsers.DataTextField = "CU_UserID";

ChkBoxListUsers.DataValueField = "CU_UserCode";

ChkBoxListUsers.DataBind();

}

protected void ChkBoxListUsers_DataBound(object sender, EventArgs e)

{

CheckBoxList chkList = (CheckBoxList)(sender);

if (Request.QueryString["Users"] != null && Request.QueryString["Users"].ToString() != "")

{

string[] users = Request.QueryString["Users"].ToString().Split(',');

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

{

if (chkList.Items.FindByText(users[i]) != null)

{

chkList.Items.FindByText(users[i]).Selected = true;

}

}

}

foreach (ListItem item in chkList.Items)

{

item.Attributes.Add("title", item.Value);

}

}

Search