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.
Thursday, December 18, 2008
Preventing Caching of htm and images being stored in Client Machine
Open IIS by:
1. Go to START-->RUN-->Type inetmgr
2. Click Website/Default Web Site.
3.Select Properties by Right Clicking your Virtual Directory Ex: TestApp.
4.In the Properties Dialog Box, Select HTTP Header Tab.
5.In the Custom HTTP Header Column, Click Add Button.
6. It will open another dialog box.
7. In the Add/Edit Custom HTTP Header.
1.Type "cache-control" in Header Name and
2.Type "no-cache" in Header Value
3.Click Ok
8.Again In the Add/Edit Custom HTTP Header.
1.Type "programa" in Header Name and
2.Type "no-cache" in Header Value
3.Click Ok
9.Click ok in all dialog boxes and exit from IIS.
Now check your cache in Temporary Internet Files folder.
No no no no no cache..................rit...........
How is it!!!!!!!! Coo000000000l............
Sunday, November 23, 2008
Generating pdf report using asp.net
I have found some free components for generating pdf report using asp.net
iTextSharp.dll
ghtml2Pdf.exe
PDFSharp.dll
ApacheFop.net.dll
But I found some difficulty in the above components :
iTextSharp.dll:
In iTextSharp,
we can use 2 methods here
By passing the whole html script as string
by create a table in the code behind.
Our requirement is to generate the 1000 lines of html script into pdf.
So it is high risk to pass the 1000 lines of html script into string and also in the code behind it is not possible to create a each table in the code behind because every time the script generated may vary..
Only we can create a simple pdf not complex html scripts.
We cannot write the 1000 lines of html script into iTextSharp.dll.
ghtml2Pdf.exe:
Here we are using the exe component to generate the pdf file by passing the html file.
We have to generate the html file first and then pass that file into ghtml2Pdf.exe.
It is high riskable in the dotnet framework. Morever the we cannot use this in our whole servers.
It has the rights to work in only limited number of computers.
PDFSharp.dll
Here again we cannot use the html scripts to generate the pdf.
We have to create our own design in the codebehind. Again the same problem that every time the design or the html script may vary according to the report generated.
ApacheFop.net.dll
This is the good method to generate the pdf in dotnet using java classes.
Also we need vjslib.dll to work with the Java classess.
The process is some wat critical.
First we have to create a xml file to store the datas needed.
Then we have to create a design pattern like stylesheet using xsl.
After creating the xml and xsl, we have to transform these two and need to generate the fo file ie Formatted object file.
After the fo file created , we can generate the pdf from the fo file.
This is the structure.
But this requires some amount of time.
Using Java:
http://www.javaworld.com/javaworld/jw-04-2006/jw-0410-html.html
Here is the link where I read article for generating pdf using java.
It is a difficult process same as the above one.
Conclusion.
I have found lot of premium shareware components to generate the pdf from html.
It average costs from 600 to 1000 $.
The best is
http://www.winnovative-software.com/Buy.aspx#redistributable
cost for redistributable pacakage is
INR 33938.41
Some other premium components
http://www.html-to-pdf.net/Pricing.aspx
Hope all got some knowledge anyone who started creating pdf.
Monday, August 11, 2008
Yahoo contacts!!! import class in C#
I've implemented importing and you can use it for free.
(But you need to make some change in code to compile it)
using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
namespace Gnilly.Syndication.Mail
{
public class YahooExtract
{
private const string _addressBookUrl = "http://address.yahoo.com/yab/us/Yahoo_ab.csv?loc=us&.rand=1671497644&A=H&Yahoo_ab.csv";
private const string _authUrl = "https://login.yahoo.com/config/login?"; private const string _loginPage = "https://login.yahoo.com/config/login";
private const string _userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3";
public bool Extract( NetworkCredential credential, out MailContactList list )
{
bool result = false;
list = new MailContactList();
try
{
WebClient webClient = new WebClient(); webClient.Headers[ HttpRequestHeader.UserAgent ] = _userAgent; webClient.Encoding = Encoding.UTF8;
byte[] firstResponse = webClient.DownloadData( _loginPage );
string firstRes = Encoding.UTF8.GetString( firstResponse );
NameValueCollection postToLogin = new NameValueCollection();
Regex regex = new Regex( "type=\"hidden\" name=\"(.*?)\" value=\"(.*?)\"", RegexOptions.IgnoreCase );
Match match = regex.Match( firstRes );
while ( match.Success )
{
if ( match.Groups[ 0 ].Value.Length > 0 )
{
postToLogin.Add( match.Groups[ 1 ].Value, match.Groups[ 2 ].Value );
}
match = regex.Match( firstRes, match.Index + match.Length );
}
postToLogin.Add( ".save", "Sign In" );
postToLogin.Add( ".persistent", "y" );
string login = credential.UserName.Split( '@' )[ 0 ];
postToLogin.Add( "login", login );
postToLogin.Add( "passwd", credential.Password );
webClient.Headers[ HttpRequestHeader.UserAgent ] = _userAgent;
webClient.Headers[ HttpRequestHeader.Referer ] = _loginPage;
webClient.Encoding = Encoding.UTF8;
webClient.Headers[ HttpRequestHeader.Cookie ] = webClient.ResponseHeaders[ HttpResponseHeader.SetCookie ];
webClient.UploadValues( _authUrl, postToLogin );
string cookie = webClient.ResponseHeaders[ HttpResponseHeader.SetCookie ];
if ( string.IsNullOrEmpty( cookie ) )
{
return false;
}
string newCookie = string.Empty;
string[] tmp1 = cookie.Split( ',' );
foreach ( string var in tmp1 )
{
string[] tmp2 = var.Split( ';' );
newCookie = String.IsNullOrEmpty( newCookie ) ? tmp2[ 0 ] : newCookie + ";" + tmp2[ 0 ];
}
// set login cookie
webClient.Headers[ HttpRequestHeader.Cookie ] = newCookie;
byte[] thirdResponse = webClient.DownloadData( _addressBookUrl );
string thirdRes = Encoding.UTF8.GetString( thirdResponse );
string crumb = string.Empty;
Regex regexCrumb = new Regex( "type=\"hidden\" name=\"file://.crumb/" id=\"crumb1\" value=\"(.*?)\"", RegexOptions.IgnoreCase );
match = regexCrumb.Match( thirdRes );
if ( match.Success && match.Groups[ 0 ].Value.Length >) )
{
crumb = match.Groups[ 1 ].Value;
}
NameValueCollection postDataAB = new NameValueCollection();
postDataAB.Add( ".crumb", crumb );
postDataAB.Add( "vcp", "import_export" );
postDataAB.Add( "submit[action_export_yahoo]", "Export Now" );
webClient.Headers[ HttpRequestHeader.UserAgent ] = _userAgent;
webClient.Headers[ HttpRequestHeader.Referer ] = _addressBookUrl;
byte[] FourResponse = webClient.UploadValues( _addressBookUrl, postDataAB );
string csvData = Encoding.UTF8.GetString( FourResponse );
string[] lines = csvData.Split( '\n' ); foreach ( string line in lines )
{
string[] items = line.Split( ',' );
if ( items.Length < 5 )
{ continue;
}
string email = items[ 4 ];
string name = items[ 3 ];
if ( !string.IsNullOrEmpty( email ) && !string.IsNullOrEmpty( name ) )
{
email = email.Trim( '\"' );
name = name.Trim( '\"' );
if ( !email.Equals( "Email" ) && !name.Equals( "Nickname" ) )
{
MailContact mailContact = new MailContact();
mailContact.Name = name;
mailContact.Email = email;
list.Add( mailContact );
}
}
}
result = true;
}
catch
{
}
return result;
}
}
}
Sunday, July 27, 2008
Adding google MAP into your .NET website in just 15 minutes
Adding GOOGLE MAP into your .NET website in just 15 minutes by Florence
Ever wanted to add a Google Map to your site but only had 15 minutes to spare? Now you can add a map and still have time to brag to your mates and bask in the worship that (inevitably) comes afterward. Basically, the guys over at subgurim.net have already done all the hard work in writing the .Net wrapper for Google Maps. Problem is, the examples on their site are mostly in spanish & its a bit difficult to find out exactly what is needed to get everything working. But all this is cutting into your bragging time - so lets get started!
1. Get a Google Maps API key from here:http://www.google.com/apis/maps/
2. Download the SubGurim wrapper dll from here:http://en.googlemaps.subgurim.net/descargar.aspx
3. Unzip it, and put it in your \bin directory
4. Add it to your toolbox byTools -> Choose Toolbox Items -> Browse -> Select the .dll file -> OKGMap will now be in the ‘Standard’ area of your Toolbox.
5. Add a new webpage. 6. Drag the GMap from the toolbox onto the page. A new instance of the GMap will appear on the page, with the name ‘GMap1′
7. Add the following lines to your web.config file: appsettings add value="YourGoogleMapsAPIKeyHere" key="googlemaps.subgurim.net" appsettings 8. Add the following code to your Page.Load sub
Dim sStreetAddress As String Dim sMapKey As String = ConfigurationManager.AppSettings("googlemaps.subgurim.net") Dim GeoCode As Subgurim.Controles.GeoCode sStreetAddress = "100 Russell St. Melbourne. VIC. 3000. Australia" GeoCode = GMap1.geoCodeRequest(sStreetAddress, sMapKey) Dim gLatLng As New Subgurim.Controles.GLatLng(GeoCode.Placemark.coordinates.lat, GeoCode.Placemark.coordinates.lng) GMap1.setCenter(gLatLng, 16, Subgurim.Controles.GMapType.GTypes.Normal) Dim oMarker As New Subgurim.Controles.GMarker(gLatLng) GMap1.addGMarker(oMarker)
Press F5, and start basking in the glory!