Friday, December 9, 2011

Beauty of Math!

Absolutely amazing!
Beauty of Math!

1 x 8 + 1 = 9
12 x 8 + 2 = 98
123 x 8 + 3 = 987
1234 x 8 + 4 = 9876
12345 x 8 + 5 = 98765
123456 x 8 + 6 = 987654
1234567 x 8 + 7 = 9876543
12345678 x 8 + 8 = 98765432
123456789 x 8 + 9 = 987654321

1 x 9 + 2 = 11
12 x 9 + 3 = 111
123 x 9 + 4 = 1111
1234 x 9 + 5 = 11111
12345 x 9 + 6 = 111111
123456 x 9 + 7 = 1111111
1234567 x 9 + 8 = 11111111
12345678 x 9 + 9 = 111111111
123456789 x 9 +10= 1111111111

9 x 9 + 7 = 88
98 x 9 + 6 = 888
987 x 9 + 5 = 8888
9876 x 9 + 4 = 88888
98765 x 9 + 3 = 888888
987654 x 9 + 2 = 8888888
9876543 x 9 + 1 = 88888888
98765432 x 9 + 0 = 888888888

Brilliant, isn't it?

And look at this symmetry:

1 x 1 = 1
11 x 11 = 121
111 x 111 = 12321
1111 x 1111 = 1234321
11111 x 11111 = 123454321
111111 x 111111 = 12345654321
1111111 x 1111111 = 1234567654321
11111111 x 11111111 = 123456787654321
111111111 x 111111111=12345678987654321





Now, take a look at this...





From a strictly mathematical viewpoint,

What Equals to 100%?
What does it mean to give MORE than 100%?


Ever wonder about those people who say they are giving more than 100%...

We have all been in situations where someone wants you to

GIVE OVER 100%.
How about ACHIEVING 101%?

What equals to 100% in life?


Here's a little mathematical formula that might help answering these questions:


If:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

Is represented as:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26


It is
H-A-R-D-W-O-R- K

8+1+18+4+2 3+15+18+11 = 98%

And

K-N-O-W-L-E-D-G-E

11+14+15+23+12+5+4+7+5 = 96%

But
A-T-T-I-T-U-D-E
1+20+20+9+20+21+4+5 = 100%

AND
L-O-V-E-O-F-G-O-D

12+15+22+5+15+6+7+15+4 = 101%


Therefore, one can conclude with mathematical certainty that:

While Hard Work and Knowledge will get you close and Attitude will get you there...
It's the Love of God that will put you over the top!!!

Please share this with your friends, colleagues & loved ones just the way I did...

God bless you!!

Friday, February 4, 2011

Handy session class :: Base Page For Detecting Session Timeout in ASP.Net/C#

In this tutorial we will be going over how to create a base page class to handle your sessions. The number one question I get asked time and time again is how to manage sessions, and how to detect if a session has expired. Back in the days before .Net things were a little more complicated when it came to solving this riddle, but with the advent of the .Net Framework 2.0 a new class was introduced, the HttpSessionState Class, which is a member of the System.Web.SessionState Namespace. The new HttpSessionState Class gives us access to session state items and other lifetime management methods.

One of the items in the HttpSessionState class we will be looking at is the IsNewSession Property. This property lets us know whether the current session was created wtih the current request, or if it was an existing session. This is invaluable as we can use it to determine if the users session had expired or timed out. The IsNewSession Property is more robust and advanced then simply checking if the session is null because it takes into account a session timeout as well.

In this tutorial we will create a base page class that we can inherit all our pages from, and in this class we will check the status of the users session in the Page.OnInit Method. The OnOnit Method fires before the Page Load Event, giving us the ability to check the session before the page is actually rendered. So lets get to some code.

The first thing we will need to do, as with any class you create, is to make sure we have a reference to the appropriate Namespaces. For our class we need but 2 Namespaces, the System.Web.UI Namespace and the System Namespace, so lets add them to our class.

NOTE: All Namespace references need to come before the declaration of your class.

using System;
using System.Web.UI;
Now we are going to declare our class, the class in this example is named SessionCheck, and it looks like

public class SessionCheck: System.Web.UI.Page
{

}
You will notice that our base class, which we will be inheriting from, inherits from the System.Web.UI.Page class. Doing this gives us access to all the methods, properties and events of the Page class. In our base class we will have a single property, this will be the property that will hold the URL we want the user to redirect to if there is a problem with their session. We make this property static so we can access it without having to create an instance of the class. We dont want to have to do this because we are inheriting from it.
This is our property
///
/// property vcariable for the URL Property
///

private static string _url;

///
/// property to hold the redirect url we will
/// use if the users session is expired or has
/// timed out.
///

public static string URL
{
get { return _url; }
set { _url = value; }
}
Now that we have our property out of the way, we will look at the only of our base class, the OnInit which we will override in order to add our ow functionality. In
this method we will also initialize our base class, you do that with line

base.OnInit(e);
In our OnInit Method we will first check to
see if the current session is null. If the session is null we then will
check the IsNewSession Property to see if
this session was created in this request. If we determine the session is
a new session, we will then cal upon the Headers
Property of the HttpRequest
Class, which is located in the System.Web
Namespace.

In our OnInit Method we will first check to
see if the current session is null. If the session is null we then will
check the IsNewSession Property to see if
this session was created in this request. If we determine the session is
a new session, we will then cal upon the Headers
Property of the HttpRequest
Class, which is located in the System.Web
Namespace.

The Header we are retrieving is the Cookie Header. Once we have this, we will first
check to see if it’s null, if it’s not null we will look for the value ASP.Net_SessionId. Now if we make it this far, and
that cookie exists, we know the session has timed out, so we will then
redirect the user to our redirect page, which is set with the URL Property. So lets take a look at our new OnInit Method:

override protected void OnInit(EventArgs e)
{
//initialize our base class (System.Web,UI.Page)
base.OnInit(e);
//check to see if the Session is null (doesnt exist)
if (Context.Session != null)
{
//check the IsNewSession value, this will tell us if the session has been reset.
//IsNewSession will also let us know if the users session has timed out
if (Session.IsNewSession)
{
//now we know it's a new session, so we check to see if a cookie is present
string cookie = Request.Headers["Cookie"];
//now we determine if there is a cookie does it contains what we're looking for
if ((null != cookie) && (cookie.IndexOf("ASP.NET_SessionId") >= 0))
{
//since it's a new session but a ASP.Net cookie exist we know
//the session has expired so we need to redirect them
Response.Redirect("Default.aspx?timeout=yes&success=no");
}
}
}
}
That’s it, we have completed our base class which all our web forms will inherit from, allowing us to keep an eye on the users session. Now that we have the class completed we need to use it. Before it can be affected we need to do 1 of 2 things

Add EnableSessionState = true to the @Page directive on all pages that will inherit from our base class or
Add the following line to the section of our web.config file:
That’s it, we have completed our base class which all our web forms will inherit from, allowing us to keep an eye on the users session. Now that we have the class completed we need to use it. Before it can be affected we need to do 1 of 2 things

Add EnableSessionState = true to the @Page directive on all pages that will inherit from our base class or
Add the following line to the section of our web.config file

Number 2 on that list will enable session state on all pages in the web. If you dont access session items in each of your pages, this might be overkill. Next we will need to inherit from our base class. Doing this will give our web form the following declaration

public partial class _Default : SessionCheck
{

}
Then in the Page_Load Event we will set the redirect URL for our base class

protected void Page_Load(object sender, EventArgs e)
{
SessionCheck.URL = "Default.aspx";
}
Now here is the entire base page in its entirety

// A Base Page class for detecting session time outs
//
// Copyright © 2008
// Richard L. McCutchen
// Created: 05MAR08
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see .
//*****************************************************************************************

using System;
using System.Web.UI;

///
/// This is a custom "base page" to inherit from which will be used
/// to check the session status. If the session has expired or is a timeout
/// we will redirect the user to the page we specify. In the page you use
/// to inherit this from you need to set EnableSessionState = True
///

public class SessionCheck : System.Web.UI.Page
{
///
/// property vcariable for the URL Property
///

private static string _redirectUrl;

///
/// property to hold the redirect url we will
/// use if the users session is expired or has
/// timed out.
///

public static string RedirectUrl
{
get { return _redirectUrl; }
set { _redirectUrl = value; }
}

public SessionCheck()
{
_redirectUrl = string.Empty;
}

override protected void OnInit(EventArgs e)
{
//initialize our base class (System.Web,UI.Page)
base.OnInit(e);
//check to see if the Session is null (doesnt exist)
if (Context.Session != null)
{
//check the IsNewSession value, this will tell us if the session has been reset.
//IsNewSession will also let us know if the users session has timed out
if (Session.IsNewSession)
{
//now we know it's a new session, so we check to see if a cookie is present
string cookie = Request.Headers["Cookie"];
//now we determine if there is a cookie does it contains what we're looking for
if ((null != cookie) && (cookie.IndexOf("ASP.NET_SessionId") >= 0))
{
//since it's a new session but a ASP.Net cookie exist we know
//the session has expired so we need to redirect them
Response.Redirect("Default.aspx?timeout=yes&success=no");
}
}
}
}
}
And there you have it, a custom base class that you can use to detect session timeouts. I hope you found this tutorial helpful and useful, and thank you for reading

Happy Coding!


-----------------------------------------------------------------------------------

GoDaddy, MySQL, iTextSharp and Shared Hosting Woes

Beginnings

In the summer of 2008, I volunteered to help out a local political organization Get Out The Vote this election year. There is an old saying that goes something along the lines of, “No good deed goes unpunished”

I wish I’d remembered that before I started all this!

NOTE:
I’ve prepared a Programmer’s Cheat Sheet of
how I resolved my issues. If you just need the answers,
click here.
But, if you’d like to read a good story, carry on!


Original Plans

The project involved creating a .NET based website that was to leverage some data stored in a MS SQL Database.

“Easy enough,” I thought at first. After all, I’ve been creating websites using these tools for several years now.

.NET provides several tools for interacting with a MS SQL Server database. I opted for the ADO.NET since they work well, and I have lots of experience using them. I managed to create my web application and database and imported all the raw data that we would need for the project. So far, so good.

We then purchased our shared Windows hosting account with GoDaddy.com (the same
company that is hosting this site). I have another site site using this exact same setup. This setup is working well and I’ve experienced no problems whatsoever. I uploaded the application and prepared to create and populate the database.

This is where things started to unravel.

Database Size

My database was large. The table that held the bulk of the data has over 500 thousand records. MS SQL Databases on the GoDaddy system can import records via CSV files (CSV files are “comma separated value” files; plain text files that can be used to represent a lost of data).

I tried to upload the large CSV file, but kept getting time-out errors using the standard web-based file upload process.

I then made the first of many unsuccessful calls to GoDaddy Tech Support. The techie on the other end of the line instructed me to upload a database backup into a special folder in my account’s file system. I uploaded the backup (over 500MB in size!) and then tried to initiate a restore of the database per the instructions in GoDaddy’s help system.

Shortly, after I had started the restore, I went back to check the progress, only to find that the restore had failed. The reason given was that a MS SQL Restore can only be performed using backup files that are created by the GoDaddy system. It seems that there is a MS Security bulletin out on this. But I guess that the Tech Support staff did not know this.

The second call to Tech Support taught me about the Database Publishing Wizard produced by Microsoft. I downloaded this wizard and began to publish my data.

This, too, failed.

It seems that there is a limit on the physical size of database available to Windows shared hosting accounts. The limit, it seems is 200MB. My main data table is over 200MB by itself. The problem, is that I was not made aware of this limitation at any point during the account creating process. And this limit was not visible on any of the sign up screens that I came across when setting up the account.

Another call to tech support informed me of the 200 MB limit. The Techie’s only solution was to transfer to a dedicated hosting account. Exept that because of the database size, we would need a full MS SQL license fo our site.

Did I mention that this work is for a non-profit organization?

So the dedicated hosting with a full MS SQL Server license was out of the question.

The tech support person informed me that there is no limit on the size of a MySQL database (actually there is, but it is the size of the actual account space; mutiple GBs).

Conversion to MySQL


After much cursing and swearing, I got down to the business of downloading and installing MySQL on my development laptop (as if I needed anything else slowing things down on my old laptop). I ran the Database import/conversion wizard and copied all my data into my brand spankin’ new MySQL datbabase. But, it seems, none of the stored procedures were duplicated.

I then exported my MS SQL stored procedures into a text based SQL file. I opened the text/sql file and tried to execute the SQL in MySQL only to find that there are significant differences in how MySQL interprets SQL, when compared to MS SQL.

So I had to re-write approximately 50 stored procedures, using MySQL syntax. Did I mention that I had not used MySQL before?

After I finished re-writing the stored procs, I then had to convert my web app to make use of the new data source. Fortuntately, I had all my database functions in a single file. Even better, there were only four functions that needed to be modified.

So I downloaded the MySQL ASP.NET database connector/DLL and rewrote my application. Initial testing identified about 6 places where I needed to “tweak” some code. And then voila it worked!!

So, I then created a database backup and uploaded the backup file (~250MB) to GoDaddy and then initiated a Restore operation. It eventually ran successfully. I ran some test using the MyPHPAdmin application. (MyPHPAdmin runs slower than molasses in winter on the GoDaddy servers, of course).

ASP.NET Login Controls

Because this application has restrictions on who has access to what, I wrote the application using the .NET login controls. They use a database to track users,
permissions, etc. But…. you will recall the we moved our database over to
MySQL.

Fortunately, GoDaddy allows you to have both a MS SQL Database and multiple
MySQL databases. So I then set about learning how to use a SQL database as my
Authentication provider’s backing store. Another two days later, and I was able to get the accounts logging in, resetting passwords, etc.

I then uploaded my application and tried to perform some of the tasks that this application was designed to do.

No go.

MySQL .NET Connector

The .NET connector that MySQL makes available requires “full trust” in order to run. But the shared hosting environment is a “medium trust” environment so the connection would not work. I downloaded a patch and recompiled the .NET connector so that it allows a medium trust application to use the connector.

So I uploaded the new connector’s DLL and executed some AdHoc queries. Success! Or so I thought. I then tried to use the application’s pages which called on some of my stored procedures (which I discussed above).

No go. Again.

The .NET connector now worked using ad hoc queries, but required admin rights in order to execute stored procedures. Obviously, GoDaddy was not about to give my account admin rights. So, all seemed lost. Again.

But, I then realized that I had been able to use AdHoc queries to call my stored procedures. So, I re-wrote my database access class to create SQL statements that get executed as AdHoc queries, and FINALLY, I was able to get the application to work as designed.

Well, not as designed, but as originally intended.

Almost…..

iTextSharp Library


I had originally designed my application to use Crystal Reports to generate PDF outputs. But (surprise!) GoDaddy does not make Crystal Reports available on their servers. So Crystal Reports is out.

I then found the iTextSharp library which can generate PDF files from C# code. But, the reports has to be created in code, not in a designer, as are the Crystal Reports outputs.

So five days of coding later, and I was able to generate my reports using the iTextSharp library. Almost…

When I first tried to create some reports I got an error telling me that I did not have permissions to write to my report output folder. I then tried deleting the folder and having the application create the folder. Still no-go.
Finally, I found the “Permission” page on the GoDaddy site and gave my output folder “Write” permissions. Good to go? Well, not quite.

When I next tried to run a report, I got error messages stating:
System.Security.SecurityException: That assembly does not allow partially trusted callers
in that ugly yellow colored window that we’ve all come to hate. After some deft Googling, I determined that the iTextSharp library would need to be re-compiled so that Partially-Trusted callers would be able to use the iTextSharp library.

So I then downloaded the source code, and re-compiled the library to allow Partially-Trusted callers.

Specifically, I modified the AssemblyInfo.cs file by adding these references and attribute:

using System.Security;
using System.Security.Permissions;
[assembly: AllowPartiallyTrustedCallers]
Once that new library was in place (and some API calls re-written in the report), I was
finally able to generate some PDFs.

Retrospective

This is where things stand today (September, 2008): I am generating data using a MySQL database, managing user accounts using MS SQL, and producing reports using the iTextSharp library.

Would I do it again? No. There are other hosting providers that would allow me to host my large database and use Crystal Reports to produce my output. But they cost considerably more that what we are paying for GoDaddy hosting.

So… since this website is for a non-profit organization we’re here to stay.

I don’t know if anyone will read this. But if you have any questions just drop me a note.


-------------------------------------------------------------------------------------
4 Responses to GoDaddy, MySQL, iTextSharp and Shared Hosting Woes
Regan Rispoli says:
January 17, 2011 at 00:12
This blog seems to recieve a great deal of visitors. How do you promote it? It offers a nice individual spin on things. I guess having something real or substantial to talk about is the most important factor.

-------------------------------------------------------------------------------------
Reply
Kevin Olson says:
January 12, 2011 at 22:44
I was having this exact problem with GoDaddy and itextsharp. I downloaded the source code and made the modification to the AssemblyInfo.cs file.

I just installed the updated itextsharp.dll file and now my site works perfectly.

Thank you so much for this simple, yet completely effective, solution. I would have floundered-around for days searching for a solution – with no guarantee for success – were it not for you.

Well done!


-------------------------------------------------------------------------------------
Reply
darts says:
January 12, 2011 at 19:33
I don’t even know how I ended up here, but I thought this post was good. Cheers!

-------------------------------------------------------------------------------------
Reply
Touseef Ahmad Rehan says:
January 4, 2011 at 03:19
Excellent Article.. I spent almost two days to resolve the problem while writing pdf files. I was having same problem “System.Security.SecurityException: That assembly does not allow partially trusted callers”. I tried different ways but of no use. Later on i found your article while searching and tried the method you explained. Thankfully it worked…!

Touseef
Reply

-------------------------------------------------------------------------------------
Full Post is below ::

DataGrid to PDF Export With proper Allignment.

Q. Query asked by one of the Programmer to Techies...?

I have a DataGrid on my Aspx page which will be bound with data during run time [from various functions consisting of different queries]. I am trying to export the data grid to a PDF using iTextSharp.dll [Version 4.0]. I am able to export but the alignment is not proper. My code looks like this:

protected void imgExportToPDF_Click(object sender, ImageClickEventArgs e)
{
try
{
HtmlForm form = new HtmlForm();
form.Controls.Add(DataGrid1);
StringWriter sw = new StringWriter();
HtmlTextWriter hTextWriter = new HtmlTextWriter(sw);
form.Controls[0].RenderControl(hTextWriter);
string html = sw.ToString();
Document Doc = new Document();

string reportName = DropDownList1..SelectedItem.Text;

//PdfWriter.GetInstance
//(Doc, new FileStream(Request.PhysicalApplicationPath
//+ "\\AmitJain.pdf", FileMode.Create));

PdfWriter.GetInstance(Doc, new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + reportName + ".pdf", FileMode.Create));
Doc.Open();



Chunk c = new Chunk(reportName + " Report \n\n", FontFactory.GetFont("Verdana", 15, iTextSharp.text.Color.BLUE));
Paragraph p = new Paragraph();
p.Alignment = Element.ALIGN_CENTER;
p.Add(c);

if (txtFromDate.Text != "" || txtToDate.Text != "")
{
Chunk chunk1 = new Chunk("Report Generated For Dates Bestween:" + txtFromDate.Text + " And " + txtToDate.Text + " Report Generated On:" + System.DateTime.Now.ToString(), FontFactory.GetFont("Verdana", 8, iTextSharp.text.Color.DARK_GRAY));
Paragraph p1 = new Paragraph();
p1.Alignment = Element.ALIGN_CENTER;
p1.Add(chunk1);
Doc.Add(p);
Doc.Add(p1);
}
else
{
Chunk chunk2 = new Chunk("Report Generated On:" + System.DateTime.Now.ToString(), FontFactory.GetFont("Verdana", 8, iTextSharp.text.Color.ORANGE));
Paragraph p2 = new Paragraph();
p2.Alignment = Element.ALIGN_CENTER;
p2.Add(chunk2);
Doc.Add(p);
Doc.Add(p2);
}


System.Xml.XmlTextReader xmlReader = new System.Xml.XmlTextReader(new StringReader(html));
HtmlParser.Parse(Doc, xmlReader);

Doc.Close();
string Path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + reportName + ".pdf";


ShowPdf(Path);



}
catch (Exception ex)
{
throw ex;
}



}

private void ShowPdf(string strS)
{
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition","attachment; filename=" + strS);
Response.TransmitFile(strS);
Response.End();
//Response.WriteFile(strS);
Response.Flush();
Response.Clear();

}

Kindly help with this issue...

Thanks in advance.
Sathya


---------------------------------------------------------
re: DataGrid to PDF Export With proper Allignment.
Nowshad M replied to Sathya on 29-Nov-10 04:52 AM
Hi,
Build your Headers and rows of PDF like this

public PdfPTable BuildRows(PdfPTable pdfTable, params string[] rowValues)
{
try
{
for (int count = 0; count < rowValues.Length; count++)
{
PdfPCell cel;
if (rowValues[count]+"" != "Fail")
cel = new PdfPCell(new Phrase(rowValues[count].ToString(), new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 9f, (int)System.Drawing.FontStyle.Regular, new iTextSharp.text.Color(System.Drawing.Color.Black))));
else
cel = new PdfPCell(new Phrase(rowValues[count].ToString(), new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 9f, (int)System.Drawing.FontStyle.Regular, new iTextSharp.text.Color(System.Drawing.Color.Red))));
cel.PaddingLeft = 10f;
cel.PaddingBottom = 4f;
cel.BorderColor = new iTextSharp.text.Color(229, 229, 229);
cel.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
pdfTable.AddCell(cel);
}
return pdfTable;
}
catch (Exception ex)
{
return pdfTable;
}
}
public void BuildPdfHeaders(PdfPTable pdfTable, string reportHeading, string reportSubHeading,int colCount, params string[] headerValues)
{
try
{
PdfPCell dateCell = new PdfPCell(new Phrase("Date : " + DateTime.Now.Date.ToString("dd/MM/yyyy") + "", new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 8f, (int)System.Drawing.FontStyle.Regular, new iTextSharp.text.Color(System.Drawing.Color.Black))));
dateCell.PaddingTop = 10f;
dateCell.Colspan = colCount;
dateCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
dateCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
pdfTable.AddCell(dateCell);
PdfPCell reportHeader = new PdfPCell(new Phrase(reportHeading, new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 12f, (int)System.Drawing.FontStyle.Bold, new iTextSharp.text.Color(System.Drawing.Color.Black))));
reportHeader.PaddingTop = 0f;
reportHeader.Colspan = colCount;
reportHeader.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
reportHeader.Border = iTextSharp.text.Rectangle.NO_BORDER;
pdfTable.AddCell(reportHeader);
PdfPCell subHeader = new PdfPCell(new Phrase(reportSubHeading, new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 8f, (int)System.Drawing.FontStyle.Italic, new iTextSharp.text.Color(System.Drawing.Color.Black))));
subHeader.PaddingBottom = 10f;
subHeader.Colspan = colCount;
subHeader.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
subHeader.Border = iTextSharp.text.Rectangle.NO_BORDER;
pdfTable.AddCell(subHeader);
for (int emptyCount = 0; emptyCount < colCount*2; emptyCount++)
{
PdfPCell emptyCel = new PdfPCell(new Phrase(""));
emptyCel.PaddingBottom = 10f;
emptyCel.Border = iTextSharp.text.Rectangle.NO_BORDER;
pdfTable.AddCell(emptyCel);
}
for (int count = 0; count < headerValues.Length; count++)
{
PdfPCell header = new PdfPCell(new Phrase(headerValues[count].ToString(), new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 10f, (int)System.Drawing.FontStyle.Regular, new iTextSharp.text.Color(System.Drawing.Color.Black))));
header.PaddingBottom = 5f;
header.BorderColor = new iTextSharp.text.Color(229, 229, 229);
header.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
header.BackgroundColor = new iTextSharp.text.Color(242, 242, 242);
pdfTable.AddCell(header);
}
}
catch (Exception ex)
{
throw ex;
}
}

---------------------------------------------------------

Reply

re: DataGrid to PDF Export With proper Allignment.
Nowshad M replied to Sathya on 29-Nov-10 04:58 AM
Hi,
Find the below code also

public void CreatePdfTable(out iTextSharp.text.Document pdfDoc, out string path, out PdfPTable pdfTable, int colCount, string fileName)

{

string deletePath = HttpContext.Current.Server.MapPath("~/PDF");

if (Directory.Exists(deletePath))

{

string[] files = Directory.GetFiles(deletePath);

foreach (string file in files)

{

File.Delete(file);

}

}



pdfDoc = new iTextSharp.text.Document();

path = HttpContext.Current.Server.MapPath("~/PDF\\" + fileName + ".pdf");

iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, new FileStream(path, FileMode.Create));

pdfTable = new PdfPTable(colCount);

pdfTable.WidthPercentage = 100.0f;

HeaderFooter footer = new HeaderFooter(new Phrase(""), false);

footer.Border = 0;

pdfDoc.Footer = footer;

footer.Alignment = HeaderFooter.ALIGN_CENTER;

}



You should make function call like below in the button click



protected void btnExportPdf_Click(object sender, ImageClickEventArgs e)

{

try

{

grvCountryReport.AllowPaging = false;

grvCountryReport.DataSource = objDA.GetCountryDetails();

grvCountryReport.DataBind();

int rowCount = grvCountryReport.Rows.Count;

int colCount = grvCountryReport.Columns.Count;

iTextSharp.text.Document pdfDoc;

string path;

PdfPTable pdfTable;

objLib.CreatePdfTable(out pdfDoc, out path, out pdfTable, colCount, "Country Details Report");



pdfDoc.Open();

objLib.BuildPdfGridHeaders(pdfTable, "Country Details Report", "This shows a detailed country report", colCount, "Country Name");

BuildPdfGridRows(rowCount, pdfDoc, pdfTable);

pdfDoc.Add(pdfTable);

pdfDoc.Close();

objLib.Exportpdf(path, "Country Details Report");



if (!ClientScript.IsStartupScriptRegistered("alert"))

{



Page.ClientScript.RegisterStartupScript



(this.GetType(), "alert", "viewmaskpanelReport();", true);



}

}

catch (Exception ex)

{



}



}



-------------------------------------------------------------------
Reply

re: DataGrid to PDF Export With proper Allignment.
Sathya replied to Nowshad M on 29-Nov-10 05:12 AM
Wow.. Thanks a lot for your Immediate Response Dear Nowshad,

Can u please post the definition for the function ExportPDF that you have mentioned above...?

Will adopt everything and get back to you

Thanks and Regards,
Sathya
Reply

re: DataGrid to PDF Export With proper Allignment.
Nowshad M replied to Sathya on 29-Nov-10 05:15 AM
Hi,
Find the Export PDF function as below

public void Exportpdf(string path, string fileName)
{
try
{
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".pdf");
HttpContext.Current.Response.TransmitFile(path);
HttpContext.Current.Response.End();
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Clear();
}
catch (Exception ex)
{
}
}

Hope this helps


---------------------------------------------------------

Reply

re: DataGrid to PDF Export With proper Allignment.
Sathya replied to Nowshad M on 29-Nov-10 05:28 AM
I am sure its gonna help a lot Nowshad,

Are these functions and their definitions same..?

BuildPdfGridHeaders as BuildPdfHeaders? and BuildPdfGridRows is same as BuildRows? because they have different parameters...

If they are different kindly post it here as I can see that your code is absolutely fantabulous...

---------------------------------------------------------

Reply

re: DataGrid to PDF Export With proper Allignment.
Nowshad M replied to Sathya on 29-Nov-10 05:31 AM
Hi,
Please find the full length of code an dlet me know the results

public void CreatePdfTable(out iTextSharp.text.Document pdfDoc, out string path, out PdfPTable pdfTable, int colCount, string fileName)
{
string deletePath = HttpContext.Current.Server.MapPath("~/PDF");
if (Directory.Exists(deletePath))
{
string[] files = Directory.GetFiles(deletePath);
foreach (string file in files)
{
File.Delete(file);
}
}

pdfDoc = new iTextSharp.text.Document();
path = HttpContext.Current.Server.MapPath("~/PDF\\" + fileName + ".pdf");
iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, new FileStream(path, FileMode.Create));
pdfTable = new PdfPTable(colCount);
pdfTable.WidthPercentage = 100.0f;
HeaderFooter footer = new HeaderFooter(new Phrase(""), false);
footer.Border = 0;
pdfDoc.Footer = footer;
footer.Alignment = HeaderFooter.ALIGN_CENTER;
}

public void BuildPdfGridHeaders(PdfPTable pdfTable, string reportHeading, string reportSubHeading,int colCount, params string[] headerValues)
{
try
{
PdfPCell dateCell = new PdfPCell(new Phrase("Date : " + DateTime.Now.Date.ToString("dd/MM/yyyy") + "", new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 8f, (int)System.Drawing.FontStyle.Regular, new iTextSharp.text.Color(System.Drawing.Color.Black))));
dateCell.PaddingTop = 10f;
dateCell.Colspan = colCount;
dateCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
dateCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
pdfTable.AddCell(dateCell);

PdfPCell reportHeader = new PdfPCell(new Phrase(reportHeading, new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 12f, (int)System.Drawing.FontStyle.Bold, new iTextSharp.text.Color(System.Drawing.Color.Black))));
reportHeader.PaddingTop = 0f;
reportHeader.Colspan = colCount;
reportHeader.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
reportHeader.Border = iTextSharp.text.Rectangle.NO_BORDER;
pdfTable.AddCell(reportHeader);

PdfPCell subHeader = new PdfPCell(new Phrase(reportSubHeading, new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 8f, (int)System.Drawing.FontStyle.Italic, new iTextSharp.text.Color(System.Drawing.Color.Black))));
subHeader.PaddingBottom = 10f;
subHeader.Colspan = colCount;
subHeader.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
subHeader.Border = iTextSharp.text.Rectangle.NO_BORDER;
pdfTable.AddCell(subHeader);

for (int emptyCount = 0; emptyCount < colCount*2; emptyCount++)
{
PdfPCell emptyCel = new PdfPCell(new Phrase(""));
emptyCel.PaddingBottom = 10f;
emptyCel.Border = iTextSharp.text.Rectangle.NO_BORDER;
pdfTable.AddCell(emptyCel);
}


for (int count = 0; count < headerValues.Length; count++)
{
PdfPCell header = new PdfPCell(new Phrase(headerValues[count].ToString(), new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 10f, (int)System.Drawing.FontStyle.Regular, new iTextSharp.text.Color(System.Drawing.Color.Black))));
header.PaddingBottom = 5f;
header.BorderColor = new iTextSharp.text.Color(229, 229, 229);
header.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
header.BackgroundColor = new iTextSharp.text.Color(242, 242, 242);
pdfTable.AddCell(header);
}
}
catch (Exception ex)
{
throw ex;
}
}

private void BuildPdfGridRows(int rowCount, iTextSharp.text.Document pdfDoc, PdfPTable pdfTable)
{
try
{
for (int rCount = 0; rCount < rowCount; rCount++)
{

Label CountryName = (Label)grvCountryReport.Rows[rCount].FindControl("lblCountryName");
pdfTable = objLib.BuildPdfGridRows(pdfTable, CountryName.Text);
}
}
catch (Exception ex)
{
throw ex;
}
}


---------------------------------------------------------

Reply

re: DataGrid to PDF Export With proper Allignment.
Sathya replied to Nowshad M on 29-Nov-10 07:06 AM
Dear Nawshad,

Your code is really superb and working fine for a test case. However I need one more help. in the code give by you,

private void BuildPdfGridRows(int rowCount, iTextSharp.text.Document pdfDoc, PdfPTable pdfTable)
{
try
{
for (int rCount = 0; rCount < rowCount; rCount++)
{

(Label)DataGrid1.Items[rCount].FindControl("lblCountryName");
pdfTable = BuildRows(pdfTable, cboPerformanceType.SelectedItem.Text);
}
}
catch (Exception ex)
{
throw ex;
}
}

You are using a "lblCountryName" in the DataGrid's find control attribute. However my DataGrid is a Dynamic one and Doesnt contain any templateColumns. All are dynamic data generated during run time [As I am using Same DataGrid as common datagrid to bind data executed by dynamic queries]...

So what would be the best alternative for the above function definition.

Eagerly awaiting your response.

Thanks and Regards,
Sathya


---------------------------------------------------------
Reply

re: DataGrid to PDF Export With proper Allignment.
Nowshad M provided a helpful reply to Sathya on 29-Nov-10 07:20 AM
Hi,
For that u need changes in two functions as below

private void BuildPdfGridRows(int rowCount, iTextSharp.text.Document pdfDoc, PdfPTable pdfTable)
{
try
{
for (int rCount = 0; rCount < rowCount; rCount++)
{
string[] text = new string[grvCountry.Columns.Count];
for (int cCount = 0; cCount < grvCountry.Columns.Count; cCount++)
{
if (cCount == 0)
text[cCount] = grvCountryReport.Rows[rCount].Cells[cCount].Text;
else
text[cCount] = "," + grvCountryReport.Rows[rCount].Cells[cCount].Text;
}
pdfTable = objLib.BuildPdfGridRows(pdfTable, text);
}
}
catch (Exception ex)
{

}
}

public PdfPTable BuildPdfGridRows(PdfPTable pdfTable, string[] rowValues)
{
try
{
for (int count = 0; count < rowValues.Length; count++)
{
PdfPCell cel = new PdfPCell(new Phrase(rowValues[count].ToString(), new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 9f, (int)System.Drawing.FontStyle.Regular, new iTextSharp.text.Color(System.Drawing.Color.Black))));
cel.PaddingLeft = 10f;
cel.PaddingBottom = 4f;

cel.BorderColor = new iTextSharp.text.Color(229, 229, 229);
cel.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
pdfTable.AddCell(cel);

}
return pdfTable;
}
catch (Exception ex)
{

return pdfTable;
}
}


---------------------------------------------------------
Reply

re: DataGrid to PDF Export With proper Allignment.
Sathya replied to Nowshad M on 29-Nov-10 08:49 AM
Hey Dear Nawshad,

You know what... It perfectly worked for me dear.. Thanks a lot...

However each cell is separated by a comma. I think I will do some RnD get it sorted to ensure, like entire datagrid is printed on to PDF...

Let me also know in future if you have any better ideas for the same..

But Really really thank you for your timely and valuable response.

You helped me a lot

Thanks and Regards,
Sathya
Reply



-------------------------------------------------------------------------------------
Full Post is below ::

Tuesday, January 25, 2011

Add an Image to pdf document using ItextSharp

In this article we will show how to add Image in pdf document using Itextsharp in asp.net. For some report which is in pdf format we need to add image .jpg, .gif, .bmp or any image format.
Itextsharp is an open source free pdf generate library which will generate the pdf and yes you can add the image into it.

you can also refer to my articles on ItextSharp in asp.net here to create table in pdf doc here

Step 1 : Download the ITextsharp library from here.

Step 2 : Add Itextsharp.dll to your project by right click and add reference on the project explorer

Step 3 : Now add the Namespace to your .cs or .vb file


using iTextSharp.text;
using iTextSharp.text.pdf;




Step 4 :

Lets see this code which will be place image into PDF document


// Now image in the pdf file
string imageFilePath = Server.MapPath(".") + "/image/Sunset.jpg";
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath);

//Resize image depend upon your need
jpg.ScaleToFit(280f, 260f);

//Give space before image
jpg.SpacingBefore = 30f;

//Give some space after the image
jpg.SpacingAfter = 1f;
jpg.Alignment = Element.ALIGN_CENTER;

doc.Add(paragraph); // add paragraph to the document

doc.Add(jpg); //add an image to the created pdf document



Now to see full code you can place the below code in any event like on button click

In C# sample code function:

private void CreatePDFFile()
{
Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
try
{
string pdfFilePath = Server.MapPath(".") + "/pdf/myPdf.pdf";

//Create Document class object and set its size to letter and give space left, right, Top, Bottom Margin
PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(pdfFilePath, FileMode.Create));
doc.Open();//Open Document to write

//Write some content into pdf file
Paragraph paragraph = new Paragraph("This is my first line using Paragraph.");

// Now image in the pdf file
string imageFilePath = Server.MapPath(".") + "/image/Sunset.jpg";
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath);

//Resize image depend upon your need
jpg.ScaleToFit(280f, 260f);

//Give space before image
jpg.SpacingBefore = 30f;

//Give some space after the image
jpg.SpacingAfter = 1f;
jpg.Alignment = Element.ALIGN_CENTER;

doc.Add(paragraph); // add paragraph to the document

doc.Add(jpg); //add an image to the created pdf document
}
catch (DocumentException docEx)
{
//handle pdf document exception if any
}
catch (IOException ioEx)
{
// handle IO exception
}
catch (Exception ex)
{
// ahndle other exception if occurs
}
finally
{
//Close document and writer
doc.Close();

}
}



Same above code vb.net method:

Private Sub CreatePDFFile()
Dim doc As New Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35)
Try
Dim pdfFilePath As String = Server.MapPath(".") & "/pdf/myPdf.pdf"

'Create Document class object and set its size to letter and give space left, right, Top, Bottom Margin
Dim wri As PdfWriter = PdfWriter.GetInstance(doc, New FileStream(pdfFilePath, FileMode.Create))
doc.Open()
'Open Document to write
'Write some content into pdf file
Dim paragraph As New Paragraph("This is my first line using Paragraph.")

' Now image in the pdf file
Dim imageFilePath As String = Server.MapPath(".") & "/image/Sunset.jpg"
Dim jpg As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(imageFilePath)

'Resize image depend upon your need
jpg.ScaleToFit(280F, 260F)

'Give space before image
jpg.SpacingBefore = 30F

'Give some space after the image
jpg.SpacingAfter = 1F
jpg.Alignment = Element.ALIGN_CENTER

doc.Add(paragraph)
' add paragraph to the document
'add an image to the created pdf document
doc.Add(jpg)
Catch docEx As DocumentException
'handle pdf document exception if any
Catch ioEx As IOException
' handle IO exception
Catch ex As Exception
' ahndle other exception if occurs
Finally
'Close document and writer

doc.Close()
End Try
End Sub



If you run your application you can see the image in pdf document like this:




Hope this will help all!



Thank You for your valuable time.

Irfan Ahmad alias (Isfan Habib)
(Team Lead)
DZ International
Srinagar, Kashmir
e-mail: irfanhabib06@gmail.com

Monday, January 24, 2011

Visual Studio / SQL Server Unable to open database / Operating systerm Error 5

Operating systerm Error 5 usually means not enough permission.

Make sure account under which SQL server service is runing has modify permission on the folder where you have kept your MDF File.

Not account under you are logged in Windows (does not matter you have permission; it is the SQL server service account that needs permission)

•Right click on the folder D:\Development Workx\Hamza Workingx\hamriqueweb_1_Edited_ALi2\App_Data and click on properties
•Click on security tab
•Click on Add button and add sql service account
•Provide modify privilege and click ok
•Verify both mdf and ldf have modify privilege
•Attach the db