Florence Blogspot about asp.net tutorials and web design and web development
Saturday, July 18, 2009
JavaScript Progress Bar
<table align="center"><tr><td>
<div id="showbar" style="font-size:8pt;padding:2px;border:solid black 1px;visibility:hidden">
<span id="progress1"> </span>
<span id="progress2"> </span>
<span id="progress3"> </span>
<span id="progress4"> </span>
<span id="progress5"> </span>
<span id="progress6"> </span>
<span id="progress7"> </span>
<span id="progress8"> </span>
<span id="progress9"> </span>
</div>
</td></tr></table>
<script language="javascript">
var progressEnd = 9; // set to number of progress <span>'s.
var progressColor = 'blue'; // set to progress bar color
var progressInterval = 1000; // set to time between updates (milli-seconds)
var progressAt = progressEnd;
var progressTimer;
function progress_clear() {
for (var i = 1; i <= progressEnd; i++) document.getElementById('progress'+i).style.backgroundColor = 'transparent';
progressAt = 0;
}
function progress_update() {
document.getElementById('showbar').style.visibility = 'visible';
progressAt++;
if (progressAt > progressEnd) progress_clear();
else document.getElementById('progress'+progressAt).style.backgroundColor = progressColor;
progressTimer = setTimeout('progress_update()',progressInterval);
}
function progress_stop() {
clearTimeout(progressTimer);
progress_clear();
document.getElementById('showbar').style.visibility = 'hidden';
}
//progress_update(); // start progress bar
</script>
<input type="button" name="b1" value="Start Progress Bar" onClick="progress_update()">
<input type="button" name="b2" value="Stop Progress Bar" onClick="progress_stop()">
Monday, July 6, 2009
Asp.Net CAPTCHA and Asp.Net AJAX CAPTCHA
Asp.Net CAPTCHA and Asp.Net AJAX CAPTCHA
I am using a great Asp.Net CAPTCHA by BrainJar in a number of web sites with and without Asp.Net AJAX. It’s a simple and really easy to use Asp.Net CAPTCHA. The actual source code is in C#, but you can use it with both C# and VB.Net by simply wrapping the functionality in a class library.In Asp.Net forums and in many other user communities I have seen lot of people asking for VB.Net CAPTCHA. So I thought to write a blog post and create some sample implementations. The zip file contains C# CAPTCHA and VB.Net CAPTCHA. I have included the samples for Asp.Net AJAX CAPTCHA also.
You can download the samples and implementation from here
Implementing Asp.Net AJAX CAPTCHA is really simple. Just wrap the main Asp.Net CAPTCHA with Asp.Net AJAX update panel and put a random query string at the end of CAPTCHA image src. The random query string will avoid showing the old CAPTCHA from browser cache.
STEPS TO ADD ASP.NET CAPTCHA IN YOUR WEBSITE
- Refer the assembly CaptchaDLL.dll in your project
- Copy JpegImage_CS.aspx or JpegImage_VB.aspx (according to the language of choice) to your website.
- Open the above file and make changes in Colors and Font if needed. (read the inline comments to know more)
- Now user the sample codes from Default.aspx or Ajax.aspx pages. The code is straight forward. You make a session and generate an image with the string in the Session. Now when you submit you have to check the session value and textbox value to see whether the entered CAPTCHA is correct.
If you have any questions please put as a comment.
Wednesday, June 3, 2009
Date Formatting in C#
Cheat sheet
<%= String.Format("{specifier}", DateTime.Now) %>
Specifier Description Output
d Short Date 08/04/2007
D Long Date 08 April 2007
t Short Time 21:08
T Long Time 21:08:59
f Full date and time 08 April 2007 21:08
F Full date and time (long) 08 April 2007 21:08:59
g Default date and time 08/04/2007 21:08
G Default date and time (long) 08/04/2007 21:08:59
M Day / Month 08 April
r RFC1123 date Sun, 08 Apr 2007 21:08:59 GMT
s Sortable date/time 2007-04-08T21:08:59
u Universal time, local timezone 2007-04-08 21:08:59Z
Y Month / Year April 2007
dd Day 08
ddd Short Day Name Sun
dddd Full Day Name Sunday
hh 2 digit hour 09
HH 2 digit hour (24 hour) 21
mm 2 digit minute 08
MM Month 04
MMM Short Month name Apr
MMMM Month name April
ss seconds 59
tt AM/PM PM
yy 2 digit year 07
yyyy 4 digit year 2007
: seperator, e.g. {0:hh:mm:ss} 09:08:59
/ seperator, e.g. {0:dd/MM/yyyy} 08/04/2007
Friday, May 29, 2009
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.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
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
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);
}
}
Sunday, April 5, 2009
Popup reminder on particular time in asp.net
Hi ,
I have a implementation on reminders scenario on my webpage .It should work like outlook reminders with snooze functionality.i dont no how to starwith it Can any one guide me on this. I am using VS2005 & SQL2005.
Answer 1 :
The delegate is used when you need to access private variables in a method called by an event handler. The bennefit is one javascript that can be attached to multiple elements and each element has its own life cycle and private data.
setTimeout only runs once after a delay miliseconds.
I'm not that great with javascript. I'm great with using the javascript client libraries ( microsoft.ajax.js jquery.js ...) and implementing the ajaxextender control pattern in my own custom controls.
Answer 2:
USe Timer and run it for certain interval .. Store the time in database .for every interval check the time . on time show the pop up..
Or use windows services.
http://www.c-sharpcorner.com/UploadFile/mahesh/window_service11262005045007AM/window_service.aspx
this link has the basic to create a windows service ..
In on_start event you can create a timer which will help to do ur work
Monday, March 16, 2009
saving TreeView's state
It's implemented in two static methods that I popped into a "TreeViewHelper" static class. Whenever you need to leave the page, call the "StoreTreeViewStateToSession" method. In your method to bind data to your TreeView, call RestoreTreeViewStateFromSession. If there's no stored state, it just returns silently. If there is stored state, it'll restore it (which nodes are expanded and collapsed, and which node is selected).
They use Session state, which seems appropriate since it's obviously by-user, and cross-page. But the Session variable key has the page name embedded in it, which would cause it *not* to work in your solution (since it's a different page trying to restore the state). A minor tweak to this routine would remedy that issue, however. Store as the variable name suffix a "key" common to your PageA, PageB, etc., instead of Request.ServerVariables["path_info"].
Here's the code. I've just recently adapted it from the IEWebControls TreeView add-on (circa .NET 1.0) and updated it to work with the ASP.NET 2.0 TreeView control. It seems to work like a charm:
public static void StoreTreeViewStateToSession(TreeView tvIn)
{
// Takes the TreeView's state and saves it in a Session variable
// Call this method before leaving the page if we expect to be back
string strVarName;
string strList = "";
strVarName = "tv_" + HttpContext.Current.Request.ServerVariables["path_info"];
if (HttpContext.Current.Session[strVarName] + "" != "")
{
HttpContext.Current.Session.Remove(strVarName);
}
StoreTreeViewStateToSession_Recurse(tvIn.Nodes[0], ref strList);
strList = tvIn.SelectedNode.ValuePath + strList;
HttpContext.Current.Session.Add(strVarName, strList);
}
private static void StoreTreeViewStateToSession_Recurse(TreeNode tnIn, ref string strList)
{
if (tnIn.Expanded == true)
{
strList = "," + tnIn.ValuePath + strList;
}
foreach (TreeNode tnCurrent in tnIn.ChildNodes)
{
StoreTreeViewStateToSession_Recurse(tnCurrent, ref strList);
}
}
public static void RestoreTreeViewStateFromSession(TreeView tvIn)
{
// Takes the Session-stored TreeView state and restores it
// to the passed-in TreeView control.
// Call this method on entry to the page. Nothing will
// happen if the variable doesn't exist.
string strVarName;
// See if stored data exists for this treeview
strVarName = "tv_" + HttpContext.Current.Request.ServerVariables["path_info"];
if (HttpContext.Current.Session[strVarName] + "" != "")
{
string strSelectedNodeIndex = "";
foreach (string strCurrent in HttpContext.Current.Session[strVarName].ToString().Split(','))
{
if (strSelectedNodeIndex == "") // First element in list is selected node
{
strSelectedNodeIndex = strCurrent;
}
else
{
try
{
tvIn.FindNode(strCurrent).Expanded = true;
}
catch
{
//eat exception
}
}
}
try
{
// Verify that node exists before setting SelectedNodeIndex
TreeNode tnTest = tvIn.FindNode(strSelectedNodeIndex);
// Select the node (will only happen if it exists)
tvIn.FindNode(strSelectedNodeIndex).Select();
// Ensure the selected node's parent is expanded
((TreeNode)tvIn.FindNode(tvIn.SelectedNode.ValuePath).Parent).Expanded = true;
}
catch
{
// eat exception
}
HttpContext.Current.Session.Remove(strVarName);
}
}
... Hope that helps!!! See my other post on client-side node selection without forcing PostBack (http://forums.asp.net/thread/1452479.aspx) if you're interested in another of my TreeViewHelper tools, which I'm pretty pleased with lately. Microsoft so needs to hire me. ;-)
Friday, March 13, 2009
Ajax PageMethods using JSON (JavaScript Object Notation)
Page Methods
Page methods allow ASP.NET AJAX pages to directly execute a page’s static methods, using JSON (JavaScript Object Notation). JSON is basically a minimalistic version of SOAP, which is perfectly suited for light weight communication between client and server. For more information about how to implement page methods and JSON, take a look at Microsoft’s Exposing Web Services to Client Script in ASP.NET AJAX.
Instead of posting back and then receiving HTML markup to completely replace our UpdatePanel’s contents, we can use a web method to request only the information that we’re interested in:
Using JSON, the entire HTTP round trip is 24 bytes, as compared to 872 bytes for the UpdatePanel. That’s roughly a 4,000% improvement, which will only continue to increase with the complexity of the page.
Not only has this reduced our network footprint dramatically, but it eliminates the necessity for the server to instantiate the UpdatePanel’s controls and take them through their life cycles to render the HTML sent back to the browser.