Create HTML, Javascript, or XML String Variables the Easy Way Using C#

The title of this post is a bit misleading. The tips in this post can really be applied to any string, but I have found these tips to be most useful when creating markup language strings.

There are six tips applied to the HTML example below that make creating the string variable intuitive and easy to look at –

  1. Use the @ verbatim string literal syntax instead of the \ backslash character
  2. When inserting variables into the string variable, use the + concatenator before and after the variable then use the @ verbatim symbol to restart the static content of the variable
  3. If more data is necessary after the insertion of other variables, begin the new data with the @ verbatim symbol
  4. If you need to specify a double-quote (“), then escape it with an additional double-quote (Example @ <body style=””background-color:PowderBlue;””>)
  5. If you can, use single-quotes instead of double-quotes. If you use single-quotes, you will not need to escape the double-quotes. (Example: @ <p style=’font-family:verdana;color:red’>)
  6. Specify C# variables with an arbitrary prefix/suffix, then call Replace() after the string is built

1 class Class1

2 {

3 static int i = 123;

4 string s = @”

5 <html>

6 <body style=””background-color:PowderBlue;””>

7 <h1>Look! Styles and colors</h1>

8 <p style=’font-family:verdana;color:red’>Escape double-quotes with double-quotes</p>

9 <p style=’font-family:times;color:green’>

10 + i.ToString() +

11 When inserting variables, use the concatenator before and after the variable. Then, to restart the string

12 content, use the @ symbol again. Or use a prefix/suffix then call Replace() like this #i#</p>

13 <p style=’font-size:30px’>This text is 30 pixels high</p>

14 </body>

15 </html>

16 ;

17 s = s.Replace(“#i#”,i);

18 }

 

For a better way to use C# variables within the string variable, check out this Stack Overflow answer. For clarity, notice in our code example above we added the “#i#” inside of the string variable. Then, we Replace()’d the “#i#” with the value from the “i” variable. This works fine, however if we have many variables, it can be a bit tedious calling the Replace() method for each variable that we need to evaluate. The String Extension example at Stack Overflow, shows a useful way to handle this sort of thing.

Here’s the example of the String Extension that you can use to replace strings within a string with a list of corresponding variable names:

    1     public static class StringExtensions

   2     {

   3         public static string PHPIt<T>(this string s, string prefix, T values)

   4         {

   5             var sb = new StringBuilder(s);

   6             foreach (var p in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance))

   7             {

   8                 sb = sb.Replace(prefix + p.Name, p.GetValue(values, null).ToString());

   9             }

   10             return sb.ToString();

   11         }

   12     }

Now, you can do something like this:

    1             DateTime date = DateTime.Now;

    2             string message = "Hello World";

    3 

    4             string html = @"#message. The date is #date.";

    5 

    6             var result = StringExtensions.PHPIt(html, "#", new

    7             {

    8                 date,

    9                 message

   10             });

   11 

   12             Console.WriteLine(result);

The output would read:

Hello World. The date is 4/12/2011 2:46:43 PM.

Advertisements

Reference a Code Behind Variable in ASPX page

To reference a code behind variable in an .aspx page, use the syntax
<%= variableName %>

For example:
Code Behind

    public partial class vars : System.Web.UI.Page
    {
        protected string someVariable = "Hello";
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }

ASPX Source

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="vars.aspx.cs" Inherits="UserLogin.vars" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>    
    <%= someVariable %>
</body>
</html>

Rendered Web Page

How to quickly create class properties in Visual Studio

In Visual Studio 2010 (and probably earlier versions) there is a shortcut for writing out class properties.

Say you wanted to create a Person class with the properties FirstName, LastName, and PersonID. After you construct the Person class…

public class Person()
{

}

type in the keyword “prop”, then hit TAB-TAB.

So, this…

public class Person()
{
  prop [TAB] [TAB]
}

will turn into this…

public class Person()
{
  public int MyProperty { get; set; }
}

At this point you can change the type (int) and/or the name of the property (MyProperty). To toggle back and forth between the int and the name, hit your TAB key.

When the property is just as you like it, hit [ENTER][ENTER]. This will take you to a new line where you can repeat the process of quickly creating your class properties.

Programmatically Read Web.config Settings

To read the values that are configured in an ASP.NET Web.config file you will need to create objects for different sections of the Web.config file.

For example: To read the Web.config settings that are in the system.web/authentication/forms section, check out the code snippet below:

<configuration>
 <system.web>
  <authentication>
   <forms>
    <!-- The example below shows how you can read the settings within this forms element -->
   </forms>
  </authentication>
 </system.web>
</configuration>
// Get the Web application configuration.
System.Configuration.Configuration configuration =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/");

// Get the external Authentication section.
System.Web.Configuration.AuthenticationSection authenticationSection =
(System.Web.Configuration.AuthenticationSection)configuration.GetSection(
"system.web/authentication");

// Get the external Forms section .
System.Web.Configuration.FormsAuthenticationConfiguration formsAuthentication =
authenticationSection.Forms;

System.Diagnostics.Debug.WriteLine(string.Format("DefaultUrl: {0}.", formsAuthentication.DefaultUrl));
System.Diagnostics.Debug.WriteLine(string.Format("Domain: {0}.", formsAuthentication.Domain));
System.Diagnostics.Debug.WriteLine(string.Format("EnableCrossAppRedirects: {0}.", formsAuthentication.EnableCrossAppRedirects));
System.Diagnostics.Debug.WriteLine(string.Format("LoginUrl: {0}.", formsAuthentication.LoginUrl));
System.Diagnostics.Debug.WriteLine(string.Format("Name: {0}.", formsAuthentication.Name));
System.Diagnostics.Debug.WriteLine(string.Format("Path: {0}.", formsAuthentication.Path));
System.Diagnostics.Debug.WriteLine(string.Format("Protection: {0}.", formsAuthentication.Protection));
System.Diagnostics.Debug.WriteLine(string.Format("RequireSSL: {0}.", formsAuthentication.RequireSSL));
System.Diagnostics.Debug.WriteLine(string.Format("SlidingExpiration: {0}.", formsAuthentication.SlidingExpiration));
System.Diagnostics.Debug.WriteLine(string.Format("Timeout: {0}.", formsAuthentication.Timeout));

Auto-stub ASP.NET Page Event Handlers

For whatever reason, Visual Studio does not offer an intuitive procedure for stubbing out an .aspx page’s event handlers.

The easiest procedure that I can come up with is:

  1. View the .aspx page in Code View
  2. Within the page’s class, create a method using the override modifier. Visual Studio’s Intellisense will display the list of the classes members that can be overridden.

Example:
Create a method using the override modifier, then select the method, event, property, or indexer that you would like to override.

Visual Studio will stub out the method for you calling the base.

Note how the overridden event handler in the above example is named OnPreRender(). It’s worth noting that this method is the same as the Page_PreRender() event handler.

Windows Shortcut Commands

The list below contains commands that you can enter into a “Run” window to quickly open applets.

This list is shortened version of Kioskea Network’s “Command prompts for Windows” list.

Control Panel
CONTROL: opens the control panel window
CONTROL ADMINTOOLS: opens the administrative tools
CONTROL FOLDERS: opens folder options
CONTROL INTERNATIONAL or INTL.CPL: opens Regional and Language option
CONTROL PRINTERS: opens faxes and printers available
APPWIZ.CPL: opens Add or Remove programs utility tool
MMSYS.CPL: opens Sound and Audio device Properties. Volume tab
SYSDM.CPL: opens System properties
TELEPHON.CPL: Opens phone and Modem options
CERTMGR.MSC: opens certificate management tool
COMPMGMT.MSC: opens the Computer management tool
DEVMGMT.MSC: opens Device Manager
EVENTVWR or EVENTVWR.MSC: opens Event Viewer
SERVICES.MSC: opens Service manager
GPEDIT.MSC: opens Group Policy utility tool
LUSRMGR.MSC: opens Local Users and Groups
SECPOL.MSC: opens local security settings
PERFMON or PERFMON.MSC: opens the Performance monitor
MDSCHED: opens memory diagnostics tools
REGEDIT or REGEDT32: opens Registry Editor
CLICONFG: opens SQL Server Client Network Utility
MSCONFIG: opens System Configuration Utility

Windows utility and applications
CHARMAP: opens Character Map
NOTEPAD: opens Notepad
CALC: opens Calculator
MSINFO32: Opens the System Information
Taskmgr : Opens the Windows Task Manager
CMD: opens a command prompt
Winver : Opens the window for your Windows version
Mstsc : opens the tool connection Remote Desktop

Disk management
DISKMGMT.MSC: opens disk management utility
CLEANMGR: opens disk drive clean up utility
DFRG.MSC: opens disk defragmenter
CHKDSK: complete analysis of disk partition
DISKPART: disk partitioning tool

Connection management
IPCONFIG (Requires a console window): list the configuration of IP addresses on your PC (for more information type IPCONFIG/? in the CMD menu)
INETCPL.CPL: opens internet properties
FIREWALL.CPL: opens windows firewall
NCPA.CPL: opens the “Network Connections” window

Add NetBios Exception to Windows XP Firewall

My SonicWall TZ150W network is configured such that the wired LAN lives on 10.10.7.0 and the wireless WLAN lives on 10.10.6.0.

Due to the fact that the LAN is on a different subnet than the WLAN, Windows XP Firewall blocks (by default) NetBios – more specifically, I am unable to connect to a computer that lives on the wired LAN from a computer that lives on the wireless LAN by the name of the computer. I am forced to use the IP Address of the computer(s) in order to connect to it.

Example:
Computer1 on the wired LAN has been given (via DHCP) a LAN IP of 10.10.7.100.
Computer2 on the WLAN has been given (via DHCP) a WLAN IP of 10.10.6.100.

When Computer2 attempts to connect to Computer1 in Windows Explorer via "\\Computer1", an error message is thrown that states:

Windows cannot find \\Computer1. Check the spelling and try again, or try searching for the item by clicking the Start button and then clicking Search.

The cause behind the error message is due to the Windows Firewall on Computer2 blocking NetBios. Since the firewall is blocking NetBios, Computer2 is unable to receive the broadcast of Computer1’s name.

To resolve this problem we need to add an Exception to Computer2’s firewall.

  1. Click Start > Run, type “firewall.cpl”, then hit OK.
  2. Click the Exceptions tab
  3. Enable the checkbox for “File and Printer Sharing”

    The File and Printer Sharing service uses NetBios and, therefore, includes the NetBios ports (UDP 137, UDP 138, and TCP 139).
  4. Click “File and Printer Sharing” so that it his highlighted, then click the “Edit” button.
  5. The “Edit a Service” window displays the ports that you will be allowing through the firewall – TCP 139, TCP 445, UDP 137, and UDP 138). Notice, however, that the Scope is defined as “Subnet”. This means that the firewall will only allow traffic for these ports if and only if the traffic is within the same subnet (i.e. ┬áthe WLAN on 10.10.6.0). We need to change the scope to allow for the LAN on 10.10.7.0 as well.

    Continuing on…
  6. For each port in the “Edit a Service” window you will need to do the following…
  7. Select the service Name, then click the “Change scope…” button
  8. Click the “Custom list:” radio button, then enter 10.10.6.0/23.
    This syntax resolves to 10.10.6.0/255.255.254.0 which means that the minimum IP can be 10.10.6.1 and the maximum IP can be 10.10.7.254. In other words, we are configuring the service to allow traffic through the firewall for anything that lives on the WLAN and the LAN. If your subnets are different than this example, you may find the IP Calculator to be a helpful tool for you to figure out what your custom scope is.
  9. Remember to do the above step for each port that is specified in the “Edit a Service” window.
  10. Close out of the firewall and try to connect to “Computer1” from “Computer2” by simply entering the “Computer1” name in the address bar of Windows Explorer. – Note: You may have to wait a minute or two for the broadcast from Computer1 to transmit to Computer2.

Keep in mind that if you would like to be able to connect to Computer2 from Computer1 via NetBios, you will probably need to add an exception to Computer1’s firewall as well.