Wednesday, June 8, 2011

Deserialize javascript JSON into dictionary



This code uses a DictionaryConverter class which is a custom class that inherits from JavsScriptConverter.

string decodedPayLoad;

System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
// Register the custom converter.
js.RegisterConverters(new JavaScriptConverter[] { new DictionaryConverter() });
IDictionary list = js.Deserialize<IDictionary>(decodedPayLoad);

This is the custom class that was called above

public class DictionaryConverter : JavaScriptConverter
    {

        public override IEnumerable<Type> SupportedTypes
        {
            //Define the ListItemCollection as a supported type.
            get { return new ReadOnlyCollection<Type>(new List<Type>(new Type[] { typeof(IDictionary) })); }
        }

        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            if (dictionary == null)
                throw new ArgumentNullException("dictionary");
            return dictionary;
        }

    }

Hope it helps :)

Sunday, June 5, 2011

Get Users IP Address

You can use the following :

To get the IP address of the machine and not the proxy :

HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

If the above is null or empty use this code :

HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

Happy coding :)