Blog Stats
  • Posts - 94
  • Articles - 0
  • Comments - 10
  • Trackbacks - 0

 

C#

Coding in C#

Retrieve Image from Windows Clipboard via .Net C#

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

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...

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

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

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: " +...

Read a CSV file with Regular Expressions in .Net

Here’s how you can read a CSV file using Regular Expressions in .Net: 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<int, string> headers = new Dictionary<int, string>();    ...

Reading a CSV File with an OleDbDataAdapter and Jet

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: Commas may not be your default delimiter for your UI culture Only txt, csv, asc, and tab are acceptable file extensions You can't have more than one period in a file name, e.g. myfile.test.csv won't...

Sys.WebForms.PageRequestManagerServerErrorException in FireFox with MSFT Ajax

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: <script type="text/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); } } }</script> Hope it works for you!

FireFox caches JavaScript state

Firefox uses in memory caching for JavaScript and can cause strange errors in your MSFT ASP.NET Ajax applications. Try adding this to your load event to prevent those errors:    if (Request.Browser.MSDomVersion.Major == 0) // Non IE Browser?)    {        Response.Cache.SetNoStore(); // No client side cashing for ...

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

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 -->         <add name="HttpPostLocalhost"/> <!-- So you can test/POST locally -->         <remove name="Documentation"/>  <!-- So the outside world can't see your methods 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

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.

Full C# Archive

 

 

Copyright © Greg Steen