About Hasmukh patel

My Photo
Harrow, London, United Kingdom
Dot-Net developer with expertise in Web, WPF, Win-form applications. Have worked on Asp.net,mvc , WPF and Win-forms projects in c#.net language having Sql-Server/Oracle as database with service oriented architecture using test driven development. Having complete knowledge of SDLC and have successfully worked and implemented it on projects.

Language Conversion with WPF

Language Conversion with WPF

In WPF, there is no way to load Label, button and other controls’ content based on your UI culture or allow you to override  UI contents based on your selected language. Using custom MarkupExtension can achieve the goal.  
Example of use of MarkupExtension  with Label

<Label Grid.Column="0" Grid.Row="1" Content="{Extensions:LanguageString Value=Teststring}" />
 

Implementation of MarkupExtension

Note : This is a xml file based example, file name “language-” + culture name.Xml  e.g. “language-en-gb.xml”

[MarkupExtensionReturnType(typeof(string))]
public class LanguageStringExtension : MarkupExtension
{
    #region Properties
 
    /// <summary>
    /// Gets or sets the string that is to be translated.
    /// </summary>
    public string Value { getset; }
    /// <summary>
    /// Gets or sets the format string to be used with the translated string.
    /// e.g. "({0})" to place the translated string in brackets.
    /// </summary>
    public string Format { getset; }
 
 
    #endregion
 
 
    #region Overrides of MarkupExtension
 
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        if (string.IsNullOrEmpty(Format))
        {
            return LanguageDictionary.Translate(Value);
        }
        return LanguageDictionary.Translate(Value, Format);
    }
 
    #endregion
}

public sealed class LanguageDictionary
{
    //for thread safe access
    private readonly ConcurrentDictionary<string,string> _phrases;
 
    static LanguageDictionary()
    {
        FilesDirectory = Directory.GetCurrentDirectory(); 
        Instance = new LanguageDictionary();
        //load current culture file
        Instance.LoadDictionary(CultureInfo.CurrentUICulture.Name);
    }
 
    //private constructor
    LanguageDictionary()
    {
        _phrases = new ConcurrentDictionary<stringstring>();
    }
 
    public static LanguageDictionary Instance { getprivate set; }
 
    public static string FilesDirectory { getset; }
 
    internal static string Translate(string phrase)
    {
        return Instance.TranslatePhrase(phrase, null);
    }
 
    internal static string Translate(string phrase, string formatString, params object[] prms)
    {
        return Instance.TranslatePhrase(phrase, formatString, prms);
    }
 
    internal static void Load(string culture)
    {
        Instance.LoadDictionary(culture);
    }
 
    internal static void Save()
    {
        Instance.SaveDictionary();
    }
 
    private static string _overrideCulture;
 
    internal static string OverrideCulture
    {
        get { return _overrideCulture; }
        set
        {
            Instance.LoadDictionary(value);
        }
    }
 
    private void SaveDictionary()
    {
        var fileName = GetLanguageFileName();
 
        var xmlDocument = new XmlDocument();
 
        foreach (var kpPhrase in _phrases)
        {
            var node = xmlDocument.CreateNode(XmlNodeType.Element, "Translate"string.Empty);
            node.InnerText = kpPhrase.Value;
 
            var nameAttr = xmlDocument.CreateAttribute("From");
            nameAttr.Value = kpPhrase.Key;
            node.Attributes.Append(nameAttr);
                
            xmlDocument.AppendChild(node);
        }
 
        xmlDocument.Save(fileName);
 
    }
 
    private string GetLanguageFileName()
    {
        return Path.Combine(FilesDirectory,
                            string.Format("language-{0}.xml", _overrideCulture));
    }
 
    private void LoadDictionary(string culture)
    {
        _overrideCulture = culture;
        //clear old values
        _phrases.Clear();
        var fileName = GetLanguageFileName();
 
        if (File.Exists(fileName))
        {
            var xmlDocument = new XmlDocument();
            xmlDocument.Load(fileName);
            foreach (XmlNode childNode in xmlDocument.ChildNodes)
            {
                _phrases.TryAdd(childNode.Attributes["From"].Value, childNode.InnerText);
            }
        }
    }
 
    private string TranslatePhrase(string phrase, string formatString, params object[] prms)
    {
        //get value or add for save
        var lanValue = _phrases.GetOrAdd(phrase, phrase);
 
        if (prms == null || prms.Length == 0)
        {
            return lanValue;
        }
        return string.Format(lanValue, prms);
    }
}

Generate EF code first DBContext from Database

Generate EF code first DBContext from existing Database
SET NOCOUNT off 
begin
 declare @UserTables table
    (
            Id [int],
            Name [nvarchar](200),
            PropertyName [nvarchar](200)
    )
 
 insert into @UserTables
  select id, name ,
   case 
   when  Right(Name,2) in ('ss','ch') then Name + 'es'
   when  Right(Name,2) = 'ff' then left(Name, len(Name)-2) + 'ves'
   when  Right(Name,2) = 'fe' then left(Name, len(Name)-2) + 'ves'
   when  Right(Name,1) = 'f' then left(Name, len(Name)-1) + 'ves'
   when  Right(Name,1) = 'y' then 
     case when IsPrecedingVowel = 1 
     then Name + 's' 
     else left(Name, len(Name)-1) + 'ies'
     end
   when  Right(Name,1) = 'o' then
     case when IsPrecedingVowel = 1 
     then Name + 's' 
     else Name + 'es'
     end
   else Name + 's' 
   end as PropertyName
  from ( select id, name,
   case when left(right(name,2),1) in ('a','e','i','o','u') then 1 else 0 end as IsPrecedingVowel
    from sysobjects where xtype = 'U' ) as x
 
    --select * from INFORMATION_SCHEMA.TABLES 
 
 
 declare @EntityPriFix [nvarchar](20);
 
 declare @Id int;         
 declare @TableName [nvarchar](200);
 declare @PropertyName [nvarchar](200);
  
 set @EntityPriFix = 'POCO';
 
 declare tableCursor cursor for
  select * from @UserTables
 
 print 'using System.Data.Entity;'
 
 print ' public class ' + db_name() + 'Context : DbContext'
 print ' {'
 print '  public QslLoyaltyContext(string connectionString)'
 print '   : base(connectionString)'
 print '        { }'
 
 OPEN tableCursor
 
 FETCH NEXT FROM tableCursor 
  INTO @Id, @TableName, @PropertyName
 
 WHILE @@FETCH_STATUS = 0
 BEGIN
  
  print '  public DbSet<'+ @EntityPriFix + @TableName +'> ' + @PropertyName +' { get; set; }'
  
 FETCH NEXT FROM tableCursor 
  INTO @Id, @TableName, @PropertyName
 END 
 CLOSE tableCursor;
 
 print '  protected override void OnModelCreating(DbModelBuilder modelBuilder)'
 print '  {'
 OPEN tableCursor
 
 FETCH NEXT FROM tableCursor 
  INTO @Id, @TableName, @PropertyName
 
 WHILE @@FETCH_STATUS = 0
 BEGIN
  
  print '   modelBuilder.Entity<'+ @EntityPriFix + @TableName +'>().ToTable("' + @TableName +'");'
  
 FETCH NEXT FROM tableCursor 
  INTO @Id, @TableName, @PropertyName
 END
 print '  }'
 
 CLOSE tableCursor;
 DEALLOCATE tableCursor; 
 
 print ' }'
 print '' 
end
 
Output will be like as below
using System.Data.Entity;
public class QslLoyaltyContext : DbContext
{
    public QslLoyaltyContext(string connectionString)
        : base(connectionString)
    { }
    
    public DbSet<POCOUsers> Userss { getset; }
    public DbSet<POCORoles> Roless { getset; }
 
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<POCOUsers>().ToTable("Users");
        modelBuilder.Entity<POCORoles>().ToTable("Roles");
    }
}
 

Generate POCO classes from Database for Entity Framework Code First

Generate POCO classes from Database for Entity Framework Code First
Generate POCO classes from Database using SQL script using INFORMATION_SCHEMA.COLUMNS & INFORMATION_SCHEMA.TABLES system tables.

SETET NOCOUNT off 
begin
 declare @UserTables table
    (
            SchemaName [nvarchar](200),
            TableName [nvarchar](200)
    )
 
 declare @UserColumns table
    (
            TableName [nvarchar](200),    
            Name [nvarchar](200),
            DataType [nvarchar](50),
            isnullable [nvarchar](5),
            ColLength int,
            ColOrder int
    )
 
 insert into @UserTables 
 select TABLE_SCHEMA, TABLE_NAME from INFORMATION_SCHEMA.TABLES
 
 insert into @UserColumns
 select t.TableName, c.COLUMN_NAME,    
   case 
      when c.DATA_TYPE = 'varchar' then 'string'
      when c.DATA_TYPE = 'nvarchar' then 'string'
   when c.DATA_TYPE = 'datetime' then 'DateTime'
   when c.DATA_TYPE = 'date' then 'DateTime'
   when c.DATA_TYPE = 'timestamp' then 'DateTime'
   when c.DATA_TYPE = 'numeric' then 'decimal'
   else c.DATA_TYPE end,
   c.IS_NULLABLE,
   c.CHARACTER_MAXIMUM_LENGTH,
   c.ORDINAL_POSITION
  from @UserTables t, INFORMATION_SCHEMA.COLUMNS c
  where t.TableName = c.TABLE_NAME and t.SchemaName = c.TABLE_SCHEMA
  order by c.ORDINAL_POSITION
    
 declare @EntityPriFix [nvarchar](20);
 
 declare @SchemaName [nvarchar](200);
 declare @TableName [nvarchar](200);
 
 declare @DataType [nvarchar](20);
 declare @ColumnName [nvarchar](200);
 declare @isnullable [nvarchar](5)
 declare @colLength [int];
 
 set @EntityPriFix = 'POCO';
 
 declare tableCursor cursor for
  select * from @UserTables
 OPEN tableCursor
 
 print 'using System.ComponentModel.DataAnnotations;'
 print 'using System.ComponentModel.DataAnnotations.Schema;'
 
 FETCH NEXT FROM tableCursor 
  INTO @SchemaName, @TableName
 
 WHILE @@FETCH_STATUS = 0
 BEGIN
 
 print ' public class ' + @EntityPriFix + @TableName
 print ' {'
 
   declare columnCursor cursor for
   select Name, DataType, isnullable, ColLength
    from @UserColumns 
    where TableName = @TableName
    order by ColOrder
   
   OPEN columnCursor
   FETCH NEXT FROM columnCursor
    INTO @ColumnName, @DataType, @isnullable, @colLength
   WHILE @@FETCH_STATUS = 0
   BEGIN
   
   if(@TableName + 'ID' = @ColumnName)
   begin
    print '  [Key]'
   end
   else
   begin
    if(@isnullable = 'YES')
    begin
     print case when @DataType <> 'string' then '//' else '' end + '  [Required]'
    end
    if(@TableName = @ColumnName)
    begin
     print '  [Column("'+ @ColumnName +'")]'
    end
   end
   
   if(@DataType = 'string')
   begin
    print '  [MaxLength(' +
     cast(@colLength  as varchar(50)) + ',ErrorMessage = "' + @ColumnName + ' must be '+
     cast(@colLength  as varchar(50)) ++ '")]'
   end
 
   print case when @DataType p;= 'image' then '' else '' end +
   '  public ' + @DataType + 
   case when @DataType <> 'string' then ' ? ' else ' ' end +
   case when  Right(@ColumnName,2) = 'ID' 
    then substring(@ColumnName,1,len(@ColumnName)-2)+ 'Id' 
    else case when @ColumnName = @TableName 
      then @ColumnName + '_1' else @ColumnName end  end +  ' {get; set;}'
      
   FETCH NEXT FROM columnCursor
    INTO @ColumnName, @DataType, @isnullable, @colLength
   END 
   CLOSE columnCursor;
   DEALLOCATE columnCursor;
 
 print ' }'
 print ''
 
 FETCH NEXT FROM tableCursor 
  INTO @SchemaName, @TableName
 END 
 CLOSE tableCursor;
 DEALLOCATE tableCursor; 
end 
Generate POCO classes from Database using SQL script using sysObjects & syscolumns system tables.
SET NOCOUNT off 
begin
 declare @UserTables table
    (
            Id [int],
            Name [nvarchar](200)
    )
 
 declare @UserColumns table
    (
            Id [int],
            Name [nvarchar](200),
            xtype int,
            TypeName [nvarchar](50),
            isnullable bit,
            ColLength int,
            ColOrder int
    )
 
 insert into @UserTables 
 select id, name from sysobjects where xtype = 'U'
 
 insert into @UserColumns
 select id, sc.name, ty.[type], ty.name, sc.isnullable , 
  case when sc.typestat =2  then sc.length/else sc.length end,
  sc.colorder
  from syscolumns sc, systypes ty
  where sc.xusertype = ty.xusertype and id in(select id from @UserTables)
 
 declare @EntityPriFix [nvarchar](20);
 
 declare @Id [int];
 declare @Name [nvarchar](200);
 
 declare @xtype [int];
 declare @ColumnName [nvarchar](200);
 declare @typeName [nvarchar](50);
 declare @isnullable bit
 declare @colLength [int];
 
 set @EntityPriFix = 'POCO';
 
 declare tableCursor cursor for
  select * from @UserTables
 OPEN tableCursor
 
 print 'using System.ComponentModel.DataAnnotations;'
 print 'using System.ComponentModel.DataAnnotations.Schema;'
 
 FETCH NEXT FROM tableCursor 
  INTO @Id, @Name
 
 WHILE @@FETCH_STATUS = 0
 BEGIN
 
 print ' public class ' + @EntityPriFix + @Name
 print ' {'
 
   declare columnCursor cursor for
   select Name,xtype, TypeName, isnullable, ColLength
   from @UserColumns where id = @Id
   order by ColOrder
   
   OPEN columnCursor
   FETCH NEXT FROM columnCursor
   INTO @ColumnName, @xtype, @typeName, @isnullable, @colLength
   WHILE @@FETCH_STATUS = 0
   BEGIN
   
   if(@Name + 'ID' = @ColumnName)
   begin
    print '  [Key]'
   end
   else
   begin
    if(@isnullable = 0)
    begin
     print case when @xtype in(34,45) then '//' else '' end + '  [Required]'
    end
    if(@Name = @ColumnName)
    begin
     print '  [Column("'+ @ColumnName +'")]'
    end
   end
   
   if(@xtype in(35,37,39,47))
   begin
    print '  [MaxLength(' +
     cast(@colLength  as varchar(50)) + ',ErrorMessage = "' + @ColumnName + ' must be '+
     cast(@colLength  as varchar(50)) +' characters or less' + '")]'
   end
   
   print  case when @xtype in(34,45) then '//' else '' end +  -- comment out image type
   '  public ' +
   case when @xtype in(35,37,39,47) then 'string'
   when @xtype in(50) then 'bool'
   when @xtype in(48) then 'Byte'
   when @xtype in(52,56) then 'int'
   when @xtype in(63) then 'long'
   when @xtype in(122,60,55,59) then 'decimal'
   when @xtype in(58,61) then 'DateTime'
   when @xtype in(34,45) then 'Binary'
   else @typeName end  +
   case when @isnullable = 1 and @xtype not in(35,37,39,47) then ' ? ' else ' ' end +
   case when  Right(@ColumnName,2) = 'ID' 
     then substring(@ColumnName,1,len(@ColumnName)-2)+ 'Id' 
     else case when @ColumnName = @Name 
       then @ColumnName + '_1' else @ColumnName end  end +  ' {get; set;}'
   
   FETCH NEXT FROM columnCursor
   INTO @ColumnName, @xtype, @typeName, @isnullable,@colLength
   END 
   CLOSE columnCursor;
   DEALLOCATE columnCursor;
 
 print ' }'
 print ''
 
 FETCH NEXT FROM tableCursor 
  INTO @Id, @Name
 END 
 CLOSE tableCursor;
 DEALLOCATE tableCursor; 
 
end
Output will be like as below
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class POCOUsers
{
    public int? Id { getset; }
    public int? SiteId { getset; }
    [MaxLength(255, ErrorMessage = "Username must be 255 characters or less")]
    public string Username { getset; }
    [MaxLength(255, ErrorMessage = "Password must be 255 characters or less")]
    public string Password { getset; }
    [MaxLength(255, ErrorMessage = "Token must be 255 characters or less")]
    public string Token { getset; }
    [Required]
    [MaxLength(20, ErrorMessage = "SwipeId must be 20 characters or less")]
    public string SwipeId { getset; }
    [MaxLength(20, ErrorMessage = "Title must be 20 characters or less")]
    public string Title { getset; }
    [MaxLength(255, ErrorMessage = "Forename must be 255 characters or less")]
    public string Forename { getset; }
    [MaxLength(255, ErrorMessage = "Surname must be 255 characters or less")]
    public string Surname { getset; }
    [MaxLength(255, ErrorMessage = "Phone must be 255 characters or less")]
    public string Phone { getset; }
    [MaxLength(255, ErrorMessage = "Email must be 255 characters or less")]
    public string Email { getset; }
    //  [Required]
    public DateTime? Dob { getset; }
    [Required]
    [MaxLength(255, ErrorMessage = "Address1 must be 255 characters or less")]
    public string Address1 { getset; }
    [Required]
    [MaxLength(255, ErrorMessage = "Address2 must be 255 characters or less")]
    public string Address2 { getset; }
    [Required]
    [MaxLength(255, ErrorMessage = "Town must be 255 characters or less")]
    public string Town { getset; }
    [Required]
    [MaxLength(255, ErrorMessage = "County must be 255 characters or less")]
    public string County { getset; }
    [Required]
    [MaxLength(255, ErrorMessage = "Postcode must be 255 characters or less")]
    public string Postcode { getset; }
    [Required]
    [MaxLength(255, ErrorMessage = "Country must be 255 characters or less")]
    public string Country { getset; }
    //  [Required]
    public int? RoleId { getset; }
    //  [Required]
    public int? Status { getset; }
}
 
 
public class POCORoles
{
    public int? Id { getset; }
    [MaxLength(50, ErrorMessage = "Name must be 50 characters or less")]
    public string Name { getset; }
    [Required]
    [MaxLength(50, ErrorMessage = "Description must be 50 characters or less")]
    public string Description { getset; }
}

WPF Observble Extensions



using System;
using System.ComponentModel;
using System.Linq.Expressions;

namespace DemoCode.Shared.Extensions
{
    public static class ObservableExts
    {
        public static IObservable<IObservedChange<TSender, TValue>> ObservableForProperty<TSender, TValue>
            (this TSender This, Expression<Func<TSender, TValue>> property, bool beforeChange = false)
            where TSender : INotifyPropertyChanged
        {
            var observedChange = new ObservedChange<TSender, TValue>(This, property);
            return new Observable<TSender, TValue>(observedChange);
        }

        public static IDisposable Subscribe<TSource>(this IObservable<TSource> source, Action<TSource> onNext)
            where TSource : class
        {
            return new Unsubscriber<TSource>(source, onNext);
        }

    }

    internal interface INotifySender
    {
        INotifyPropertyChanged Sender { get; }
        string PropertyName { get; }
        TSource GetSource<TSource>();
    }

    public interface IObservedChange<out TSender, out TValue>
    {
        TSender Sender { get; }
        TValue Value { get; }
        string PropertyName { get; }
    }

    public class ObservedChange<TSender, TValue> : IObservedChange<TSender, TValue>
    {
        private Expression<Func<TSender, TValue>> _property;

        public ObservedChange(TSender sender, Expression<Func<TSender, TValue>> property)
        {
            Sender = sender;

            var expression = property.Body as MemberExpression;
            if (expression != null)
            {
                var member = expression.Member;
                PropertyName = member.Name;
            }
            _property = property;

        }

        public TSender Sender { get; private set; }
        public TValue Value { get { return (TValue)Sender.GetType().GetProperty(PropertyName).GetValue(Sender, null); } }
        public string PropertyName { get; private set; }
    }

    public class Observable<TSender, TValue> : IObservable<IObservedChange<TSender, TValue>>, INotifySender
    {
        public Observable(IObservedChange<TSender, TValue> observedChange)
        {
            ObservedChange = observedChange;
        }

        public IObservedChange<TSender, TValue> ObservedChange { get; private set; }

        public IDisposable Subscribe(IObserver<IObservedChange<TSender, TValue>> observer)
        {
            throw new NotImplementedException();
        }

        public INotifyPropertyChanged Sender
        {
            get { return ObservedChange.Sender as INotifyPropertyChanged; }
        }

        public string PropertyName
        {
            get { return ObservedChange.PropertyName; }
        }

        public TSource GetSource<TSource>()
        {
            return (TSource)ObservedChange;
        }
    }

    internal class Unsubscriber<TSource> : IDisposable
        where TSource : class
    {
        private IObservable<TSource> _source;
        private readonly Action<TSource> _onNext;
        private readonly INotifySender _notifySender;

        public Unsubscriber(IObservable<TSource> source, Action<TSource> onNext)
        {
            _source = source;
            _notifySender = source as INotifySender;
            if (_notifySender != null && _notifySender.Sender != null)
            {
                _notifySender.Sender.PropertyChanged += SenderPropertyChanged;
            }
            _onNext = onNext;
        }

        void SenderPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (_onNext != null && e.PropertyName == _notifySender.PropertyName)
            {
                //_onNext(_onNext.Target as TSource);
                System.Windows.Application.Current.Dispatcher
                    .Invoke(System.Windows.Threading.DispatcherPriority.Normal,
                            (Action) (() => _onNext(_notifySender.GetSource<TSource>())));
            }
        }

        public void Dispose()
        {
            _notifySender.Sender.PropertyChanged -= SenderPropertyChanged;
        }
    }

}