Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Friday, 25 January 2013

MVC4 StrucutureMap ControllerFactory

I am not sure if this is new to MVC4 only, but it does appear that Dependency Injection with MVC just got easier. This code is borrowed, and referenced here so I don't have to keep going off and finding it.

First off I create a ControllerFactory for StrucutureMap

public class StructureMapControllerFactory : DefaultControllerFactory
{
    public IContainer Container { getset; }
    public StructureMapControllerFactory()
    {
        Container = ObjectFactory.Container;
    }
 
    protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
    {
        IController controller;
        if (controllerType == null)
        {
            throw new HttpException(404, String.Format(Resources.ControllerNotFound, requestContext.HttpContext.Request.Path));
        }
        if (!typeof(IController).IsAssignableFrom((controllerType)))
        {
            throw new ArgumentException(string.Format(Resources.NotAController, controllerType.Name),"controllerType");
        }
        try
        {
            controller = Container.GetInstance(controllerType) as Controller;
        }
        catch (Exception ex)
        {                
            throw new InvalidOperationException(string.Format(Resources.UnableToResolveController, controllerType.Name),ex);
        }
        return controller;
    }
}

Then in the Global.asax Application_Start method.
Add the setup for StructureMap, I tend to do all that in a separate class:
DependencyInjection.StructureMap.Initialise();
And then set the ControllerFactory to your new custom factory:
ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory());

Thursday, 8 November 2012

Custom extensions that I use regularly


This is just a list of extensions that I use.

public static Guid ToGuid(this string stringValue)
        {
            try
            {
                return new Guid(stringValue);
            }
            catch (FormatException ex)
            {
                throw new FormatException("string could not convert to Guid");
            }
            catch (ArgumentNullException ex)
            {

                return Guid.Empty;
            }
        }

        public static int ToInt32(this string stringValue)
        {
            if (string.IsNullOrEmpty(stringValue))
            {
                return -0;
            }
            else
            {
                return Convert.ToInt32(stringValue);
            }
        }

        public static bool ToBoolean(this string stringValue)
        {
            if (string.IsNullOrEmpty(stringValue))
            {
                return false;
            }
            else
            {
                return Convert.ToBoolean(stringValue.ToInt32());
            }
        }

// dont really use this one, cannot guarentee that the lastname wasnt supposed to start with a lowercase
        public static string ToProperCase(this string stringValue)
        {
            if (string.IsNullOrEmpty(stringValue))
            {
                return string.Empty;
            }
            else
            {
                var ti = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo;
                return ti.ToTitleCase(stringValue.ToLower());
            }
        }

        public static bool IsNull(this object o)
        {
            return o == null;
        }

        public static bool IsNotNull(this object o)
        {
            return !o.IsNull();
        }

        public static bool IsNullOrEmpty(this string s)
        {
            return string.IsNullOrEmpty(s);
        }

        public static bool IsNotNullOrEmpty(this string s)
        {
            return !string.IsNullOrEmpty(s);
        }

        public static string ToValidFileName(this string value)
        {
            return Regex.Replace(Regex.Replace(value, @"\W", "_"), "_{2,}", "_");
        }

// this is a fun one, passing in a list of type T will generate a typed dataset
        public static DataSet ToDataSet<T>(this IList<T> value)
        {
            if (value != null && value.Count > 0)
            {
                var type = typeof(T);
                var properties = type.GetProperties();
                ConstructorInfo ci = type.GetConstructor(new Type[] { });
                T item = (T)ci.Invoke(new object[] { });
                var ds = new DataSet();
                var dt = new DataTable();
                foreach (PropertyInfo property in properties)
                {
                    var row = value.FirstOrDefault();
                    var dc = new DataColumn()
                    {
                        Caption = property.Name,
                        ColumnName = property.Name
                    };
                    if (row.IsNotNull())
                    {
                        var itemValue = property.GetValue(row, null);
                        if (itemValue.IsNotNull())
                        {
                            dc.DataType = itemValue.GetType();
                        }
                    }
                    dt.Columns.Add(dc);
                }
                foreach (T listItem in value)
                {
                    var dr = dt.NewRow();
                    foreach (var property in properties)
                    {
                        var listItemValue = property.GetValue(listItem, null);
                        if(listItemValue != null)
                        {
                            dr[property.Name] = property.GetValue(listItem, null);
                        }
                    }
                    dt.Rows.Add(dr);
                }
                ds.Tables.Add(dt);
                return ds;
            }
            else
            {
                return new DataSet();
            }
        }

Tuesday, 8 February 2011

Disable asp.net button

adding the following in the page load event in your ASP.NET page. This will setup the ability to disable the button you click, until the submission is complete or an error occurs.

MyButton.Attributes.Add("onclick", "this.disabled=true;" + Page.ClientScript.GetPostBackEventReference(MyButton, "").ToString());

Monday, 17 January 2011

Split String To Dictionary

I have created a Survey System, which allows an admin to set the questions.

One question type is a dropdownlist and the information needed (to keep it simple) was stored as a semi-colon separated list (I also extended this to allow colon separated values within that to allow key and value sets).

for example:
spring;summer;autumn;winter
or
0:spring;1:summer;2:autumn;3:winter

Both are valid and the second example will store the values defined as the answer.

I wanted to split a string into a Dictionary and set a return for use on an MVC SelectList,

I refactored out the SplitAndReturnIndex to handle case where the string does not contain a Key, only a value, as can be seen from the code:


public IDictionary QuestionValues()
{
return Question.SurveyItemValues.Split(';')
.Select(x => new { Key = SplitAndReturnIndex(x, 0), Value = SplitAndReturnIndex(x, 1) })
.ToDictionary(x => x.Key, x => x.Value);
}

private string SplitAndReturnIndex(string x, int indexValue)
{
return x.IndexOf(':') == -1 ? x : x.Split(':')[indexValue];
}

Tuesday, 4 January 2011

Hash Password using HMACSHA1 or HMACSHA512

Quite a handy snippet to generate an HMACSHA1 encoded string, I use this for passwords, but it could be used generate a check sum when passing values through to a webservice.

public static string GeneratePassword(string valueToHash)
{
byte[] saltValueBytes = Encoding.ASCII.GetBytes("This is for the Salt");
// Change passkey value to known value, I tend to use a guid
Rfc2898DeriveBytes passwordKey = new Rfc2898DeriveBytes("96D9E8D3-1318-4291-B459-84EAB0E268A6", saltValueBytes);
byte[] secretKey = passwordKey.GetBytes(16);
HMACSHA1 myHash = new HMACSHA1(secretKey);
byte[] encodedValue = Encoding.UTF8.GetBytes(valueToHash);

return Convert.ToBase64String(myHash.ComputeHash(encodedValue));
}


The problem with this, has always been everyone has the same salt.

So a change in security and use of SHA512:

With a way to generate a unique Salt:


public byte[] GenerateSalt()
        {
            System.Security.Cryptography.RNGCryptoServiceProvider r = new System.Security.Cryptography.RNGCryptoServiceProvider();

            byte[] array = new byte[16];

            r.GetBytes(array);

            return array;
        }

And return the Hash value with Generated Salt Passed in:

        public string GetHash(string password, byte[] salt)
        {
            string ret = string.Empty;

            try
            {
                byte[] passwordBytes = Encoding.ASCII.GetBytes(password);

                byte[] input = new byte[salt.Length + passwordBytes.Length];

                salt.CopyTo(input, 0);

                passwordBytes.CopyTo(input, salt.Length);

                System.Security.Cryptography.SHA512CryptoServiceProvider cr = new System.Security.Cryptography.SHA512CryptoServiceProvider();

                ret = Convert.ToBase64String(cr.ComputeHash(input));
            }
            catch (Exception Ex)
            {
                throw new Exception("Error hashing password", Ex);
            }

            return ret;
        }

Remember to save the salt somewhere that can be referrenced with the encrypted value, so you can check it.

Friday, 17 December 2010

Find the index of a list item

It took me a while to find how to do this, but once I had, my eyes will be ever open to the beauty of Linq.

The following code was used in a problem I was working on from Programming Praxis and compares a specific charater to a list of strings

//where row is a List variable and char1 is a charater of interest
var row1 = rows.FindIndex(r => r.Contains(char1) == true)

In the problem above the character can only appear once in the collection.

Understanding Aggregate.. well ish anyway

Combine values from list items
var x is of type collection/list/array


var out = x.Aggregate(<seed,>(acc,item) => acc + item);

acc is the accumulator which is returned
item is each item

At position acc + item, a function can exist to provide extra functionallity.

item is never the first item of the array unless you seed from a blank string.

For example:

var out = x.Aggregate("",(acc,item) => acc + item);

Loading Regex matches to a varaible using Linq

How to get your Regex matches into a Linq variable:

string inString = "ABCDEFGH"
Regex re = new Regex(@"\w{1}");
var list = (from Match m in re.Matches(inString) select m.Value).ToList()


Another easy way to make sure you get words and numbers:


var list = inString.Select(x => 
                {
                    return Regex.Match(x.ToString(), "[a-zA-Z0-9]+");
                });

Conditional String replacement

Found this by accident when doing some linq, but I think this is a nice standard funtion

var x = "A";
Console.Write(String.Format("HELLO WORLD {0}", x.Length == 1 ? x + "X" : x));


Not sure if this works in other version prior to VS2008

One way to return an assembly from a string input

Where T is the interface you have defined to use with the assembly you are passing in and returning;

public class Core
{
public static T GetClass<T>(string Assembly)
{
string[] strAssembly = Assembly.Split(Convert.ToChar("."));
System.Runtime.Remoting.ObjectHandle oObjectHandle;

oObjectHandle = System.Activator.CreateInstance(strAssembly[0].ToString(), Assembly);
T oIinsert = (T)oObjectHandle.Unwrap();
return oIinsert;
}
}

dotNet Mailer

Standard chunk of mailing code.


private System.Net.Mail.MailMessage m;
string Subject = "FOO";
string Message = "F001";
string email = "FOO2";
string strField = "F003";

//PDF,DOC etc
string extn = "PDF";

//application/pdf etc
string strType = "application/pdf";

// This needs filling for attachment to be added
System.IO.MemoryStream memstream;

m = new System.Net.Mail.MailMessage();
m.From = new System.Net.Mail.MailAddress(strEmailAddress);
m.IsBodyHtml = false;
m.Subject = Subject;
m.Body = Message;
System.Net.Mail.MailAddress aTo = new System.Net.Mail.MailAddress(email);
m.To.Add(aTo);
if (memstream.Length != 0)
{
memstream.Position = 0;
m.Attachments.Add(new System.Net.Mail.Attachment(memstream, strField + "." + extn, strType));
}
System.Net.Mail.SmtpClient smServer = new System.Net.Mail.SmtpClient(Configuration.Instance.EmailServer);
smServer.Send(m);