Thursday, December 4, 2008

C#: Calculate Statistics of a Word Document

//***
//Label names are self Explanatory
//Stats include content from FootNotes and EndNotes
//Use objFalse = false instead of objMissing to exclude FootNotes and EndNotes
//***

Word.Document WDocument = Globals.ThisAddIn.Application.ActiveDocument;
object objMissing = System.Reflection.Missing.Value;

lblNumberOfPages.Text = WDocument.ComputeStatistics(Word.WdStatistic.wdStatisticPages, ref objMissing).ToString();

lblNumberOfParagraphs.Text = WDocument.ComputeStatistics(Word.WdStatistic.wd
StatisticParagraphs, ref objMissing).ToString();

lblNumberOfSentences.Text = WDocument.Sentences.Count.ToString();

lblNumberOfLines.Text = WDocument.ComputeStatistics(Word.WdStatistic.wdStatisticLines, ref objMissing).ToString();

lblNumberOfWords.Text = WDocument.ComputeStatistics(Word.WdStatistic.wdStatisticWords, ref objMissing).ToString();

lblNumberOfCharactersIncludingSpaces.Text = WDocument.ComputeStatistics(Word.WdStatistic.wdStatisticCharactersWithSpaces, ref objMissing).ToString();

lblNumberOfCharactersExcludingSpaces.Text = WDocument.ComputeStatistics(Word.WdStatistic.wdStatisticCharacters, ref objMissing).ToString();

Thursday, November 20, 2008

C#: Capture ScreenShot

Courtesy: NOBUGZ (http://forums.microsoft.com/MSDN/User/Profile.aspx?UserID=170041&SiteID=1)


using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace KSeeSharp
{
class ScreenShot
{
[DllImport("gdi32.dll")]
static extern bool BitBlt(IntPtr hdcDest, int xDest, int yDest, int wDest, int hDest, IntPtr hdcSource, int xSrc, int ySrc, CopyPixelOperation rop);
[DllImport("user32.dll")]
static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDc);
[DllImport("gdi32.dll")]
static extern IntPtr DeleteDC(IntPtr hDc);
[DllImport("gdi32.dll")]
static extern IntPtr DeleteObject(IntPtr hDc);
[DllImport("gdi32.dll")]
static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight);
[DllImport("gdi32.dll")]
static extern IntPtr CreateCompatibleDC(IntPtr hdc);
[DllImport("gdi32.dll")]
static extern IntPtr SelectObject(IntPtr hdc, IntPtr bmp);
[DllImport("user32.dll")]
public static extern IntPtr GetDesktopWindow();
[DllImport("user32.dll")]
public static extern IntPtr GetWindowDC(IntPtr ptr);

public void CaptureScreenShot(string filePath)
{
Size sz = Screen.PrimaryScreen.Bounds.Size;
IntPtr hDesk = GetDesktopWindow();
IntPtr hSrce = GetWindowDC(hDesk);
IntPtr hDest = CreateCompatibleDC(hSrce);
IntPtr hBmp = CreateCompatibleBitmap(hSrce, sz.Width, sz.Height);
IntPtr hOldBmp = SelectObject(hDest, hBmp);
bool b = BitBlt(hDest, 0, 0, sz.Width, sz.Height, hSrce, 0, 0, CopyPixelOperation.SourceCopy | CopyPixelOperation.CaptureBlt);
Bitmap bmp = Bitmap.FromHbitmap(hBmp);
SelectObject(hDest, hOldBmp);
DeleteObject(hBmp);
DeleteDC(hDest);
ReleaseDC(hDesk, hSrce);
bmp.Save(filePath);
bmp.Dispose();
}

}
}

C#: Retrieve Machine Information

using System.Management;
using System.Diagnostics;

class MachineInfo
{
ManagementObjectSearcher query;
ManagementObjectCollection result;
string responseString;
int responseInt;

public string GetMachineName()
{
return Environment.MachineName.ToUpper();
}

public string GetOSVersion()
{
return Environment.OSVersion.VersionString;
}

public string GetProcessorCount()
{
return Environment.ProcessorCount.ToString();
}

public string GetIPAddress()
{
IPHostEntry ipEntry = Dns.GetHostEntry(Dns.GetHostName());
IPAddress[] ipAddress = ipEntry.AddressList;
return ipAddress[0].ToString();
}

public string GetTotalPhysicalMemory()
{
query = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalMemoryConfiguration");
result = query.Get();
foreach (ManagementObject managementObject in result)
{
responseInt = Convert.ToInt32(managementObject["TotalPhysicalMemory"].ToString());
}
responseInt = (responseInt / 1024);
responseString = responseInt.ToString() + " MB";
return responseString;
}

public string GetAvailablePhysicalMemory()
{
PerformanceCounter counter = new PerformanceCounter("Memory", "Available Bytes");
responseInt = ((int)Convert.ToInt64(counter.NextValue())) / (1024 * 1024);
responseString = responseInt.ToString() + " MB";
return responseString;
}

public string GetTotalVirtualMemory()
{
query = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalMemoryConfiguration");
result = query.Get();
foreach (ManagementObject managementObject in result)
{
responseInt = Convert.ToInt32(managementObject["TotalVirtualMemory"].ToString());
}
responseInt = (responseInt / 1024);
responseString = responseInt.ToString() + " MB";
return responseString;
}

public string GetAvailableVirtualMemory()
{
query = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalMemoryConfiguration");
result = query.Get();
foreach (ManagementObject managementObject in result)
{
responseInt = Convert.ToInt32(managementObject["AvailableVirtualMemory"].ToString());
}
responseInt = (responseInt / 1024);
responseString = responseInt.ToString() + " MB";
return responseString;
}

public string GetCpuFrequency()
{
query = new ManagementObjectSearcher("SELECT * FROM Win32_Processor");
result = query.Get();
foreach (ManagementObject managementObject in result)
{
responseInt = Convert.ToInt32(managementObject["CurrentClockSpeed"].ToString());
}
responseString = responseInt.ToString() + " MHz";
return responseString;
}
}

Thursday, November 13, 2008

C#: Check if an application is already running

using System.Diagnostics;

bool IsApplicationAlreadyRunning()
{
string proc=Process.GetCurrentProcess().ProcessName;
Process[] processes=Process.GetProcessesByName(proc);
if (processes.Length > 1)
return true;
else
return false;
}

Thursday, May 15, 2008

C#: Convert System.Drawing.Color to Microsoft.Office.Interop.Word.WdColor

Using Microsoft.VisualBasic as an added reference to your C# projects, this is a smart way to convert Color to WdColor.

using VB = Microsoft.VisualBasic;
using Word = Microsoft.Office.Interop.Word;
...

Word.WdColor ConvertSystemColorToWdColor(System.Drawing.Color color)
{
int rgbColor = VB.Information.RGB(color.R, color.G, color.B);
Word.WdColor wdColor = (Word.WdColor)rgbColor;
return wdColor;
}

Monday, April 28, 2008

C#: Get MimeType from a File Name

private string GetMimeType (string fileName)
{
string mimeType = "application/unknown";
string ext = System.IO.Path.GetExtension(fileName).ToLower();
Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if (regKey != null && regKey.GetValue("Content Type") != null)
mimeType = regKey.GetValue("Content Type").ToString();
return mimeType;
}

Tuesday, March 18, 2008

C#: Handle new line characters ("\n") while saving text to file

New line charactars as observed in multi line TextBox or RichTextBox controls ("\n") often cause invalid characters to be saved in the file when it is saved. In order to appropriately handle new line characters, the following code can be used in stead of WriteLine:

FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.OpenOrCreate,FileAccess.ReadWrite);
StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
sw.Write(txtReturn.Text.Replace("\n",Environment.NewLine)); // Environment.NewLine is the real trick ;-)
sw.Dispose(); sw = null;
fs.Dispose(); fs = null;

Monday, January 28, 2008

C#: Execute a windows batch script and wait for return

Unlike simply calling Process.Start("executable_name.exe","arguments") - which does not pause the parent C# process thread, use the below implementation for waiting for the batch script to finish executing before proceeding with the next set of instructions:

using System.Diagnostics;

Process proc = new Process();
proc.StartInfo.FileName = "C:\\myscript.bat";
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.Start();
proc.WaitForExit();
int exitCode = proc.ExitCode;
proc.Close();

Wednesday, January 23, 2008

C#: Equivalent of JavaScript escape function

Although Uri.EscapeDataString, Uri.EscapeUriString, HttpUtility.UrlEncode and HttpUtility.UrlPathEncode are available to use in C# out of the box, they can not convert all the characters exactly the same way as JavaScript escape function does. For example let's say original string is: "KC's trick /Hello". Then,

Uri.EscapeDataString("KC's trick /Hello") gives:
"KC's%20trick%20%2FHello"
Uri.EscapeUriString("KC's trick /Hello") gives:
"KC's%20trick%20/Hello"
System.Web.HttpUtility.UrlEncode("KC's trick /Hello") gives:
"KC's+trick+%2fHello"
System.Web.HttpUtility.UrlPathEncode("KC's trick /Hello") gives:
"KC's%20trick%20/Hello"

Hence the full proof solution is to use the JScript.Net's own implementation. In order to do that here's what you need to use:

1. Reference Microsoft.JScript.dll in the project reference
2. Use Microsoft.JScript.GlobalObject.escape function to do the encode.

So finally Microsoft.JScript.GlobalObject.escape("KC's trick /Hello") gives:
"KC%27s%20trick%20/Hello"

Similarly to unescape, use Microsoft.JScript.GlobalObject.unescape function. So Microsoft.JScript.GlobalObject.unescape("KC%27s%20trick%20/Hello") gives back:
"KC's trick /Hello"

Friday, January 4, 2008

C#: Send email using SmtpClient

using System.Net.Mail;

//mailFrom > "KSeeSharp " - shows up as "KSeeSharp" as sender
//mailTo > Comma delimited email address(es)
//mailServer > Something like smtp.xyz.com

public bool SendEmail(string mailFrom, string mailTo, string subject, string message, string mailServer)
{
bool returnCode = false;

try
{
MailMessage msg = new MailMessage(mailFrom, mailTo, subject, message);
SmtpClient emailClient = new SmtpClient(mailServer);
emailClient.UseDefaultCredentials = true;
emailClient.Send(msg);

returnCode = true;
}
catch (Exception ex)
{
throw ex
}

return returnCode;
}