WebClient that supports login and cookies


Hi, Here is a simple wrapper of WebClient that has an additional method Login, to allow for it to access and download user-only data, authenticated via a login-form post.public class CookieAwareWebClient : WebClient {   public void Login(string loginPageAddress, NameValueCollection loginData)   {     CookieContainer container;     var request = (HttpWebRequest)WebRequest.Create(loginPageAddress);     request.Method = "POST";     request.ContentType = "application/x-www-form-urlencoded";     var buffer = Encoding.ASCII.GetBytes(loginData.ToString());     request.ContentLength = buffer.Length;     var requestStream = request.GetRequestStream();     requestStream.Write(buffer, 0, buffer.Length);     requestStream.Close();     container = request.CookieContainer = new CookieContainer();     var response = request.GetResponse();     response.Close();     CookieContainer = container;   }   public CookieAwareWebClient(string loginPageAddress, NameValueCollection loginData)   {     Login(loginPageAddress, loginData);   }   public CookieAwareWebClient(CookieContainer container)   {     CookieContainer = container;   }   public CookieAwareWebClient()     : this(new CookieContainer())   { }   public CookieContainer CookieContainer { get; private set; }   protected override WebRequest GetWebRequest(Uri address)   {     var request = (HttpWebRequest)base.GetWebRequest(address);     request.CookieContainer = CookieContainer;     return request;   } } The usage is simple, call the Login method, and the login cookie will be set internally so the upcoming calls are authenticated:static void Main() {   var loginPage = "www.site.com/login";   var loginData = new NameValueCollection   {     { "username", "shimmy" },     { "password", "mypassword" },     { "rememberme", "1" }   };   var client = new CookieAwareWebClient(loginPage, loginData); } The Login method can be called after initialization as well.The upcoming requests and downloads of the WebClient should all be authenticated.Hope this helps,Shimmy
no comments

Entity-Framework Code First Designer with Database Initialization in few simple steps!


I find it very frustrating that I cannot use the entity model designer to generate code-first DbContext & entities that retains all the aspects of code-first including database initialization. Here are a set of instructions that can easily help you to achieve true code-first using the EDM designer, and allowing initialization of database (database initialization is not supported in model-first, it only allows generation of database scripts that has to be generated on the server). This is very useful in small projects where you don't want to mess with the database, and you rather it being generated automatically. In my example I...

Get a list of all countries in C#

I'm sharing it here mostly for myself, but I hope someone else would also be able to enjoy it once...static IEnumerable<Country> GetCountries() {   return from ri in             from ci in CultureInfo.GetCultures(CultureTypes.SpecificCultures)             select new RegionInfo(ci.LCID)           group ri by ri.TwoLetterISORegionName into g           //where g.Key.Length == 2           select new Country           {             CountryId = g.Key,             Title = g.First().DisplayName           }; } class Country {   public string CountryId { get; set; }   public string Title { get; set; } }
tags: ,
no comments

Get Jewish date string


 namespace System.Globalization {   public static class DateTimeExtensions   {     private const string HebrewCultureName = "he-IL";     private static readonly CultureInfo HebrewCulture = #if SILVERLIGHT  new CultureInfo(HebrewCultureName); #else  CultureInfo.CreateSpecificCulture(HebrewCultureName); #endif     /// <summary>     /// Converts a gregorian date to its hebrew date string representation,     /// using custom DateTime format string.     /// </summary>     /// <param name="value">The <see cref="DateTime"/> value to convert.</param>     /// <param name="format">A standard or custom date and time format string.</param>     public static string ToJewishDateString(this DateTime value, string format)     {       HebrewCulture.DateTimeFormat.Calendar = new HebrewCalendar();       return value.ToString(format, HebrewCulture);     }     /// <summary>     /// Converts a gregorian date to its hebrew date string representation,     /// using DateTime format options.     /// </summary>     /// <param name="value">The <see cref="DateTime"/> value to convert.</param>     /// <param name="dayOfWeek">Specifies whether the return string should     /// include the day of week.</param>     public static string ToJewishDateString(this DateTime value, bool dayOfWeek)     {       var format = dayOfWeek ? "D" : "d";       return value.ToJewishDateString(format);     }   } }
no comments

Determine if char is Hebrew (2)


About 2 weeks ago I posted a function that determines whether a given char is hebrew:// avoid unicode chars in code private const char FirstHebChar = (char)1488; //א private const char LastHebChar = (char)1514; //ת private static bool IsHebrew(this char c) {   return c >= FirstHebChar && c <= LastHebChar; } Schabse Laks commented that it won't include punctuation marks / vowels etc. This week I needed a more sophisticated function that does the job, so I ended up with the extension methods bellow (view raw code here).Note, that I needed the function for a one-time-use application so I didn't optimize the code well enough, any improvements will be welcomed as always, and especially now.namespace System {   using System.Linq;   using System.Collections.Generic;   public static class HebrewCharsExtensions   {     public static bool IsHebrew(this char c)     {       return IsHebrew(c, HebrewCharTypes.All);     }     public static bool IsHebrew(this char c, HebrewCharTypes charTypes)     {       foreach (var kv in Map.Where(ct => charTypes.HasFlag(ct.Key)))       {         var locMap = kv.Value;         for (int i = 0; i <= locMap.GetUpperBound(0); i++)           if (c >= locMap && c <= locMap) return true;       }       return false;     }     public static HebrewCharTypes GetHebrewCharType(this char c)     {       foreach (var kv in Map)       {         var locMap = kv.Value;         for (int i = 0; i <= locMap.GetUpperBound(0); i++)           if (c >= locMap && c <= locMap) return kv.Key;       }       return HebrewCharTypes.None;     }     public static IEnumerable<char> GetHebChars()     {       return GetHebChars(HebrewCharTypes.All);     }     public static IEnumerable<char> GetHebChars(HebrewCharTypes charTypes)     {       foreach (var kv in Map.Where(ct => charTypes.HasFlag(ct.Key)))       {         var locMap = kv.Value;         for (int i = 0; i <= locMap.GetUpperBound(0); i++)         {           var start = locMap;           var end = locMap;           foreach (var ch in Enumerable.Range(start, end - start + 1))             yield return (char)ch;         }       }     }     private static readonly Dictionary<HebrewCharTypes, int> Map = new Dictionary<HebrewCharTypes, int>     {        {HebrewCharTypes.Letter,   new int { { 0x05d0, 0x05ea } } },        {HebrewCharTypes.Vowel,    new int { { 0x05b0, 0x05b9 }, { 0x05bb, 0x05c4 }, { 0xfb2a, 0xfb36 }, { 0xfb38, 0xfb3c }, { 0xfb3e, 0xfb3e }, { 0xfb40, 0xfb41 }, { 0xfb43, 0xfb44 }, { 0xfb46, 0xfb4e} } },        {HebrewCharTypes.Biblical, new int { { 0x0591, 0x05a1 }, { 0x05a3, 0x05af }, { 0xfb1e, 0xfb1e }, { 0xfb4f, 0xfb4f } } },        {HebrewCharTypes.Yiddish,  new int { { 0x05f0, 0x05f2 }, { 0xfb1f, 0xfb1f } } },        {HebrewCharTypes.Special,  new int { { 0x05f3, 0x05f4 }, { 0xfb20, 0xfb29 } } }     };   }      public enum HebrewCharTypes   {     /// <summary>     /// Not a Hebrew character.     /// </summary>     None = 0,     /// <summary>     /// Alef to Tav.     /// </summary>     Letter = 1,     /// <summary>     /// Qamats to Hataf Segol.     /// </summary>     Vowel = 2,     /// <summary>     /// Kadma Munah Pashta etc.     /// </summary>     Biblical = 4,     /// <summary>     /// Double Yod etc.     /// </summary>     Yiddish = 8,     /// <summary>     /// Other special characters (wide chars and more).     /// </summary>     Special = 16,     All = Letter | Vowel | Biblical | Yiddish | Special   } }
no comments

LeakEvent → WeakEvent


I'm sure not any Silverlight developer is aware of the fact that when one subscribes to an event, a strong reference to the handler class ('target') is attached to the event source ('source'), hence, if the source object life-cycle is longer than the target, memory is leaked, becuase when you don't need the target anymore and all its references are removed, there is still one reference to it by that event handler in the source, and thus, won't get collected by GC. A strong reference is a normal reference that protects the referred object from collection by a garbage collector. The term is used...

UniqueAttribute that validates a unique field against its fellow rows in the database (inherits DataAnnotations.ValidationAttribute)

UPDATE: Jan 30 2012: Added check that entity is not itself (i.e. when user attempts to save the same entity).UPDATE: Feb 26 2012: Added support for inherited entities, where the validated property is on the sub-class of the inheritance hierarchy. Here is a ValidationAttribute subclass that will allow you to validate that a column doesn't have duplicates. It's intended to be used with EF 4.1 DbContext, or with the EF4's ObjectContext.namespace System.ComponentModel.DataAnnotations { #if !SILVERLIGHT   using System;   using System.Data.Entity;   using System.Data.Entity.Infrastructure;   using System.Data.Metadata.Edm;   using System.Data.Objects;   using System.Linq; #endif   /// <summary>   /// Validates whether a value is set in another row at the same column.   /// Does not validate null empty or whitespace strings.   /// </summary>      public class UniqueAttribute : ValidationAttribute   { #if SILVERLIGHT        /// <summary>     /// Just a body method, the ValidationAttribute requires the IsValid method to be overridden.     /// </summary>     protected override ValidationResult IsValid(object value, ValidationContext validationContext)     {       return ValidationResult.Success;     } #else     private readonly Type _ContextType;     public Type ContextType     {       get       {         return _ContextType;       }     }     //TODO: If placed in your domain, uncomment and replace MyDbContext with your domain's DbContext/ObjectContext class.     //public UniqueAttribute() : this(typeof(MyDbContext)) { }     /// <summary>     /// Initializes a new instance of <see cref="UniqueAttribute"/>.     /// </summary>     /// <param name="contextType">The type of <see cref="DbContext"/> or <see cref="ObjectContext"/> subclass that will be used to search for duplicates.</param>     public UniqueAttribute(Type contextType)     {       if (contextType == null)         throw new ArgumentNullException("contextType");       if (!contextType.IsSubclassOf(typeof(DbContext)) && !contextType.IsSubclassOf(typeof(ObjectContext)))         throw new ArgumentException("The contextType Type must be a subclass of DbContext or ObjectContext.", "contextType");       if (contextType.GetConstructor(Type.EmptyTypes) == null)         throw new ArgumentException("The contextType type must declare a public parameterless consructor.");       _ContextType = contextType;     }     /// <summary>     /// Validates the value against the matching columns in the other rows of this table.     /// Note that this method does not validate null or empty strings.     /// </summary>     /// <param name="value">The value to validate</param>     /// <param name="validationContext">The context information about the validation operation.</param>     /// <returns>An instance of the <see cref="ValidationResult"/> class.</returns>     protected override ValidationResult IsValid(object value, ValidationContext validationContext)     {       if (value == null || (value is string && string.IsNullOrWhiteSpace((string)value))) return ValidationResult.Success;       var type = validationContext.ObjectType;       var property = type.GetProperty(validationContext.MemberName);       type = property.DeclaringType;       using (var dbcontext = (IDisposable)Activator.CreateInstance(_ContextType))       {         var context = dbcontext is DbContext ? ((IObjectContextAdapter)dbcontext).ObjectContext : (ObjectContext)dbcontext;         var md = context.MetadataWorkspace;         var entityType = md.GetItems<EntityType>(DataSpace.CSpace).SingleOrDefault(et => et.Name == type.Name);         while (entityType.BaseType != null)           entityType = (EntityType)entityType.BaseType;         var objectType = typeof(object);         var isInherited = false;         var baseType = type;         while (baseType.Name != entityType.Name && baseType.BaseType != objectType)         {           baseType = baseType.BaseType;           isInherited = true;         }         var methodCreateObjectSet = typeof(ObjectContext).GetMethod("CreateObjectSet", Type.EmptyTypes).MakeGenericMethod(baseType);         var baseObjectSet = (ObjectQuery)methodCreateObjectSet.Invoke(context, new object { });         var objectSet = baseObjectSet;         var setType = baseObjectSet.GetType();         if (isInherited)         {           var ofType = setType.GetMethod("OfType");           ofType = ofType.MakeGenericMethod(type);           objectSet = (ObjectQuery)ofType.Invoke(baseObjectSet, null);           setType = objectSet.GetType();         }         var methodWhere = setType.GetMethod("Where");         var eSql = string.Format("it.{0} = @{0}", validationContext.MemberName);         var query = (ObjectQuery)methodWhere.Invoke(objectSet,           new object { eSql, new { new ObjectParameter(validationContext.MemberName, value) } });         var result = query.Execute(MergeOption.NoTracking).Cast<object>();         bool isValid = true;         using (var enumerator = result.GetEnumerator())         {           if (enumerator.MoveNext())           {             var nameProperty = typeof(ObjectSet<>).MakeGenericType(baseType).GetProperty("EntitySet");             var entitySet = (EntitySet)nameProperty.GetValue(baseObjectSet, null);             var entitySetName = entitySet.Name;             do             {               var current = enumerator.Current;               var curKey = context.CreateEntityKey(entitySetName, current);               var validatingKey = context.CreateEntityKey(entitySetName, validationContext.ObjectInstance);               if (curKey != validatingKey)               {                 isValid = false;                 break;               }             } while (enumerator.MoveNext());           }         }         return isValid ?           ValidationResult.Success :           new ValidationResult(             string.Format("There is already a '{0}' record that has its '{1}' field set to '{2}'.",               validationContext.ObjectType.Name,               validationContext.DisplayName,               value),             new { validationContext.MemberName });       }     } #endif   } }  As soon as you will be trying to call DbContext.SaveChanges in the...

Determine if char is Hebrew


Simple Ex. method:// avoid unicode chars in code private const char FirstHebChar = (char)1488; //א private const char LastHebChar = (char)1514; //ת  private static bool IsHebrew(this char c) {   return c >= FirstHebChar && c <= LastHebChar; }Note: a comment bellow noted that the above function solely checks for hebrew characters within the א-ת range,it won't include punctuation marks, vowels or other biblical symbols.For a function that covers all (all that I'm aware of) Hebrew characters, please refer here.
one comment