Blog

CSS: Override Inline Styles from Stylesheet

Normally inline styles within your html markup is a way to override more global stayles which you have set within your stylesheets. Well if you have been developing within 3rd party CMS systems or 3rd party controls for any length of time you must have run into a situation where styles exists which you cannot alter because they are wrapped up in the 3rd party markup. In cases like this there is a very useful CSS option we have which allows us to do the exact opposite, we can actually set styles in our stylesheets which will override the more specific inline styles. 

This is done by adding some extra info to our CSS selectors. We simply add the [style] psuedo selector to our CSS class within the stylesheet. See the example below.


This inline style now gives us a blue rectangle with red text. Which is extremely hard to read.

With the use of the psuedo selector we can now override the inline style with this.

div[style] {
background-color: yellow !important; color: green !important;
}

C# Dynamically Creating Objects by Class Name

This is an example of how to use the System.Reflection namespace within .Net framework to look inside an assembly in an attempt to locate and instantiate a class of a specific type when you only know its string name and which fits a specific interface.

When would you use this?  Although not very common in everyday coding there really are a few times in my experience where this method has helped me out. For example I used an Enumeration with Attributes to hold various values. One of those Attributes contained the string name of the class which needed to be instantiated by the code using the Enumeration. Because at run-time I only had the string name of the class I was unable to actually instantiate the type or the class from just the string. The method below allowed me to pass in the string name of the class and get back an instantiation of that type in the form of its implemented Interface and then use that class as needed.

Lets see just how creative you can be, add a comment with an example of how you used it.

public static IPerson GetPersonObject(string className, out Type objectType)

        {

            //Get a reference to the assembly containing the target classes

            Assembly assembly = Assembly.Load("DynamicalClassInvokation");

 

            //Get a list of all the classes in that assembly

            List<Type> classes = assembly.GetTypes().ToList();

 

            //Locate the class by its string name

            objectType = classes.Single(x => x.Name.Equals(className, StringComparison.InvariantCultureIgnoreCase));

 

            //Create the object, cast it and return it to the caller

            return (IPerson)Activator.CreateInstance(objectType);

        }

.Net TrippleDES Encryption

Although TrippleDES is no longer considered to be a very secure encryption method you may find there are still uses for it. In my case I ended up needing to encrypt some sensitive query string parameters which were being passed between an application I worked on and a 3rd party. The encryption needed to be easily implemented, use a common key to encrypt and decrypt the data as well as require very little alterations by the 3rd party code. In order to meet all of these demands the application Architect (one awesome mentor) decided we would use the TrippleDESCryptoServiceProvider built into the .Net Cryptography library.

In order to use the provider you first need to add a reference to System.Security.Cryptography (using System.Security.Cryptography).

Now because cryptographic algorithms encrypt data block by block and because contiguous blocks may contain identical data it is always wise to use what is called an ‘Initialization Vector’. This provides TrippleDES with a beginning block of data which it uses to encrypt the first block of actual data. This starts a chain reaction as the algorithm then uses the previous blocks data to process and encrypt each subsequent block. Why is this important you ask? Well had we not used the previous blocks data to encrypt each following block, then all blocks with identical data would have been encrypted using the private key to the exact same result, i.e. they would be identical. With identical blocks throughout the encryption it is much easier for someone to figure out the patterns and begin to identify individual characters and decode what was meant to be secret.

An example would be a text document which is made up of English letters. If every ‘e’ was encrypted to the same result and we were aware that in the English language the letter ‘e’ is the most commonly used letter we could then scan the encrypted results for a pattern which happens the most and conclude they are all the letter ‘e’. Following the same pattern we could run down the alphabet by priority of common use and eventually decode the entire document, of course inserting characters as need like in ‘Wheel of Fortune’. The Initializer Vector allows us to reduce the patterns that begin to show up within the encrypted results thus reducing the ease of decryption by those without the private key (This was of course a simplistic example).

Here are examle Encryption/Decryption methods you can use to accomplish TrippleDES encryption:

using System;

using System.Text;

using System.Security.Cryptography;

public static class StringExtensions

{

    public static string EncryptString3Des(this string value, string key, byte[] iVector)

    {

        //(Example) Initialization Vector: byte[] IVector = new byte[8] { 27, 9, 45, 27, 0, 72, 171, 54 };

        byte[] buffer = Encoding.ASCII.GetBytes(value);

        TripleDESCryptoServiceProvider tripleDes = new TripleDESCryptoServiceProvider();

        MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();

        tripleDes.Key = MD5.ComputeHash(Encoding.ASCII.GetBytes(key));

        tripleDes.IV = iVector;

        ICryptoTransform ITransform = tripleDes.CreateEncryptor();

        return Convert.ToBase64String(ITransform.TransformFinalBlock(buffer, 0, buffer.Length));

    }

    public static string DecryptString3Des(this string value, string key, byte[] iVector)

    {

        //(Example) Initialization Vector: byte[] IVector = new byte[8] { 27, 9, 45, 27, 0, 72, 171, 54 };

        byte[] buffer = Convert.FromBase64String(value);

        TripleDESCryptoServiceProvider tripleDes = new TripleDESCryptoServiceProvider();

        MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();

        tripleDes.Key = MD5.ComputeHash(Encoding.ASCII.GetBytes(key));

        tripleDes.IV = iVector;

        ICryptoTransform ITransform = tripleDes.CreateDecryptor();

        return Encoding.ASCII.GetString(ITransform.TransformFinalBlock(buffer, 0, buffer.Length));

    }

}

WCF Register in IIS

In order to use WCF (Windows Communication Foundation) you first need to register it with IIS. In order to accomplish this you need to use the ServiceModelReg.exe tool supplied when .Net 3.0 is installed on your system.

You can find the utility under C:\WINDOWS\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\ServiceModelReg.exe and run it in a console with the flag -i (ServiceModelReg.exe -i).

ASP.net Membership Provider Setup

In order to set up your application to use Microsoft’s ASP.net Membership Provider you need to do the following.

1. Set up your database by installing the Membership schema. This is done by locating the aspnet_regsql.exe utility found in the C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727 directory. Run it using the -W flag (aspnet_regsql -W) and walk through the wizard that you are presented with.

2. Add a connection string to your web.config which points to the database you just installed the Memberhsip schema in.



<add name="LocalSqlServer"
connectionString="server=THESQLSERVER;uid=DATABASEUSERID;pwd=DATABASEPASSWORD;database=DATABASENAME"
providerName="System.Data.SqlClient" />

3. Then you need to add the membership provider to the web.config as follows




<add connectionStringName="LocalSqlServer" name="AspNetSqlMembershipProvider"
enablePasswordRetrieval="false" enablePasswordReset="true"
applicationName="/" requiresUniqueEmail="false" passwordFormat="Hashed"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
passwordStrengthRegularExpression="" requiresQuestionAndAnswer="true"
type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

4. Thats it, your done!

C# Dynamically Creating XDocuments from Collections

        private XDocument GenerateExtendedAttributes(Dictionary<string, List<string>> attributes)

        {

            XDocument xDoc = new XDocument();

            XElement xRoot = new XElement("ExtendedAttributes");

            xDoc.Add(xRoot);

            foreach (KeyValuePair<string, List<string>> attribute in attributes)

            {

                XElement xExtendedAttribute = new XElement("Attribute",

                                                   new XAttribute("Key", attribute.Key));

                foreach (string value in attribute.Value)

                {

                    xExtendedAttribute.Add(

                        new XElement("Value", value));

                }

                xRoot.Add(xExtendedAttribute);

            }

            return xDoc;

        }