Wednesday, November 30, 2016

Tips and Tricks for Dev(.net).


Every Developer need few tools which should be handy at any given point of time. This would increase the productivity and would allow us to concentrate on the specif piece of work. Deviations are less when tools are handy.


Let's say that we want too test a wcf service. If the Service is already live and running.

1. Adding the WCF Test Client to Visual Studio .
path : C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE





In addition one can add this to Visual Studio Tools menu.
Tools => External Tools
Click on add and show the path: 

Then click on apply and ok.
Finally you can see the option under the Tools.





Tuesday, October 25, 2016

Filter Data for Generic Requriements.


Filter the Data.

In a day to day life the dev come across so many new and changing requirements ,where in we the requirements are tend to change. But how many times does the dev changes the code.

After the dev writes the code if he/she looks the code the dev might get different ideas to change the code. But again it should fit the new requirements.

Lets come up with a requirements first.

Requirements.
1. Filter the List<int> to get odd numbers.
2. Filter the List<int> to get Even numbers.

if we can sit and brain strom this requirements. We can come up with code which would be feasible for future requirements too. Lets get a try now.

Lets define a Generic Class with T and a method which would take the parameters as List<T> and delegate which would filter and return the List of T items.

public static class FilterData<T>
    {
        public static  IEnumerable<T> Filter(IEnumerable<T> input,Func<T,bool> Predicate)
        {
            foreach (var item in input)
            {
                if (Predicate(item))
                {
                    yield return item;
                }
            }
        }
    }


Lets see the final Main program how does it does look like.

namespace ConsoleApplicationForCSharp
{
    class Program
    {
     
        static void Main(string[] args)
        {
            var myintList = new List<int> {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
         
            Func<int, bool> IsOdd = i => i % 2 != 0;
            Func<int, bool> IsEven = i => i % 2 == 0;

           
            var results = FilterData<int>.Filter(myintList, IsOdd);
            var results2 = FilterData<int>.Filter(myintList, IsEven);
        }
    }

    public static class FilterData<T>
    {
        public static  IEnumerable<T> Filter(IEnumerable<T> input,Func<T,bool> Predicate)
        {
            foreach (var item in input)
            {
                if (Predicate(item))
                {
                    yield return item;
                }
            }
        }
    }

 
}


The calling guy know i would be passing the list of int or string and the filter criteria as a predicate and it would filter the predicate and return the Filtered data with the help of yield.






Wednesday, June 1, 2016

Design Patterns.



Provider Patterns.

1. Provider pattern.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProviderPattern
{
    interface IExternalAuth_Provider
    {
        Groups AddGroup();
        Users AddUser();

    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProviderPattern.ExternalAuthDev
{
    public class ExternalAuthDev_Provider : IExternalAuth_Provider
    {
        public Groups AddGroup()
        {
            Groups obj = new Groups { Id =1,Name = "gr1 coming from database ...." };

            Console.WriteLine("Id " + obj.Id + " Name" + obj.Name);
            return obj;
        }

        public Users AddUser()
        {
            return new Users { Id = 1, Name = "user1 coming from database ...." };
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProviderPattern.ExternalAuthDev
{
    public class ExternalAuth_Production: IExternalAuth_Provider
    {
        public Groups AddGroup()
        {
            return new Groups { Id = 1, Name = "gr1 coming from Ad Groups...." };
        }

        public Users AddUser()
        {
            return new Users { Id = 1, Name = "user1 coming from Ad Groups...." };
        }
    }
}



using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProviderPattern
{
    public class AzureAdFactory
    {
        private static IExternalAuth_Provider DataProvider = null;


        protected AzureAdFactory()
        {

        }

       

        public static T InitProvider<T>()
        {
            string ProviderName;

            if (DataProvider == null)
            {
                // Get provider type to create
                ProviderName = "ProviderPattern.ExternalAuthDev." + ConfigurationManager.AppSettings["ProviderName"];
              //  ProviderName =   ConfigClass.ProviderName
                // Create new DataProvider
                DataProvider = (IExternalAuth_Provider)Activator.CreateInstance(Type.GetType(ProviderName));

                
            }
            return (T)DataProvider;
        }
    }
}

<appSettings>
    <!--<add key="ProviderFactory" value="AzureAdFactory"/>-->
    <add key="ProviderName" value="ExternalAuthDev_Provider"/>
  </appSettings>

  <connectionStrings>
        <add name="ExternalAuthDev_Provider"  connectionString="ProviderPattern.ExternalAuthDev.ExternalAuthDev_Provider"/>
    
  </connectionStrings>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProviderPattern
{
    class Program
    {
        static void Main(string[] args)
        {
           
            var obj  = AzureAdFactory.InitProvider<IExternalAuth_Provider>();
            Console.WriteLine(obj.AddGroup()); 
        }
    }
}



Friday, May 13, 2016

Web Api For Creating,Updating,Deleting the Active Directory groups and Users


At this point of time when i am writing the article i only know that i have create,update,delete users in the active directory.
But i know that requirements would change and i would end up writing and modifying many things and i am prepared for it.

So lets start my creating a new Web Api project and Add entity Framework for this.
I would be using the code first approach. But once my requirements are freeze i may switch to the Db first. Its up to the our decision making.



As i am going with the code first approach and i would know that i need data models and mapping and DataAccess layers i have created the folders for it.
Actually i want to separte it out the layers but i am short of time so i am doing everything in this.

The code first apporach fundamentals are explained at this article. Go through once url:http://www.entityframeworktutorial.net/code-first/simple-code-first-example.aspx



Now i am going to add few models to it.

public class ProjectDetails
    {
        public int ProjectId { get; set; }

        public int Name { get; set; }

        public int AdGroupName { get; set; }

        public int ReferenceId { get; set; }

        public virtual ICollection<OrgGroupNames> OrgGroupNames { get; set; }



    }

 public class OrgGroupNames
    {
        public int Id { get; set; }

        public string GroupName { get; set; }

        public int RefrenceId { get; set; }

        public int ProjectId { get; set; }

        public virtual ICollection<OrgGroupNamesDetails> OrgGroupNamesDetails { get; set; }
    }


public class OrgGroupNamesDetails
    {
        public int Id { get; set; }
           

        public string AdUserId { get; set; }

        public string Role { get; set; }

        public int ProjectId { get; set; }

        public int RefrenceId { get; set; }

        public int OrgGroupNamesId { get; set; }

        public virtual OrgGroupNames OrgGroupNames { get; set; }
    }


Now i will add the Context class and there respective mapping classes, with which i will do the upstream and downstream of data.

First i will create the mapping files which are very important for us to configure the constraints on table and columns with fluent validations.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ActiveDirectoryPractice
{
    public class ProjectDetails
    {
        public int Id { get; set; }

        public int Name { get; set; }

        public string AdGroupName { get; set; }

        public int ReferenceId { get; set; }

        public virtual ICollection<OrgGroupNames> OrgGroupNames { get; set; }



    }
}

namespace ActiveDirectoryPractice
{
    public class OrgGroupNames
    {
        public int Id { get; set; }

        public string GroupName { get; set; }

        public int RefrenceId { get; set; }

        public int ProjectId { get; set; }

        public virtual ICollection<OrgGroupNamesDetails> OrgGroupNamesDetails { get; set; }
    }
}

namespace ActiveDirectoryPractice
{
    public class OrgGroupNamesDetails
    {
        public int Id { get; set; }
           

        public string AdUserId { get; set; }

        public string Role { get; set; }

        public int ProjectId { get; set; }

        public int RefrenceId { get; set; }

        public int OrgGroupNamesId { get; set; }

        public virtual OrgGroupNames OrgGroupNames { get; set; }
    }


}

The Context class will have all  the dataset pointers to the Tables  and their respective mappings about how each entity is configured in the above mapping classes.


 public class OrgStructureContext : DbContext
    {
        public OrgStructureContext() : base("MyConnectionString")
        {

        }

        public DbSet<ProjectDetails> Students { get; set; }
        public DbSet<OrgGroupNames> OrgGroupNames { get; set; }
        public DbSet<OrgGroupNamesDetails> OrgGroupNamesDetails { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //Mapping Classes
            modelBuilder.Configurations.Add(new ProjectDetailsMap());
            modelBuilder.Configurations.Add(new OrgGroupNamesMap());
            modelBuilder.Configurations.Add(new OrgGroupNamesDetailsMap());
        }
    }

I would need one more class for the DataBase initilizer to set few of the seed values.


Sunday, May 1, 2016

Web Api v2



ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building Restful applications on the .NET Framework.



Lets see how we can implement the web api security.





Saturday, April 23, 2016

Entity Framework Code First Approach



Entity Framework (EF) is an object-relational mapper that enables .NET developers to work with relational data using domain-specific objects. It eliminates the need for most of the data-access code that developers usually need to write.


EF has two different types of approaches.
1. Db First.
2. Code First.

Scenario details below.
I want to speak more about the Accounting packages,where in we deal with stock in and stock out details.

First create the data model project of type (Class library.)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataModels
{
    public class Customer
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public int MobileNo { get; set; }
        public int HomePhoneNo { get; set; }
        public string ResidentialAddress { get; set; }
        public string BusinessAddress { get; set; }
        public string ReferredByName { get; set; }
        public int ReferredById { get; set; }
        public int RefereedByMobileNo { get; set; }
        public DateTime CreationDate { get; set; }
        public DateTime ModifiedDate { get; set; }
        public string Description { get; set; }

    }

}

Create a Separte project for Data Access Layer.


Install the Nuget package for Entity Framework.











Then we have to create the mapping for this. Basically this is needed as we have to create the validations at db level. This is a kind of standard approach. Dev's can skip if they want. 

using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using System;
using System.Collections.Generic;

using System.Linq;
using System.Text;
using DataAccess;

namespace DataAccessLayer
{
    public class CustomerMap : EntityTypeConfiguration<DataModels.Customer>
    {
        /// <summary>
        /// Mapping class for Customer details...
        /// </summary>
        public CustomerMap()
        {
            // Primary Key
            this.HasKey(t => t.Id);
            this.Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            // Properties           
            this.Property(t => t.FirstName).HasColumnType("nvarchar").HasMaxLength(Constant.StringMaxLength).IsRequired();
            this.Property(t => t.MiddleName).HasColumnType("nvarchar").HasMaxLength(Constant.StringMaxLength).IsRequired();
            this.Property(t => t.LastName).HasColumnType("nvarchar").HasMaxLength(Constant.StringMaxLength).IsRequired();
            this.Property(t => t.Age).IsOptional();
            this.Property(t => t.MobileNo).IsRequired();
            this.Property(t => t.HomePhoneNo).IsOptional();
            this.Property(t => t.ResidentialAddress).HasColumnType("nvarchar").HasMaxLength(Constant.StringMaxLength).IsRequired();
            this.Property(t => t.ReferredByName).IsOptional();
            this.Property(t => t.ReferredById).IsRequired();
            this.Property(t => t.ModifiedDate).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed).IsRequired();
            this.Property(t => t.CreationDate).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed).IsRequired();
            this.Property(t => t.Description).HasMaxLength(Constant.StringMaxLength).IsOptional();
        }
    }

}




Your typical Data Access Layer Solution Structure should look like below screen shot.





The Accounts Context class would be inherited from the dbContext. It would be passing the connection string in the constructor. We have mention the dbSet of all the Models which are to be seen as tables after migrations.

Few important points in the Context Class are below.
1. Connection string,the way we pass it.
2. DbSets Or Models refferred.
3. Save changes method. We can override it.
4. OnModelCreating Method ,where in we refer the mapping classes (validation kept on the models).

Find the below Context class for your reference.


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using DataModels;
using DataAccessLayer;
using System.Configuration;

namespace DataAccess
{
    public class AccountsContext : DbContext
    {
     public static string connstr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
        public AccountsContext()
            : base(connstr)
        {
            this.Configuration.ProxyCreationEnabled = false;
        }

        public DbSet<DataModels.Customer> Projects { get; set; }
        public DbSet<DataModels.StockIn> Purchase { get; set; }






        public override int SaveChanges()
        {
            var changedEntries = this.ChangeTracker.Entries()
                                .Where(item => item.State == EntityState.Added 
                                        || item.State == EntityState.Deleted 
                                        || item.State == EntityState.Modified);

           // var auditLogs = this.ConstructAuditLogs(changedEntries);


            int rowsAffected = 0;
            try
            {
                // Save User Operations
                rowsAffected = base.SaveChanges();
               // this.AuditLogs.AddRange(auditLogs);
                var task = base.SaveChangesAsync();
                task.Wait();
            }
            catch (Exception exception)
            {
               
            }

            return rowsAffected;
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
           //for mapping the stored proc
            modelBuilder.Entity<DataModels.Customer>().MapToStoredProcedures();
            //for Mapping Classes that are set with fluent validations..
            modelBuilder.Configurations.Add(new CustomerMap());


        }

        private List<AuditLog> ConstructAuditLogs(IEnumerable<DbEntityEntry> dbEntityEntries)
        {
            var auditLogs = new List<AuditLog>();

            var jsonSerializerSettings = new Newtonsoft.Json.JsonSerializerSettings
            {
                PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects
            };

            // Get the Table() attribute, if one exists
            TableAttribute tableAttr = null;

            // Get table name (if it has a Table attribute, use that, otherwise get the pluralized name)
            string tableName = null;

            foreach (var dbEntry in dbEntityEntries)
            {
                // Get Table Attribute
                tableAttr = dbEntry.Entity.GetType().GetCustomAttributes(typeof(TableAttribute), false).SingleOrDefault() as TableAttribute;

                // Use Table Name from Table Attribute else use the type name
                tableName = tableAttr != null ? tableAttr.Name : dbEntry.Entity.GetType().Name;

                // AuditLog
                var auditLog = new AuditLog()
                {
                    TableName = tableName,
                    ActionType = dbEntry.State.ToString(),
                    CreatedBy = System.Threading.Thread.CurrentPrincipal.Identity.Name,
                    CreatedDateTime = DateTime.Now,
                    OriginalValues = (dbEntry.State != EntityState.Added) ? this.ConstructValues(dbEntry.OriginalValues, jsonSerializerSettings) : null,
                    NewValues = (dbEntry.State != EntityState.Deleted) ? this.ConstructValues(dbEntry.CurrentValues, jsonSerializerSettings) : null,
                    EntityLog = Newtonsoft.Json.JsonConvert.SerializeObject(dbEntry.Entity, Newtonsoft.Json.Formatting.Indented, jsonSerializerSettings)
                };

                auditLogs.Add(auditLog);
            }

            return auditLogs;
        }

        private string ConstructValues(DbPropertyValues dbPropertyValues, Newtonsoft.Json.JsonSerializerSettings jsonSettings)
        {
            var dictionary = new Dictionary<string, object>();

            foreach (var propertyName in dbPropertyValues.PropertyNames)
            {
                dictionary.Add(propertyName, dbPropertyValues[propertyName]);
            }

            var result = Newtonsoft.Json.JsonConvert.SerializeObject(dictionary, Newtonsoft.Json.Formatting.Indented, jsonSettings);

            return result;
        }
    }

}


Now we are ready with all the setting of entity framework ,go  ahead and run the migration comments.


The data access layer project should be having the app.config which would be having the connection string.

Then Run the entity framework commands for the code first.
Follow the below article for the reference.

http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/migrations-and-deployment-with-the-entity-framework-in-an-asp-net-mvc-application

Saturday, March 19, 2016

Windows Azure.

Any developer or the I.T professional can be more productive with azure. Things are more simple to do.  The integrated tools and the build in templates and managed services helps the developer to build and manage the enterprise based application manage with much simple steps.


The new concepts which are coming in my line are below from the developer point of view in Azure.
1. Creating a web site and deploying it on azure.
2. Creating a web job(windows service) and deploying it.
3. Service Bus (service bus in itself is a big concept and it is ocean).
4. Migrating a 3.5 framework application  to azure. (checklist which would evolve in future).
5. Creating a Service Bus.
6. Creating the Queue.
7. Creating the Topic



I will be updating the above content as my research move to the next level.
I will try to give more examples.





Enjoy .net :)