2019年4月2日 星期二

Enable Other Protocols (TCP, PIPE, MSMQ etc.) In IIS

By default it's available only in HTTP, HTTPS and FTP protocols Windows IIS though it supports others like TCP, PIPE protocols as well. This blog demonstrates how to enable other protocols like TCP in IIS.
Getting started, we know that Windows IIS by default supports only HTTP, HTTPS and FTP protocols and you will get those protocols in the binding window of IIS.
 

But other protocols like TCP, PIPE etc. Can be enabled by changing IIS feature, the below steps defines how to tune IIS features to enable TCP protocols.
Follow the Steps
  1.  Open Control Panel=>Programs=>Click on Uninstall or Change a Program=> Click on Link ‘Turn Windows Features on or off’.
  1. Windows Features window will be opened, expand .NET Framework Advance Service.
  2. Expand WCF Services=>Select All the Features HTTPActivation, Message Queuing (MSMQ) Activation, Named Pipe Activation, TCPActivation, TCP Port Sharing .Click OK button. 
 
Windows will apply the changes you made and you will get message popup, close the window (Clicking on close button), restart your machine and follow the below steps.
Open IIS=> in Connections panel=> expand Sites=>Select your website=>Go to Right site Action Pane=> click on Advanced Settings=> Expand the ‘Behavior’ section In the field ‘Enable Protocols’ set these below values by commas, (http,net.tcp,net.pipe,net.msmq,msmq.formatname). Click OK button.
  • For activating TCP protocol set ‘net.tcp’
  • For activating PIPE protocol set ‘net.pipe’
  • For activating MSMQ Protocol set’ net.msmq’
 

Now you are done, if you follow the above steps correctly, you will get the mentioned protocols in the binding window.

Web Request Certificate Error


Troubleshooting ASP.NET – The remote certificate is invalid according to the validation procedure


This error message is caused because the process is not being able to validate the Server Certificate supplied by the Server during an HTTPS (SSL) request.  The very first troubleshooting step should be to see if the server supplied certificate and every certificate in the chain is trouble free.
Example 1 – Root Certificate only (self signed certificate in this case)
Step 1 – Validate the certificate, any intermediate certificates and the root certificate
One super handy and technical tool to help you do this first step is Internet Explorer.  Simply try to hit the same URL that your ASP.NET web application tries to hit when it gets this error.  For example, type in to the browser the path to the .asmx file and see what Internet Explorer says about the certificate.
This would be a bad sign:
image
If Internet Explorer has certificate problems, chances are you will have problems with the HttpWebRequest (or Web Service) call as well.  The easiest fix is to install a valid certificate for the server, the root authority and all intermediate authorities.  Then go back and verify Internet Explorer can access the https site with no errors at all.
If you continue to the site using Internet Explorer, sometimes you can diagnose the certificate problem by viewing the certificate.  In this example the problem is spelled out for me when I typed in https://jsanders4.
image
So in my case, it appears that the I simply need to install the certificate in the ‘Trusted Root Certification Authorities’ store.  So indeed I do this!
image  image  image
But I still got the certificate error…  To avoid a long discussion about this, the problem is simple.  I typed in https://jsanders4 but note the certificate is for the full domain name of this machine.  If I instead browse to https://jsanders4.northamerica.corp.microsoft.com then I get no certificate error.  Now that I am sure I can browse ok to the site with no certificate errors using Internet Explorer.
You would continue to solve problems with the other Certificates in the Certificate chain by using Internet Explorer until they are all resolved.  For example, perhaps the certificate is expired, or the Intermediate Authority is not in the Intermediate Certificate Authorities store (a very common one).  Once you have resolved all errors with Internet Explorer your are only half way finished.  You need to get the same information into the Local Computer store.
Step 2 – Troubleshoot the ASP.NET problem
I try my ASP.NET application and try to access the same site.  I get this error: ‘The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.’
But Internet Explorer was fine…
The next step should be to get a System.Net trace.  To do this open the Web.Config for the troubled ASP.NET application and see if there is a <configuration> section in the file.  If there is, add the contents inside the <configuration> </configuration> tags from this blog: http://blogs.msdn.com/jpsanders/archive/2009/03/24/my-favorite-system-net-trace-configuration-file-dumps-process-id-and-date-time-information.aspx.  If it does not exist, add the entire contents before the closing tag of the Web.Config.  Now edit this line:   initializeData="System.Net.trace.log"  You must ensure that the Network Service account can write this .log so change this entry to a folder that the Network Service account can write to.  For example, I created a folder c:\mylogs and assigned the Network Service account FULL privileges.  Then changed this setting to initializeData="c:\mylogs\System.Net.trace.log"
I ran the asp.net application and saw at the end of the log file (c:\mylogs\System.Net.trace.log) this information:
System.Net Information: 0 : [0880] SecureChannel#14701405 - Remote certificate has errors:
    ProcessId=5700
    DateTime=2009-09-16T12:54:06.5718699Z
System.Net Information: 0 : [0880] SecureChannel#14701405 -     A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider.
    ProcessId=5700
    DateTime=2009-09-16T12:54:06.5718699Z
System.Net Information: 0 : [0880] SecureChannel#14701405 - Remote certificate was verified as invalid by the user.
    ProcessId=5700
    DateTime=2009-09-16T12:54:06.5718699Z
System.Net.Sockets Verbose: 0 : [0880] Socket#26833123::Dispose()
    ProcessId=5700
    DateTime=2009-09-16T12:54:06.5718699Z
System.Net Error: 0 : [0880] Exception in the HttpWebRequest#31364015:: - The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
    ProcessId=5700
    DateTime=2009-09-16T12:54:06.5718699Z
This is the key to this particular problem:  A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider.
However I thought I just added this certificate trough Internet Explore to my Trusted Root Authorities!  In reality I simply added it so the store of the logged on user.  ASP.NET is running in the local machine context.  To resolve this, start MMC (Windows key + R and type MMC) and add the following snap-ins:
image image image
And ensure you see the ‘Current User’ and ‘(Local Computer)’ Certificates listed (then hit OK):
image
In the console expand the ‘Current User’ Trusted Root store and you see I have the certificate stored there.  However expanding the ‘(Local Computer)’ trusted root, it is NOT there:
image image
Simply Copy (do not Drag and drop) the jsanders4 certificate from the Current User\Trusted Root store to the (Local Computer)\Trusted Root store and retest. 
image image
Success!
Example 2 – Intermediate Certificate Authorities Involved
This next example is a bit manufactured but illustrates a problem that I have had to help solve a few times.  The trouble shooting steps remain the same, but in this case there are one or more intermediate certificates.  This intermediate certificates should be in the ‘Intermediate Certification Authorities’ store to resolve this problem Take a look at the certificate chain for https://www.microsoft.com (you do this by clicking on the padlock icon in Internet Explorer and choosing the Certification Path tab:
image 
For the purpose of this example, assume that the three certificates that are not highlighted all have a warning icon next to them indicating a problem.
Step 1 – Validate the certificate, any intermediate certificates and the root certificate
Note: For Internet Explorer there actually was no problem with the certification path.  The four certificates show no warning icons.  For thisexample, let’s say that the ‘GTE CyberTrust Global Root’, ‘Microsoft Internet Authority’ and ‘Microsoft Secure Server Authority’ certificates were all missing from my ‘Current User’ stores.  The steps below are contrived from this assumption.
To fix this I add the ‘GTE CyberTrust Global Root’ cert to the ‘Trusted Root Certification Authorities’ Store and the other two certificates to the ‘Intermediate Certification Authorities’ store of the Current User.  Test with IE again and Internet Explorer shows no problem after installing the certificates.  Next when I tested the ASP.NET application I got an error (because I did not add these certificates to the same stores in the (Local Computer) store).
Step 2 – Troubleshoot the ASP.NET problem
From the first example I was smart enough to copy the ‘GTE CyberTrust Global Root’ certificate to the ‘(Local Computer)’ trusted root store but I still have an error!
The ASP.NET program now has an error: System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
Again taking the System.Net trace you see an error towards the end of the file in these entries:
Remote certificate has errors:
A certificate chain could not be built to a trusted root authority. 
Remote certificate was verified as invalid by the user.
The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
This entry is the key: ‘A certificate chain could not be built to a trusted root authority.’  This means that a certificate before the Root Authority is not in the ‘(Local Computer) Intermediate Certification Authorities’ store.  Once the two intermediate certificates are copied to the Intermediate store from the Current User intermediate store the problem is solved!
I hope this blog helped you get to the root of your problem.  If this was helpful please leave me a comment!


Ref : https://blogs.msdn.microsoft.com/jpsanders/2009/09/16/troubleshooting-asp-net-the-remote-certificate-is-invalid-according-to-the-validation-procedure/

2018年6月12日 星期二

2017年12月6日 星期三

How to get the all collection of sub-collection latest record

Environment
- .Net Framework 4.6.1
- EF 6.1.3
- Ms Visual Studio 2015

Table

Expected Result


Code
static public IEnumerable<History> GetAllLatestHistoryGroupedByUser(bool includedChild = false)
        {
            var predicate = PredicateBuilder.New<History>();

            if (includedChild)
            {
                predicate = predicate.And(c => c.IsDeleted == false);

                return dataContext.Historys.AsExpandable()
                                           .Where(predicate)
                                           .Include(c => c.User)
                                           .AsEnumerable()
                                           .GroupBy(c => c.userid)
                                           .Select(grp => grp.OrderByDescending(x => x.createdOn).FirstOrDefault());
            }
            else
            {
                return dataContext.Historys.AsExpandable()
                                           .Where(predicate)                                            
                                           .GroupBy(c => c.userid)
                                           .Select(grp => grp.OrderByDescending(x => x.createdOn).FirstOrDefault());
            }
        }            

*** Important Note ***
for include sub-collection, using .Include()

but very important that if any operation after .Include() such as .GroupBy(), .Select()
.Include() will negligible
So it need to add .AsEnumerable() before any operation

2017年12月5日 星期二

EF 6.1.3 Model First

Environment
- .Net Framework 4.6.1
- EF 6.1.3
- Ms Visual Studio 2015

Technique Applied
- Model First
- Fluent API
- Eager loading

        public MyContext() : base("DLSContext")
        {
            Configuration.LazyLoadingEnabled = false;
        }

- 1 to many configuration
            modelBuilder.Entity<User>()
                        .HasOptional(e => e.Creator)
                        .WithMany()
                        .HasForeignKey(m => m.CreatedBy);



- many to many configuration ( relationship table )
            // User2Right Table
            modelBuilder.Entity<User>()
                        .HasMany<UserRight>(r => r.UserRights)
                        .WithMany(u => u.PermittedUsers)
                        .Map(m =>
                                {
                                    m.MapLeftKey("UserId");
                                    m.MapRightKey("RightId");
                                    m.ToTable("User2Right");
                                }
                            );

.Map => generate relationship table in database


- virtual sub-collection
public virtual ICollection<UserRight> UserRights { get; set; }

- pluralizing

public DbSet<User> Users { get; set; }

modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();


- lower camelCase
   modelBuilder.Properties().Configure(c =>
            {
                var name = c.ClrPropertyInfo.Name;
                var newName = char.ToLower(name[0]) + name.Substring(1);
                c.HasColumnName(newName);
            });


- Key and Index Attribute

  
        [Index]  
        [Key]      
        public int Id { get; set; }



Model

User
public class User
    {
        public User()
        {
            if (this.UserRights == null)
            {
                this.UserRights = new HashSet<UserRight>();
            }
        }

        [Index]  
        [Key]      
        public int Id { get; set; }

        [Column(TypeName = "nvarchar")]
        [StringLength(255)]
        [Required]
        public string Name { get; set; }

        [Column(TypeName = "nvarchar")]
        [StringLength(125)]
        [Required]
        [Index("IX_Login", IsUnique = true)]
        public string Login { get; set; }

        [Column(TypeName = "nvarchar")]
        [StringLength(500)]
        [Required]
        public string Password { get; set; }

        [Column(TypeName = "bit")]        
        public bool IsDisabled { get; set; }

        [Column(TypeName = "nvarchar")]
        [StringLength(255)]
        [Required]
        public string Email { get; set; }

        [Required]
        public int FailedLoginAttempts { get; set; }

        public DateTime CreatedOn { get; set; }

        public int? CreatedBy { get; set; }

        public virtual User Creator { get; set; }

        public DateTime ModifiedOn { get; set; }

        public int? ModifiedBy { get; set; }

        public virtual User Modifier { get; set; }

        [Column(TypeName = "bit")]
        [Required]
        public bool IsDeleted { get; set; }

        public virtual ICollection<UserRight> UserRights { get; set; }
        public virtual ICollection<Status> StatusesCreated { get; set; }
        public virtual ICollection<Status> StatusesModified { get; set; }

    }

UserRight
public class UserRight
    {
        public UserRight()
        {
            if (this.PermittedUsers == null)
            {
                this.PermittedUsers = new HashSet<User>();
            }
        }

        [Index]
        [Key]
        [Required]
        public int Id { get; set; }

        [Column(TypeName = "nvarchar")]
        [StringLength(255)]
        [Required]
        public string Name { get; set; }

        [Column(TypeName = "nvarchar")]
        [StringLength(255)]
        public string Description { get; set; }

        public DateTime CreatedOn { get; set; }

        public int? CreatedBy { get; set; }

        public User Creator { get; set; }

        public DateTime ModifiedOn { get; set; }

        public int? ModifiedBy { get; set; }

        public virtual User Modifier { get; set; }

        [Column(TypeName = "bit")]
        [Required]
        public bool IsDeleted { get; set; }

        public virtual ICollection<User> PermittedUsers { get; set; }

    }

Status
 public class Status
    {
        [Index]
        [Key]
        public int Id { get; set; }

        [Column(TypeName = "nvarchar")]
        [StringLength(255)]
        [Required]
        public string Name { get; set; }

        public DateTime CreatedOn { get; set; }

        public int? CreatedBy { get; set; }
        public virtual User Creator { get; set; }

        public DateTime ModifiedOn { get; set; }

        public int? ModifiedBy { get; set; }

        public virtual User Modifier { get; set; }

        [Column(TypeName = "bit")]
        [Required]
        public bool IsDeleted { get; set; }

        public virtual ICollection<Contact> Contacts { get; set; }
    }


DAL

Context
public class MyContext : DbContext
    {
        public MyContext() : base("MyContext")
        {
            Configuration.LazyLoadingEnabled = false;
        }
        public DbSet<User> Users { get; set; }
        public DbSet<UserRight> UserRights { get; set; }        
        public DbSet<Status> Statuses { get; set; }


        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            // Pluralizing
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

            // lower camelCase
            modelBuilder.Properties().Configure(c =>
            {
                var name = c.ClrPropertyInfo.Name;
                var newName = char.ToLower(name[0]) + name.Substring(1);
                c.HasColumnName(newName);
            });

            // User Table 
            modelBuilder.Entity<User>()
                        .HasOptional(e => e.Creator)
                        .WithMany()
                        .HasForeignKey(m => m.CreatedBy);

            modelBuilder.Entity<User>()
                        .HasOptional(e => e.Modifier)
                        .WithMany()
                        .HasForeignKey(m => m.ModifiedBy);

            // User2Right Table
            modelBuilder.Entity<User>()
                        .HasMany<UserRight>(r => r.UserRights)
                        .WithMany(u => u.PermittedUsers)
                        .Map(m =>
                                {
                                    m.MapLeftKey("UserId");
                                    m.MapRightKey("RightId");
                                    m.ToTable("User2Right");
                                }
                            );              

            // Status Table
            modelBuilder.Entity<Status>()
                        .HasRequired(c => c.Creator)
                        .WithMany(u => u.StatusesCreated)
                        .HasForeignKey(c => c.CreatedBy)
                        .WillCascadeOnDelete(false);

            modelBuilder.Entity<Status>()
                        .HasRequired(c => c.Modifier)
                        .WithMany(u => u.StatusesModified)
                        .HasForeignKey(c => c.ModifiedBy)
                        .WillCascadeOnDelete(false);
            
        }
    }

Initializer
public class MyInitializer : System.Data.Entity.DropCreateDatabaseIfModelChanges<MyContext>
    {
        protected override void Seed(MyContext context)
        {
            // Create Master User
            var systemUser = new User { Name = "System Admin", Login = "System Admin", Password = "1234567890", IsDisabled = false, Email = "abc", FailedLoginAttempts = 0, CreatedOn = DateTime.Today, ModifiedOn = DateTime.Today, IsDeleted = false };
            context.Users.Add(systemUser);
            context.SaveChanges();

            // Create User Right
            var userRights = new List<UserRight>
            {
                new UserRight { Name = "Administrative", Description = "Administrative Permission", CreatedOn=DateTime.Today, Creator=systemUser, ModifiedOn=DateTime.Today, Modifier=systemUser, IsDeleted=false },
                new UserRight { Name = "Super User", Description = "Super User Permission", CreatedOn=DateTime.Today, Creator=systemUser, ModifiedOn=DateTime.Today, Modifier=systemUser, IsDeleted=false },
                new UserRight { Name = "Dashboard Read", Description = "Read Permission for Dashboard", CreatedOn=DateTime.Today, Creator=systemUser, ModifiedOn=DateTime.Today, Modifier=systemUser, IsDeleted=false },
                new UserRight { Name = "Dashboard Write", Description = "Write Permission for Dashboard", CreatedOn=DateTime.Today, Creator=systemUser, ModifiedOn=DateTime.Today, Modifier=systemUser, IsDeleted=false },                
            };
            userRights.ForEach(u => context.UserRights.Add(u));
            context.SaveChanges();           

            // Create Status
            var statuses = new List<Status>
            {
                new Status { Name = "Active", CreatedOn=DateTime.Today, Creator=systemUser, ModifiedOn=DateTime.Today, Modifier=systemUser, IsDeleted=false },
                new Status { Name = "InActive", CreatedOn=DateTime.Today, Creator=systemUser, ModifiedOn=DateTime.Today, Modifier=systemUser, IsDeleted=false },
                new Status { Name = "Pending", CreatedOn=DateTime.Today, Creator=systemUser, ModifiedOn=DateTime.Today, Modifier=systemUser, IsDeleted=false }
            };
            statuses.ForEach(u => context.Statuses.Add(u));
            context.SaveChanges();           

            // Create User
            var users = new List<User>
            {
                new User { Name = "User A", Login = "userA", Password = "1234567890", IsDisabled = false, Email = "userA@mydomain.com", FailedLoginAttempts = 0, Creator=systemUser, CreatedOn = DateTime.Today, Modifier=systemUser, ModifiedOn = DateTime.Today, IsDeleted = false },
                new User { Name = "User B", Login = "userB", Password = "1234567890", IsDisabled = false, Email = "userB@mydomain.com", FailedLoginAttempts = 0, Creator=systemUser, CreatedOn = DateTime.Today, Modifier=systemUser, ModifiedOn = DateTime.Today, IsDeleted = false },
            };
            users.ForEach(u => u.UserRights.Add(context.UserRights.Where(ur => ur.Name == "Administrative").FirstOrDefault()));
            users.ForEach(u => context.Users.Add(u));
            context.SaveChanges();
            

        }
    }    


DAO

constant
    public enum SearchOperatorOption
    {
        And,
        Or
    };
    public enum SearchDateTimeOption
    {
        Inclusive,
        Exclusive
    };



UserService
static public class UserService
    {
        private static MyContext dataContext = new MyContext();

        static public IQueryable<User> SearchUser(SearchOperatorOption searchOperatorOption = SearchOperatorOption.And,
                                                  SearchDateTimeOption searchDateTimeOption = SearchDateTimeOption.Inclusive,
                                                  bool includedChild = false,
                                                  int? id = null,
                                                  string name = null,
                                                  string login = null,
                                                  bool? isDisabled = null,
                                                  string email = null,
                                                  int? failedLoginAttempts = null,
                                                  DateTime? createdFrom = null,
                                                  DateTime? createdTo = null,
                                                  int? createdBy = null,
                                                  DateTime? modifiedFrom = null,
                                                  DateTime? modifiedTo = null,
                                                  int? modifiedBy = null,
                                                  bool? isDeleted = null)
        {            
            var predicate = PredicateBuilder.New<User>();

            switch (searchOperatorOption)
            {
                #region SearchOperatorOption.And
                case SearchOperatorOption.And:
                    {
                        // Id
                        if (id != null)
                        {
                            predicate = predicate.And(u => u.Id == id);
                        }

                        // Name
                        if (!string.IsNullOrWhiteSpace(name))
                        {
                            predicate = predicate.And(u => u.Name.Contains(name));
                        }

                        // Login
                        if (!string.IsNullOrWhiteSpace(login))
                        {
                            predicate = predicate.And(u => u.Login.Contains(login));
                        }

                        // IsDisabled
                        if (isDisabled != null)
                        {
                            predicate = predicate.And(u => u.IsDisabled == isDisabled);
                        }

                        // Email
                        if (!string.IsNullOrWhiteSpace(email))
                        {
                            predicate = predicate.And(u => u.Email.Contains(email));
                        }

                        // FailedLoginAttempts
                        if (failedLoginAttempts != null)
                        {
                            predicate = predicate.And(u => u.FailedLoginAttempts >= failedLoginAttempts);
                        }

                        // CreatedOn
                        if (createdFrom != null)
                        {
                            switch (searchDateTimeOption)
                            {
                                case SearchDateTimeOption.Inclusive:
                                    {
                                        predicate = predicate.And(u => u.CreatedOn >= createdFrom);
                                        break;
                                    }
                                case SearchDateTimeOption.Exclusive:
                                    {
                                        predicate = predicate.And(u => u.CreatedOn > createdFrom);
                                        break;
                                    }
                            }
                        }

                        // CreatedOn
                        if (createdTo != null)
                        {
                            switch (searchDateTimeOption)
                            {
                                case SearchDateTimeOption.Inclusive:
                                    {
                                        predicate = predicate.And(u => u.CreatedOn <= createdTo);
                                        break;
                                    }
                                case SearchDateTimeOption.Exclusive:
                                    {
                                        predicate = predicate.And(u => u.CreatedOn < createdTo);
                                        break;
                                    }
                            }
                        }

                        // CreatedBy
                        if (createdBy != null)
                        {
                            predicate = predicate.And(u => u.CreatedBy == createdBy);
                        }

                        // ModifiedOn
                        if (modifiedFrom != null)
                        {
                            switch (searchDateTimeOption)
                            {
                                case SearchDateTimeOption.Inclusive:
                                    {
                                        predicate = predicate.And(u => u.ModifiedOn >= modifiedFrom);
                                        break;
                                    }
                                case SearchDateTimeOption.Exclusive:
                                    {
                                        predicate = predicate.And(u => u.ModifiedOn > modifiedFrom);
                                        break;
                                    }
                            }
                        }

                        // ModifiedOn
                        if (modifiedTo != null)
                        {
                            switch (searchDateTimeOption)
                            {
                                case SearchDateTimeOption.Inclusive:
                                    {
                                        predicate = predicate.And(u => u.ModifiedOn <= modifiedTo);
                                        break;
                                    }
                                case SearchDateTimeOption.Exclusive:
                                    {
                                        predicate = predicate.And(u => u.ModifiedOn < modifiedFrom);
                                        break;
                                    }
                            }
                        }

                        // ModifiedBy
                        if (modifiedBy != null)
                        {
                            predicate = predicate.And(u => u.ModifiedBy == modifiedBy);
                        }

                        // IsDeleted
                        if (isDeleted != null)
                        {
                            predicate = predicate.And(u => u.IsDeleted == isDeleted);
                        }
                        
                        break;
                    }
                #endregion
                #region SearchOperatorOption.Or
                case SearchOperatorOption.Or:
                    {
                        // Id
                        if (id != null)
                        {
                            predicate = predicate.Or(u => u.Id == id);
                        }

                        // Name
                        if (!string.IsNullOrWhiteSpace(name))
                        {
                            predicate = predicate.Or(u => u.Name.Contains(name));
                        }

                        // Login
                        if (!string.IsNullOrWhiteSpace(login))
                        {
                            predicate = predicate.Or(u => u.Login.Contains(login));
                        }

                        // IsDisabled
                        if (isDisabled != null)
                        {
                            predicate = predicate.Or(u => u.IsDisabled == isDisabled);
                        }

                        // Email
                        if (!string.IsNullOrWhiteSpace(email))
                        {
                            predicate = predicate.Or(u => u.Email.Contains(email));
                        }

                        // FailedLoginAttempts
                        if (failedLoginAttempts != null)
                        {
                            predicate = predicate.Or(u => u.FailedLoginAttempts >= failedLoginAttempts);
                        }

                        // CreatedOn
                        if (createdFrom != null)
                        {
                            switch (searchDateTimeOption)
                            {
                                case SearchDateTimeOption.Inclusive:
                                    {
                                        predicate = predicate.Or(u => u.CreatedOn >= createdFrom);
                                        break;
                                    }
                                case SearchDateTimeOption.Exclusive:
                                    {
                                        predicate = predicate.Or(u => u.CreatedOn > createdFrom);
                                        break;
                                    }
                            }
                        }

                        // CreatedOn
                        if (createdTo != null)
                        {
                            switch (searchDateTimeOption)
                            {
                                case SearchDateTimeOption.Inclusive:
                                    {
                                        predicate = predicate.Or(u => u.CreatedOn <= createdTo);
                                        break;
                                    }
                                case SearchDateTimeOption.Exclusive:
                                    {
                                        predicate = predicate.Or(u => u.CreatedOn < createdTo);
                                        break;
                                    }
                            }
                        }

                        // CreatedBy
                        if (createdBy != null)
                        {
                            predicate = predicate.Or(u => u.CreatedBy == createdBy);
                        }

                        // ModifiedOn
                        if (modifiedFrom != null)
                        {
                            switch (searchDateTimeOption)
                            {
                                case SearchDateTimeOption.Inclusive:
                                    {
                                        predicate = predicate.Or(u => u.ModifiedOn >= modifiedFrom);
                                        break;
                                    }
                                case SearchDateTimeOption.Exclusive:
                                    {
                                        predicate = predicate.Or(u => u.ModifiedOn > modifiedFrom);
                                        break;
                                    }
                            }
                        }

                        // ModifiedOn
                        if (modifiedTo != null)
                        {
                            switch (searchDateTimeOption)
                            {
                                case SearchDateTimeOption.Inclusive:
                                    {
                                        predicate = predicate.Or(u => u.ModifiedOn <= modifiedTo);
                                        break;
                                    }
                                case SearchDateTimeOption.Exclusive:
                                    {
                                        predicate = predicate.Or(u => u.ModifiedOn < modifiedFrom);
                                        break;
                                    }
                            }
                        }

                        // ModifiedBy
                        if (modifiedBy != null)
                        {
                            predicate = predicate.Or(u => u.ModifiedBy == modifiedBy);
                        }

                        // IsDeleted
                        if (isDeleted != null)
                        {
                            predicate = predicate.Or(u => u.IsDeleted == isDeleted);
                        }

                        break;
                    }
                    #endregion
            }

            if (includedChild)
            {
                return dataContext.Users.AsExpandable().Where(predicate).Include(u => u.Creator).Include(u => u.Modifier);
            }
            else
            {
                return dataContext.Users.AsExpandable().Where(predicate);
            }
        }

        #region Basic Method
        static public IEnumerable<User> GetAllUser(bool includedChild = false)
        {
            return SearchUser(includedChild: includedChild, isDeleted: false).ToList();
        }        

        static public User GetUserById(int id, bool includedChild = false)
        {
            return SearchUser(includedChild: includedChild, id: id).FirstOrDefault();
        }

        static public IEnumerable<User> GetUserByName(string name, bool includedChild = false)
        {
            return SearchUser(includedChild: includedChild, name: name);
        }

        static public IEnumerable<User> GetUsersByName(bool includedChild = false, params string[] name)
        {
            throw new NotImplementedException();            
        }
        static public User GetUserByLogin(string login, bool includedChild = false)
        {
            return SearchUser(includedChild: includedChild, login: login).FirstOrDefault();
        }

        static public IEnumerable<User> GetAllDisabledUser(bool includedChild = false)
        {
            return SearchUser(includedChild: includedChild, isDisabled: true).ToList();
        }

        static public IEnumerable<User> GetUserByEmail(string email, bool includedChild = false)
        {
            return SearchUser(includedChild: includedChild, email: email);
        }

        static public IEnumerable<User> GetUserByCreationDate(DateTime? from, DateTime? to, bool includedChild = false)
        {
            return SearchUser(includedChild: includedChild, createdFrom: from, createdTo: to);
        }

        static public IEnumerable<User> GetUserByCreator(int creatorId, bool includedChild = false)
        {
            return SearchUser(includedChild: includedChild, createdBy: creatorId);
        }

        static public IEnumerable<User> GetUserByCreator(User creator, bool includedChild = false)
        {
            return GetUserByCreator(includedChild: includedChild, creatorId: creator.Id);
        }

        static public IEnumerable<User> GetUserByModificationDate(DateTime? from, DateTime? to, bool includedChild = false)
        {
            return SearchUser(includedChild: includedChild, modifiedFrom: from, modifiedTo: to);
        }

        static public IEnumerable<User> GetUserByModifier(int modifierId, bool includedChild = false)
        {
            return SearchUser(includedChild: includedChild, modifiedBy: modifierId);
        }

        static public IEnumerable<User> GetUserByModifier(User modifier, bool includedChild = false)
        {
            return GetUserByModifier(includedChild: includedChild, modifierId: modifier.Id);
        }

        static public IEnumerable<User> GetAllDeletedUser(bool includedChild = false)
        {
            return SearchUser(includedChild: includedChild, isDeleted: true).ToList();
        }
        #endregion

        #region Extend Method
        #endregion
    }


How to use PredicateBuilder to build dynamic query

Environment
- .Net Framework 4.6.1
- EF 6.1.3
- Ms Visual Studio 2015

using LinqKit;
using System.Data.Entity;
using System.Linq;

Usage
Multiple search criteria (like search filter)



static public IQueryable<Contact> SearchContact(SearchOperatorOption searchOperatorOption = SearchOperatorOption.And,
            SearchDateTimeOption searchDateTimeOption = SearchDateTimeOption.Inclusive,
            bool includedChild = false,
            int? id = null,
            string name = null,
            string telephone = null,
            string fax = null,
            string contactPerson = null,
            string email = null,
            int? categoryId = null,
            int? statusId = null,
            DateTime? createdFrom = null,
            DateTime? createdTo = null,
            int? createdBy = null,
            DateTime? modifiedFrom = null,
            DateTime? modifiedTo = null,
            int? modifiedBy = null,
            bool? isDeleted = null)
        {            
            var predicate = PredicateBuilder.New<Contact>();

            switch (searchOperatorOption)
            {
                #region SearchOperatorOption.And
                case SearchOperatorOption.And:
                    {
                        // Id
                        if (id != null)
                        {
                            predicate = predicate.And(c => c.Id == id);
                        }

                        // Name
                        if (!string.IsNullOrWhiteSpace(name))
                        {
                            predicate = predicate.And(c => c.Name.Contains(name));
                        }                       

                        // Telephone
                        if (!string.IsNullOrWhiteSpace(telephone))
                        {
                            predicate = predicate.And(c => c.Telephone.Contains(telephone));
                        }

                        // Fax
                        if (!string.IsNullOrWhiteSpace(fax))
                        {
                            predicate = predicate.And(c => c.Fax.Contains(fax));
                        }

                        // ContactPerson
                        if (!string.IsNullOrWhiteSpace(contactPerson))
                        {
                            predicate = predicate.And(c => c.ContactPerson.Contains(contactPerson));
                        }

                        // Email
                        if (!string.IsNullOrWhiteSpace(email))
                        {
                            predicate = predicate.And(c => c.Email.Contains(email));
                        }

                        // CategoryId
                        if (categoryId != null)
                        {
                            predicate = predicate.And(c => c.CategoryId == categoryId);
                        }

                        // StatusId
                        if (statusId != null)
                        {
                            predicate = predicate.And(c => c.StatusId == statusId);
                        }

                        // CreatedOn
                        if (createdFrom != null)
                        {
                            switch (searchDateTimeOption)
                            {
                                case SearchDateTimeOption.Inclusive:
                                    {
                                        predicate = predicate.And(c => c.CreatedOn >= createdFrom);
                                        break;
                                    }
                                case SearchDateTimeOption.Exclusive:
                                    {
                                        predicate = predicate.And(c => c.CreatedOn > createdFrom);
                                        break;
                                    }
                            }
                        }

                        // CreatedOn
                        if (createdTo != null)
                        {
                            switch (searchDateTimeOption)
                            {
                                case SearchDateTimeOption.Inclusive:
                                    {
                                        predicate = predicate.And(c => c.CreatedOn <= createdTo);
                                        break;
                                    }
                                case SearchDateTimeOption.Exclusive:
                                    {
                                        predicate = predicate.And(c => c.CreatedOn < createdTo);
                                        break;
                                    }
                            }
                        }

                        // CreatedBy
                        if (createdBy != null)
                        {
                            predicate = predicate.And(c => c.CreatedBy == createdBy);
                        }

                        // ModifiedOn
                        if (modifiedFrom != null)
                        {
                            switch (searchDateTimeOption)
                            {
                                case SearchDateTimeOption.Inclusive:
                                    {
                                        predicate = predicate.And(c => c.ModifiedOn >= modifiedFrom);
                                        break;
                                    }
                                case SearchDateTimeOption.Exclusive:
                                    {
                                        predicate = predicate.And(c => c.ModifiedOn > modifiedFrom);
                                        break;
                                    }
                            }
                        }

                        // ModifiedOn
                        if (modifiedTo != null)
                        {
                            switch (searchDateTimeOption)
                            {
                                case SearchDateTimeOption.Inclusive:
                                    {
                                        predicate = predicate.And(c => c.ModifiedOn <= modifiedTo);
                                        break;
                                    }
                                case SearchDateTimeOption.Exclusive:
                                    {
                                        predicate = predicate.And(c => c.ModifiedOn < modifiedFrom);
                                        break;
                                    }
                            }
                        }

                        // ModifiedBy
                        if (modifiedBy != null)
                        {
                            predicate = predicate.And(c => c.ModifiedBy == modifiedBy);
                        }

                        // IsDeleted
                        if (isDeleted != null)
                        {
                            predicate = predicate.And(c => c.IsDeleted == isDeleted);
                        }
                        
                        break;
                    }
                #endregion
                #region SearchOperatorOption.Or
                case SearchOperatorOption.Or:
                    {
                        // Id
                        if (id != null)
                        {
                            predicate = predicate.Or(c => c.Id == id);
                        }

                        // Name
                        if (!string.IsNullOrWhiteSpace(name))
                        {
                            predicate = predicate.Or(c => c.Name.Contains(name));
                        }                     

                        // Telephone
                        if (!string.IsNullOrWhiteSpace(telephone))
                        {
                            predicate = predicate.Or(c => c.Telephone.Contains(telephone));
                        }

                        // Fax
                        if (!string.IsNullOrWhiteSpace(fax))
                        {
                            predicate = predicate.Or(c => c.Fax.Contains(fax));
                        }

                        // ContactPerson
                        if (!string.IsNullOrWhiteSpace(contactPerson))
                        {
                            predicate = predicate.Or(c => c.ContactPerson.Contains(contactPerson));
                        }

                        // Email
                        if (!string.IsNullOrWhiteSpace(email))
                        {
                            predicate = predicate.Or(c => c.Email.Contains(email));
                        }

                        // CategoryId
                        if (categoryId != null)
                        {
                            predicate = predicate.Or(c => c.CategoryId == categoryId);
                        }

                        // StatusId
                        if (statusId != null)
                        {
                            predicate = predicate.Or(c => c.StatusId == statusId);
                        }

                        // CreatedOn
                        if (createdFrom != null)
                        {
                            switch (searchDateTimeOption)
                            {
                                case SearchDateTimeOption.Inclusive:
                                    {
                                        predicate = predicate.Or(c => c.CreatedOn >= createdFrom);
                                        break;
                                    }
                                case SearchDateTimeOption.Exclusive:
                                    {
                                        predicate = predicate.Or(c => c.CreatedOn > createdFrom);
                                        break;
                                    }
                            }
                        }

                        // CreatedOn
                        if (createdTo != null)
                        {
                            switch (searchDateTimeOption)
                            {
                                case SearchDateTimeOption.Inclusive:
                                    {
                                        predicate = predicate.Or(c => c.CreatedOn <= createdTo);
                                        break;
                                    }
                                case SearchDateTimeOption.Exclusive:
                                    {
                                        predicate = predicate.Or(c => c.CreatedOn < createdTo);
                                        break;
                                    }
                            }
                        }

                        // CreatedBy
                        if (createdBy != null)
                        {
                            predicate = predicate.Or(c => c.CreatedBy == createdBy);
                        }

                        // ModifiedOn
                        if (modifiedFrom != null)
                        {
                            switch (searchDateTimeOption)
                            {
                                case SearchDateTimeOption.Inclusive:
                                    {
                                        predicate = predicate.Or(c => c.ModifiedOn >= modifiedFrom);
                                        break;
                                    }
                                case SearchDateTimeOption.Exclusive:
                                    {
                                        predicate = predicate.Or(c => c.ModifiedOn > modifiedFrom);
                                        break;
                                    }
                            }
                        }

                        // ModifiedOn
                        if (modifiedTo != null)
                        {
                            switch (searchDateTimeOption)
                            {
                                case SearchDateTimeOption.Inclusive:
                                    {
                                        predicate = predicate.Or(c => c.ModifiedOn <= modifiedTo);
                                        break;
                                    }
                                case SearchDateTimeOption.Exclusive:
                                    {
                                        predicate = predicate.Or(c => c.ModifiedOn < modifiedFrom);
                                        break;
                                    }
                            }
                        }

                        // ModifiedBy
                        if (modifiedBy != null)
                        {
                            predicate = predicate.Or(c => c.ModifiedBy == modifiedBy);
                        }

                        // IsDeleted
                        if (isDeleted != null)
                        {
                            predicate = predicate.Or(c => c.IsDeleted == isDeleted);
                        }

                        break;
                    }
                    #endregion
            }

            if (includedChild)
            {
                return dataContext.Contacts.AsExpandable().Where(predicate).Include(c => c.Creator)
                                                                           .Include(c => c.Modifier)
                                                                           .Include(c => c.Status)
                                                                           .Include(c => c.Category);
            }
            else
            {
                return dataContext.Contacts.AsExpandable().Where(predicate);
            }
        }




Reference : http://www.albahari.com/nutshell/predicatebuilder.aspx

2017年11月22日 星期三

How to push value into structured array in Angularjs v1.x

How to push value into structured array in Angularjs v1.x 

Background
- angularjs v1.x
          
  // define $scope variables for store result
  $scope.roles = [];

        var getSomething = function () {            
            return $http({
                method: 'GET',
                url: 'http://www.somewhere.com/GetSomething'
            }).then(function successCallback(response) {
    // Assume return value is something like "ValueA, ValueB, ValueC, ValueD"
                angular.forEach(response.data, function(value, key){
     
     //target structure like this
     //  roles [ 
     //   {
     //   value : "ValueA",
     //   attr1 : false,
     //   attr2 : "attr2 value"
     //   },
     //   {
     //   value : "ValueB",
     //   attr1 : false,
     //   attr2 : "attr2 value"
     //   },
     //   {
     //   value : "ValueC",
     //   attr1 : false,
     //   attr2 : "attr2 value"
     //   },
     //   {
     //   value : "ValueD",
     //   attr1 : false,
     //   attr2 : "attr2 value"
     //   }     
     //       ]    
                    $scope.roles.push( {value:value, attr1:false, attr2:"attr2 value"} )
                });                
            }, function errorCallback(response) {                
            });
        };