Saturday 26 September 2015

Iterate the Array Model and render the values in application using Angular JS

In this post we are going to see how to iterate the array model and render the values in application using angular js.

Basic Steps to do is,
1.Add the angular js Library
2. Bootstrap the app
3. Initialize the Array Model

Generally Array is a collection of values, so if you want to get the values then we have to iterate, Here we are going to see two types of array 1. string array, 2. object array

For any array if you want to iterate then pass that to the ng-repeat, like ng-repeat="item in items", Here items is a collection and item is a single item of each iteration.

Now we see a sample.

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script type="application/javascript" src="Scripts/angular.js"></script>
    <style>
        .liStyle
        {
            list-style: none;
            border-radius: 5px;border: 1px solid cornflowerblue;
            padding: 5px;margin:5px;width:250px;
            align-content: center;
            text-align: center";
        }
    </style>
</head>
<body ng-app ng-init="
        Topics = ['Services','Factory','Provider','Config','Run','Scope','Controller'];
        Styles={BackColor:'#269abc',ForeColor:'#ffffff'};
        Languages=[{ID:1,Value:'C#'},{ID:2,Value:'Java'},{ID:3,Value:'C++'}]">
  
   <div>
     
     <strong style="color:darkblue;margin-left: 100px">Angular JS Topics</strong>
      <br/>
      <br/>
    
       <ul>
          
            <li class="liStyle" style="color:{{Styles.ForeColor}};
                    background-color: {{Styles.BackColor}};"
              ng-repeat="mod in Topics">{{mod}}</li>

          
          <li class="liStyle">Languages</li>
          <li class="liStyle"
                  ng-repeat="lang in Languages">
              <div>
                  <span>{{lang.ID}}</span> place goes to the <span>{{lang.Value}}</span>
              </div>
          </li>


      </ul>

  </div>
</body>

</html>


Output:
*************
1. String Array.


2. Object Array.



From this post you can learn how to iterate the Array like model and render the values in application using angular js .

Initialize a model before application gets rendered in angular js

In this post we are going to see how to Initialize a model before application get rendered in angular js. First let we start from the first step how to design a application.

Steps :
1. Download and include the angular js library reference to the application.
2. Bootstrap the application using ng-app directive
3. Initialize the model using ng-init, which will initialize before the application gets rendered. 

In the below code sample you can see angular js library is added in head section, application is bootstrap using ng-app in body section, finally models like Application and Modules are initialize using the mg-init directive.

Application is a single model, Modules is a Array model. When render a single variable we have to use the vairable itself inside a curly braces {{ Application }}, for an array we have to use the ng-repeat directive to iterate the each and every elements. 

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script type="application/javascript" src="Scripts/angular.js"></script>
</head>

<body ng-app ng-init="
        Application = 'Angular js Basic Sample';
        Modules = ['Services','Factory','Provider','Config','Run','Scope','Controller']">
  <div>
      
     <strong style="color:darkblue;margin-left: 100px">{{Application}}</strong>

      <br/>
      <br/>

      <div style="text-align: center;width: 350px">Modules Covered</div>
      <ul>
          <li style="color:darkorange;list-style: none;
                    border-radius: 5px;border: 1px solid cornflowerblue;
                    padding: 5px;margin:5px;width:250px;
                    align-content: center;text-align: center"
              ng-repeat="mod in Modules">{{mod}}</li>
      </ul>

  </div>
</body>


</html>

you can see the output for the above code

Output:
***********


From this post you can learn how to Initialize a model before application gets rendered in angular js

Sunday 20 September 2015

Validate a Email Address when assign it from a string in C#

In this post we are going to see how to create a class which can validate a email address when it is assign from a string.


    public class EmailAddress
    {
        Regex regex = new Regex(@"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.                                          [0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
       
        public bool IsValid { set; get; }
        public string Address { set; get; }

        public EmailAddress(string value)
        {
            Address = value;
            ValidateEmail();
        }

        public static implicit operator EmailAddress(string value)
        {
            return new EmailAddress(value);
        }

        private void ValidateEmail()
        {
            Match match = regex.Match(Address);
            IsValid = match.Success;
        }

        public override string ToString()
        {
            return Address;
        }

    }

         

Program.cs
**************

            EmailAddress address = "rajeshgmail.com";
            if (address.IsValid)
                Console.WriteLine(address + " is a valid Email");
            else
                Console.WriteLine(address + " is not a valid Email");


            EmailAddress emailAdd = "rajhseg@gmail.com";
            if (emailAdd.IsValid)
                Console.WriteLine(emailAdd + " is a valid Email");
            else
                Console.WriteLine(emailAdd + " is not valid Email");
         


Output:

rajeshgmail.com is not a valid Email
rajhseg@gmail.com is a valid Email





From this post you can understand that how to create a class which can validate an email address.

Create a custom Paragraph class and Iterate the elements from paragraph based on settings like Letter,Word,Line, EachParagraph

In this post we are going to see create a custom paragraph class and Iterate the elements from the objects based on the settings like Word, Letter, Line, Each Paragraph.

i.e While passing the Object we will get the iteration as  Letter, Word, Line, EachParagraph based on the settings. 
For example, We are going to do the sample like below which will give the output in foreach as Based on the settings for that object.


Paragraph para = "This a good book ,   Every one wants to read it.\n\nThis book deals with                     technology.   ";


Iteration Sample 1:

            Console.WriteLine("\n****************************");
            para.IterationType = ParaIterationType.EachParagraph;
            
            foreach (var item in para)
            {
                Console.WriteLine(item);

            }


Output:
****************************
This a good book ,   Every one wants to read it.
This book deals with technology.



Iteration Sample 2: 

            Console.WriteLine("\n****************************");
            para.IterationType = ParaIterationType.Line;

            foreach (var item in para)
            {
                Console.WriteLine(item);
            }


Output:
****************************
This a good book ,   Every one wants to read it.

This book deals with technology.



Iteration Sample 3: 

            Console.WriteLine("\n****************************");
            para.IterationType = ParaIterationType.Word;

            foreach (var item in para)
            {
                Console.WriteLine(item);
            }


Output:
****************************
This
a
good
book
,


Every
one
wants
to
read
it.

This
book
deals
with
technology.


Iteration Sample 4: 
            
            Console.WriteLine("\n****************************");
            para.IterationType = ParaIterationType.Letter;

            foreach (var item in para)
            {
                Console.WriteLine(item);
            }


Output:
****************************
T
h
i
etc ... Remaining letters are print in screen based on the settings.


From the above sample you can see that an string is assigned to a class variable, then we are assign a iteration settings based on that settings , when we pass variable in foreach it will give the result like Lettter, Word, Line, EachParagraph.

Let we see now how we can do like this class and make the iteration differ based on the settings.
In this sample we have to create following file and class.

1. Paragraph
2. ParagraphIterationContainer
3. AbstractIterator
4. LetterIterator
5. LineIterator
6. WordIterater
7. ParagraphIterator

Enum

1. IterationSettings
2. ParagraphComparison
3. ParaIterationType


Paragraph.cs


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


namespace StringExtensions
{      
    public sealed class Paragraph
      : IComparable, IComparable<Paragraph>, IEnumerable<string>,
IEnumerable, IEquatable<Paragraph>, ICloneable,IConvertible
    {

        private string value;

        public ParaIterationType IterationType
        {
            set;
            get;
        }

        public IterationSettings IterationSettings
        {
            set;
            get;
        }

        public string Content { get { return value; } }
               
        public Paragraph(string value):this(value,ParaIterationType.Word){  }

public Paragraph(string value,ParaIterationType iterationType)    
             :this(value,iterationType,IterationSettings.None){  }

        public Paragraph(string value,ParaIterationType iterationType,IterationSettings
iterationSettings)
        {
            this.value = value;
            this.IterationType = iterationType;
            this.IterationSettings = iterationSettings;
        }

        public int CompareTo(object para2)
        {
            if (para2 == null)
                return 1;
           
            if (!(para2 is Paragraph))
            {
                throw new ArgumentException("Input is not a Paragraph type");
            }

            return Paragraph.Compare(this, (Paragraph)value,
ParagraphComparison.CurrentCulture);
        }

        public int CompareTo(Paragraph para2)
        {
            if (para2 == null)
                return 1;
            return Paragraph.Compare(this, para2, ParagraphComparison.CurrentCulture);
        }

public static int Compare(Paragraph paragraph1, Paragraph paragraph2,
ParagraphComparison comparisonType)
        {
            if (comparisonType > ParagraphComparison.OrdinalIgnoreCase)
            {
                throw new ArgumentException("Not supported comparison type");
            }

            if (paragraph1 == paragraph2)
                return 0;
            if (paragraph1 == null)
                return -1;
            if (paragraph2 == null)
                return 1;
            switch (comparisonType)
            {            
                case ParagraphComparison.CurrentCulture:
                    return CultureInfo.CurrentCulture.CompareInfo.Compare( 
paragraph1.value, paragraph2.value, CompareOptions.None);
                case ParagraphComparison.CurrentCultureIgnoreCase:
                    return CultureInfo.CurrentCulture.CompareInfo.Compare(
paragraph1.value, paragraph2.value, CompareOptions.IgnoreCase);
                case ParagraphComparison.InvariantCulture:
                    return CultureInfo.InvariantCulture.CompareInfo.Compare(
paragraph1.value, paragraph2.value, CompareOptions.None);
                case ParagraphComparison.InvariantCultureIgnoreCase:
                    return CultureInfo.InvariantCulture.CompareInfo.Compare(
paragraph1.value, paragraph2.value, CompareOptions.IgnoreCase);               
                default:
                  throw new NotSupportedException("Not supported Paragraph comparison");
            }

        }
       
        public static implicit operator Paragraph(string value)
        {
            if (value == null)
                value = string.Empty;

            return new Paragraph(value);
        }
       
        public IEnumerator<string> GetEnumerator()
        {
            return ParagraphIterationContainer.GetIterator(this);
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public bool Equals(Paragraph other)
        {
            return other.Content == this.Content;
        }

        public object Clone()
        {
            return new Paragraph(this.Content,IterationType,IterationSettings);
        }
      
        public TypeCode GetTypeCode()
        {
            return TypeCode.String;
        }

        public bool ToBoolean(IFormatProvider provider)
        {
            return Convert.ToBoolean(this.Content, provider);
        }

        public byte ToByte(IFormatProvider provider)
        {
            return Convert.ToByte(this.Content, provider);
        }

        public char ToChar(IFormatProvider provider)
        {
            return Convert.ToChar(this.Content, provider);
        }

        public DateTime ToDateTime(IFormatProvider provider)
        {
            return Convert.ToDateTime(this.Content, provider);
        }

        public decimal ToDecimal(IFormatProvider provider)
        {
            return Convert.ToDecimal(this.Content, provider);
        }

        public double ToDouble(IFormatProvider provider)
        {
            return Convert.ToDouble(this.Content, provider);
        }

        public short ToInt16(IFormatProvider provider)
        {
            return Convert.ToInt16(this.Content, provider);
        }

        public int ToInt32(IFormatProvider provider)
        {
            return Convert.ToInt32(this.Content, provider);
        }

        public long ToInt64(IFormatProvider provider)
        {
            return Convert.ToInt64(this.Content, provider);
        }

        public sbyte ToSByte(IFormatProvider provider)
        {
            return Convert.ToSByte(this.Content, provider);
        }

        public float ToSingle(IFormatProvider provider)
        {
            return Convert.ToSingle(this.Content, provider);
        }

        public string ToString(IFormatProvider provider)
        {
            return this.Content;
        }

        public object ToType(Type conversionType, IFormatProvider provider)
        {
            return this.ToString(provider);
        }

        public ushort ToUInt16(IFormatProvider provider)
        {
            return Convert.ToUInt16(this.Content, provider);
        }

        public uint ToUInt32(IFormatProvider provider)
        {
            return Convert.ToUInt32(this.Content, provider);
        }

        public ulong ToUInt64(IFormatProvider provider)
        {
            return Convert.ToUInt64(this.Content, provider);
        }

        private class ParagraphIterationContainer
        {
            public static AbstractIterator GetIterator(Paragraph doc)
            {
                AbstractIterator Iterator = null;

                switch (doc.IterationType)
                {
                    case ParaIterationType.Word:
                        Iterator = new WordIterater(doc);
                        break;
                    case ParaIterationType.Letter:
                        Iterator = new LetterIterator(doc);
                        break;
                    case ParaIterationType.Line:
                        Iterator = new LineIterator(doc);
                        break;
                    case ParaIterationType.EachParagraph:
                        Iterator = new ParagraphIterator(doc);
                        break;
                    default:
                        break;
                }
                return Iterator;
            }
        }

    }
   
}



2. AbstractIterator

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

namespace StringExtensions
{
    public abstract class AbstractIterator:IEnumerator<string>
    {
        protected int currentPos = -1;
        protected int startPos = -1;
        protected int endPos = -1;

        protected ParaIterationType _iterationType;
        protected Paragraph _doc;
        protected int _docLength;

        protected AbstractIterator(ParaIterationType iterationtype,Paragraph value)
        {
            this._iterationType = iterationtype;
            this._doc = value;
            this._docLength = this._doc.Content.Length;
        }

        public string Current
        {
            get
            {
                startPos = endPos;
                return GetCurrentItem();
            }
        }

        public void Dispose()
        {
            _doc = null;
            _docLength = -1;
        }

        object IEnumerator.Current
        {
            get
            {
                startPos = endPos;
                return GetCurrentItem();
            }
        }

        public bool MoveNext()
        {
            if (currentPos < _docLength-1)
                return true;
            else
                return false;
        }

        public void Reset()
        {
            currentPos = startPos = endPos = -1;
        }

       public abstract string GetCurrentItem();

    }
}



3. LetterIterator

   public class LetterIterator:AbstractIterator
    {
        public LetterIterator(Paragraph doc):base(ParaIterationType.Letter,doc)
        {

        }

        public override string GetCurrentItem()
        {                      
            currentPos = startPos + 1;
            endPos = startPos + 1;
            return _doc.Content[startPos + 1].ToString();           
        }
    }


4. WordIterater


public class WordIterater:AbstractIterator
    {
        public WordIterater(Paragraph doc):base(ParaIterationType.Word,doc)
        {

        }

        public override string GetCurrentItem()
        {           
            return FindNextWord(startPos + 1);
        }

        private string FindNextWord(int index)
        {
            string _word = string.Empty;
            for (int i = index; i < _docLength; i++)
            {
                currentPos = i;
                if (_doc.Content[i] == ' ')
                {
                    endPos = i;
                    break;
                }
                _word = _word + _doc.Content[i];
            }

            //if (index < _docLength)
            //{
            //    if (this._doc.IterationSettings ==
IterationSettings.IgnoreSpace && _word.Trim() == string.Empty)
            //        return Current;
            //}

            return _word;
        }


    }



5. LineIterator

    public class LineIterator:AbstractIterator
    {
        public LineIterator(Paragraph doc):base(ParaIterationType.Line,doc)
        {

        }

        public override string GetCurrentItem()
        {
            return FindNextLine(startPos+1);           
        }

        private string FindNextLine(int index)
        {
            string _word = string.Empty;
            for (int i = index; i < _docLength; i++)
            {
                currentPos = i;
                if (_doc.Content[i] == '\n')
                {
                    endPos = i;
                    break;
                }
                _word = _word + _doc.Content[i];
            }
            return _word;
        }

    }


6. ParagraphIterator

public class ParagraphIterator:AbstractIterator
    {
        public ParagraphIterator(Paragraph doc):base(ParaIterationType.EachParagraph,doc)
        {

        }

        public override string GetCurrentItem()
        {
            string _word = string.Empty;
            bool firstNewline = false;
            bool newParagraphIndication = false;

            for (int i = startPos+1; i < _docLength; i++)
            {
                currentPos = i;
                if (_doc.Content[i] == '\n')
                {

                    if (!firstNewline)
                    {
                        firstNewline = true;
                        continue;
                    }
                    else
                        newParagraphIndication = true;

                    if (newParagraphIndication)
                    {
                        endPos = i;
                        break;
                    }
                }
                _word = _word + _doc.Content[i];
            }
            return _word;
        }

    }





public enum IterationSettings
    {
        None,
        IgnoreSpace,
        IgnoreNewLine,
        IgnoreTabSpace,
        IgnoreCarriageReturn,
        IgnoreAllSpaces = IgnoreSpace | IgnoreTabSpace,
        IgonreAll = IgnoreCarriageReturn | IgnoreNewLine | IgnoreAllSpaces
    }


    public enum ParagraphComparison
    {
        CurrentCulture,
        CurrentCultureIgnoreCase,
        InvariantCulture,
        InvariantCultureIgnoreCase,
        Ordinal,
        OrdinalIgnoreCase
    }

   public enum ParaIterationType
    {
        Word,
        Letter,
        Line,
        EachParagraph
    }


Now let we see how to see the Paragraph class.


Program.cs


    class Program
    {
        static void Main(string[] args)
        {
            Paragraph para = "This a good book ,   Every one wants to read it.\n\nThis book 
                              deals with technology.   ";

            para.IterationType = ParaIterationType.EachParagraph;

            Console.WriteLine("\n****************************");
            foreach (var item in para)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("\n****************************");
            para.IterationType = ParaIterationType.Line;
            foreach (var item in para)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("\n****************************");
            para.IterationType = ParaIterationType.Word;
            foreach (var item in para)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("\n****************************");
            para.IterationType = ParaIterationType.Letter;
            foreach (var item in para)
            {
                Console.WriteLine(item);
            }



            Console.Read();

        }
    }


Output:










  


From this post you can understand that how to create a class like paragraph and change the iteration based on the settings.