Sandip's Programming Zen

An attempt to share tech/coding experiences

Posts Tagged ‘C#

A Basic SQLite DAL class in C#

leave a comment »

 

You have to first download ADO.Net provider for SQLite from here and use it’s reference in your project.

The class has enough functions for basic DAL operations but you are free to enhance it as per your need.

public static class SqliteDal
{
    public static string cnstr = "Data Source =" + "yourdb.db3";

    /// <summary>
    /// Returns datatbale for given sql query.
    /// </summary>
    /// <param name="sql"></param>
    /// <returns></returns>
    public static DataTable getData(string sql)
    {
        SQLiteConnection cn = new SQLiteConnection(cnstr);
        cn.Open();

        try
        {
            SQLiteCommand cm = new SQLiteCommand(sql, cn);
            SQLiteDataReader dr = cm.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Load(dr);
            cn.Close();

            return dt;
        }
        catch (Exception ex)
        {
            cn.Close();
            throw ex;
        }
    }

    /// <summary>
    /// Returns count of executed insert, update, delete statement.
    /// </summary>
    /// <param name="sql"></param>
    /// <returns></returns>
    public static int execNQ(string sql)
    {
        SQLiteConnection cn = new SQLiteConnection(cnstr);
        cn.Open();
        SQLiteCommand cm = new SQLiteCommand(sql, cn);
        int rows;
        rows = cm.ExecuteNonQuery();
        cn.Close();
        return rows;
    }

    /// <summary>
    /// Returns scalar for given sql query.
    /// </summary>
    /// <param name="sql"></param>
    /// <returns></returns>
    public static object execSC(string sql)
    {
        SQLiteConnection cn = new SQLiteConnection(cnstr);
        cn.Open();
        SQLiteCommand cm = new SQLiteCommand(sql, cn);
        object rows;
        rows = cm.ExecuteScalar();
        cn.Close();
        if (rows == null)
        {
            rows = 0;
        }
        return rows;
    }

}

Advertisements

Written by Sandip

April 6, 2010 at 8:51 am

Posted in .Net

Tagged with ,

Convert scanned pdf into image in C#

leave a comment »

I needed to convert scanned pdf into any image format so that I can run OCR operation for one of the DMS solutions I am working on. Actually I am using Tesseract (Open source OCR solution from Google) for OCR and it only takes image format as input. After spending few hours searching and trying few solution I zeroed in on this codeproject article which is making use of Ghostscript to achieve the core functionality.
So far this is the only solution I think works seamlessly on most windows platforms including Win7 (already tested on XP, Win2003, Win7).

Written by Sandip

March 23, 2010 at 7:16 am

Posted in .Net

Tagged with , , ,

C#: Accessing resources on network

leave a comment »

Accessing files and other resources on network from within code is achieved in following way in C# (of course there are other ways but this seems neat):

Take following assembly reference first:

using System.Runtime.InteropServices;

[DllImport(“advapi32.dll”, SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

Private void YourFunction()

{

WindowsImpersonationContext wic;
IntPtr tokenHandle = new IntPtr(0);
bool returnValue = LogonUser(f.cUserName, f.cDomain, f.cPassword, 2, 0, ref tokenHandle);
WindowsIdentity ImpersonatedIdentity = new WindowsIdentity(tokenHandle);
WindowsImpersonationContext MyImpersonation = ImpersonatedIdentity.Impersonate();

wic = MyImpersonation;

// do some file IO activity here on server…

wic.Undo();

}

Written by Sandip

March 15, 2010 at 1:16 pm

Posted in .Net, Programming

Tagged with , ,

C# MP3 files organizer

leave a comment »

I have a huge collection of mp3 music files and locating music was bit difficult if I would like to hear a particular artist, I quickly tried to search on google , found some programs but unnecessarily complex, so I wrote my own , which is very simple.  it does following:

  • Asks for a target directory where your mp3 files are located.
  • On click of a button it extracts the meta info and organizes the files in folders per artist.

It’s very basic but useful to me at least. you are free to modify/use/distribute at your own risk 🙂

Download it from here.

Written by Sandip

March 15, 2010 at 1:07 pm

Posted in .Net, Programming

Tagged with ,

Retrieve compilation date of a .Net Assembly

leave a comment »

I wanted to display last update date on the application interface so users know when something is changed, mostly at the time of customer acceptance tests. I found following code from here. cool.

private DateTime DateCompiled()
{
    // The assembly version must have the last two numbers removed and replaced with *
    // It should look something like this: 
    // [assembly: AssemblyVersion("1.0.*")]
 
    //Build dates start from 01/01/2000
    System.DateTime result = DateTime.Parse("1/1/2000");
 
    //Retrieve the version information from the assembly from which this code is being executed
    System.Version version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
 
    //Add the number of days (build)
    result = result.AddDays(version.Build);
 
    //Add the number of seconds since midnight (revision) multiplied by 2
    result = result.AddSeconds(version.Revision * 2);
 
    //If we're currently in daylight saving time add an extra hour
    if (TimeZone.IsDaylightSavingTime(System.DateTime.Now, 
        TimeZone.CurrentTimeZone.GetDaylightChanges(System.DateTime.Now.Year))) 
    { 
        result = result.AddHours(1); 
    }
 
    return result;
}

Written by Sandip

February 16, 2010 at 11:11 am

Posted in .Net, Asp.Net, Programming

Tagged with ,

C# Winforms: Sending an email with attachment

leave a comment »

Sending an email from C# winforms application is exactly same as we do in webapps using System.Net.Mail namespace. Here is a sample code which sends out an email with an attachment (again it is not specific to winforms can be used in webapps as it is).

MailMessage msg = new MailMessage();
SmtpClient client;
Attachment attach = new Attachment(filepath);

if (varEmailID.IndexOf(',') > 0)
{
    string[] iDs;
    iDs = varEmailID.Split(',');
    for (int i = 0; i <= iDs.Length - 1; i++)
    {
        msg.To.Add(new MailAddress(iDs.GetValue(i).ToString()));
    }
}
else
{
    msg.To.Add(new MailAddress(varEmailID));
}

msg.Attachments.Add(attach);
msg.Subject = varSubject;
msg.Body = varBody;
msg.IsBodyHtml = false;
msg.Priority = MailPriority.Normal;

string FromEmail = ConfigurationSettings.AppSettings["SystemMailID"];
string SmtpServer = ConfigurationSettings.AppSettings["SmtpServer"];
string UserName = ConfigurationSettings.AppSettings["UserName"];
string Password = ConfigurationSettings.AppSettings["Password"]; 
client = new SmtpClient(SmtpServer);
client.UseDefaultCredentials = false;
System.Net.NetworkCredential creds = new System.Net.NetworkCredential(UserName, Password);
client.Credentials = creds;

msg.From = new MailAddress(FromEmail);

client.Send(msg);

Written by Sandip

October 17, 2009 at 4:22 am

Posted in .Net, Programming

Tagged with ,

C# : Resize image in Picture Box for Best fit

with 3 comments

Got a useful piece of here which I have implemented in following way to make a image preview form.

private void frmPreview_Load(object sender, EventArgs e)
{
try
{

pboxMain.Image = Image.FromFile(_imagePath);
pboxMain.Tag = Image.FromFile(_imagePath);
}
catch(Exception ex)
{
Log.Error(ex);
}
}

private void btFit_Click(object sender, EventArgs e)
{

if (btFit.Text == “Fit to Screen”)
{
handleFitToWindow(true);
btFit.Text = “Actual Size”;
}
else
{
handleFitToWindow(false);
btFit.Text = “Fit to Screen”;
}

}

private void handleFitToWindow(bool doFit)
{
try
{
/* Don’t perform any operation if no image is loaded. */
if (this.pboxMain.Tag != null)
{
if (doFit)  /* We’re fitting it to the window, and centering it. */
{
/* Create a temporary Image.

* Always work from the original image, stored in the Tag.
*/

Image tempImage = (Image)this.pboxMain.Tag;

/* Calculate the dimensions necessary for an image to fit. */
Size fitImageSize = this.getScaledImageDimensions(
tempImage.Width, tempImage.Height, this.pboxMain.Width, this.pboxMain.Height);

/* Create a new Bitmap from the original image with the new dimensions.

* The constructor for the Bitmap object automatically scales as necessary.
*/

Bitmap imgOutput = new Bitmap(tempImage, fitImageSize.Width, fitImageSize.Height);

/* Clear any existing image in the PictureBox. */
this.pboxMain.Image = null;

/* When fitting the image to the window, we want to keep it centered. */
this.pboxMain.SizeMode = PictureBoxSizeMode.CenterImage;

/* Finally, set the Image property to point to the new, resized image. */
this.pboxMain.Image = imgOutput;
}

else  /* Restore the image to its original size */
{
/* Clear any existing image int he PictureBox. */
this.pboxMain.Image = null;

/* Set the resize more to Normal; this will place the image

* in the upper left-hand corner, clipping the image as required.
*/

this.pboxMain.SizeMode = PictureBoxSizeMode.Normal;

/* Finally, set the Image property to point to the original image. */
this.pboxMain.Image = (Image)this.pboxMain.Tag;
}
}
}
catch (System.Exception e)
{
Console.WriteLine(e);
}
}

private Size getScaledImageDimensions(
int currentImageWidth,
int currentImageHeight,
int desiredImageWidth,
int desiredImageHeight)
{
/* First, we must calculate a multiplier that will be used

* to get the dimensions of the new, scaled image.
*/

double scaleImageMultiplier = 0;

/* This multiplier is defined as the ratio of the

* Desired Dimension to the Current Dimension.
* Specifically which dimension is used depends on the larger
* dimension of the image, as this will be the constraining dimension
* when we fit to the window.
*/

/* Determine if Image is Portrait or Landscape. */
if (currentImageHeight > currentImageWidth)    /* Image is Portrait */
{
/* Calculate the multiplier based on the heights. */
if (desiredImageHeight > desiredImageWidth)
{
scaleImageMultiplier = (double)desiredImageWidth / (double)currentImageWidth;
}

else
{
scaleImageMultiplier = (double)desiredImageHeight / (double)currentImageHeight;
}
}

else /* Image is Landscape */
{
/* Calculate the multiplier based on the widths. */
if (desiredImageHeight >= desiredImageWidth)
{
scaleImageMultiplier = (double)desiredImageWidth / (double)currentImageWidth;
}

else
{
scaleImageMultiplier = (double)desiredImageHeight / (double)currentImageHeight;
}
}

/* Generate and return the new scaled dimensions.

* Essentially, we multiply each dimension of the original image
* by the multiplier calculated above to yield the dimensions
* of the scaled image. The scaled image can be larger or smaller
* than the original.
*/

return new Size(
(int)(currentImageWidth * scaleImageMultiplier),
(int)(currentImageHeight * scaleImageMultiplier));
}

}

Written by Sandip

September 17, 2009 at 11:27 am

Posted in .Net, Programming

Tagged with ,