Tuesday 16 December 2014

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

Saturday 13 December 2014

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/

Saturday 6 December 2014

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

Friday 5 December 2014

Save File Dialog in WPF (Microsoft.Win32.SaveFileDialog)


The following code example shows a quick way on how to use the Microsoft.Win32.SaveFileDialog namespace within WPF to show the SaveFileDialog.

Code Snippet
  1. Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
  2. dlg.FileName = "Image"; // Default file name
  3. dlg.DefaultExt = ".bmp"; // Default file extension
  4. dlg.Filter = "Bitmap File (.bmp)|*.bmp"; // 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.     // Use filename here if required!
  13.     string filename = dlg.FileName;
  14. }
End of Code Snippet

Saving a Window or Canvas as a PNG Bitmap in WPF


The following code snippet takes a file name and a DPI value and you can chose weather to save the canvas or window to a PNG Bitmap image.

Usage:
Code Snippet
  1. Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
  2. dlg.FileName = "Image"; // Default file name
  3. dlg.DefaultExt = ".png"; // Default file extension
  4. dlg.Filter = "PNG File (.png)|*.png"; // 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.     SaveCanvasToFile(this, DrawingCanvas, 96, filename);
  15. }
End of Code Snippet


Code Snippet
  1. public static void SaveCanvasToFile(Window window, Canvas canvas, int dpi, string filename)
  2. {
  3.     Size size = new Size(window.Width, window.Height);
  4.     canvas.Measure(size);
  5.     //canvas.Arrange(new Rect(size));
  6.  
  7.     var rtb = new RenderTargetBitmap(
  8.         (int)window.Width, //width
  9.         (int)window.Height, //height
  10.         dpi, //dpi x
  11.         dpi, //dpi y
  12.         PixelFormats.Pbgra32 // pixelformat
  13.         );
  14.     rtb.Render(canvas);
  15.  
  16.     SaveRTBAsPNGBMP(rtb, filename);
  17. }
  18.  
  19. public static void SaveWindowToFile(Window window, int dpi, string filename)
  20. {
  21.     var rtb = new RenderTargetBitmap(
  22.         (int)window.Width, //width
  23.         (int)window.Width, //height
  24.         dpi, //dpi x
  25.         dpi, //dpi y
  26.         PixelFormats.Pbgra32 // pixelformat
  27.         );
  28.     rtb.Render(window);
  29.  
  30.     SaveRTBAsPNGBMP(rtb, filename);
  31. }
  32.  
  33. private static void SaveRTBAsPNGBMP(RenderTargetBitmap bmp, string filename)
  34. {
  35.     var enc = new System.Windows.Media.Imaging.PngBitmapEncoder();
  36.     enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bmp));
  37.  
  38.     using (var stm = System.IO.File.Create(filename))
  39.     {
  40.         enc.Save(stm);
  41.     }
  42. }
End of Code Snippet

Tuesday 25 November 2014

Hosting Multiple Domains Under One Hosting Plan (Web.config, IIS, Windows)


Great blog article detailing how to host and manage multiple domains under a single hosting plan.
http://weblogs.asp.net/owscott/iis-url-rewrite-hosting-multiple-domains-under-one-site

Monday 24 November 2014

iPhone/iPad - How to Sniff iOS Traffic Using Fiddler on Windows


Here is a great article on how to sniff all traffic on an iOS device! Great way to see what servers apps are calling and what data is being passed in the background
http://www.diaryofaninja.com/blog/2010/11/09/using-fiddler-to-sniff-mobile-device-application-traffic

Saturday 22 November 2014

How to Host a Primary Domain from a Subdirectory (Using .htaccess)


Like some of you, you may have multiple domain names pointing to different servers, but sometimes, you may wish to have a domain name point to a specific server path (Without URL Forwarding). This post offers a solution on how to accomplish this using a web server that supports .htaccess

Preliminary - What is .htaccess (Read to understand the remainder of this post)
http://en.wikipedia.org/wiki/.htaccess

Modifying the .htaccess
The following code will need to be added to the .htaccess file in the main folder of your web server. You will need to insert the following code block and make modifications as noted in the (#) comments. You will need to change the two instances of example.com to your domain, and the three instances of subdirectory to the folder where you want your site.

Code Snippet
  1. # .htaccess main domain to subdirectory redirect
  2. # Do not change this line.
  3. RewriteEngine on
  4. # Change example.com to be your main domain.
  5. RewriteCond %{HTTP_HOST} ^(www.)?example.com$
  6. # Change 'subdirectory' to be the directory you will use for your main domain.
  7. RewriteCond %{REQUEST_URI} !^/subdirectory/
  8. # Don't change the following two lines.
  9. RewriteCond %{REQUEST_FILENAME} !-f
  10. RewriteCond %{REQUEST_FILENAME} !-d
  11. # Change 'subdirectory' to be the directory you will use for your main domain.
  12. RewriteRule ^(.*)$ /subdirectory/$1
  13. # Change example.com to be your main domain again.
  14. # Change 'subdirectory' to be the directory you will use for your main domain
  15. # followed by / then the main file for your site, index.php, index.html, etc.
  16. RewriteCond %{HTTP_HOST} ^(www.)?example.com$
  17. RewriteRule ^(/)?$ subdirectory/index.html [L]
End of Code Snippet


Visitors to your Web site will not be able to tell that your main domain is using a subdirectory, they will still see the Web site address as http://www.example.com/page.html.

Please note that this will not work with some website software. You may also need to modify the $base_url, $live_site or other configuration settings to finish the process.

Sunday 16 November 2014

CD and DVD File Systems Explained!


ISO9660
The original one that's been around for years and has quite limited functionality.
For Example:
You're limited to 8.3 characters for a file name (i.e. SOMEDOCU.TXT)
You're limited to all uppercase file names.
You're limited to file less than 4GB in size.

Joliet
An extension of ISO9660 and allows for longer / mixed case file names. The file size limit still applies. For Joliet to be used, ISO9660 must also be present - this is reflected in the options available.

UDF
UDF is a file system in it's own right and does not depend on another one also being present.
UDF supports long / mixed case file names and does NOT have the 4GB file size limit of Joliet and ISO9660.
It is the 'better' option for those people using up-to-date operating system. I say 'up-to-date' because older ones like Windows 95 and 98 cannot read / understand the UDF file system and will probably report the disc as being corrupt if that's the only one on it.

Standalone DVD players are only supposed to (made to) understand UDF. Being able to read ISO9660 / Joliet is optional. As such, if you're building a DVD Video disc, you at least want to make sure the UDF filesystem is present in any image you're building / burning.
A typical DVD Video disc you buy from a shop will use 'ISO9660 + UDF', so to be totally correct, that's what you should use too. That way, a standalone player can read it (due to UDF) and PC's with old operating systems can read it (due to ISO9660). A new operating system can read both but will favour UDF because it's more advanced.

More Info Here

Saturday 15 November 2014

Visual Studio Designer Errors - Could not find type 'CONTROL NAME HERE'. Please make sure that the assembly that contains this type is referenced


Problem
When working with visual development projects in Visual Studio (Can occur in WinForms and WPF applications!), you may encounter a Designer/XAML error such as the following:

To prevent possible data loss before loading the designer, the following errors must be resolved:

Could not find type 'CONTROL NAME HERE'. Please make sure that the assembly that contains this type is referenced. If this type is a part of your development project, make sure that the project has been successfully built using settings for your current platform or Any CPU.

The variable 'CONTROL NAME HERE' is either undeclared or was never assigned.

When these errors occur, typically you may have an error within your application. Simply fix the error, rebuild your solution, and the designer error will disappear! However.... this may not always be the case!

Who What Where Why
In Win Forms applications, Visual Studio keeps a designer file for each Form class within your application. This details where components are laid out of the form, their events, text values and more! (Basically all of their properties). Sometimes, these designer files get a little confused and they cannot sync properly with what the form contains as it's all done automatically behind the scenes. This can happen a lot when using User Controls as the project needs to be built successfully in order for the form to consume the control! (These designer errors may typically reference a User Control a lot of the time).

Resolution
If there are no errors within your application and this error appears, DO NOT EDIT THE DESIGNER FILE! (Never do this for that matter!), Visual Studio should always handle this task. Simply, re-build the whole solution, then restart Visual Studio.

Friday 14 November 2014

Task.Factory.StartNew (.NET 4.0) and Task.Run (.NET 4.5)


Task.Factory.StartNew (.NET 4.0)
Task.Run (.NET 4.5)

When to use Task.Run and Task.Factory.StartNew
http://blogs.msdn.com/b/pfxteam/archive/2011/10/24/10229468.aspx

Using Git and Bit Bucket with Visual Studio 2012


Great article here!
http://ilblogdipego.blogspot.com/2013/03/how-to-use-git-with-visual-studio-2012.html

Thursday 13 November 2014

c# WPF - Detecting Key Presses - Example: Detecting CTRL+C in a TextBox


The following example allows you to override the keyboard shortcut for copy (Control + C) on the KeyDown event of a WPF TextBox control.

Code Snippet
  1. private void TEXTBOX_KeyDown(object sender, KeyEventArgs e)
  2. {
  3.     if (e.Key == Key.C && Keyboard.Modifiers == ModifierKeys.Control)
  4.     {
  5.         MessageBox.Show("CTRL + C has been pressed!");
  6.     }
  7. }
End of Code Snippet

Monday 10 November 2014

Visual Studio Does Not Show Unhandled Exception Message on a 64-bit version of Windows (Silent Exceptions x64)


Silent exceptions on x64 development machines

Have you ever expected an exception to present itself in Visual Studio but the application seemed to play it cool and continue to run (With very unexpected results ensued!)? Then you may have experienced Silent Exception Syndrome! This seems to occur all in 64bit versions of Windows prior to Windows 8 (Vista, 7 etc...)

The Cause
When a user mode exception crosses a kernel transition, x64 versions of Windows do not allow the exception to propagate. Therefore attached debuggers are unaware of the fact that an exception occured resulting in the debugger failing to break on the unhandled exception.

Work Around
This is a known bug with x64 versions of Windows and the way exceptions are handled. One way to work around this issue while debugging is to go to the Debug -> Exceptions and select 'Thrown' for for the exception types you are interested in. This will stop the debugger when the exception is first hit (and before Windows eats it up).

Permanent Fix
Install this Hot Fix

More Information
http://blog.paulbetts.org/index.php/2010/07/20/the-case-of-the-disappearing-onload-exception-user-mode-callback-exceptions-in-x64/

Friday 7 November 2014

C# WinForms and WPF - Getting an Accurate Line Count for a Multline Textbox


You may have used the TextBox.LineCount Property for a standard Textbox control, but you'll quickly notice that if lines overflow onto the next line you'll have an extra line added to your line count. Really, you would like to count every physical line (Which ends in a physical return. I.e. \r\n)

Here is a code snippet that I use, it also ignores empty lines...

Code Snippet
  1. string[] lines = System.Text.RegularExpressions.Regex.Split(MULTILINETEXTBOX.Text.Trim(), "\r\n");
  2. int lineCount = lines.Length;
End of Code Snippet

Wednesday 5 November 2014

[Return Code 550] sid: RandomSIDHere :: High probability of spam (C# System.Net.Mail Fix)


I have written an emailer application in C# using the System.Net.Mail library. The application allows me to email multiple contacts in large quantities. This is useful for many reasons but I mainly use it for notifying subscribed users of software updates and issue licence keys.

What can be frustrating something sometimes is when you email is bounced back by the receiving party's email server stating that the message could potentially be spam. You will typically receive an email back with something along the lines of: "[Return Code 550] sid: RandomSIDHere :: High probability of spam".

Incoming mail servers typically check for a "Message-Id" header as part of the email. Email clients use this to track the thread of the message among other things. You can read more about Message-Id here.

We can attach a Message-Id attribute to our outgoing mail messages in C# with one very simple line of code (Where 'mail' is a MailMessage object)

Code Snippet
  1. mail.Headers.Add("Message-Id", string.Format("<{0}@{1}>", Guid.NewGuid().ToString(), "yourdomain.com"));
End of Code Snippet

Tuesday 4 November 2014

C# and VB.NET - Google Chrome WebBrowser Control for WinForms and WPF


Anybody that has used the inbuilt WebBrowser control in WinForms and WPF has noticed that it's an old version of Internet Explorer can throws a lot of script errors, renders pages badly and is prone to memory leaks.

This blog post will provide a little insight into using The Chromium Embedded Framework (CEF) as an alternative. Chromium in a nutshell is basically a development release of Google Chrome. When a chosen release has been put through testing and deployed, it is a simply a new version of Google Chrome.

Chromium Embedded Framework (CEF) is an open source project and actively maintained (As of 2014)... These are two good things we look for when re-using existing development frameworks. You can visit the CEF development page here.

External Projects
The base CEF framework includes support for the C and C++ programming languages. Thanks to the hard work of external maintainers CEF can integrate with a number of other programming languages and frameworks. These external projects are not maintained by CEF so please contact the respective project maintainer if you have any questions or issues.

.Net - https://github.com/chillitom/CefSharp
.Net (CEF1) - https://bitbucket.org/fddima/cefglue
.Net/Mono (CEF3) - https://bitbucket.org/xilium/xilium.cefglue
Delphi (CEF1) - http://code.google.com/p/delphichromiumembedded/
Delphi (CEF3) - http://code.google.com/p/dcef3/
Go - https://github.com/CzarekTomczak/cef2go
Java - http://code.google.com/p/javachromiumembedded/
Java - http://code.google.com/p/javacef/
Python - http://code.google.com/p/cefpython/

For C# and VB.NET applications, I recommend CefSharp. Download via NuGet and add to your project with ease!

CefSharp
This project contains .NET CLR bindings for The Chromium Embedded Framework (CEF) by Marshall A. Greenblatt. A small Core of the bindings are written in C++/CLI but the majority of code here is C#. It can of course be used from any CLR language, e.g. C# or VB.

CefSharp provides both WPF and WinForms web browser control implementations. See the CefSharp.Wpf.Example or CefSharp.WinForms.Example projects for example web browsers built using this library; they are (at this moment) the best "documentation" of features. In addition see the CefSharp.MinimalExample repo for how CefSharp can actually be used via NuGet packages.

Sunday 2 November 2014

Encode and Decode to Base64 in C#


Base64
Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding.

Base64 encoding schemes are commonly used when there is a need to encode binary data that needs to be stored and transferred over media that are designed to deal with textual data. This is to ensure that the data remains intact without modification during transport. Base64 is commonly used in a number of applications including email via MIME, and storing complex data in XML.

Here is a simple static class that allows you to Encode and Decode a value to and from Base64 encoding!

Code Snippet
  1. public class Base64Helper
  2. {
  3.     public static string Encode(string plainText)
  4.     {
  5.         var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
  6.         return System.Convert.ToBase64String(plainTextBytes);
  7.     }
  8.  
  9.     public static string Decode(string base64EncodedData)
  10.     {
  11.         var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
  12.         return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
  13.     }
  14. }
End of Code Snippet

Thursday 30 October 2014

C# WinForms - How to Select All Text in a Multiline Textbox


You can either override KeyUp or KeyDown for your TextBox. Simply use the following code...


Code Snippet
  1. private void TextBox_KeyUp(object sender, KeyEventArgs e)
  2. {
  3.     if (e.KeyData == (Keys.Control | Keys.A))
  4.         TextBox.SelectAll();
  5. }
End of Code Snippet

Wednesday 29 October 2014

Email Marketing Lists - Email Lists - Targeted Business Email Campaigns


Web Contact Scraper is a fully automated software application for gathering targeted business contact information!
Web Contact Scraper allows you to retrieve thousands of business contact information entries in real-time. You can use this information to start your very own business campaign. Are you a new business owner? Want to advertise to other similar businesses to promote yourself or a service? Then Web Contact Scraper is for you!
Web Contact Scraper allows you to set multiple business key words and locations within a single search. For example, you can search for: Construction, Plumbing, Electricians, Building, Landscaping in all 50 states! While this search may take a little time to complete, you can leave the application running while you see results appear in real-time! No more waiting for long queries to complete!
Web Contact Scraper allows you to remove duplicate contact information on-the-fly.
You may chose to export you results to CSV any time!
Web Contact Scraper includes proxy support to build your business databases anonymously!
  • 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
  • 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


How to get Business Data & Contact Information (Web Contact Scraper)


Web Contact Scraper is a fully automated software application for gathering targeted business contact information!
Web Contact Scraper allows you to retrieve thousands of business contact information entries in real-time. You can use this information to start your very own business campaign. Are you a new business owner? Want to advertise to other similar businesses to promote yourself or a service? Then Web Contact Scraper is for you!
Web Contact Scraper allows you to set multiple business key words and locations within a single search. For example, you can search for: Construction, Plumbing, Electricians, Building, Landscaping in all 50 states! While this search may take a little time to complete, you can leave the application running while you see results appear in real-time! No more waiting for long queries to complete!
Web Contact Scraper allows you to remove duplicate contact information on-the-fly.
You may chose to export you results to CSV any time!
Web Contact Scraper includes proxy support to build your business databases anonymously!
  • 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
  • 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


Wednesday 22 October 2014

C# - How to Return a Substring Between Two Strings


Here is a non-RegEx solution for returning a substring between two strings in C#. I have also added a function for retrieving multiple occurrences which outputs as a List of strings.

The parameters called: includeFrom and includeUntil allow you to append the from and until fields to the result.


Usage:

Code Snippet
  1. // Example for one occurrences
  2. // This extracts 'Message Here' from this example chat log
  3. string message = "[12th July 2014] Message Here (Sent by Sean)".Substring(from: "]", until: "(", includeFrom: false, includeUntil: false);
  4. // Example for multiple occurances
  5. // This extracts all of the names which are enclosed between single quotes
  6. List<string> listOfNames = "'sean' random text 'dave' 355353 'jane' some text here 'tom'".SubstringAll(from: "'", until: "'");
End of Code Snippet



The Code:
Code Snippet
  1. /// <summary>
  2. /// Returns a substring between two anchor strings
  3. /// If from is null - Start of the string until the Second anchor
  4. /// If until is null - First anchor to the end of the string is returned
  5. /// </summary>
  6. /// <param name="this">Input string</param>
  7. /// <param name="from">An optional string to search after</param>
  8. /// <param name="until">An optional string to search before</param>
  9. /// <param name="includeFrom">Include from in the result</param>
  10. /// <param name="includeUntil">Include until in the result</param>
  11. /// <param name="comparison">An optional comparison for the search</param>
  12. /// <returns>A substring based on the search</returns>
  13. public static string Substring(this string @this, string from = null, string until = null, bool includeFrom = false, bool includeUntil = false, StringComparison comparison = StringComparison.InvariantCulture)
  14. {
  15.     var fromLength = (from ?? string.Empty).Length;
  16.     var startIndex = !string.IsNullOrEmpty(from)
  17.         ? @this.IndexOf(from, comparison) + fromLength
  18.         : 0;
  19.  
  20.     if (startIndex < fromLength) { return string.Empty; }
  21.  
  22.     var endIndex = !string.IsNullOrEmpty(until)
  23.     ? @this.IndexOf(until, startIndex, comparison)
  24.     : @this.Length;
  25.  
  26.     if (endIndex < 0) { return string.Empty; }
  27.  
  28.     if (includeFrom) // Do these AFTER start and end have been calculated
  29.         startIndex -= from.Length;
  30.     if (includeUntil)
  31.         endIndex += until.Length;
  32.  
  33.     return @this.Substring(startIndex, endIndex - startIndex);
  34. }
  35.  
  36. /// <summary>
  37. /// Returns a List of substrings between two anchor strings
  38. /// If from is null - Start of the string until the Second anchor
  39. /// If until is null - First anchor to the end of the string is returned
  40. /// </summary>
  41. /// <param name="this">Input string</param>
  42. /// <param name="from">An optional string to search after</param>
  43. /// <param name="until">An optional string to search before</param>
  44. /// <param name="includeFrom">Include from in the result</param>
  45. /// <param name="includeUntil">Include until in the result</param>
  46. /// <param name="skipEmptyResults">If empty results are found, then they are not added to the result set.</param>
  47. /// <param name="comparison">An optional comparison for the search</param>
  48. /// <returns>A List of substrings based on the search</returns>
  49. public static List<string> SubstringAll(this string @this, string from = null, string until = null, bool includeFrom = false, bool includeUntil = false, bool skipEmptyResults = true, StringComparison comparison = StringComparison.InvariantCulture)
  50. {
  51.     List<string> result = new List<string>();
  52.     try
  53.     {
  54.         while (true)
  55.         {
  56.             string res = @this.SubstringEx(from, until, includeFrom, includeUntil, comparison);
  57.  
  58.             if (!skipEmptyResults || !string.IsNullOrEmpty(res)) // Skip empty result sets
  59.                 result.Add(res);
  60.  
  61.             res = (!includeFrom) ? from + res : res;
  62.  
  63.             // If from and until are the same, then we can end up with problems and only returning half the result set. This fixes that problem.
  64.             if (from != until)
  65.                 res = (!includeUntil) ? res + until : res;
  66.  
  67.             @this = @this.Replace(res, string.Empty);
  68.         }
  69.     }
  70.     catch { }
  71.  
  72.     return result;
  73. }
End of Code Snippet