Archive for the ‘C#’ Category

Retrieve Image from Windows Clipboard via .Net C#

Monday, November 2nd, 2009

If you want to snag clipboard data from a different application into the context of your running .Net application, here’s how you can do it:

private static Image _clipBoardImage = null;

private static Image GetImageFromCopyPasteBuffer()
{
Thread t = new Thread(new ThreadStart(GetClipboardBitmap));
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Join();
return _clipBoardImage;
}

private static void GetClipboardBitmap()
{
IDataObject data = Clipboard.GetDataObject();
if (data == null || !data.GetDataPresent(DataFormats.Bitmap, true))
throw new ApplicationException("No clipboard image data was present.");
_clipBoardImage = (Image)data.GetData(DataFormats.Bitmap);
}

Hope this helps!

.Net Friend Assemblies

Wednesday, October 21st, 2009

Have you ever want to create a “friend” assembly while programming with the .Net framework?  They can be very useful for segmenting your codebase amongst different projects.

Friend Assemblies allow an assembly to see the internal methods and properties of a different assembly by specifying an attribute on the primary assembly that specifies the assembly name of the friend.

The simplest way to do this is to add something like the following to your AssemblyInfo.cs file in your primary project:

[assembly: InternalsVisibleTo("my.friend.assembly")]

This would allow my.friend.assembly to have access to all of the primary project’s internals.

If you need to worry about security of the assemblies (I suppose we all should), then you should also consider using strong names in conjunction with the compiler attribute.

More information on .Net Friend Assemblies can be found here:

http://msdn.microsoft.com/en-us/library/0tke9fxk.aspx

Hope this helps!

JavaScript, UTF-8 Encoding: escape() vs. encodeURIComponent()

Thursday, August 6th, 2009

ASP.Net web applications default to UTF-8 encoding.  Now, if you are using JavaScript to create or change URLs, you might run into an issue with the way the function “escape()” encodes characters if you are handling the decoding in your code behind via Request.QueryString.

To avoid ending up with “unkown” characters in your resultant string, use the JavaScript function “encodeURIComponent()” instead.  This should correctly encode your URLs for UTF-8.

 

 

Convert Hex to Readable String and Readable Text to Hex

Tuesday, June 23rd, 2009

If you ever need to convert Hex data to readable strings or the reverse, try the following methods:

private static readonly  char[] HexChars = "0123456789ABCDEF".ToCharArray();

private static string ConvertToHex(string ascii)
{
if (ascii == null) return null;
if (ascii == "") return "";

byte[] bytes = Encoding.UTF8.GetBytes(ascii);

StringBuilder converted = new StringBuilder(bytes.Length * 2);

foreach (byte b in bytes)
{
converted.Append(HexChars[b >> 4]);
converted.Append(HexChars[b & 0xf]);
}

return converted.ToString();
}

private static string ConvertFromHex(string hex)
{
if (hex == null) return null;
if (hex == "") return "";
if (hex.Length % 2 != 0)
throw new ApplicationException("hex string length should be divisble by 2: " + hex);

byte[] bytes = new byte[hex.Length / 2];

for (int i = 0; i < bytes.Length; i++)
bytes[i] = byte.Parse(hex[2 * i] + "" + hex[2 * i + 1], NumberStyles.HexNumber);

string converted = Encoding.UTF8.GetString(bytes);

if (converted[converted.Length - 1] == '\0')
converted = converted.Remove(converted.Length - 1, 1);

return converted;
}

I have found this is very useful for parsing binary data from Active Directory sources such as “csvde”.

Hope this helps you out! Let me know if you know of a better/faster method – it is always appreciated.

Read a CSV file with Regular Expressions in .Net

Tuesday, June 23rd, 2009

Here’s how you can read a CSV file using Regular Expressions in .Net:

</p>
public static DataTable GetDataTableFromCsvFile(string file)
{
// Where the CSV data goes
DataTable dt = new DataTable("CsvData");

// The pattern used to parse the CSV
const string csvPattern = ",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))";
Regex csvRegex = new Regex(csvPattern);

// Read all lines in the file
// (not great for large files)
string[] fileLines = File.ReadAllLines(file);

// Get the column headers
// (assumes first row has headers and that
//  each column contains string values and
//  that each column name is unique)

Dictionary&lt;int, string&gt; headers = new Dictionary&lt;int, string&gt;();
string[] headerValues = csvRegex.Split(fileLines[0]);

for (int i = 0; i &lt; headerValues.Length; i++)
{
headers.Add(i, headerValues[i]);
dt.Columns.Add(new DataColumn(headerValues[i], typeof (string)));
}

// Then add the the rest of the lines
for (int k = 1; k &lt; fileLines.Length; k++)
{

DataRow dr = dt.NewRow();

string line = fileLines[k];
string[] cols = csvRegex.Split(line);

for (int i = 0; i &lt; cols.Length; i++)
{
string header = headers[i];
string data = cols[i];

// remove quotes around the field
if (data.Length &gt; 1 &amp;&amp; data.StartsWith("\"") &amp;&amp; data.EndsWith("\""))
data = data.Remove(data.Length - 1, 1).Remove(0, 1);

dr[header] = data;
}

dt.Rows.Add(dr);
}

return dt;
}

Of course, you will need to add in error catching and handling as well.

Hope this helps!

Reading a CSV File with an OleDbDataAdapter and Jet

Thursday, June 18th, 2009

Reading a comma delimited is quite simple with an OleDbDataAdapter and Jet 4.0:

private static DataTable ReadCsvFileViaJetOleDb(string file)
{
string connection =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" +
Path.GetDirectoryName(file) +
"\\\";Extended Properties=\"text;HDR=Yes;FMT=Delimited\"";

string query = "SELECT * FROM " + file;

DataTable dt = new DataTable();

using (OleDbDataAdapter da = new OleDbDataAdapter(query, connection))
da.Fill(dt);

return dt;
}

However, you have to remember a few caveats:

  1. Commas may not be your default delimiter for your UI culture
  2. Only txt, csv, asc, and tab are acceptable file extensions
  3. You can’t have more than one period in a file name, e.g. myfile.test.csv won’t work

There are a few options you can tweak via the registry here:

  • HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\4.0\Engines\Text

Sys.WebForms.PageRequestManagerServerErrorException in FireFox with MSFT Ajax

Thursday, December 11th, 2008

If you encounter this error while navigating away from an AJAX-enabled page with a non-IE browser, you can silence it with the following JavaScript:

if (!document.all) //non-ie
{
window.onbeforeunload = function() {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(ignoreOnEndRequest);
}
}

function ignoreOnEndRequest(sender, e) {
err = e.get_error();
if (err) {
if (err.name == "Sys.WebForms.PageRequestManagerServerErrorException") {
e.set_errorHandled(true);
}
}
}

Hope it works for you!


ASP.Net WebServices: Enabling or Disabling POST, GET, and Documentation Requests

Wednesday, September 10th, 2008

It is relatively easy to control access to the various HTTP request types (protocols) for your ASP.Net WebService.

Add something like this to the system.web section of your web.config:

<webServices>
<protocols>
<add name="HttpSoap"/>
<add name="HttpGet"/> <!-- Because this web service is all GET methods remotely -->
<add name="HttpPostLocalhost"/> <!-- So you can test/POST locally -->
<remove name="Documentation"/>  <!-- So the outside world can't see your method documentation -->
<remove name="HttpPost"/> <!-- Remove general POSTs from the outside world -->
</protocols>
</webServices>

Of course you will want to tailor this to the needs of your own web service. :)



Regular Expression (RegEx) to Find Whole Words in a String

Thursday, July 31st, 2008

Ever want to match and replace whole words with in a string?  Regular expressions (System.Text.RegularExpressions) makes it a one line operation:

Regex.Replace(inputText, @"\b" + wordToReplace + @"\b", replacementText, RegexOptions.IgnoreCase);

This pattern uses “word boundries” as your delimiters for matching text.

WinForm Exception Catching

Monday, July 28th, 2008

Here’s a general way to catch most outside exceptions in your WinForm code.  Add this to your program wrapper:

Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);

AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

Of course, it is always better to handle specific cases with specific types of exceptions, but it is also nice to have a general handler for anything that escapes your exception handling.