jQuery: Accessing ASP.net Generated Controls Client Side

You can obtain a reference to an ASP.net generated control in your JavaScript for client side validation functions or manipulation by doing the following.


var myTextBox = $("#");

ASP.net: Custom Validator Not Firing (working)

The built in ASP.net CustomValidator control does not on its own verify that the control you are validating is not empty and therefore will not fire if it is empty. Because of this you cannot rely on the Custom Validator to handle the duties of a Required Field Validator.
So if the field you are implementing custom validation on is required and you want that custom validation to happen every time the page is posted you need to add a RequiredFieldValidator to validate the control as well as the CustomValidator.

C#: x509Certificates, IIS, Windows Server

If you are ever in need of pulling and using X509Certificates from your machine’s Certificate Store in your applications there are a few things you will need to watch out for. For this post I will be assuming you are programing a web application and are using ASP.net hosted in IIS.

  1. Make sure you generate the Certificate correctly and get it in the right place in our machine’s Certificate Store.
  2. Make sure the processes you are using have the proper rights to access the Certificate. (on your machine, ASP.net, Network Service,…)
  3. Make sure you are pulling the certificate correctly.

1. Generating your Certificate

The following command can be executed from within the Visual Studio 2008 Command Prompt (located in your start menu All Programs\Microsoft Visual Studio 2008\Visual Studio Tools).

makecert -r -pe -n “O=MyCompany,OU=MyCompany,CN=MyCertificate” -b 10/12/2009 -e 12/31/2039 -ss My -sr LocalMachine -sky exchange

I will go over some of the flags used in this command but the rest of them you can look up in the MSDN documentation for the MakeCert utility. The big ones to remember are:

  • -n which specifies the details about the key’s subject name and issuer.
  • -ss which specifies the key store where the key should be kept (My is the Personal section)
  • -sr this specifies the location of the key store that will be used to store the certificate (LocalMachine is the local key store for the machine you are on)
  • -sky this specifies the key type. exchange allows you to sign and encrypt items with the certificate whereas signature only allows you to sign.

2. Make Sure Necessary Processes can Access the Certificate

In order for your website code to access a certificate it has to be accessible to your ASP.net application. To grant access to your newly created certificate you need to use a utility designed to manage access to your computer’s certificates. The utility is titled winhttpcertcfg and can be downloaded from Microsoft.

Once you have the utility installed run the following scripts in your command prompt (cmd.exe) to grant both ASP.net and the Network Service access to the certificate. You of course will need to make sure that the new utility is either in the direct path of the command prompt by switching to the install folder of the utility or by adding the utility to the Path environment variable of your computer.

winhttpcertcfg -g -a “%computername%\NT AUTHORITY\NETWORK SERVICE” -c LOCAL_MACHINE\My -s “StayWellICPFrameworkSSO”

winhttpcertcfg -g -a %computername%\ASPNET -c LOCAL_MACHINE\My -s “StayWellICPFrameworkSSO”

winhttpcertcfg -g -a “%computername%\NT AUTHORITY\NETWORK SERVICE” -c LOCAL_MACHINE\My -s “MyCertificate”

winhttpcertcfg -g -a %computername%\ASPNET -c LOCAL_MACHINE\My -s “MyCertificate”

if you want to verify that the correct permissions have been granted you can run this next script which will tell you all processes which have access to the certificate.

winhttpcertcfg -l -c LOCAL_MACHINE\My -s “MyCertificate”

3. Pulling the Certificate Correctly

The following is a code snippet in C# detailing how to pull the certificate from the key store.

private X509Certificate2 GetX509Certificate()

        {

            X509Certificate2 x509Certificate;

            X509Store keyStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);

            keyStore.Open(OpenFlags.ReadOnly);

            X509Certificate2Collection x509Certificates = keyStore.Certificates.Find(

                X509FindType.FindBySubjectName,

                "MyCertificate",

                false);

            if(x509Certificates.Count > 0)

            {

                x509Certificate = x509Certificates[0];

            }

            else

            {

                throw new Exception(

                    "x509 Certificate does not exist. Name: MyCertificate ";

            }

            return x509Certificate;

        }

Telerik: RadEditor Change Content Background Color

When it comes to the Telerik RadEditor and the background color of the content within it you may run into some issues if your website’s layout and design incorporates a black background.
This is because the RadEditor, by default, takes the background color of the actual web page (body) as the color it uses for its content area. In order to override the content area of the RadEditor so that you have a clean white background and a black font you must add a Style element to the RadEditor’s markup which points to a Cascading Style Sheet (.CSS) file with the Body selector overridden to contain the colors you want.
Here is how you add the style to your RadEditor instance:
   

Here is what the content of the CSS file looks like to get a white background with black text:
body
{
    color: #000;
    background-color: #fff;
    padding:3px;
    background-image: none;
    margin: 0px;
    text-align: left;
}

ASP.net: User Control Specific CSS/JS Loading

(Update: the BaseUserControl class has been updated to handle loading specific CSS or JS files or one or the other. This allows a common CSS or JS file to be passed for a set of controls making up a module within your application.)

(Update: The BaseUserControl class has been updated to handle instances where your UserControl is loaded multiple times on the same page. This will stop the CSS and JS from being loaded multiple times for each control.)

(Update: If your pages are using MasterPages for their designs make sure you add a runat=”server” to the head tag of your master pages. If you do not the Header property of the page will be null. )

In ASP.net we run into an issue when it comes our User Controls and their corresponding CSS loading in the main CSS files even when that User Control is not included in the 90% of the pages a user calls. (this is the same with JavaScript files)

In order to make sure that my User Control’s CSS is not unnecessarily loaded in the application’s main CSS file and to maintain a little more order in my design I like to use a little programming magic. This magic allows me to only load the CSS for a User Control when it is included in a page or another User Control.

To accomplish this magic I create a Base User Control from which all my User Controls inherit. This base control contains a method called LoadResources which does the following:

  1. Pulls the name of the Current Control making the call.
  2. Adds a Link tag with the path to the CSS file for the current control
  3. Adds a Script tag with the path to the JavaScript file for the current control

(All of the above are based on the CSS and JavaScript files having the same name as the control and those files being located in the same location as the current control.)

Code:

public class BaseUserControl : UserControl

{

    #region Private Fields

    private string _controlName;

    #endregion

    #region Protected Methods

    /// 

    /// Used if the control has custom CSS or Javascript

    /// which needs to be loaded with the control.

    /// The resources consist of a .css and .js files 

    /// which have the same name as the control. This method

    /// will search the control's location for those 2

    /// files and add them as CSS and Javascript links to

    /// the control's ascx content.

    /// 

    protected void LoadResources()

    {

        PullControlName();

        LoadCssFile();

        LoadJsFile();

    }

    /// 

    /// Loads the resources.

    /// 

    /// Name of the file.

    /// Type of the file.

    protected void LoadResources(string fileName, FileType fileType)

    {

        switch (fileType)

        {

            case FileType.Script:

                LoadJsFile(fileName);

                break;

            case FileType.Style:

                LoadCssFile(fileName);

                break;

        }

    }

    /// 

    /// Loads the resources.

    /// 

    /// 
styleFileName">
Name of the style file.

    /// 
scriptFileName">
Name of the script file.

    protected void LoadResources(string styleFileName, string scriptFileName)

    {

        LoadCssFile(styleFileName);

        LoadJsFile(scriptFileName);

    }

    #endregion

    #region Private Methods

    private void PullControlName()

    {

        string controlType = GetType().ToString();

        List<string> controlParts = controlType.Split('_').ToList();

        if (controlParts.Count > 0)

        {

            if (!string.IsNullOrEmpty(controlParts[controlParts.Count - 2]))

            {

                _controlName = controlParts[controlParts.Count - 2];

            }

        }

    }

    private void LoadCssFile()

    {

        try

        {

            // Injects the CSS for this control into the page header

            string cssUrl = ResolveUrl(_controlName + ".css");

            string cssPath = cssUrl.Remove(0, 1).Replace('/', '\\');

            if (File.Exists(Request.PhysicalApplicationPath + cssPath))

            {

                string controlId = _controlName + "Style";

                if (!DoesControlExist(controlId))

                {

                    HtmlLink css = new HtmlLink();

                    css.ID = controlId;

                    css.Href = cssUrl;

                    css.Attributes.Add("rel", "stylesheet");

                    css.Attributes.Add("type", "text/css");

                    Page.Header.Controls.Add(css);

                }

            }

        }

        catch (Exception ex)

        {

            //TODO: Handle exception as a warning

        }

    }

    private void LoadCssFile(string fileName)

    {

        try

        {

            // Injects the CSS for this control into the page header

            string cssUrl = ResolveUrl(fileName);

            string cssPath = cssUrl.Remove(0, 1).Replace('/', '\\');

            if (File.Exists(Request.PhysicalApplicationPath + cssPath))

            {

                string controlId = fileName + "Style";

                if (!DoesControlExist(controlId))

                {

                    HtmlLink css = new HtmlLink();

                    css.ID = controlId;

                    css.Href = cssUrl;

                    css.Attributes.Add("rel", "stylesheet");

                    css.Attributes.Add("type", "text/css");

                    Page.Header.Controls.Add(css);

                }

            }

        }

        catch (Exception ex)

        {

            //TODO: Handle exception as a warning

        }

    }

    private void LoadJsFile()

    {

        try

        {

            // Injects the JavaScript for this control into the page header

            string jsUrl = ResolveUrl(_controlName + ".js");

            string jsPath = jsUrl.Remove(0, 1).Replace('/', '\\');

            if (File.Exists(Request.PhysicalApplicationPath + jsPath))

            {

                string controlId = _controlName + "Script";

                if (!DoesControlExist(controlId))

                {

                    HtmlGenericControl js = new HtmlGenericControl("script");

                    js.ID = controlId;

                    js.Attributes.Add("type", "text/javascript");

                    js.Attributes.Add("src", jsUrl);

                    Page.Header.Controls.Add(js);

                }

            }

        }

        catch (Exception ex)

        {

            //TODO: Handle exception as a warning

        }

    }

    private void LoadJsFile(string fileName)

    {

        try

        {

            // Injects the JavaScript for this control into the page header

            string jsUrl = ResolveUrl(fileName);

            string jsPath = jsUrl.Remove(0, 1).Replace('/', '\\');

            if (File.Exists(Request.PhysicalApplicationPath + jsPath))

            {

                string controlId = fileName + "Script";

                if (!DoesControlExist(controlId))

                {

                    HtmlGenericControl js = new HtmlGenericControl("script");

                    js.ID = controlId;

                    js.Attributes.Add("type", "text/javascript");

                    js.Attributes.Add("src", jsUrl);

                    Page.Header.Controls.Add(js);

                }

            }

        }

        catch (Exception ex)

        {

            //TODO: Handle exception as a warning

        }

    }

    private bool DoesControlExist(string controlId)

    {

        object control = Page.Header.FindControl(controlId);

        if (control != null)

            return true;

        return false;

    }

    #endregion

    #region Utility Classes

    /// 

    /// Types of files which are accepted by the 

    /// resource loader.

    /// 

    public enum FileType

    {

        /// 

        /// Cascading Style Sheet files

        /// 

        Style,

        /// 

        /// JavaScript files

        /// 

        Script

    }

    #endregion

}

ASP.net: CS0012: The type ‘System.Data.Objects.DataClasses.EntityObject’ is defined in an assembly that is not referenced. You must add a reference to assembly ‘System.Data.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089’.

If you are using the .Net Entity Framework and you are passing those Entity Framework objects through controls in your UI (.aspx, .ascx) pages such as a Repeater control (using the ) you will most likely see the following error message:

CS0012: The type ‘System.Data.Objects.DataClasses.EntityObject’ is defined in an assembly that is not referenced. You must add a reference to assembly ‘System.Data.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089’.

You may have added the assembly to your web application’s References but I guess this is not enough. You must also add the reference to your web.config file. You can do this by adding the following line to your ‘compilation/assemblies’ section so it looks like the following: