Shopping Basket Basket (0 Items)

TutorialGenius.com Technical Blog

Welcome to the Ginko Solutions blog. This page provides various tips, projects and helping aides for software developers and web developers. The blog is updated weekly and the latest entries appear within this page. To view the full Ginko Solutions blog, please click the following link

Get and Set Private Properties using Reflection in C#
It's frustrating when you're using an API and some properties you requuire are set as private. This certainly was the case when attempting to resume a video using the YouTube V3 API the other day.

Here is a code snippet on how to set private properties using Reflection.
Code Snippet
  1. private static void SetPrivateProperty<T>(Object obj, string propertyName, object value)
  2. {
  3. var propertyInfo = typeof(T).GetProperty(propertyName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
  4. if (propertyInfo == null) return;
  5. propertyInfo.SetValue(obj, value, null);
  6. }
  7. private static object GetPrivateProperty<T>(Object obj, string propertyName)
  8. {
  9. if (obj == null) return null;
  10. var propertyInfo = typeof(T).GetProperty(propertyName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
  11. return propertyInfo == null ? null : propertyInfo.GetValue(obj, null);
  12. }
End of Code Snippet



MsgBox - A Better Winforms MessageBox in C#

Introduction

MsgBox is an enhanced solution to the in-built MessageBox class. It's designed so that the styles, features and behaviour mimic the in-built control with added features.

MsgBox allows a better Messagebox experience by allowing the following features:
- Do not display this message again
- Custom font styles and font colors
- Scrollbars for text which is too long

Using the code

MsgBox is used like a standard MessageBox object. There is a different return object which encapsulates the original DialogResult. This handles extra information which as whether the user clicked 'Do no display this message again'.

 

Simple Example

Code Snippet
  1. MsgBox.Show(this, &quot;Hello&quot;, &quot;Caption Text&quot;, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
End of Code Snippet

 

Custom Fonts

Code Snippet
  1. MsgBox.Show(this, &quot;Hello&quot;, &quot;Caption Text&quot;, MessageBoxButtons.OK, MessageBoxIcon.Information, true, new Font(&quot;Verdana&quot;, 12f, FontStyle.Bold), Color.Red);
End of Code Snippet

 

Long Text

Code Snippet
  1. MsgBox.Show(this, &quot;Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello&quot;, &quot;Caption Text&quot;, MessageBoxButtons.OK, MessageBoxIcon.Information, true, new Font(&quot;Verdana&quot;, 40f, FontStyle.Bold), Color.Blue);
End of Code Snippet

 

Handling the do not display message again checkbox

Code Snippet
  1. DialogResultNew res = MsgBox.Show(this, &quot;Hello&quot;, &quot;Caption Text&quot;, MessageBoxButtons.OK);
  2. if (res.DoNotDisplayMessageAgain) // Do something here
End of Code Snippet

Download


Download MsgBox Here

 

History

v1.0 - Initial write-up




YouTube Comments and Commenting with YouTube API V3 (Google.Apis.YouTube.v3)


Google deprecated V2 of the YouTube API over a year ago, but as of last month, the URLs have been taken offline; forcing users to upgrade to V3 of the API. One of the last features requiring implementating on the V3 platform was the ability to comment on channels and videos. The following example shows how to leave a top level comment on a channel or video using V3 of the API with C#

Example
Code Snippet
  1.  
  2. YouTubeService youtube; // Init your service here - Make sure you include the new required scope: YouTubeService.Scope.YoutubeForceSsl
  3.  
  4. CommentThreadSnippet commentThreadSnippet = new CommentThreadSnippet();
  5. //commentThreadSnippet.ChannelId; Comment on a channel - leave video id blank if so
  6. commentThreadSnippet.VideoId = v.ID; // Comment on a Video by VideoID
  7.  
  8. // A top level comment is a new comment (Not a reply to an existing comment)
  9. commentThreadSnippet.TopLevelComment = new Comment() { Snippet = new CommentSnippet() { TextOriginal = comment }};
  10.  
  11. // Make an insert request and get result snippet
  12. CommentThreadsResource.InsertRequest commentReq = youtube.CommentThreads.Insert(new CommentThread() { Snippet = commentThreadSnippet}, "snippet");
  13. CommentThread commentRes = commentReq.Execute();
End of Code Snippet



Silently Delete a File within a Windows Batch File (BAT File)
I have recently been preparing some custom install scripts lately and I found a few things that may prove to be of some use! This script deletes a file silently and will not report the result in the console window.

Code Snippet
  1. @echo off
  2. del /s randomtextfile.txt >nul 2>&1 REM Delete file silently
End of Code Snippet



How to get operating system 32bit or 64bit from a Windows Batch File (BAT File)
I have recently been preparing some custom install scripts lately and I found a few things that may prove to be of some use! This script uses a registry key to determine weather the host system is a 32bit or a 64bit system

Code Snippet
  1. @echo off REM Hide output from commands
  2. @echo Attempting to get operating system type (32bit or 64bit)...
  3.  
  4. REM -------------- Get 32bit or 64bit --------------
  5. Set RegQry=HKLM\Hardware\Description\System\CentralProcessor\0
  6. REG.exe Query %RegQry% > checkOS.txt
  7. Find /i "x86" < CheckOS.txt > StringCheck.txt
  8.  
  9. If %ERRORLEVEL% == 0 (
  10.     @echo This is 32 Bit Operating system!
  11.     SET ostype = "32bit"
  12. ) ELSE (
  13.     @echo This is 64 Bit Operating System!
  14.     SET ostype = "64bit"
  15. )
  16. del /s checkOS.txt >nul 2>&1 REM Clean up silently
  17. del /s StringCheck.txt >nul 2>&1 REM Clean up silently
End of Code Snippet



YouTube Bulk Uploader for the Lazy - An Offline Auto-Tagger, Bulk Uploader and VMS for YouTube!
Being a hardcore videographer with very limited time in the world to share my vast collection of videos, I begun the search for an all encompassing video management system with the ability to auto-tag and upload my videos in bulk to YouTube. As I tend to travel lot and have a lot of time where I could be preparing my videos to upload, I found that I needed an internet connection to even tag them and place them into categories and apply the appropriate finishing details. I found a couple of programs which lightly touched on my requirements, but nothing stood up even close to my needs. Therefore I develped my own solution: "YouTube Bulk Uploader: For the Lazy!".



YouTube Bulk Uploader for the Lazy is your simple and fast solution for offline tagging and uploading videos to YouTube in Bulk. Save hours of time and effort today!

YouTube Bulk Uploader for the Lazy allows you to easily BULK UPLOAD and TAG 1000's of videos OFFLINE! The software provides bulk editing of videos (Tags, Categories, Descriptions, Titles etc) and provides a simple to use interface for uploading and managing videos. The software 'tags' each physical video on your drive so you can freely move and rename them and the software will be able to detect where they are at all times! This can all be done offline, so no need for an internet connection until you're ready to upload!

  • Supports ALL YouTube supported video file types. MP4, MOV, MKV, MPEG, 3GP, AVI and more
  • Allows bulk editing of video titles, descriptions, tags, categories, privacy and more
  • Supports multiple YouTube accounts
  • Ability to copy video information between multiple accounts
  • The Tag Manager allows you to pre-define a set of video tags to tag videos faster!
  • The Upload Queue allows to you prioritize your video uploads
  • The Video Database allows you to edit and manage video information
  • File Path Sync allows you to scan your hard drive for video files which have been moved or renamed
  • All features can be performed offline (WITHOUT AN INTERNET CONNECTION!!) (Apart from the uploading part!)
  • YouTube video titles, descriptions and video tags are automatically created using the videos file name!
  • 1 Full Year of Free Product Updates
  • Excellent Customer Support Service
  • All This for Only $19.95!

- See more at: http://ginkosolutions.com/youtube-bulk-uploader




Yellow Pages & Yelp Data Extraction - Crawler Spider Business Email List Capture Grabber Scraper
Developed by an old university friend. Very useful software to build your own business email lists and databases!



Web Contact Scraper is a fully automated software application for gathering targeted business contact information!

You can search and gather thousands of business details matching a chosen profession within any location worldwide! Build your own targeted Email Marketing Lists yourself! You can instantly retrieve 1000 Plumbers in New York or 10,000 Dance Instructors in Australia, the possibilities are endless! Export emails, phone numbers, websites, addresses to CSV and start your targeted business campaign today!

  • Search for multiple business key words (I.e. Construction, Dentist, Lawyer)
  • Search within multiple cities, states and countries!
  • See the search results appear in real-time!
  • In-built tool to remove duplicate contact information
  • Supports Yellow Pages and Yelp!
  • Export results to CSV
  • Proxy IP Support to scrape anonymously!
  • Lifetime Licence Key for up to 2 Computers
  • 1 Full Year of Free Product Updates
  • Excellent Customer Support Service
  • All This for Only $19.95!

- See more at: http://ginkosolutions.com/webcontactscraper




Getting and Setting File Tag Meta Information in C# and ASP.NET - With TagLib and DsoFile Examples
The Problem
I recently developed a video content management system, and rather than store hidden files to track versioning and movement of physical files, I wanted to modify the internal file meta information of the videos themselves. I planned to stuff a database ID into the comment tag within each video file, but this proved to be very challenging given the very disoraganised way in which various operating system handled different file types.

Possible Solutions
MediaInfo - http://sourceforge.net/projects/mediainfo/. Cool API, updated a lot, but there is no support for setting file meta information. The entire API is READ ONLY!

TagLib - https://taglib.github.io/. Again, good API with scope to set file tag meta information. So I decided to try this API out and see how far I could get with it. I started hitting it's limits when I couldn't set file meta information for a LOT of video file types: MKV, MOV, 3GP, ASF and more.

DsoFile - http://support.microsoft.com/en-gb/kb/224351. Microsoft's answer to tagging Microsoft Office file tag information. It's able to set Office file tags but also totally new custom properties within each file. You cannot see these values in Windows Explorer without a handy Powershell script plugin, but it works for ALL file types, not just office documents. It's written in C++ and includes the source code also. The downside is that it's a COM component, 32bit and no longer supported. However, somebody compiled a 64bit version here

The Ideal Solution
DsoFile seems like a great solution to the problem. TagLib works hard to achieve an ideal solution, but there are too many file types out there ever changing and the library finds it hard to keep up. I decided to use DsoFile for my project for the time being. I have provided some sample code below so you can see how TagLib and DsoFile libraries modify file meta tag information.

TagLib Sample Code - How to Get and Set the Comment File Meta Tag Field
Code Snippet
  1. using System;
  2. using TagLib;
  3.  
  4. /// <summary>
  5. /// (c) GinkoSolutions.com
  6. /// This sample class enables you to set meta file information within physical files.
  7. /// This is similar to EXIF information for picture files.
  8. /// TagLib doesn't seem to work for a lot of file types: MKV, MOV etc
  9. /// It seems to work ok for MP4 files though.
  10. /// </summary>
  11. public static class TagLibExample
  12. {
  13.     /// <summary>
  14.     /// Gets the comment tag from a files meta information
  15.     /// </summary>
  16.     /// <param name="filename">Path to the file</param>
  17.     /// <returns>Our custom value stored in the files comment tag</returns>
  18.     public static string GetCommentField(string filename)
  19.     {
  20.         string comment = string.Empty;
  21.         TagLib.File file = null;
  22.  
  23.         try
  24.         {
  25.             file = TagLib.File.Create(filename);
  26.             comment = file.Tag.Comment;
  27.         }
  28.         catch (Exception ex)
  29.         {
  30.             // This library works with limited file types, so unsupported file types are
  31.             // thrown here when trying to use "TagLib.File.Create()"
  32.         }
  33.         finally
  34.         {
  35.             if (file != null) file.Dispose(); // Clean up
  36.         }
  37.  
  38.         return comment;
  39.     }
  40.  
  41.     /// <summary>
  42.     /// Sets the comment tag within a files meta information
  43.     /// </summary>
  44.     /// <param name="filename">Path to the file</param>
  45.     /// <param name="value">Value to store in the comment tag</param>
  46.     public static void SetCommentField(string filename, string value)
  47.     {
  48.         TagLib.File file = null;
  49.  
  50.         try
  51.         {
  52.             file = TagLib.File.Create(filename);
  53.  
  54.             // Set comment tag
  55.             // NOTE: file.Tag.Comment cannot be an empty string, it defaults to null if empty
  56.             file.Tag.Comment = GetCommentField;
  57.             file.Save();
  58.  
  59.             // Check comment was added successfully.
  60.             // For some reason, TagLib won't throw an error if the property doesnt save
  61.             // for certain file types, yet they appear to be supported.
  62.             // So we have to check it actually worked...
  63.             file = TagLib.File.Create(filename);
  64.  
  65.             if (file.Tag.Comment != value)
  66.                 throw new Exception("Could not set comment tag. This file format is not supported.");
  67.         }
  68.         catch (Exception ex)
  69.         {
  70.             // Handle errors here
  71.         }
  72.         finally // Always called, even when throwing in Exception block
  73.         {
  74.             if (file != null) file.Dispose(); // Clean up
  75.         }
  76.     }
  77. }
  78.  
End of Code Snippet


DsoFile Sample Code - How to Store a Value into a Custom Property and Get it back!
Code Snippet
  1. using System;
  2. using DSOFile;
  3.  
  4. /// <summary>
  5. /// (c) GinkoSolutions.com
  6. /// This sample class enables you to set meta file information within physical files.
  7. /// This is similar to EXIF information for picture files.
  8. /// DSOFile works for every file type, not just office files.
  9. ///
  10. /// NOTE
  11. /// DsoFile is an unmnaged 32bit dll. We need to compile in x86 mode or we get 'class not registered exception'
  12. /// There is a third party 64bit version available online, or recompile the C++ source manually.
  13. /// </summary>
  14. public static class DSOFileExample
  15. {
  16.     /// <summary>
  17.     /// A property name that this sample code uses to store tag information.
  18.     /// </summary>
  19.     private static string FILE_PROPERTY = "CustomFileTag";
  20.  
  21.     /// <summary>
  22.     /// Gets value stored in a custom tag
  23.     /// </summary>
  24.     /// <param name="filename">Path to the file</param>
  25.     /// <returns>Our custom value stored in the custom file tag</returns>
  26.     public static string GetCustomPropertyValue(string filename)
  27.     {
  28.         string comment = string.Empty;
  29.         OleDocumentProperties file = new DSOFile.OleDocumentProperties();
  30.  
  31.         try
  32.         {
  33.             // Open file
  34.             file.Open(filename, false, DSOFile.dsoFileOpenOptions.dsoOptionDefault);
  35.             comment = GetTagField(file);
  36.         }
  37.         catch (Exception ex)
  38.         {
  39.             // Handle errors here
  40.         }
  41.         finally
  42.         {
  43.             if (file != null) file.Close(); // Clean up
  44.         }
  45.  
  46.         return comment;
  47.     }
  48.  
  49.     /// <summary>
  50.     /// Sets value stored in a files custom tag
  51.     /// </summary>
  52.     /// <param name="filename">Path to the file</param>
  53.     /// <param name="value">Value to store in the custom file tag</param>
  54.     public static void SetCustomPropertyValue(string filename, string value)
  55.     {
  56.         OleDocumentProperties file = new DSOFile.OleDocumentProperties();
  57.  
  58.         try
  59.         {
  60.             file.Open(filename, false, DSOFile.dsoFileOpenOptions.dsoOptionDefault);
  61.             SetTagField(file, value);
  62.         }
  63.         catch (Exception ex)
  64.         {
  65.             // Handle errors here
  66.         }
  67.         finally // Always called, even when throwing in Exception block
  68.         {
  69.             if (file != null) file.Close(); // Clean up
  70.         }
  71.     }
  72.  
  73.     /// <summary>
  74.     /// Gets the value of the file tag property
  75.     /// </summary>
  76.     /// <param name="file">Ole Document File</param>
  77.     /// <returns>Contents of the file tag property. Can be null or empty.</returns>
  78.     private static string GetTagField(DSOFile.OleDocumentProperties file)
  79.     {
  80.         string result = string.Empty;
  81.         foreach (DSOFile.CustomProperty property in file.CustomProperties)
  82.         {
  83.             if (property.Name == FILE_PROPERTY) // Check property exists
  84.             {
  85.                 result = property.get_Value();
  86.                 break;
  87.             }
  88.         }
  89.         return result;
  90.     }
  91.  
  92.     /// <summary>
  93.     /// Sets the value of the file tag property
  94.     /// </summary>
  95.     /// <param name="file">Ole Document File</param>
  96.     /// <param name="value">Value to set as the property value</param>
  97.     /// <param name="saveDocument">Saves document if set to true</param>
  98.     /// <param name="closeDocument">Closes the document if set to true</param>
  99.     private static void SetTagField(DSOFile.OleDocumentProperties file, string value, bool saveDocument = true, bool closeDocument = true)
  100.     {
  101.         bool found = false;
  102.         foreach (DSOFile.CustomProperty property in file.CustomProperties)
  103.         {
  104.             if (property.Name == FILE_PROPERTY) // Check property exists
  105.             {
  106.                 property.set_Value(value);
  107.                 found = true;
  108.                 break;
  109.             }
  110.         }
  111.  
  112.         if (!found)
  113.             file.CustomProperties.Add(FILE_PROPERTY, value);
  114.  
  115.         if (saveDocument)
  116.             file.Save();
  117.  
  118.         if (closeDocument)
  119.             file.Close();
  120.     }
  121. }
  122.  
End of Code Snippet



How To Link To And Embed YouTube Videos In HD Or A Specific Quality Level
Here is a great post on how to change the default quality of an embedded YouTube video on a webpage.

http://www.h3xed.com/web-and-internet/link-directly-to-and-embed-hd-youtube-videos



Download ALL Old Versions of iTunes
Found a really great website that let's you download ALL older versions of iTunes for iOS, Windows 32bit and Windows 64bit!

Website: http://appstudio.org/itunes/



C# - Serialize and Deserialize using BinaryFormatter with Strings (WITHOUT Files)
This code snippet will allow you to Serialize and DeSerialize any serializable object to a standard string and back. No need for binary files!

Usage:
Code Snippet
  1. // Inits
  2. CustomClass instance = new CustomClass();
  3.  
  4. // Serialize
  5. string data = SerializeObject<CustomClass>(instance);
  6.  
  7. // DeSerialize
  8. CustomClass instance = DeSerializeObject<CustomClass>(data);
End of Code Snippet


Code Snippet
  1. // NOTE: The result of serializing an object with BinaryFormatter is an octet stream, not a string.
  2. //       If we encode the serialized object with Base64, we will get our string.
  3. public static string SerializeObject<T>(T toSerialize)
  4. {
  5.     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
  6.  
  7.     if (!toSerialize.GetType().IsSerializable)
  8.     {
  9.         throw new Exception("Object cannot be serialized in it's current state.");
  10.     }
  11.  
  12.     using (MemoryStream ms = new MemoryStream())
  13.     {
  14.         new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter().Serialize(ms, toSerialize);
  15.         return Convert.ToBase64String(ms.ToArray());
  16.     }
  17. }
  18.  
  19. public static T DeSerializeObject<T>(string data)
  20. {
  21.     byte[] bytes = Convert.FromBase64String(data);
  22.  
  23.     using (MemoryStream ms = new MemoryStream(bytes))
  24.     {
  25.         return (T)new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter().Deserialize(ms);
  26.     }
  27. }
End of Code Snippet



Recursion and Recursive Methods for Dummies - Working C# Example
In Brief
What is Recursion: Very simply put... A method that calls itself.
Why use Recursion?: So we can repeat a methods logic any number of times with differing arguments.
What is an Example of Recursion?: Directories which contain directories which contain more directories and you would like to scan through all of the files within this directory chain. We can create ONE SINGLE method to do this by calling itself recursively. See below for full example.

Here is a working example of a recursive method in C#. It takes a file directory as an argument and recursively loops through all of the files which the WHOLE directory structure. It goes in deep, then works backwards. This is an example of backwards or tail recursion.

Code Snippet
  1. public void NameOfRecursiveMethod(string directoryToSearch)
  2. {
  3.     // Go in deep as far as possible, then work backwards.
  4.     // Find all the subdirectories under this directory.
  5.     foreach (string dir in Directory.GetDirectories(directoryToSearch))
  6.     {
  7.         // Recursive call for each subdirectory.
  8.         this.NameOfRecursiveMethod(dir);
  9.     }
  10.    
  11.     // Note: The First time we arrive here will be inside the deepest first directory
  12.     // Get all files in the directory
  13.     string[] files = Directory.GetFiles(directoryToSearch);
  14.  
  15.     foreach (string filename in files)
  16.     {
  17.         // Do something for each file here
  18.        
  19.     }
  20. }
End of Code Snippet



How to Deep Clone an Object by Value and not by Reference in C#
The following code snippet using serialization to deep clone an object in C#. Please note: ICloneable is a deprecated API. ICloneable is considered a poor API, since it does not specify whether the result is a deep or a shallow copy.

Code Snippet
  1. // Usage
  2. CLASSNAME clonedInstance = DeepClone<CLASSNAME>(instance);
  3.  
  4.  
  5. // Deep clones an object
  6. // Your class (and all sub-classes) MUST be marked as [Serializable] in order for this to work.
  7. public static T DeepClone<T>(T obj)
  8. {
  9.     using (var ms = new System.IO.MemoryStream())
  10.     {
  11.         var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
  12.         formatter.Serialize(ms, obj);
  13.         ms.Position = 0;
  14.  
  15.         return (T)formatter.Deserialize(ms);
  16.     }
  17. }
End of Code Snippet



SQL - Find Duplicate Data Column Values
Here is a quick snippet on how to find duplicate columns within your tables

Code Snippet
  1. select col1, col2, count(*)
  2. from TABLE
  3. group by col1, col2
  4. having count(*) > 1
End of Code Snippet



Free DNS Tools: Ping, Lookup, Trace, Whois, DNS Records, Spam Blacklist Check, Network Lookup and more!
http://network-tools.com/ is a great website that allows you to perform an array of network and troubleshooting steps on any domain or IP address. I use it a lot when troubleshooting domain nameservers and other things that domain registrars should get right, but fail to do so!

Some of the sample operations that can be performed on a domain:
Express
Ping
Lookup
Trace
Whois (IDN Conversion Tool)
DNS Records (Advanced Tool)
Network Lookup
Spam Blacklist Check
URL Decode
URL Encode
HTTP Headers with optional SSL
Email Tests

Check it out!



Binding a DataGridView to a Collection - Notify Grid When Properties are Changed (BindingList and INotifyPropertyChanged)
When utilising a DataGridView or similar control within your windows and web applications, you may wish to bind to a collection (List, ArrayList etc). Binding is always great as you can maintain and manage your custom objects very easily. What can be tough to manage is when you may wish to edit the controls data (A cells contents within a DataGridView for example), so you have to edit the data within your data source (I.e. List of custom objects), then re-bind to reflect the new changes.

The method above would work, but utilising a more Observer Pattern approach to our programming, we can automatically notify the grid when we update any of our properties within our custom collection. You simply need to inherit from INotifyPropertyChanged within your custom object and bind to a DataGridView with a BindingList collection (Very similar to a List). Within the set properties for your custom object, simply raise an event.

A full example can be found here: http://tech.pro/tutorial/776/csharp-tutorial-binding-a-datagridview-to-a-collection



Free DataGrid / DataGridView for WinForms and ASP.NET MVC (SourceGrid)
SourceGrid is a .NET Windows Forms grid control written entirely in C# with managed code. SourceGrid can be used to visualize or to change data in a table format.



Features
- three sub-components, Grid, DataGrid, ArrayGrid
- Multi selection mode, Row Selection, Column selection, Free selection
- Cell and Row spanning
- MVC support
- Full feature list

Website: http://sourcegrid.codeplex.com
Code Project: http://www.codeproject.com/Articles/3531/SourceGrid-Open-Source-C-Grid-Control



Lock Web.Config ASP.NET Configuration Settings
By default, ASP.NET configuration files that are located in subdirectories override and extend configuration settings that are declared in parent configuration files. In application hosting scenarios, you might want to lock some settings of an ASP.NET application to prevent modification at lower levels. For example, you can lock the security settings for hosted applications to help prevent administrators from inadvertently changing those security settings.

You can lock configuration settings in ASP.NET configuration files (Web.config files) by adding an allowOverride attribute to a location element and setting the allowOverride attribute to false. Then within the location element, you can define the configuration section that you want to lock. ASP.NET will throw an exception if another configuration file attempts to override any configuration section that is defined within this locked location element.

Using a location element with an allowOverride=false attribute locks the entire configuration section. You can also lock individual configuration elements and attributes using lockItem, lockElements, lockAttributes, lockAllAttributesExcept, and lockAllElementsExcept.

Example:
The following code example shows part of a Web.config file that locks the trust level of two different ASP.NET applications: application1 and application2. Any attempt to override the configuration settings in the trust configuration section raises a configuration system error.
Code Snippet
  1. <configuration>
  2.   <location path="application1" allowOverride="false">
  3.     <system.web>
  4.       <trust level="High" />
  5.     </system.web>
  6.   </location>
  7.  
  8.   <location path="application2" allowOverride="false">
  9.     <system.web>
  10.       <trust level="Medium" />
  11.     </system.web>
  12.   </location>
  13. </configuration>
End of Code Snippet



Avoid Web.Config Inheritance in Child Web Application by using location inheritInChildApplications = false
With shared hosting platforms like: HostGator, GoDaddy, Dreamhost to name a few, you can easily pickup some entry level Windows Plesk Hosting with all the ASP.NET trimmings quite cheaply! If you're an avid developer with a hand in all the pies, you probably have at least 5 or more web apps and/or web services you want to host all in the same shared hosting space!
If this IS your scenario, beware that entry level shared hosting plans have ONE APP POOL for ALL of your apps! See my post on Application Pools and Web Applications for more information.

Why may I need to do this?
If you have a web application, for example, sitting in your root directory and another web application/service sitting in a sub folder, then by default, this child web app will inherit the Web.Config settings of the root application.
If your root application is .NET 4.5 and your sub-apps are .NET 2.0, then you may already be seeing a few fancy errors! This is just one of many reasons why we need to prevent this. This post outlines TWO methods to do this...

Method 1
You can prevent inheritance by utilizing the location tag's inheritInChildApplications attribute. You should put the location tag in the ROOT Web.Config and NOT the child app's Web.Config in our example. The path attribute of the location tag is set to a wildcard (.) to specify ANY child app location. You can set this to a path attribute to target a single app if you prefer by entering it's location. As good practice, you should wrap individual tags with the location tag (The location tag can appear more than once in the Web.Config file!). Do not wrap EVERYTHING in the Web.Config with the location tag.
Code Snippet
  1. <?xml version="1.0"?>
  2. <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
  3. <!-- disable inheritance for the connectionStrings section -->
  4. <location path="." inheritInChildApplications="false">
  5.    <connectionStrings>
  6.    </connectionStrings>
  7. </location>
  8.  
  9. <!-- leave inheritance enabled for appSettings -->
  10. <appSettings>
  11. </appSettings>
  12.  
  13. <!-- disable inheritance for the system.web section -->
  14. <location path="." inheritInChildApplications="false">
  15.    <system.web>
  16.         <webParts>
  17.         </webParts>
  18.         <membership>
  19.         </membership>
  20.  
  21.         <compilation>
  22.         </compilation>
  23.       </system.web>
  24.  </location>
  25. </configuration>
End of Code Snippet

Note: I included xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0" as an attribute of the configuration tag as inheritInChildApplications is defined in the .NET 2.0 schema. Setting this is good practise and will also remove the warning in Visual Studio about the inheritInChildApplications attribute not being recognized.
WARNING!!! There is no good way of disabling inheritance of the configSections tag (As configSections must appear as the first tag in the Web.Config!). Microsoft issued a statement stating that it would be too complex to handle this appropriately using their given development methods. Simply, make sure that your sectiongroup name's don't clash with child apps. You can simply rename one of them if they do share the same name. Easy fix!


Method 2
You can also prevent inheritance by using clear and/or remove tags in the child's Web.Config to clear our any inherited values defined in the root Web.Config.
This is an example of a child app's Web.Config. It clears our any inherited connection strings defined by the root application. You then define the child app's connection strings BELOW the clear attribute. Note: Depending upon the Web.Config tag involved, you may need a remove attribute rather than a clear.
Code Snippet
  1. <?xml version="1.0"?>
  2. <configuration>
  3.     <connectionStrings>
  4.         <clear/>
  5.         <!-- Child config's connection strings -->
  6.     </connectionStrings>
  7. </configuration>
End of Code Snippet





How Many Web Applications Should I Run Per Application Pool
When we think of desktop applications like notepad, we know that each time it runs, the OS defines a new process (notepad.exe for example)...

This is not the same for a web application... A web application needs a host process to be executed. This means that a process manages the web application and allows its execution. Starting from IIS6, this process is called w3wp.exe.
A web application runs on top of an application pool that you define in IIS. An application pool, can be associated to one or more worker processes.

The following example defines a common mistake people make when setting up web applications within web servers.... A web server administrator defines an application pool and executes multiple web applications on top of it. I worked with customer who has 20 -30-web applications on top of a single application pool!
This is bad very bad especially for 32-bit processes. Let me try to explain why...

Every web application needs:
1. Assemblies loaded in memory
2. Memory to calculate the application goal.

If you define a single application pool for all web applications, what happens is that all web apps have to load their assemblies and share the same memory. Do you think that this memory is infinite? No, it is not.

In a 32-bit process, by default every application can allocate 2GB of memory and a 32-bit process on a 64-bit machine 4GB. Those values are the maximum ones available by default, but do not except to use all that memory.

Typically, an Out Of Memory exception occurs before that value. It happens due to internal memory fragmentation!

In the case that your applications are managed: ASP.NET to be clear, what happens is that Garbage Collector (GC) cleans up the memory. If all web applications share the same memory, then this one is under pressure.
It means that GC runs multiple times per second in order to provide clean memory for your app. What is the side effect? In server mode, the GC is required to stop all threads activities to clean up the memory (this was improved on .NET Fx 4.5, where the collation does not require to stop all threads).

What is the side effect?
Slow performance of your web application
High impact on CPU time due to GC’s activity.

Furthermore, if one of your web applications crashes, all application running on the same pool will be impacted. There are also other things to consider....
Threadpool, the number of threads that a single process can define is not infinite. So all of the web applications have to share that number/threads. Same thing for the connection pool and so on.

Please do not consider this post in the following way: define necessarily one application pool per web application. This is not the goal, IIS gives you the flexibility to host multiple applications on the same application pool. However, when you decide how many applications have to run on top of the same application pool, take care!




WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)
Example scenario when you might stumble across this error
When your creating a web application which utilizes the jquery framework and is targeted against .NET 4.5 framework (I.e. When httpRuntime targetFramework is set to 4.5 in your config).

What is jQuery Unobtrusive Validation?
Basically, it is simply Javascript validation that doesn't pollute your source code with its own validation code. This is done by making use of data- attributes in HTML. You can then read the validation even in the HTML source.

With the unobtrusive way:

You don't have to call the validate() method.
You specify requirements using data attributes (data-val, data-val-required, etc.)

Jquery Validate Example:

Code Snippet
  1. <input type="text" name="email" class="required">
  2.         $(function () {
  3.             $("form").validate();
  4.         });
End of Code Snippet


Jquery Validate Unobtrusive Example:

Code Snippet
  1. <input type="text" name="email" data-val="true"
  2. data-val-required="This field is required.">  
  3.  
  4. <div class="validation-summary-valid" data-valmsg-summary="true">
  5.     <ul><li style="display:none"></li></ul>
  6. </div>
End of Code Snippet


How to use jQuery Unobtrusive Validation and FIX the issue
You can fix this problem by registering jQuery in Global.asax in the Application_Start event. Be sure to replace the jquery version with your particular version!

Code Snippet
  1. ScriptManager.ScriptResourceMapping.AddDefinition("jquery",
  2.     new ScriptResourceDefinition
  3. {
  4. Path = "~/scripts/jquery-1.7.2.min.js",
  5. DebugPath = "~/scripts/jquery-1.7.2.min.js",
  6. CdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.1.min.js",
  7. CdnDebugPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.1.js"
  8. });
End of Code Snippet

How to disable jQuery Unobtrusive Validation
Add this code snippet to your web.config file. If this key value is set to "None" [default], the ASP.NET application will use the pre-4.5 behavior (JavaScript inline in the pages) for client-side validation logic. However, If this key value is set to "WebForms", ASP.NET uses HTML5 data-attributes and late bound JavaScript from an added script reference for client-side validation logic.
Code Snippet
  1. <appSettings>
  2.      <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
  3. </appSettings>
End of Code Snippet



Apply a Text Label with Optional background on to a Graphics Object (System.Drawing)
The following code allows you to apply to text label on to a Graphics object in C#. The background is optional but very useful if you want to set a properly aligned background color for your text label. Note: I use a lot of using statements so that anything implementing IDisposable is disposed of properly.

Usage:
Code Snippet
  1. using (Bitmap b = new Bitmap("FULL PATH TO YOUR IMAGE"))
  2. {
  3.     using (Graphics g = Graphics.FromImage(b))
  4.     {
  5.         using (Font fontText = new Font(new FontFamily("Verdana"), 14, FontStyle.Bold)) // Verdana 14em Bold
  6.         {
  7.             using (Brush fontTextBrush = new SolidBrush(Color.White)) // White Text Color
  8.             {
  9.                 PointF fontTextPoint = new PointF(5, 5); // Write the text at position (5,5)
  10.                 string textLabel = "Hello From TutorialGenius.com!";
  11.                
  12.                 // Example - Black background
  13.                 this.ApplyText(g, textLabel, fontText, fontTextBrush, fontTextPoint, Color.Black);
  14.                
  15.                 // Example - No background
  16.                 this.ApplyText(g, textLabel, fontText, fontTextBrush, fontTextPoint);
  17.             }
  18.         }
  19.     }
  20. }
End of Code Snippet


Code Snippet
  1. // Applies a text layer with optional background onto a Graphics object
  2. private void ApplyText(Graphics g, string text, Font font, Brush brush, PointF? point = null, Color? backgroundColor = null)
  3. {
  4.     if (point == null) point = new PointF(0, 0);
  5.  
  6.     // First - Apply optional background color
  7.     if (backgroundColor.HasValue)
  8.     {
  9.         SizeF fontTextSize = g.MeasureString(text, font);
  10.         using (Brush fillBrush = new SolidBrush(Color.Black))
  11.             g.FillRectangle(fillBrush, point.Value.X, point.Value.Y, fontTextSize.Width, fontTextSize.Height);
  12.     }
  13.  
  14.     // Second - Draw string on graphics object
  15.     g.DrawString(text, font, brush, point.Value);
  16. }
End of Code Snippet



How to Reflow Electronic Components - Motherboards, Video Cards, PCBs etc! (Oven Baking Method!)
What is a Reflow?
The term ‘reflow’ describes a process of briefly melting (reflowing) the solder on an electrical circuit board, in this case a laptop motherboard.

Why would you perform a Reflow on a laptop motherboard?
The solder used in laptop motherboards tends to degrade over time, becoming brittle and weak. It can change from being a solid block of solder into more of a honeycomb structure. This weaker solder joint can fracture causing tiny broken connections in the circuit, invisible to the naked eye. The idea behind performing a reflow is that it melts the solder, allowing it to form a solid block again and joining up the electrical circuit.

See more here, it uses a motherboard as an example
http://www.computerrepairtips.net/how-to-reflow-a-laptop-motherboard/



C#/ASP.NET - Testing Email from localhost without SMTP Server
A lot of the time when developing apps, you need to send emails from your application. Developers need a way to test this and sometimes setting up a SMTP server is a little overkill. Thankfully, the .NET framework has a built in way for you to set this up so you can send the emails to your hard drive as opposed to a SMTP server.

Simply add the following code to your web.config or app.config...

Code Snippet
  1. <system.net>
  2. <mailSettings>
  3. <smtp deliveryMethod="SpecifiedPickupDirectory">
  4. <specifiedPickupDirectory pickupDirectoryLocation="c:\Temp\" />
  5. </smtp>
  6. </mailSettings>
  7. </system.net>
End of Code Snippet


Usage:
Code Snippet
  1. System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage("fromEmail@email.com",
  2. "toEmail@email.com", "Test", "Test Body");
  3. System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
  4. client.Send(mail);
End of Code Snippet



Serialize and Deserialize any WPF UIElement to XAML and Back!
The following snippet uses XamlReader and XamlWriter objects to serialize and deserialize WPF UIElements (Like Canvas for example!) to XAML and back.

Usage (Serialize):
Code Snippet
  1. Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
  2. dlg.FileName = "UIElement File"; // Default file name
  3. dlg.DefaultExt = ".xaml"; // Default file extension
  4. dlg.Filter = "Xaml File (.xaml)|*.xaml"; // Filter files by extension
  5.  
  6. // Show save file dialog box
  7. Nullable<bool> result = dlg.ShowDialog();
  8.  
  9. // Process save file dialog box results
  10. if (result == true)
  11. {
  12.     // Save document
  13.     string filename = dlg.FileName;
  14.     SerializeToXAML(MYUIELEMENTOBJECT, filename);
  15. }
End of Code Snippet


Usage (Deserialize) - Example using a Canvas:
Code Snippet
  1. Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
  2. dlg.DefaultExt = ".xaml"; // Default file extension
  3. dlg.Filter = "Xaml File (.xaml)|*.xaml"; // Filter files by extension
  4.  
  5. // Show open file dialog box
  6. Nullable<bool> result = dlg.ShowDialog();
  7.  
  8. // Process open file dialog box results
  9. if (result == true)
  10. {
  11.     string filename = dlg.FileName;
  12.     Canvas canvas = DeSerializeXAML(filename) as Canvas;
  13.  
  14.     // Add all child elements (lines, rectangles etc) to canvas
  15.     while (canvas.Children.Count > 0)
  16.     {
  17.         UIElement obj = canvas.Children[0]; // Get next child
  18.         canvas.Children.Remove(obj); // Have to disconnect it from result before we can add it
  19.         MYCANVASOBJECT.Children.Add(obj); // Add to canvas
  20.     }
  21. }
End of Code Snippet


Code Snippet
  1. // De-Serialize XML to UIElement using a given filename.
  2. public static UIElement DeSerializeXAML(string filename)
  3. {
  4.     // Load XAML from file. Use 'using' so objects are disposed of properly.
  5.     using (System.IO.FileStream fs = System.IO.File.Open(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read))
  6.     {
  7.         return System.Windows.Markup.XamlReader.Load(fs) as UIElement;
  8.     }
  9. }
  10.  
  11. // Serializes any UIElement object to XAML using a given filename.
  12. public static void SerializeToXAML(UIElement element, string filename)
  13. {
  14.     // Use XamlWriter object to serialize element
  15.     string strXAML = System.Windows.Markup.XamlWriter.Save(element);
  16.  
  17.     // Write XAML to file. Use 'using' so objects are disposed of properly.
  18.     using (System.IO.FileStream fs = System.IO.File.Create(filename))
  19.     {
  20.         using (System.IO.StreamWriter streamwriter = new System.IO.StreamWriter(fs))
  21.         {
  22.             streamwriter.Write(strXAML);
  23.         }
  24.     }
  25. }
End of Code Snippet