Sunday, 10 December 2017

Code of Web API ASP.Net

public class Employee
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string Surname { get; set; }
        public string Email { get; set; }

        public int AddressID { get; set; }
        public virtual Address Address { get; set; }

        public int CompanyID { get; set; }
        public virtual Company Company { get; set; }
    }

public class Company
    {
        public int ID { get; set; }
        public string Name { get; set; }

        public virtual List<Employee> Employees { get; set; }

        public Company()
        {
            Employees = new List<Employee>();
        }
    }

public class EntitiesContext : DbContext
    {
        public EntitiesContext()
            : base("EntitiesContext")
        {
            // Do not forget to set the connection string in Web.config..
            Configuration.ProxyCreationEnabled = false;
        }

        public DbSet<Employee> Employees { get; set; }
        public DbSet<Company> Companies { get; set; }
        public DbSet<Address> Addresses { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new EmployeeConfiguration());
            modelBuilder.Configurations.Add(new CompanyConfiguration());
        }
    }

public class EntitiesInitializer : DropCreateDatabaseIfModelChanges<EntitiesContext>
    {
        protected override void Seed(EntitiesContext context)
        {
            // Companies
            GetCompanies().ForEach(c => context.Companies.Add(c));

            // Addresses
            GetAddresses().ForEach(a => context.Addresses.Add(a));

            // Employees
            GetEmployees().ForEach(e => context.Employees.Add(e));

            base.Seed(context);
        }

        private static List<Company> GetCompanies()
        {
            List<Company> _companies = new List<Company>();

            for (int i = 1; i <= 10; i++)
            {
                _companies.Add(new Company()
                    {
                        ID = i,
                        Name = MockData.Company.Name()
                    });
            }

            return _companies;
        }

        private static List<Address> GetAddresses()
        {
            List<Address> _addresses = new List<Address>();

            for (int i = 1; i <= 200; i++)
            {
                _addresses.Add(new Address()
                {
                    ID = i,
                    City = MockData.Address.City(),
                    Country = MockData.Address.Country(),
                    State = MockData.Address.State(),
                    ZipCode = MockData.Address.ZipCode()
                });
            }

            return _addresses;
        }

        private static List<Employee> GetEmployees()
        {
            List<Employee> _employees = new List<Employee>();

            for (int i = 1; i <= 200; i++)
            {
                _employees.Add(new Employee()
                {
                    ID = i,
                    FirstName = MockData.Person.FirstName(),
                    Surname = MockData.Person.Surname(),
                    AddressID = i,
                    CompanyID = new Random().Next(1, 10),
                    Email = MockData.Internet.Email(),
                });
            }

            return _employees;
        }
    }

public class EmployeesController : ApiController
    {
        private EntitiesContext _dbContext;

        public EmployeesController()
        {
            this._dbContext = new EntitiesContext();
        }

        public IEnumerable<Employee> GetEmployees()
        {
            try
            {
                return _dbContext.Employees.ToArray();
            }
            catch(Exception ex)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            _dbContext.Dispose();
        }
    }

public class EmployeesController : EntitySetController<Employee, int>
    {
        private EntitiesContext _dbContext;

        public EmployeesController()
        {
            this._dbContext = new EntitiesContext();
        }

        [Queryable]
        public override IQueryable<Employee> Get()
        {
            return _dbContext.Employees;
        }

        protected override Employee GetEntityByKey(int key)
        {
            return _dbContext.Employees.Where(e => e.ID == key).FirstOrDefault();
        }

        // /odata/Employees(1)/Address
        public Address GetAddressFromEmployee(int key)
        {
            return _dbContext.Employees.Where(e => e.ID == key)
                .Select(e => e.Address).FirstOrDefault();
        }

        protected override Employee CreateEntity(Employee entity)
        {
            _dbContext.Employees.Add(entity);
            _dbContext.SaveChanges();
            return entity;
        }

        protected override Employee UpdateEntity(int key, Employee update)
        {
            if (!_dbContext.Employees.Any(e => e.ID == key))
            {
                throw new HttpResponseException(
                    Request.CreateODataErrorResponse(
                    HttpStatusCode.NotFound,
                    new ODataError
                    {
                        ErrorCode = "NotFound.",
                        Message = "Employee " + key + " not found."
                    }));
            }

            update.ID = key;

            _dbContext.Employees.Attach(update);
            _dbContext.Entry(update).State = System.Data.Entity.EntityState.Modified;
            _dbContext.SaveChanges();
            return update;
        }

        protected override Employee PatchEntity(int key, Delta<Employee> patch)
        {
            var employee = _dbContext.Employees.FirstOrDefault(e => e.ID == key);
            if (employee == null)
                throw new HttpResponseException(
                    Request.CreateODataErrorResponse(
                    HttpStatusCode.NotFound,
                    new ODataError
                    {
                        ErrorCode = "NotFound.",
                        Message = "Employee " + key + " not found."
                    }));

            patch.Patch(employee);
            _dbContext.SaveChanges();

            return employee;
        }

        public override void Delete(int key)
        {
            var employee = _dbContext.Employees.Where(a => a.ID == key).FirstOrDefault();
            if (employee != null)
            {
                _dbContext.Employees.Remove(employee);
                _dbContext.SaveChanges();
            }
            else
                throw new HttpResponseException(
                    Request.CreateODataErrorResponse(
                    HttpStatusCode.NotFound,
                    new ODataError
                    {
                        ErrorCode = "NotFound.",
                        Message = "Employee " + key + " not found."
                    }));
        }

        // The base POST method will call to form the location header
        protected override int GetKey(Employee entity)
        {
            return entity.ID;
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            _dbContext.Dispose();
        }
    }

Secure a Web API with Individual Accounts and Local Login in ASP.NET Web API 2.2

https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/individual-accounts-in-web-api

Web API in ASP.Net


ASP.Net Web API


Web API


UI Layer


Sunday, 3 December 2017

Creating an Image Processing Library with C#

http://studentguru.gr/b/jupiter/archive/2009/10/14/creating-an-image-processing-library-with-c-part-1

Saturday, 2 December 2017

Algorithms in C#

http://www.c-sharpcorner.com/technologies/algorithms-in-csharp

Deadlock in C# Threading

using System;
using System.Threading;
namespace deadlockincsharp
{
public class Akshay
    {
        static readonly object firstLock = new object();
        static readonly object secondLock = new object();
        static void ThreadJob()
        {
            Console.WriteLine("\t\t\t\tLocking firstLock");
            lock (firstLock)
            {
                Console.WriteLine("\t\t\t\tLocked firstLock");
                // Wait until we're fairly sure the first thread
                // has grabbed secondLock
                Thread.Sleep(1000);
                Console.WriteLine("\t\t\t\tLocking secondLock");
                lock (secondLock)
                {
                    Console.WriteLine("\t\t\t\tLocked secondLock");
                }
                Console.WriteLine("\t\t\t\tReleased secondLock");
            }
            Console.WriteLine("\t\t\t\tReleased firstLock");
        }
        static void Main()
        {
            new Thread(new ThreadStart(ThreadJob)).Start();
            // Wait until we're fairly sure the other thread
            // has grabbed firstLock
            Thread.Sleep(500);
            Console.WriteLine("Locking secondLock");
            lock (secondLock)
            {
                Console.WriteLine("Locked secondLock");
                Console.WriteLine("Locking firstLock");
                lock (firstLock)
                {
                    Console.WriteLine("Locked firstLock");
                }
                Console.WriteLine("Released firstLock");
            }
            Console.WriteLine("Released secondLock");
            Console.Read();
        }     
    }
}

object lockA = new object();
object lockB = new object();
        Thread 1 void t1()
        {
            lock (lockA)
            {
                lock (lockB)
                {
                    /* ... */
                }
            }
        }
        Thread 2 void t2()
        {
            lock (lockB)
            {
                lock (lockA)
                   {
                    /* ... */
                   }
            }
        }

Deadlock Sample in C#

public class DeadlockSamples
{
    private static object staticObjLockA = new Object();
    private static object staticObjLockB = new Object();

    public static void Main()
    {
        // Initialize thread with address of DoWork1
        Thread thread1 = new Thread(DoWork1);

        // Initilaize thread with address of DoWork2
        Thread thread2 = new Thread(DoWork2);

        // Start the Threads.
        thread1.Start();
        thread2.Start();

        thread1.Join();
        thread2.Join();

        // This statement will never be executed.
        Console.WriteLine("Done Processing...");
    }

    private static void DoWork1()
    {
        lock (staticObjLockA)
        {
            Console.WriteLine("Trying to acquire lock on staticObjLockB");

            // Sleep to yield.
            Thread.Sleep(1000);
            lock (staticObjLockB)
            {
                // This block will never be executed.
                Console.WriteLine("In DoWork1 Critical Section.");
                // Access some shared resource here.
            }
        }
    }

    private static void DoWork2()
    {
        lock (staticObjLockB)
        {
            Console.WriteLine("Trying to acquire lock on staticObjLockA");
            lock (staticObjLockA)
            {
                // This block will never be executed.
                Console.WriteLine("In DoWork2 Critical Section.");
                // Access some shared resource here.
            }
        }
    }
}

public class DeadlockSamplesMonitor
{
    private static object staticObjLockA = new Object();
    private static object staticObjLockB = new Object();

    public static void Main()
    {
        // Initialize thread with address of DoWork1
        Thread thread1 = new Thread(DoWork1);

        // Initilaize thread with address of DoWork2
        Thread thread2 = new Thread(DoWork2);

        // Start the Threads.
        thread1.Start();
        thread2.Start();

        thread1.Join();
        thread2.Join();
       
        Console.WriteLine("Done Processing...");
    }

    private static void DoWork1()
    {
        lock (staticObjLockA)
        {
            Console.WriteLine("Trying to acquire lock on staticObjLockB");

            // Sleep to yield.
            Thread.Sleep(1000);

            // This will try to acquire lock for 5 seconds.
            if (Monitor.TryEnter(staticObjLockB, 5000))
            {
                try
                {
                    // This block will never be executed.
                    Console.WriteLine("In DoWork1 Critical Section.");
                    // Access some shared resource here.
                }
                finally
                {
                    Monitor.Exit(staticObjLockB);
                }
            }
            else
            {
                // Print lock not able to acquire message.
                Console.WriteLine("Unable to acquire lock, exiting DoWork1.");
            }               
        }
    }

    private static void DoWork2()
    {
        lock (staticObjLockB)
        {
            Console.WriteLine("Trying to acquire lock on staticObjLockA");
            lock (staticObjLockA)
            {                   
                Console.WriteLine("In DoWork2 Critical Section.");
                // Access some shared resource here.
            }
        }
    }
}

WPF Programs

http://www.c-sharpcorner.com/technologies/wpf

WPF in C#

http://www.wpf-tutorial.com/about-wpf/what-is-wpf/