Friday, December 26, 2014

Abstract-Classes

using System;

public abstract class Animal
{
    public abstract string GetName();
    abstract public int Speed { get; }
}



using System;

public class Cheetah : Animal
{
    public override int Speed
    {
        get
        {
            return 100;
        }
    }

    public override string GetName()
    {
        return "cheetah";
    }
}


using System;

public class Turtle : Animal
{
    public override int Speed
    {
        get
        {
            return 1;
        }
    }

    public override string GetName()
    {
        return "turtle";
    }
}


using System;

class AbstractClasses
{
    static void Main()
    {
        Turtle turtle = new Turtle();
        Console.WriteLine("The {0} can go {1} km/h ",
            turtle.GetName(), turtle.Speed);
        Cheetah cheetah = new Cheetah();
        Console.WriteLine("The {0} can go {1} km/h ",
            cheetah.GetName(), cheetah.Speed);

        System.Collections.Generic.List<int> l;
        System.DateTime dt;
    }
}


OUTPUT

The turtle can go 1 km/h

The cheetah can go 100 km/h

Polymorphism

using System;

abstract class Figure
{
    public abstract double CalcSurface();
}


using System;

class Circle : Figure
{
    public double Radius { get; set; }
   
    public override double CalcSurface()
    {
        return Math.PI * this.Radius * this.Radius;
    }
}

using System;

class Rectangle : Figure
{
    public double Width { get; set; }
    public double Height { get; set; }
   
    public override double CalcSurface()
    {
        return this.Width * this.Height;
    }
}

using System;

class Square : Figure
{
    public double Size { get; set; }
   
    public override double CalcSurface()
    {
        return this.Size * this.Size;
    }
}


using System;

class Polymorphism
{
    static void Main()
    {
        Figure[] figures = new Figure[] {
            new Square() { Size = 3 },
            new Circle() { Radius = 2 },
            new Rectangle() { Width = 2, Height = 3 },
            new Circle() { Radius = 3.5 },
            new Square() { Size = 2.5 },
            new Square() { Size = 4 },
        };

        foreach (Figure figure in figures)
        {
            Console.WriteLine("Figure = {0} surface = {1:F2}",
                figure.GetType().Name.PadRight(9,' '),
                figure.CalcSurface());
            Console.ReadLine();
        }
    }
}

OUTPUT

Figure = Square    surface = 9.00

Figure = Circle    surface = 12.57

Figure = Rectangle surface = 6.00

Figure = Circle    surface = 38.48

Class-Diagrams

using System;

struct Point
{
    public int X { get; set; }
    public int Y { get; set; }

    public Point(int x, int y) : this()
    {
        this.X = x;
        this.Y = y;
    }
}

using System;

abstract class Shape
{
    protected Point Position { get; set; }

    public Shape(Point position)
    {
        this.Position = position;
    }
}


using System;

struct Color
{
    public byte RedValue { get; set; }
    public byte GreenValue { get; set; }
    public byte BlueValue { get; set; }

    public Color(byte redValue, byte greenValue, byte blueValue)
        : this()
    {
        this.RedValue = redValue;
        this.GreenValue = greenValue;
        this.BlueValue = blueValue;
    }
}




using System;

interface ISufraceCalculatable
{
    float CalculateSurface();
}




using System;

class Square : Shape, ISufraceCalculatable
{
    private float Size { get; set; }

    public Square(float size, int x, int y)
        : base (new Point(x,y))
    {
        this.Size = size;
    }

    public float CalculateSurface()
    {
        return this.Size * this.Size;
    }
}



using System;

class Rectangle : Shape, ISufraceCalculatable
{
    private float Width { get; set; }
    private float Height { get; set; }

    public Rectangle(float width, float height, int x, int y)
        : base (new Point(x,y))
    {
        this.Width = width;
        this.Height = height;
    }

    public float CalculateSurface()
    {
        return this.Width * this.Height;
    }
}


using System;

class FilledSquare : Square
{
    private Color Color { get; set; }

    public FilledSquare(float size, int x, int y, Color color)
        : base(size, x, y)
    {
        this.Color = color;
    }
}





Inheritance And Accessibility

using System;

public class Creature
{
    protected string Name { get; private set; }

    public Creature(string name)
    {
        this.Name = name;
    }

    private void Talk()
    {
        Console.WriteLine("I am creature ...");
    }

    protected void Walk()
    {
        Console.WriteLine("Walking, walking, walking ....");
    }
}


using System;

public class Mammal : Creature
{
    public int Age { get; set; }

    public Mammal(string name, int age) : base(name)
    {
        this.Age = age;
    }

    public void Sleep()
    {
        Console.WriteLine("Shhh! {0} is sleeping!", this.Name);
    }
}



using System;

public class Dog : Mammal
{
    public string Breed { get; private set; }

    public Dog(string name, int age, string breed) : base(name, age)
    {
        this.Breed = breed;
    }

    public void WagTail()
    {
        Console.WriteLine("{0} is {1} wagging his {2}-aged tail ...",
            this.Name, this.Breed, this.Age);
        //this.Walk(); // This will successfully compile - Walk() is protected
        //this.Talk(); // This will not compile - Talk() is private
        //this.Name = "Doggy"; // This will not compile - Name.set is private
    }
}


using System;

class InheritanceAndAccessibility
{
    static void Main()
    {
        Dog joe = new Dog("Sharo", 6, "labrador");
        joe.Sleep();
        Console.WriteLine("Breed: " + joe.Breed);
        Console.ReadLine();
        joe.WagTail();

     }
}

OUTPUT

Shhh! Sharo is sleeping!
Breed: labrador

Simple-Inheritance

using System;

public class Mammal
{
    public int Age { get; set; }

    public Mammal(int age)
    {
        this.Age = age;
    }
   
    public void Sleep()
    {
        Console.WriteLine("Shhh! I'm sleeping!");
    }
}


using System;

public class Dog : Mammal
{
    public string Breed { get; set; }

    public Dog(int age, string breed) : base(age)
    {
        this.Breed = breed;
    }

    public void WagTail()
    {
        Console.WriteLine("Tail wagging...");
    }
}

using System;

class SimpleInheritance
{
    static void Main()
    {
        Dog joe = new Dog(8, "Labrador");
        joe.Sleep();
        joe.WagTail();
        Console.WriteLine("Joe is {0} years old dog of breed {1}.",
            joe.Age, joe.Breed);
        Console.ReadLine();
    }
}



OUTPUT

Shhh! I'm sleeping!
Tail wagging...
Joe is 8 years old dog of breed Labrador.


Sunday, November 30, 2014

Sunday, November 16, 2014

Method to automatic print

  public static void Print()
        {
            const string printerName =
               "Microsoft Office Document Image Writer";
            if (m_streams == null || m_streams.Count == 0)
                return;
            PrintDocument printDoc = new PrintDocument();
            printDoc.PrinterSettings.PrinterName = printerName;
            if (!printDoc.PrinterSettings.IsValid)
            {
                string msg = String.Format(
                   "Can't find printer \"{0}\".", printerName);
                return;
            }
            printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
            printDoc.Print();
        }
        private static void PrintPage(object sender, PrintPageEventArgs ev)
        {
            Metafile PageImage = new Metafile(m_streams[m_currentPageIndex]);
            ev.Graphics.DrawImage(PageImage, ev.PageBounds);
            Debug.Print(m_currentPageIndex.ToString());
            m_currentPageIndex++;
            ev.HasMorePages = (m_currentPageIndex < m_streams.Count);
        }

Method to get the Sum of specified column in the datatable

  /// <summary>
        /// Returns the Sum of specified column in the datatable
        /// </summary>
        /// <param name="columnName"></param>
        /// <param name="dtSource"></param>
        /// <returns>Decimal. The source column should be in decimal format</returns>
        public static decimal GetColumnTotal(string columnName, DataTable dtSource)
        {
            decimal total = 0;
            try
            { total = dtSource.AsEnumerable().Sum(o => Convert.ToDecimal(o.Field<object>(columnName))); }
            catch
            { }
            return total;
        }

Method to get Quantity Value

  public static string GetQty(object value)
        {
            string qty = string.Empty;
            decimal amount;
            if (value != null && Decimal.TryParse(value.ToString(), out amount))
            {
                qty = amount.ToString("N");
            }
            return qty;
        }

Method to format Currency

 public static string GetCurrency(object value)
        {
            string currency = string.Empty;
            decimal amount;
            if (value != null && Decimal.TryParse(value.ToString(), out amount))
            {
                currency = amount.ToString("c");
            }
            return currency;
        }

For getting string as Html encoded

 /// <summary>
        /// For getting string as Html encoded
        /// </summary>
        /// <param name="orginalString"></param>
        /// <param name="limit"></param>
        /// <returns>string</returns>
        public static string GetEncodedString(object evelOrginalString)
        {
            string orginalString = HttpUtility.HtmlEncode(Convert.ToString(evelOrginalString));
            return orginalString;
        }

For getting string as Html decoded

 /// <summary>
        /// For getting string as Html decoded
        /// </summary>
        /// <param name="orginalString"></param>
        /// <param name="limit"></param>
        /// <returns>string</returns>
        public static string GetDecodedString(object evelOrginalString)
        {
            string orginalString = HttpUtility.HtmlDecode(Convert.ToString(evelOrginalString));
            return orginalString;
        }

Nullable Int

  public static int? NullableInt(string str)
        {
            int i;
            if (int.TryParse(str, out i))
                return i;
            return null;
        }

Method to get List of T elements

  public static List<T> GetResults<T>(T element, ObjectContext ctx, string cmd)
        {
            // List of T elements to be returned.
            List<T> results = null;

            // Execute the query
            if (cmd == "")
            {
                results = null;
            }
            else
            {
                results = ctx.ExecuteStoreQuery<T>(cmd, null).ToList();
            }

            // Return the results
            return results;
        }

Process multiline message

 /// <summary>
        /// Process multiline message
        /// </summary>
        /// <param name="heading"></param>
        /// <param name="messages"></param>
        /// <returns></returns>
        public static string ProcessMessageList(string heading, List<string> messages)
        {
            StringBuilder messageText;
            messageText = new StringBuilder();
            messageText.Append(heading);
            messageText.Append(messages.Count > 0 ? ERPUtilityResources.MsgStart : string.Empty);
            foreach (string message in messages)
            {
                messageText.Append(string.Format(ERPUtilityResources.MsgFormat, message));
            }
            messageText.Append(messages.Count > 0 ? ERPUtilityResources.MsgEnd : string.Empty);
            return messageText.ToString();
        }

Generate Dynamic Script

 /// <summary>
        /// Add Date Time/Time script dynamically
        /// </summary>
        /// <param name="controlType"></param>
        /// <param name="controlID"></param>
        /// <returns></returns>
        public static string GenerateDynamicScript(string controlType, string controlID, string hdfToRange, string fromDate, string hdfFrmDate)
        {
            string script = string.Empty;
            switch ((ControlTypes)(Enum.Parse(typeof(ControlTypes), controlType)))
            {
                case ControlTypes.TimePicker:
                    script = "$('input:text[id$=" + controlID + "]').timepicker();";
                    break;
                case ControlTypes.DateTime:
                    script = "ERPScriptUtils.DatePickerCommon('" + controlID + "');";
                    script = script + "$('input:text[id$=" + controlID + "_Time]').timepicker();";
                    break;
                case ControlTypes.Date:
                    script = "ERPScriptUtils.DatePickerCommon('" + controlID + "');";
                    break;
                case ControlTypes.DateRange:
                    script = "ERPScriptUtils.AddDateRangeCommon('" + fromDate + "', '" + hdfFrmDate + "', '" + controlID + "', '" + hdfToRange + "', false, false);";
                    break;
                case ControlTypes.MonthPicker:
                    script = "ControlID= '" + controlID + "';";
                    break;
            }

            return script;
        }

HTML Decode field of object

  /// <summary>
        /// HTML Decode field of object
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="item"></param>
        /// <param name="field"></param>
        public static void HtmlDecode<T>(T item, string field)
        {
            Type type;
            PropertyInfo fieldPropertyInfo;
            type = item.GetType();
            fieldPropertyInfo = type.GetProperty(field);
            if (fieldPropertyInfo.PropertyType == typeof(string))
                fieldPropertyInfo.SetValue(item, HttpUtility.HtmlDecode(Convert.ToString(fieldPropertyInfo.GetValue(item, null))), null);
        }

HTML Decode field in List

 /// <summary>
        /// HTML Decode field in List
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="lst"></param>
        /// <param name="field"></param>
        /// <returns></returns>
        public static List<T> HtmlDecode<T>(List<T> lst, string field)
        {
            lst.ForEach(itm => HtmlDecode(itm, field));
            return lst;
        }

Method to Get formated list of objects for auto complete

/// <summary>
        /// Get formated list of objects for auto complete
        /// </summary>
        /// <param name="dynamicList">List for formatting</param>
        /// <param name="textProperty1">First Text property name</param>
        /// <param name="textProperty2">Second Text property name</param>
        /// <param name="valueProperty">Value property name</param>
        /// <param name="isCombined">whether the two Text Properties are concantinated</param>
        /// <returns></returns>
        public static dynamic GetFormatedAutoCompleteList(dynamic dynamicList, string textProperty1, string textProperty2, string valueProperty, bool isCombined)
        {
            // Gets or sets list of objects for auto complete
            List<TextValue> textValueList;
            // Gets the type of dynamic object in the list
            Type type;
            // Gets or sets text property information from dynamic object
            PropertyInfo textPropertyInfo1;
            // Gets or sets text property information from dynamic object
            PropertyInfo textPropertyInfo2;
            // Gets or sets value property information from dynamic object
            PropertyInfo valuePropertyInfo;
            try
            {
                // initilize new instance of TextValue class
                textValueList = new List<TextValue>();
                // Iterate through each object in the dynamic list
                foreach (dynamic dynamicObject in dynamicList)
                {
                    // Sets type of dynamic object
                    type = dynamicObject.GetType();
                    // Sets text property information
                    textPropertyInfo1 = type.GetProperty(textProperty1);
                    // Sets text property information
                    textPropertyInfo2 = type.GetProperty(textProperty2);
                    // Sets value property information
                    valuePropertyInfo = type.GetProperty(valueProperty);
                    // Add object to text value list
                    textValueList.Add(new TextValue()
                    {
                        // Sets text propert after html decoding
                        Text = HttpUtility.HtmlDecode(string.Format(ERPUtilityResources.NameCodeFormat, Convert.ToString(textPropertyInfo1.GetValue(dynamicObject, null)),
                        Convert.ToString(textPropertyInfo2.GetValue(dynamicObject, null)))),
                        // Sets value property
                        Value = HttpUtility.HtmlDecode(Convert.ToString(valuePropertyInfo.GetValue(dynamicObject, null))),
                    });
                }
                // Returns formated list for auto complete
                return textValueList;
            }
            catch (Exception ex)
            {
                // throws exception to calling function
                throw ex;
            }
            finally
            {
                // Disposing used objects
                textValueList = null;
                type = null;
                textPropertyInfo1 = null;
                textPropertyInfo2 = null;
                valuePropertyInfo = null;
            }
        }

Method to Get formated list of objects for auto complete

  /// <summary>
        /// Get formated list of objects for auto complete
        /// </summary>
        /// <param name="dynamicList">List for formatting</param>
        /// <param name="textProperty1">Text property name</param>
        /// <param name="pairedProperty">Paired Text property name</param>
        /// <param name="valueProperty">Value property name</param>
        /// <returns></returns>
        public static dynamic GetFormatedAutoCompleteList(dynamic dynamicList, string textProperty, string pairedProperty, string valueProperty)
        {
            // Gets or sets list of objects for auto complete
            List<PairedValue> pairedValueList;
            // Gets the type of dynamic object in the list
            Type type;
            // Gets or sets text property information from dynamic object
            PropertyInfo textPropertyInfo;
            // Gets or sets value property information from dynamic object
            PropertyInfo valuePropertyInfo;
            // Gets or sets PairText property information from dynamic object
            PropertyInfo pairedPropertyInfo;
            try
            {
                // initilize new instance of TextValue class
                pairedValueList = new List<PairedValue>();
                // Iterate through each object in the dynamic list
                foreach (dynamic dynamicObject in dynamicList)
                {
                    // Sets type of dynamic object
                    type = dynamicObject.GetType();
                    // Sets text property information
                    textPropertyInfo = type.GetProperty(textProperty);
                    // Sets value property information
                    valuePropertyInfo = type.GetProperty(valueProperty);
                    // Add object to text value list
                    pairedPropertyInfo = type.GetProperty(pairedProperty);
                    pairedValueList.Add(new PairedValue()
                    {
                        // Sets text propert after html decoding
                        Text = HttpUtility.HtmlDecode(Convert.ToString(textPropertyInfo.GetValue(dynamicObject, null))),
                        // Sets value property
                        Value = HttpUtility.HtmlDecode(Convert.ToString(valuePropertyInfo.GetValue(dynamicObject, null))),
                        // Sets PairText property
                        PairText = HttpUtility.HtmlDecode(Convert.ToString(pairedPropertyInfo.GetValue(dynamicObject, null))),
                    });
                }
                // Returns formated list for auto complete
                return pairedValueList;
            }
            catch (Exception ex)
            {
                // throws exception to calling function
                throw ex;
            }
            finally
            {
                // Disposing used objects
                pairedValueList = null;
                type = null;
                textPropertyInfo = null;
                valuePropertyInfo = null;
                pairedPropertyInfo = null;
            }
        }

Using Authorization with Swagger in ASP.NET Core

 Create Solution like below LoginModel.cs using System.ComponentModel.DataAnnotations; namespace UsingAuthorizationWithSwagger.Models {     ...