Wednesday, November 10, 2010

Access admin group and copy it to another user group

http://support.microsoft.com/kb/306273

DirectoryEntry AD = new DirectoryEntry("WinNT://" +


Environment.MachineName + ",computer");



DirectoryEntry grp;



grp = AD.Children.Find("Power Users", "group");

if (grp != null)

{

using (DirectoryEntry groupEntry = new DirectoryEntry("WinNT://./Administrators,group"))

{

foreach (object member in (IEnumerable)groupEntry.Invoke("Members"))

{

using (DirectoryEntry memberEntry = new DirectoryEntry(member))

{

try

{

grp.Invoke("Add", new object[] { memberEntry.Path.ToString() });

}

catch { }



}

}

}

}

//add a new user group
try


{

DirectoryEntry AD = new DirectoryEntry("WinNT://" +

Environment.MachineName + ",computer");

DirectoryEntry qtmGroup = AD.Children.Add(QTM_POWER_USERS, "group");

qtmGroup.Invoke("Put", new object[] { "Description", QTM_GROUP_DESCRIPTION });

qtmGroup.CommitChanges();

}

catch { }

Find installation location for an installed app

Uninstall key
Registry.LocalMachine.DeleteSubKeyTree("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{06D45ED5-8A64-469B-8236-CB4DC0E897C9}");

Copied from
http://social.msdn.microsoft.com/Forums/en-US/winformssetup/thread/afb5012a-30f1-4b96-9931-a143fd76bab5

private string FindByDisplayName(RegistryKey parentKey, string name)


{

string[] nameList = parentKey.GetSubKeyNames();

for (int i = 0; i < nameList.Length; i++)

{

RegistryKey regKey = parentKey.OpenSubKey(nameList[i]);

try

{

if (regKey.GetValue("DisplayName").ToString() == name)

{

return regKey.GetValue("InstallLocation").ToString();

}

}

catch { }

}

return "";

}



RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Uninstall");

string location = FindByDisplayName(regKey, "MSN");

MessageBox.Show(location);



This example will compare the DisplayName keyvalue to your input name, if it find the value, then return the InstallLocation key value.

Tuesday, November 9, 2010

Background worker thread

http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
public partial class ProgressDialog : Form


{

public delegate void CancelEventHandler();

public event CancelEventHandler CancelButtonClick;



public ProgressDialog()

{

InitializeComponent();

}



private void buttonCancel_Click(object sender, EventArgs e)

{

if (CancelButtonClick != null)

{

CancelButtonClick();

}

this.Close();

}



public void UpdateProgressMessage(string progressMessage)

{

lblProgressMessage.Text = progressMessage;

}





}
 
private delegate void ShowProgressDialog_Delegate(string progressDialogCaption, ProgressDialog.CancelEventHandler progressCancelled, bool reportProgress);


private void ShowProgressDialog(string progressDialogCaption, ProgressDialog.CancelEventHandler progressCancelled, bool reportProgress)

{

if (InvokeRequired)

{

BeginInvoke(new ShowProgressDialog_Delegate(ShowProgressDialog), new object[] { progressDialogCaption, progressCancelled, reportProgress });

}

else

{

try

{

progressDialog = new ProgressDialog();

progressDialog.Owner = base.FindForm();

progressDialog.CancelButtonClick += progressCancelled;

progressDialog.Text = progressDialogCaption;

if (reportProgress)

{

progressDialog.progressBar.Style = ProgressBarStyle.Continuous;

}

progressDialog.Show();

}

catch { }

}



}

///

/// Close the Progress Dialog

///


private delegate void StopProgressDialog_Delegate();

private void StopProgressDialog()

{

if (InvokeRequired)

{

BeginInvoke(new StopProgressDialog_Delegate(StopProgressDialog), new object[] { });

}

else

{

if (!progressDialog.IsDisposed)

{

progressDialog.Close();

}

}



}



private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)

{

StopProgressDialog();



if (e.Cancelled == true)

{

MessageBox.Show("Installation Cancelled!");

}

else if (e.Error != null)

{

MessageBox.Show("Installation Error: " + e.Error.Message);

}

else

{

MessageBox.Show("Installed successfully!");

}



}



void progress_CancelButtonClick()

{

TestsOptionChanged_Click(null, null);

abortFlag = true;

}

Tuesday, October 26, 2010

Threading in c#

Copied from

Please note: this page is now obsolete. It is now part of my larger article about threading.




Starting threads with parameters in C#

In the C# newsgroup, quite a few people have asked how parameters should be passed to new threads. In other words, if a new thread needs specific information in order to run (as it often does), how do you get that information to the thread? The ThreadStart delegate doesn't take any parameters, so the information has to be stored somewhere else. Typically, this means creating a new instance of a class, and using that instance to store the information. For example, we might have a program which needs to fetch the contents of various URLs, and wants to do it in the background. You could write code like this:



public class UrlFetcher

{

private string url



public UrlFetcher (string url)

{

this.url = url;

}



public void Fetch()

{

// use url here

}

}



[... in a different class ...]



UrlFetcher fetcher = new UrlFetcher (myUrl);

new Thread (new ThreadStart (fetcher.Fetch)).Start();







In some cases, you actually just wish to call a method in some class (possibly the currently executing class) with a specific parameter. In that case, you may wish to use a nested class whose purpose is just to make this call - the state is stored in the class, and the delegate used to start the thread just calls the "real" method with the appropriate parameter. (Note that the object on which to call the method in the first place will also be required as state unless the method is static.)



Using ThreadPool instead

One choice you should always be aware of when starting a new thread is whether it would actually make more sense to use ThreadPool, which will recycle threads for you, and queue items if the pool is full. ThreadPool is a good choice for jobs which are fairly short and frequent, as it avoids wasting time creating and destroying threads.



To add a job to the pool, you merely need to call ThreadPool.QueueUserWorkItem with a WaitCallback delegate. One incidental advantage of using a WaitCallback is that you can also specify the "state" to use when you queue the work item, and this is presented to the delegate as a method parameter. It's not strongly typed however (the passed type is just object) and I would suggest having a more strongly typed method which is called by the WaitCallback delegate and which should be used in preference elsewhere in code. For instance, you might define two methods to fetch URLs as:



// You'd use this method elsewhere in code, if you needed it

public void Fetch (string url)

{

this.url = url;

}



// You'd use this as the WaitCallback delegate to queue in the thread pool

private void Fetch(object url)

{

Fetch ((string) url);

}



// And you'd call it like this:

ThreadPool.QueueUserWorkItem (new WaitCallback (Fetch), myUrl);







Calling a delegate asynchronously

Another alternative (which also uses the thread pool internally) is to call a delegate asynchronously. This has the advantage of allowing you to specify more than one parameter, and have those parameters checked in terms of type at compile-time. This relies on the C# compiler adding a couple of methods to the declared delegate type: BeginInvoke and EndInvoke. The BeginInvoke method always takes whatever parameters the delegate itself does, along with an AsyncCallback parameter and a plain object parameter as state. It returns an IAsyncResult reference. When BeginInvoke is called, a work item is placed on the thread pool work queue, and when it executes the delegate is called with the specified parameters. When the delegate has completed, the AsyncCallback parameter delegate is called with the resulting IAsyncResult reference which can be used to find out the original state parameter, the delegate itself, the return value of the operation (via the delegate), and more. Note that to find out the original delegate you need to cast the IAsyncResult reference to AsyncResult. I'm not aware of why the framework is designed in this way, but if you don't like to make that cast you can always provide the delegate itself as the state parameter. The EndInvoke method only takes an IAsyncResult, and has the same return type as the delegate itself, returning the result of the delegate's execution. Here's a complete example:



using System;

using System.Threading;

using System.Runtime.Remoting.Messaging;



class AsyncTest

{

delegate string UrlFetcher(string url);



public static void Main()

{

UrlFetcher u = new UrlFetcher (Fetch);

u.BeginInvoke ("some url",

new AsyncCallback (AfterFetch),

"this is state");

// Just to demonstrate stuff going on while

// the fetch happens...

for (int i=0; i < 10; i++)

{

Console.WriteLine ("Foreground thread counter: {0}", i);

Thread.Sleep(1000);

}

}



static string Fetch (string url)

{

// Just to simulate it taking a while to fetch the

// contents

Thread.Sleep (5000);

return "Contents of the url";

}



static void AfterFetch (IAsyncResult result)

{

Console.WriteLine ("Delegate completed.");

Console.WriteLine (" State: {0}", result.AsyncState);

AsyncResult async = (AsyncResult) result;

UrlFetcher fetcher = (UrlFetcher) async.AsyncDelegate;

Console.WriteLine (" Contents: {0}", fetcher.EndInvoke(result));

}

}







The output of the above is (in one test run - it might vary very slightly because the counter may get a bit further before the delegate's Sleep call returns):



Foreground thread counter: 0

Foreground thread counter: 1

Foreground thread counter: 2

Foreground thread counter: 3

Foreground thread counter: 4

Delegate completed.

State: this is state

Contents: Contents of the url

Foreground thread counter: 5

Foreground thread counter: 6

Foreground thread counter: 7

Foreground thread counter: 8

Foreground thread counter: 9







See the MSDN documentation for the BeginRead and EndRead operations in the System.IO.Stream class for more examples of how this kind of asynchronous operation works.



Important note: You should always call EndInvoke on delegates which are executed asynchronously, even if you don't actually care about the result of the operation - otherwise you may provoke a memory leak. Fortunately there are ways to make this easier, as shown in the Advanced-DotNet mailing list archives.



A future solution: anonymous methods

One of the future enhancements to C# is almost certain to be anonymous methods. These allow you to specify blocks of code as methods within other methods, and use those methods as delegates. You can access variables (including local variables and parameters of the "outside" method) within the anonymous method. For example, using an anonymous method to fetch a URL using a normal ThreadStart delegate:



ThreadStart starter = new ThreadStart()

{

Fetch (myUrl);

};

new Thread(starter).Start();







(This could have all been expressed within a single step, creating both the thread and the delegate in the same line of code, but I believe the above is more readable.) Here's similar code to use a WaitCallback and queue the job in ThreadPool:



WaitCallback callback = new WaitCallback (state)

{

Fetch ((string)state);

};

ThreadPool.QueueUserWorkItem (callback, myUrl);







Note the way that the state is declared. This is, of course, subject to change. For more details about anonymous methods and other potential enhancements to C#, see the Microsoft C# Language Future Features page.





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



Back to the main page.

Tuesday, September 28, 2010

TreeView lost focus

public partial class Form1 : Form {


public Form1() {

InitializeComponent();

treeView1.Nodes.Add("abc");

treeView1.Nodes.Add("bcd");

treeView1.Nodes[1].Nodes.Add("ppo");

treeView1.DrawMode = TreeViewDrawMode.OwnerDrawText;

treeView1.DrawNode += treeView1_DrawNode;

}

private void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e) {

Font f = e.Node.NodeFont != null ? e.Node.NodeFont : e.Node.TreeView.Font;

Size sz = TextRenderer.MeasureText(e.Node.Text, f);

Rectangle rc = new Rectangle(e.Bounds.X - 1, e.Bounds.Y, sz.Width + 2, e.Bounds.Height);

Color fore = e.Node.ForeColor;

if (fore == Color.Empty) fore = e.Node.TreeView.ForeColor;

// Have to indicate focus somehow, how about yellow foreground text?

if (e.Node == e.Node.TreeView.SelectedNode) {

fore = SystemColors.HighlightText;

if ((e.State & TreeNodeStates.Focused) != 0) fore = Color.Yellow;

}

Color back = e.Node.BackColor;

if (back == Color.Empty) back = e.Node.TreeView.BackColor;

if (e.Node == e.Node.TreeView.SelectedNode) back = SystemColors.Highlight;

SolidBrush bbr = new SolidBrush(back);

e.Graphics.FillRectangle(bbr, rc);

TextRenderer.DrawText(e.Graphics, e.Node.Text, f, rc, fore, TextFormatFlags.GlyphOverhangPadding);

bbr.Dispose();

Wednesday, September 22, 2010

File Association

http://www.codeproject.com/KB/files/custom-file-extension.aspx

using System;


using System.Collections.Generic;

using System.Text;

using System.IO;

using System.Collections;

using Microsoft.Win32;



namespace QC.QTMApplication

{

internal struct CommandArrayList

{

public ArrayList Captions;



public ArrayList Commands;

}



/// Properties of the file association.

internal struct FileType

{

public CommandArrayList Commands;

public string Extension;

public string ProperName;

public string FullName;

public string ContentType;

public string IconPath;

public short IconIndex;



}



/// Creates file associations for your programs.



/// The following example creates a file association for the type XYZ with a non-existent program.



///


VB.NET code



///



/// Dim FA as New FileAssociation



/// FA.Extension = "xyz"



/// FA.ContentType = "application/myprogram"



/// FA.FullName = "My XYZ Files!"



/// FA.ProperName = "XYZ File"



/// FA.AddCommand("open", "C:\mydir\myprog.exe %1")



/// FA.Create



///



///
C# code



///



/// FileAssociation FA = new FileAssociation();



/// FA.Extension = "xyz";



/// FA.ContentType = "application/myprogram";



/// FA.FullName = "My XYZ Files!";



/// FA.ProperName = "XYZ File";



/// FA.AddCommand("open", "C:\\mydir\\myprog.exe %1");



/// FA.Create();



///



///




public class FileAssociation

{



/// Initializes an instance of the FileAssociation class.



public FileAssociation()

{



FileInfo = new FileType();



FileInfo.Commands.Captions = new ArrayList();



FileInfo.Commands.Commands = new ArrayList();



}



/// Gets or sets the proper name of the file type.



/// A String representing the proper name of the file type.



public string ProperName

{



get

{



return FileInfo.ProperName;



}



set

{



FileInfo.ProperName = value;



}



}



/// Gets or sets the full name of the file type.



/// A String representing the full name of the file type.



public string FullName

{



get

{



return FileInfo.FullName;



}



set

{



FileInfo.FullName = value;



}



}



/// Gets or sets the content type of the file type.



/// A String representing the content type of the file type.



public string ContentType

{



get

{



return FileInfo.ContentType;



}



set

{



FileInfo.ContentType = value;



}



}



/// Gets or sets the extension of the file type.



/// A String representing the extension of the file type.



/// If the extension doesn't start with a dot ("."), a dot is automatically added.



public string Extension

{



get

{



return FileInfo.Extension;



}



set

{



if (value.Substring(0, 1) != ".")



value = "." + value;



FileInfo.Extension = value;



}



}



/// Gets or sets the index of the icon of the file type.



/// A short representing the index of the icon of the file type.



public short IconIndex

{



get

{



return FileInfo.IconIndex;



}



set

{



FileInfo.IconIndex = value;



}



}



/// Gets or sets the path of the resource that contains the icon for the file type.



/// A String representing the path of the resource that contains the icon for the file type.



/// This resource can be an executable or a DLL.



public string IconPath

{



get

{



return FileInfo.IconPath;



}



set

{



FileInfo.IconPath = value;



}



}



/// Adds a new command to the command list.



/// The name of the command.



/// The command to execute.



/// Caption -or- Command is null (VB.NET: Nothing).



public void AddCommand(string Caption, string Command)

{



if (Caption == null

Command == null)



throw new ArgumentNullException();



FileInfo.Commands.Captions.Add(Caption);



FileInfo.Commands.Commands.Add(Command);



}



/// Creates the file association.



/// Extension -or- ProperName is null (VB.NET: Nothing).



/// Extension -or- ProperName is empty.



/// The user does not have registry write access.



public void Create()

{



// remove the extension to avoid incompatibilities [such as DDE links]



try

{



Remove();



}

catch (ArgumentException) { } // the extension doesn't exist



// create the exception



if (Extension == ""

ProperName == "")



throw new ArgumentException();



int cnt;



try

{



RegistryKey RegKey = Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(Extension);



RegKey.SetValue("", ProperName);



if (ContentType != null && ContentType != "")



RegKey.SetValue("Content Type", ContentType);



RegKey.Close();



RegKey = Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(ProperName);



RegKey.SetValue("", FullName);



RegKey.Close();



if (IconPath != "")

{



RegKey = Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(ProperName + "\\" + "DefaultIcon");



RegKey.SetValue("", IconPath + "," + IconIndex.ToString());



RegKey.Close();



}



for (cnt = 0; cnt < FileInfo.Commands.Captions.Count; cnt++)

{



RegKey = Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(ProperName + "\\" + "Shell" + "\\" + (string)FileInfo.Commands.Captions[cnt]);



RegKey = RegKey.CreateSubKey("Command");



RegKey.SetValue("", FileInfo.Commands.Commands[cnt]);



RegKey.Close();



}



}

catch

{



throw new Exception();



}



}



/// Removes the file association.



/// Extension -or- ProperName is null (VB.NET: Nothing).



/// Extension -or- ProperName is empty -or- the specified extension doesn't exist.



/// The user does not have registry delete access.



public void Remove()

{



if (Extension == null

ProperName == null)



throw new ArgumentNullException();



if (Extension == ""

ProperName == "")



throw new ArgumentException();



Microsoft.Win32.Registry.ClassesRoot.DeleteSubKeyTree(Extension);



Microsoft.Win32.Registry.ClassesRoot.DeleteSubKeyTree(ProperName);



}



/// Holds the properties of the file type.



private FileType FileInfo;



}



}

Wednesday, September 15, 2010

C# DataGridView

private void FormatDataGridViewForNDaySchedule(DataGridView dgvTable)


{

if (dgvTable.Rows.Count >= 0)

{

dgvTable.Columns[0].Visible = false;
dgvTable.ReadOnly = false;



foreach (DataGridViewColumn column in dgvNDaysSchedule.Columns)

{

column.ReadOnly = true;

}



dgvTable.Columns[ParameterNames.PRIORITY].ReadOnly = false;



//set width

dgvTable.Columns[ParameterNames.PRIORITY].DefaultCellStyle = 50;

dgvTable.Columns[ParameterNames.REQUEST_STATUS_NAME].Width = 50;


dgvTable.AllowUserToAddRows = false;



//set Header Text

dgvTable.Columns[ParameterNames.NEXT_STOP].HeaderText = "Due Date";
dgvTable.Columns[ParameterNames.CHAMBER].Value = DateTime.Now;


dgvTable.Columns[ParameterNames.CHAMBER].Style.Format = "d";
}

else

{

//do nothing

}

}

Tuesday, September 7, 2010

working with File in c#

//To replace and edit a text file
StringBuilder newFile = new StringBuilder();




string temp = "";



string[] file = File.ReadAllLines(@"C:\Documents and Settings\john.grove\Desktop\1.txt");



foreach (string line in file)



{



if (line.Contains("string"))



{



temp = line.Replace("string", "String");



newFile.Append(temp + "\r\n");



continue;



}



newFile.Append(line + "\r\n");



}

File.WriteAllText(@"C:\Documents and Settings\john.grove\Desktop\1.txt", newFile.ToString());




//if file doesn't exist, search for the path


if (!System.IO.File.Exists(testContainer.Name))

{

System.IO.FileInfo fInfo = new System.IO.FileInfo(testContainer.Name);

string dllName = fInfo.Name;



foreach (string path in DLLPaths)

{

//if dll existed in this path, update the qtm container with the new path

if (System.IO.File.Exists(System.IO.Path.Combine(path, dllName)))

{

testContainer.Name = System.IO.Path.Combine(path, dllName);

//stop searching

break;

}

}

}

deepCopy C#

public static object DeepCopy(object serializableObj)


{

MemoryStream s = new MemoryStream();

BinaryFormatter f = new BinaryFormatter();

f.Serialize(s, serializableObj);

s.Position = 0;

return f.Deserialize(s);

}

Wednesday, August 11, 2010

ASP.NET Listview

Access controls inside listview using code
• ListViewItem item = (ListViewItem)ProductsListView.Items[e.NewSelectedIndex];

• Label l = (Label)item.FindControl("DiscontinuedDateLabel");

Tuesday, August 3, 2010

Enum

http://www.c-sharpcorner.com/UploadFile/mahesh/EnumToString10212005144136PM/EnumToString.aspx

Wednesday, July 28, 2010

Sorting and paging using gridview in asp.net when binding with a datable

protected void AssignedQualInbox_Sorting(object sender, GridViewSortEventArgs e)


{

//Retrieve the table from the session object.

DataTable dataTable = Session["AssignedQualInbox"] as DataTable;



if (dataTable != null)

{

// Check the DataTable itself for the previous sort expression and sort the data

if (dataTable.DefaultView.Sort.ToString() == (e.SortExpression.ToString() + " ASC"))

{

dataTable.DefaultView.Sort = e.SortExpression + " DESC";

}

else // Handles cases where the previous sort expression was the current expression descending, another expression, or none at all.

{

dataTable.DefaultView.Sort = e.SortExpression + " ASC";

}



AssignedQualInbox.DataSource = Session["AssignedQualInbox"];

AssignedQualInbox.DataBind();

}



}



protected void AssignedQualInbox_PageIndexChanging(object sender, GridViewPageEventArgs e)

{

AssignedQualInbox.PageIndex = e.NewPageIndex;

AssignedQualInbox.DataBind();

}

Friday, July 9, 2010

clean up computer

http://www.piriform.com/ccleaner/download

Tuesday, June 22, 2010

ASP Getting server variables

//// Load ServerVariable collection into NameValueCollection object.


//coll = Request.ServerVariables;

//// Get names of all keys into a string array.

//String[] arr1 = coll.AllKeys;

//for (loop1 = 0; loop1 < arr1.Length; loop1++)

//{

// Response.Write("Key: " + arr1[loop1] + "
");

// serverVariable.Append("Key: " + arr1[loop1] + ": ");

// String[] arr2 = coll.GetValues(arr1[loop1]);

// for (loop2 = 0; loop2 < arr2.Length; loop2++)

// {

// Response.Write("Value " + loop2 + ": " + Server.HtmlEncode(arr2[loop2]) + "
");

// //serverVariable.Append("Value " + loop2 + ": " + Server.HtmlEncode(arr2[loop2]) + "\n");

// }

//}

Friday, June 4, 2010

Serialize with Stylesheet

Copied from http://stackoverflow.com/questions/1461029/possible-to-add-a-xslt-stylesheet-to-a-serialized-xml-document

XmlSerializer s = new XmlSerializer(typeof(myObj));


using (XmlWriter w = XmlWriter.Create(@"c:\test.xml"))

{

w.WriteProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"USED-FILE.xsl\"");

s.Serialize(w, myObj);

}

Thursday, May 27, 2010

Creating MS Office docs without MS Office installed for .net

http://code.google.com/p/excellibrary/  for excel



For Java,
http://poi.apache.org/




For Word, we have purchased some API from Aspose, but ours is the Java version of course. You would have to purchase the .NET version.



www.aspose.com



For PDF, we use iText currently.



http://itextpdf.com/

Wednesday, May 26, 2010

Launch a URL from c#

System.Diagnostics.Process.Start(http://google.com/);

Batch files

http://www.aumha.org/a/batches.php  good link for batch file

/wait for process to be done

start /wait C:\WINDOWS\system32\MsiExec.exe /x {D74E7F02-026E-45C6-84C7-93D74F5BB0B1} /qb

Tuesday, May 25, 2010

Get installed application and extract msi to get product version

public static string GetInstalledApps()


{

//Declare the string to hold the list:

string Application = null;

//The registry key:

string SoftwareKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";

using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(SoftwareKey))

{

//Let's go through the registry keys and get the info we need:

foreach (string skName in rk.GetSubKeyNames())

{

using (RegistryKey sk = rk.OpenSubKey(skName))

{

try

{

//If the key has value, continue, if not, skip it:

if (!(sk.GetValue("DisplayName") == null))

{

//get the version string

if (sk.GetValue("InstallLocation") == null)

Application += sk.GetValue("DisplayName") + " - Install path not known\n"; //Nope, not here.

else

Application += sk.GetValue("DisplayName") + " - " + sk.GetValue("InstallLocation") + "\n"; //Yes, here it is...

}

}

catch (Exception ex)

{

//exception

}

}

}

}



return Application;

}

///this is to get the current version of msi file
public static int GetCurrVersions(string inputFile)


{

// Get the type of the Windows Installer object

Type installerType = Type.GetTypeFromProgID("WindowsInstaller.Installer");



// Create the Windows Installer object

Installer installer = (Installer)Activator.CreateInstance(installerType);



// Open the MSI database in the input file

Database database = installer.OpenDatabase(inputFile, MsiOpenDatabaseMode.msiOpenDatabaseModeReadOnly);



// Open a view on the Property table for the version property

View dataView = database.OpenView("SELECT * FROM Property WHERE Property = 'ProductVersion'");



// Execute the view query

dataView.Execute(null);



// Get the record from the view

Record dataRecord = dataView.Fetch();



// Get the version from the data

string version = dataRecord.get_StringData(2);



//close the view

dataView.Close();

}







Query LINQ



static void DisplayInstalledApplications()

{

string registryKey =

@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";



using (Microsoft.Win32.RegistryKey key =

Registry.LocalMachine.OpenSubKey(registryKey))

{

var query = from a in

key.GetSubKeyNames()

let r = key.OpenSubKey(a)

select new

{

Application = r.GetValue("DisplayName")

};



foreach (var item in query)

{

if (item.Application != null)

Console.WriteLine(item.Application);

}

}

}

Thursday, May 13, 2010

Visual Studio Environment

Choose a different settings by going to Tools menu, choose import and export settings and then choose reset all settings

Wednesday, May 5, 2010

Visual Studio, Configuration Manager

Configuration manager not able to check on an item, verify if it's readonly solution or it checked out or not

Wednesday, April 28, 2010

Event and Delegate

Event and delegate


******in the form that generate the event

public delegate void ReportNameChangedHandler(ConfigureReportProperties reportProperties);

public event ReportNameChangedHandler ReportNameChangedEvent;

if (ReportNameChangedEvent != null)

{

SaveReportProperties();

ReportNameChangedEvent(ReportProperties);

}


*****in the form that get called by the event

ConfigureReport configureReport = new ConfigureReport(pnlWorkSheet);

configureReport.LoadReportProperties(ReportProperties);

configureReport.ReportNameChangedEvent += new ConfigureReport.ReportNameChangedHandler(ConfigureReport_ReportNameChangedEvent);

configureReport.Show();


void ConfigureReport_ReportNameChangedEvent(ConfigureReportProperties updatedReportProperties)

{

ReportProperties = updatedReportProperties;

}

Monday, April 5, 2010

Visual Studio Installer

Link that talk about Custom action
http://www.simple-talk.com/dotnet/visual-studio/visual-studio-setup---projects-and-custom-actions/

msi getproductstate
msi getProductInfo
msi installProduct
Transaction Install available in Window 7

msiqueryproductstate sample code
using system

Thursday, March 25, 2010

C# Operator

a?b:c if a is true, returns the value of b, otherwise c
a??b if a is null, returns b, otherwise returns a

Tuesday, March 9, 2010

How to check office application version

(Code from Nenad Prekupec) http://www.eggheadcafe.com/community/aspnet/2/10029362/vsto--managing-excel-200.aspx

public enum eOfficeVersion { eOfficeVersion_Unknown, // error return value
eOfficeVersion_95,
eOfficeVersion_97,
eOfficeVersion_2000,
eOfficeVersion_XP, // XP = 2002 + marketing
eOfficeVersion_2003,
eOfficeVersion_2007,
};
public enum eOfficeApp // in case you are looking for a particular app
{
eOfficeApp_Word,
eOfficeApp_Excel,
eOfficeApp_Outlook,
eOfficeApp_Access,
eOfficeApp_PowerPoint,
};public static eOfficeVersion GetApplicationVersion(eOfficeApp appToCheck) { // some of this function is based on the code in the article at: http://support.microsoft.com/kb/q247985/
string progID = GetProgID(appToCheck); RegistryKey hKey = Registry.ClassesRoot.OpenSubKey(progID, RegistryKeyPermissionCheck.ReadSubTree, System.Security.AccessControl.RegistryRights.ReadKey); if (hKey == null) return eOfficeVersion.eOfficeVersion_Unknown; RegistryKey hKey1 = hKey.OpenSubKey("CurVer", RegistryKeyPermissionCheck.ReadSubTree, System.Security.AccessControl.RegistryRights.ReadKey); if (hKey1 == null) { hKey1.Close(); hKey.Close(); return eOfficeVersion.eOfficeVersion_Unknown; } // Get the Version information
string progAndVersion = (string)hKey1.GetValue(""); // Close the registry keys
hKey1.Close();
hKey.Close();
// Error while querying for value
if (progAndVersion == null) return eOfficeVersion.eOfficeVersion_Unknown; // At this point progAndVersion contains the ProgID followed by a number.
// For example, Word 97 will return Word.Application.8 and Word 2000 will return Word.Application.9
int lastDot = progAndVersion.LastIndexOf('.'); int firstCharOfVersion = lastDot + 1; // + 1 to get rid of the dot at the front
string versionString = progAndVersion.Substring(firstCharOfVersion, progAndVersion.Length - firstCharOfVersion); return StringToVersion(versionString); }

public static string GetApplicationAsString(eOfficeApp officeApp) { switch(officeApp)
{ case eOfficeApp.eOfficeApp_Word: { return "Word"; } break; case eOfficeApp.eOfficeApp_Excel: { return "Excel"; } break; case eOfficeApp.eOfficeApp_Outlook: { return "Outlook"; } break; case eOfficeApp.eOfficeApp_Access: { return "Access"; } break; case eOfficeApp.eOfficeApp_PowerPoint: { return "Powerpoint"; } break; default: { /*ASSERT(false);*/ return string.Empty; } break; // added another ??? } }
public static string GetProgID(eOfficeApp officeApp)
{
// ProgIDs from http://support.microsoft.com/kb/240794/EN-US/ switch (officeApp) { case eOfficeApp.eOfficeApp_Word: { return "Word.Application"; } break; case eOfficeApp.eOfficeApp_Excel: { return "Excel.Application"; } break; case eOfficeApp.eOfficeApp_Outlook: { return "Outlook.Application"; } break; case eOfficeApp.eOfficeApp_Access: { return "Access.Application"; } break; case eOfficeApp.eOfficeApp_PowerPoint: { return "Powerpoint.Application"; } break; default: { /*ASSERT(false);*/ return string.Empty; } break; // added another ??? }}
public static eOfficeVersion StringToVersion(string versionString)
{ // mapping between the marketing version (e.g. 2003) and the behind-the-scenes version if("7" == versionString){ return eOfficeVersion.eOfficeVersion_95; }else if("8" == versionString){ return eOfficeVersion.eOfficeVersion_97; }else if("9" == versionString){ return eOfficeVersion.eOfficeVersion_2000; }else if("10" == versionString){ return eOfficeVersion.eOfficeVersion_XP; }else if("11" == versionString){ return eOfficeVersion.eOfficeVersion_2003; }else if("12" == versionString){ return eOfficeVersion.eOfficeVersion_2007; }else{ return eOfficeVersion.eOfficeVersion_Unknown; // added another ??? } }

Friday, March 5, 2010

Dictionary in C#

Dictionary argumentCollection = commandParser.ParseCommandLineArgument(args);
foreach (KeyValuePair argument in argumentCollection)
{

string value = argument.Value as string;
value = IsStringNullOrEmpty(value)??string.Empty;
string key = argument.Key
}

Thursday, March 4, 2010

Use App.config file in C#

- Need to add System.configuration reference
- add using System.Configuration namespace

//To retrieve the information
ConfigurationManager.AppSettings[SERVER_KEY].ToUpper();

Sample of an App.config file

//?xml version="1.0" encoding="utf-8" ?>
//configuration>
//appSettings>
//add key="Server" value="SQL" />
//add key="Database" value="test"/>
///configuration>

How to get Assembly version

System.Reflection.Assembly oAssembly = System.Reflection.Assembly.GetExecutingAssembly();
System.Diagnostics.FileVersionInfo oFileVersionInfo = System.Diagnostics.FileVersionInfo.GetVersionInfo(oAssembly.Location);
this.Text = "v" + oFileVersionInfo.ProductVersion;

A cross-reference.
// FileVersionInfo.Comments = AssemblyDescription
// FileVersionInfo.CompanyName = AssemblyCompany
// FileVersionInfo.FileDescription = AssemblyTitle
// FileVersionInfo.FileVersion = AssemblyFileVersion
// FileVersionInfo.LegalCopyright = AssemblyCopyright
// FileVersionInfo.LegalTrademarks = AssemblyTrademark
// FileVersionInfo.ProductName = AssemblyProduct
// FileVersionInfo.ProductVersion = AssemblyInformationalVersion

use "linked" files in project. Solution Explorer -> Add Existin Item -> .. select_file .. -> arrow_on_left_of_add_button -> Add As Link
Then the selected file ( AssemblyInfo.cs for now ) is not copied to the direcotry of project, but is only linked from specified path.

Create a process to send email

System.Diagnostics.Process.Start("mailto:mymail@yahoo.com");

Useful links to build VS Installers

http://www.simple-talk.com/content/print.aspx?article=192 on how to use custom action
http://hunter555.blogspot.com/2007/02/installer-error-code-2869-msi-and-uac.html on how to fix the error code 2869

WPF: Links to learn WPF

http://code.msdn.microsoft.com/wpfsamples

Wednesday, March 3, 2010

Change the background color for development server

if ((ConfigurationManager.AppSettings[SERVER_KEY].ToUpper() != "QMT-ENG-SQL" ConfigurationManager.AppSettings[DATABASE_KEY].ToUpper() != "QTMDB_QES_RELI" ))
{
BackColor = Color.Red;
Text = "** DEVELOPMENT SERVER ** DEVELOPMENT SERVER ** DEVELOPMENT SERVER** DEVELOPMENT SERVER **";
}

WPF:
this.Title = "****DEVELOPMENT SERVER*****";

Friday, February 26, 2010

Display a dialog to GUI thread from C#

Delegate.Invoke: Executes synchronously, on the same thread.


Delegate.BeginInvoke: Executes asynchronously, on a threadpool thread.

Control.Invoke: Executes on the UI thread, but calling thread waits for completion before continuing.

Control.BeginInvoke: Executes on the UI thread, and calling thread doesn't wait for completion.



Use Code from link http://www.codeproject.com/KB/cs/AvoidingInvokeRequired.aspx

static public class UIHelper


{

static public void UIThread(Control control, MethodInvoker code)

{

if (control.InvokeRequired)

{

control.BeginInvoke(code);

return;

}

control.Invoke();

}

}And then invoke the UIThread like this:



Collapse
Copy Code

UIHelper.UIThread(this, delegate

{

textBoxOut.Text = "New text";

});
 
Or

private delegate void DialogMessage_Delegate(string message);
private bool DialogMessage(string message)
{
if (InvokeRequired)
{
BeginInvoke(new DialogMessage_Delegate(TextMessages), new object[] { message });
}
else
{
if (System.Windows.Forms.MessageBox.Show(message,"Excel Template", MessageBoxButtons.OKCancel)
!= System.Windows.Forms.DialogResult.OK)
return false;
}
return true;
}

Reading data from Excel and create a datatable

//read data from Excel
object[,] colDataValues = (object[,])objRange.Value2;


//create columns
for (int index = 1; index <= colDataValues.GetLength(1); index++ )
{
DataColumn col = new DataColumn();
col.ColumnName = (string)colDataValues[1,index];
excelData.Columns.Add(col);
}

//reading rows values
for (int i = 2; i <= colDataValues.GetLength(0); i++)
{
DataRow row = excelData.NewRow();
for (int j = 1; j <= colDataValues.GetLength(1); j++)
{
row[j-1] = Convert.ToString(colDataValues[i, j]);
}
excelData.Rows.Add(row);
}

Thursday, February 25, 2010

DataTable Notes

//select distinct
DataTable distinctTests = new DataTable();
distinctTests = ExistingDataTable.DefaultView.ToTable(true, columnName);

//select query and import row
DataTable oneUnit = tableGrid.Clone();
string queryStr = string.Format(NAME
+ "= '{0}' ", (string)dr[NAME]);
DataRow[] drsForOneUnit = tableGrid.Select(queryStr);
foreach (DataRow row in drsForOneUnit)
{
oneUnit.ImportRow(row);
}
SaveDataForEachUnit(oneUnit);

//set primary key

DataTable uniqueTestNFromExcel = excelData.DefaultView.ToTable(true, NAME);
DataColumn[] key = new DataColumn[1];
key[0] = uniqueTestNFromExcel.Columns[0];
uniqueTestNFromExcel.PrimaryKey = key;

Wednesday, February 17, 2010

Excel (Record macros to learn how to use Excel in code)

If need to write code to Excel, can always record macros and get the code to use

Friday, February 5, 2010

User-Defined Table Types

To create a user-defined table type, use the CREATE TYPE statement. To ensure that the data in a user-defined table type meets specific requirements, you can create unique constraints and primary keys on the user-defined table type.

When use a user-defined table type as an argument, it's READ ONLY