Caching Locally

One of the applications I have been working recently is a windows based application. Most things that the user keys into the system results in a database hit validation. To cut back on this I have implemented classes that assist in caching to the user’s local system. Based on the user’s habits, it will cache what the user uses commonly.

I am using a datatable in this example, but you could use a dictionary object. Should you choose to use a dictionary object, you could use LINQ to query the object. You could also make the caching class an extension which could cut down on some code an make it a little cleaner.

At the end of the day, this is one example only of what could be done.

Class Example

public class CurrencyCodes
private static CurrencyCodes _instance; // Instance Of Self

private static DataTable dt = new DataTable("CurrencyCodes");

public static CurrencyCodes Instance
{
get
{
if (_instance == null)
{
_instance = new CurrencyCodes();
}
return _instance;
}
}

private CurrencyCodes()
{
dt.Columns.Add("CurrencyCode", typeof(String));
dt.Columns.Add("LastUpdated", typeof(DateTime));
}

public String Search(String value)
{
DataRow[] rows = dt.Select("CurrencyCode='" + value + "'");
if (rows.Count() == 1) return value;
return "";
}

public void Add(String value)
{
DataRow row = dt.NewRow();
row["CurrencyCode"] = value;
row["LastUpdated"] = DateTime.Now;
dt.Rows.Add(row);
}

public void ClearCache()
{
dt.Rows.Clear();
}

public void LoadCache(String xml)
{
StringReader theReader = new StringReader(xml);
dt.ReadXml(theReader);
}

public String SaveCache()
{
using (MemoryStream ms = new MemoryStream())
{
dt.WriteXml(ms);
ms.Position = 0;

StreamReader sr = new StreamReader(ms, System.Text.Encoding.UTF8);

return sr.ReadToEnd();
}
}
}

Calling the class

Directory.SetCurrentDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
if (!Directory.Exists("YourSoftwareCache"))
{
Directory.CreateDirectory("YourSoftwareCache");
}

if (File.Exists("CurrencyCodes.XML"))
CurrencyCodes.Instance.LoadCache(File.ReadAllText("CurrencyCodes.XML"));

CachedCurrencyCodes cachedCurrencyCodes = CachedCurrencyCodes.Instance;
CurrencyCode = cachedCurrencyCodes.Search(Criteria);

Note Comments have been stripped to clean up the posting. Always Comment Your Code.

Converting a PDF to Excel

Converting a PDF to Excel using InvestInTech.com’s PDF to Excel SDK.

PDF Sharp and other SDKs had the ability to read text from a PDF; however, I had found that InvestInTech’s PDF to Excel kept data in grid form.
This made it easier to use OLEDB to query the excel and strip the data as needed. I had tried InvestInTech’s XML conversion, but it did not have the same clean results.

Here is a sample of how I had accomplished the conversion.

String name = Path.GetFileNameWithoutExtension(filename);
String directory = @"C:temp";

String[] files = Directory.GetFiles(directory);

Int32 iCount = 0;
foreach (String file in files)
{
iCount++;
toolStripStatusLabel2.Text = " - Converting PDF to Excel File# " + iCount + " of " + files.Count();
Application.DoEvents();

CPDF2ExcelClass pdf2Excel = new CPDF2ExcelClass();
IPDF2Excel iPDF2Excel = pdf2Excel;

iPDF2Excel.PDF2Excel(file, file.Replace(".pdf", ".xls"));

toolStripStatusLabel2.Text = " - Converting PDF to Tiff File# " + iCount + " of " + files.Count();
Application.DoEvents();
ConvertPDFToTiff(file);

File.Delete(file);
}

How To Split A PDF Using PdfSharp

I recently completed a project which broker a PDF file into multiple files from which I converted to a MS Excel file and ultimately processed the data into a database.

This segment is dealing with the portion for splitting a multi-page Adobe PDF file into multiple pages. I mostly do this step, because we will be storing the individual page into a document management system along with the data that we strip from it. This page will be used later by our data entry clerks.

When breaking down to individual pages, we need to ensure that we keep the integrity of the original page. This ensures we can still convert to an Excel file to get the data from it.

There are many open-source and free PDF SDK kits that you can try. I had best luck doing most any PDF work using PdfSharp ( http://pdfsharp.com/PDFsharp/ ). Here is a modified code segment of how you can use PdfSharp to split.

Int32 iCount = 0;

PdfDocument inputDocument = PdfReader.Open(filename, PdfDocumentOpenMode.Import);
String directory = @"C:temp";
string name = Path.GetFileNameWithoutExtension(filename);
for (int idx = 0; idx < inputDocument.PageCount; idx++)
{
iCount++;
toolStripStatusLabel2.Text = " - Processing File# " + iCount + " of " + inputDocument.PageCount;
Application.DoEvents();

// Create new document
PdfDocument outputDocument = new PdfDocument();
outputDocument.Version = inputDocument.Version;
outputDocument.Info.Title = String.Format("Page {0} of {1}", idx + 1, inputDocument.Info.Title);
outputDocument.Info.Creator = inputDocument.Info.Creator;

// Add the page and save it
outputDocument.AddPage(inputDocument.Pages[idx]);
outputDocument.Save(Path.Combine(directory , String.Format("{0} - Page {1}.pdf", name, idx + 1)));
}

Using LINQ to find a control in the ControlCollection

While writing a windows application in C#, I realized that there was no find control method in the ControlCollection class. This was a problem as it would create a significant amount of code to find a control. Well it turns out you can do it using LINQ. I had found a blog that I was able to implement the code fairly cleanly. The original code limited me a little bit, but with a very minor modification I came up with this code.

Original Blog: linq-the-uber-findcontrol

public static class PageExtensions
{
public static IEnumerable All(this Control.ControlCollection controls)
{
foreach (Control control in controls)
{
if (control.HasChildren)
{
foreach (Control child in control.Controls.All())
{
yield return child;
}
}
else
{
yield return control;
}
}
}
}

private Control GetControlByName(string name)
{
Control firstEmpty = this.Controls.All()
.OfType()
.Where(tb => tb.Name.Trim().Equals(name))
.FirstOrDefault();
return firstEmpty;
}

Posting Data From HTML to ASPX

Recently I had a need to have a web site post credentials to another web site.   The first site was standard HTML and the second site was DotNet (ASP.NET).

In this example, we will be passing a user name and password to another site.

Sending Web Site
In your sending website, you will need a log in  panel similar to the one below.

    






Receiving Web Site
In the form load of your DotNet (ASP.NET) site, you will need the following code to get the values from the request object and then pass to your log in routine.

                NameValueCollection nvc = Request.Form;
string userName = "";
string password = "";
if (!string.IsNullOrEmpty(nvc["txtUserName"]))
{
userName = nvc["txtUserName"];
}

if (!string.IsNullOrEmpty(nvc["txtPassword"]))
{
password = nvc["txtPassword"];
}

ExecuteLogin(userName, password);

DotNet Windows Form Image Transparency

Recently during a project I had a need to overlay an image on a windows form in order to indicate a status of inability.  This image had a semi-transparency quality as well as a full transparency background.  To my dismay, the semi-transparency rendered in full color and the full transparency background seemed to inherit the parent form, but not show the controls behind it as one would expect.

After sometime of researching the issue, I came to a determination that what I was trying to do could only be done in web development (HTML).  From my research I had assembled some ideas in how to make transparencies work.   I took ideas from several sources and came up with the following.

Step By Step ( see Sample Code )

1. Create a class that extends System.Windows.Forms.Control
2. Place code from sample cod
3. Compile Project
4. Add new control to the Form ( remember this is for a windows application )
5. Set Background Image

Sample Code


protected override CreateParams CreateParams
{
     // Make window transparent
     get
     {
          CreateParams cp = base.CreateParams;
          cp.ExStyle |= 0x20;  // WS_EX_TRANSPARENT return cp;
     }
}

protected override void OnPaintBackground(PaintEventArgs pevent)
{
// Do not paint the background
}

protected override void OnPaint(PaintEventArgs e)
{ 
     // Paint background image 
     if (BackgroundImage != null)
     {
          Bitmap bmp = new Bitmap(BackgroundImage);
          bmp.MakeTransparent(Color.White);
          e.Graphics.DrawImage(bmp, 0, 0, Width, Height);
     }
}

Note:  When you overlay an image – even transparent, you may see the controls behind, but you will not be able to access them.  This is true in both web and windows development.