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.

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>
  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>
  9. <!-- leave inheritance enabled for appSettings -->
  10. <appSettings>
  11. </appSettings>
  13. <!-- disable inheritance for the system.web section -->
  14. <location path="." inheritInChildApplications="false">
  15.    <system.web>
  16.         <webParts>
  17.         </webParts>
  18.         <membership>
  19.         </membership>
  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.">  
  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.

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!";
  12.                 // Example - Black background
  13.                 this.ApplyText(g, textLabel, fontText, fontTextBrush, fontTextPoint, Color.Black);
  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);
  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.     }
  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

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

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
  6. // Show save file dialog box
  7. Nullable<bool> result = dlg.ShowDialog();
  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
  5. // Show open file dialog box
  6. Nullable<bool> result = dlg.ShowDialog();
  8. // Process open file dialog box results
  9. if (result == true)
  10. {
  11.     string filename = dlg.FileName;
  12.     Canvas canvas = DeSerializeXAML(filename) as Canvas;
  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. }
  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);
  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
  6. // Show save file dialog box
  7. Nullable<bool> result = dlg.ShowDialog();
  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.

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
  6. // Show save file dialog box
  7. Nullable<bool> result = dlg.ShowDialog();
  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));
  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);
  16.     SaveRTBAsPNGBMP(rtb, filename);
  17. }
  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);
  30.     SaveRTBAsPNGBMP(rtb, filename);
  31. }
  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));
  38.     using (var stm = System.IO.File.Create(filename))
  39.     {
  40.         enc.Save(stm);
  41.     }
  42. }
End of Code Snippet