Sandip's Programming Zen

An attempt to share tech/coding experiences

Archive for the ‘.Net’ Category

Resolved: “Access denied” error on System.Diagnostics.Process.Start

with 3 comments

Wrote a piece of code which would launch an application exe using Process.Start, on development machine it worked without a problem but when deployed on client machine it started giving “Access Denied” error.

It turned out that when the code runs in domain controlled user environement Process.Start needs a set of security credentials by default to run. Now, in practical scenario we can not just hard code any credentials or even prompt for input.

The solution, there is an attribute called UseShellExecute which needs to be set False , this will allow the exe to be launched without credentials.

Sample code goes like this :

System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = _path;
p.StartInfo.Arguments = string.Format(“\”{0}\” \”{1}\””, arg1, arg2);
p.StartInfo.UseShellExecute = false;
p.Start();
p.WaitForExit();

		
Advertisements

Written by Sandip

August 6, 2011 at 5:03 pm

Posted in .Net, Programming, Softwares

Running 32 bit applications on 64 bit OS

with one comment

Lately I ran into a problem where I created a feature where user can view PDF within a winform application. To do that I first used a web browser control since it was a simple solution where you just need to provide pdf path to the navigate property. That works without problem on Win XP (32bit) , but as soon as user runs it on his Vista (64 bit) OS  , it behaved different , that said, pdf opens but in a separate window, which looks bit odd, so must be fixed.

To solve that problem , I have removed web browser control and placed Acrobat Reader control (assuming that all of my users will have at least Adobe reader installed). Now that again worked well on Win XP but simply crashed on Vista (64 bit).  Reason was Acrobat reader control is an ActiveX control which is 32 bit component , that won’t work on a 64 bit OS. After looking around for some time and find out there is no 64 bit version of Acrobat reader, I discovered that I have to make sure that my win form app runs under 32 bit process on a 64 bit OS. To, do that you have to change Target Platform property of your project (See screenshot below).

Bottom line is if you have any project dependencies which only works on 32 bit environment, you have to change your project’s target platform to run only under 32 bit process. That will make your app work fine on both 32 bit and 64 bit OSes.

target_platform

Written by Sandip

January 9, 2011 at 10:44 pm

Posted in .Net, Programming, Windows

Tagged with , , ,

Solution: Problem of focus when opening a Winform using Treeview node click

leave a comment »

I must blog this , since I could not find the fix as quickly as I should. So…
When you try to open a winform using treeview node selection (using any event like mouse_click on after_select) , the form opens, but it remains minimized even if you have set the focus and windowstate properties.  That is because treeview regains control after opening form, however there is no direct fix.  You can fix it by delaying the action of the event.

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            this.BeginInvoke(new TreeViewEventHandler(delayedClick), sender, e);
        }

        private void delayedClick(object sender, TreeViewEventArgs e)
        {
             // your code goes here…
        }

Original solution here.

Written by Sandip

January 6, 2011 at 4:12 pm

Posted in .Net

Tagged with

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;
    }

}

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 ,