Monday, February 16, 2015

Enumerators in C# (IEnumerable And IEnumerator )

Enumerators are used to read data in the collection

IEnumerator

IEnumerator it allows us to iterate over list, array, etc and process each element one-by-one.

Basic Example:

namespace Enumerators
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> names = new List<string>() { "A", "B", "C","D","E" };
            foreach (string a in names)
            {
                Console.WriteLine(a);
            }
            Console.ReadKey();
        }
    }

}

Output:




Now, if we are using IEnumerator ,



It has  two abstract methods and a property 

void Reset() : Sets  to initial position.(which is before the first element in the collection (-1)
bool MoveNext() : It moves to Next Element.
object Current : current element.

Basic Example:

namespace Enumerators
{
    class Program
    {
        static void Main(string[] args)
        {
            string name = "Uday";
            IEnumerator enumerator = name.GetEnumerator();
            while (enumerator.MoveNext())
            {
                char curObject = (char)enumerator.Current;
                Console.Write(curObject + ".");
            }
            Console.Read();
        }
    }
}


Output:


Example 2:

namespace Enumerators
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> names = new List<string>() { "A", "B", "C","D","E" };
            IEnumerator<string> ab = names.GetEnumerator();
            ab.MoveNext();
            Console.WriteLine(ab.Current);
            ab.MoveNext();
            Console.WriteLine(ab.Current);
            ab.Reset();
            Console.ReadKey();
        }
    }
}

Output:








namespace Enumerators
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> names = new List<string>() { "A", "B", "C","D","E" };
            IEnumerator a = names.GetEnumerator();
            while (a.MoveNext()) 
            Console.WriteLine(a.Current); 
            Console.ReadKey();
        }
    }
}

output:



Note:

Here we are using,while rather than foreach because foreach cannot be used with IEnumerator

IEnumerator use While, MoveNext, current to get current record
IEnumerator cannot be used in foreach loop
IEnumerator allows readonly access to a collection

We will get error if, we are using foreach.




IEnumerable:

The IEnumerable interface is a generic interface for looping over elements.
It has foreach support.

The IEnumerable interface contains an abstract member function called GetEnumerator() and return an interface IEnumerator on any success call. 


Note: IEnumerator interface is meant to be used as accessors, it wil not be useful  to make any changes in the collection or elements of the collection.

Advantages:

IEnumerable code are clear and can be used in foreach loop
IEnumerable doesn’t remember state
IEnumerable defines one method GetEnumerator which returns an IEnumerator

Example:
namespace Enumerators
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> names = new List<string>() { "A", "B", "C","D","E" };
            IEnumerable a = (IEnumerable)names;
            foreach (string name in a)
            {
                Console.WriteLine(name);
            }
            Console.ReadKey();
        }
    }

}
Output:




Building Your Own C# Enumerator To Use With The foreach 


Example:


class Students
{
    private int Id;
    private string Name;
    private string City;
    private int Department;
    public Students(int id, string name, string city, int department)
    {
        this.Id = id;
        this.Name = name;
        this.City = city;
        this.Department = department;
    }
    public int ID
    {
        get
        {
            return this.Id;
        }
    }
    public override string ToString()
    {
        return "Id:" + this.Id.ToString() + "\nName:" + Name + "\nCity :" + City + "\nDepartment:" + Department.ToString();
    }
}

class StudentsDetails : IEnumerable, IEnumerator
{
    ArrayList StudentsArray = new ArrayList();
    private int Position = -1;
    public void AddEmployee(Students student)
    {
        StudentsArray.Add(student);
    }
// Implementation of IEnumerable
    public IEnumerator GetEnumerator()
    {
        return (IEnumerator)this;
    }
   
// Implementation of IEnumerator

public bool MoveNext()
    {
        if (Position < StudentsArray.Count - 1)
        {
            ++Position;
            return true;
        }
        return false;
    }
    public void Reset()
    {
        Position = -1;
    }
    public object Current
    {
        get
        {
            return StudentsArray[Position];
        }

    }

public static void Main()
    {
        StudentsDetails studentDetails = new StudentsDetails();
        Students student1 = new Students(1,"A","HYDERABAD",9);
        Students student2 = new Students(2,"B", "HITECHCITY", 9);
        studentDetails.AddEmployee(student1);
        studentDetails.AddEmployee(student2);
        Console.WriteLine("Using foreach");
        foreach (Students emp in studentDetails)
        {
            Console.WriteLine(emp);
        }
        Console.WriteLine("\n Here GetEnumerator returns IEnumerator");
        IEnumerator StudentEnumerator = studentDetails.GetEnumerator();
        StudentEnumerator.Reset();
        while (StudentEnumerator.MoveNext())
        {
            Console.WriteLine((Students)StudentEnumerator.Current);
        }
        Console.ReadKey();

    }







Output:





Example:

class Students
{
    public static void Main()
    {
        List<string> names = new List<string>();
        names.Add("A");
        names.Add("B");
        names.Add("C");
        names.Add("D");
        names.Add("E");
        names.Add("F");
        names.Add("G");
        Console.WriteLine("list to IEnumerable");
        IEnumerable<string> names_Enumerator = (IEnumerable<string>)names;
        foreach (string a in names_Enumerator)
            Console.WriteLine(a);
        Console.ReadKey();
    }
}



Output:





Example:

class Students
{
    public static void Main()
    {
        List<string> names = new List<string>();
        names.Add("A");
        names.Add("B");
        names.Add("C");
        names.Add("D");
        names.Add("E");
        names.Add("F");
        names.Add("G");
        Console.WriteLine("list to IEnumerator");
        IEnumerator<string> names_IEnumerator = names.GetEnumerator();
        while (names_IEnumerator.MoveNext())
            Console.WriteLine(names_IEnumerator.Current); 
        Console.ReadKey();
    }

}


Output:





IEnumerable does not  remember  state, which row or record it is iterating while IEnumerator remembers the state


Example with IEnumerator ( Remembers State)


class Students
{
    public void PrintMarksUptO35(IEnumerator<int> marksa)
    {
        while (marksa.MoveNext())
        {
            Console.WriteLine(marksa.Current);
            if (marksa.Current > 60)
            {
                PrintMarksGreater60(marksa);

            }
        }
    }

    public void PrintMarksGreater60(IEnumerator<int> marks)
    {
        while (marks.MoveNext())
        {
        Console.WriteLine(marks.Current);
        Console.WriteLine("Distinction");
        }
    }
    
    static void Main()
    {
        List<int> marks = new List<int>();
        marks.Add(20);
        marks.Add(30);
        marks.Add(40);
        marks.Add(50);
        marks.Add(60);
        marks.Add(70);
        marks.Add(80);
        marks.Add(90);
        IEnumerator<int> marksa = marks.GetEnumerator(); 
        Students obj = new Students();
        obj.PrintMarksUptO35(marksa);
        Console.ReadKey();
    }
}


Output:


IEnumerable doesn’t remember state

Example:

class Students
{
    public void PrintMarksUptO35(IEnumerable<int> marksa)
    {
        foreach (int a in marksa)
        {
            Console.WriteLine(a);
            if (a > 35)
            {
                Console.WriteLine("Passed");
                PrintMarksGreater35(marksa);
            }
        }
    }

    public void PrintMarksGreater35(IEnumerable<int> marks)
    {
        foreach (int a in marks)
            Console.WriteLine(a);
    }
    
    static void Main()
    {
        List<int> marks = new List<int>();
        marks.Add(20);
        marks.Add(30);
        marks.Add(40);
        marks.Add(50);
        marks.Add(60);
        marks.Add(70);
        marks.Add(80);
        marks.Add(90);
        IEnumerable<int> a = (IEnumerable<int>)marks;
        Students obj = new Students();
        obj.PrintMarksUptO35(a);
        Console.ReadKey();
    }
}


Output:




Friday, February 13, 2015

Globalization in ASP.NET

File ->New->WebSite




Add->Add New Item



Add New WebForm


And Click on Add Button


And Again New Item






Write the following Code



And Again New Item






write the following Code
.

Write the following Code in Default.aspx

  <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="drpLanguage" runat="server" OnSelectedIndexChanged="drpLanguage_SelectedIndexChanged" AutoPostBack="true">
            <asp:ListItem Value="0">Select</asp:ListItem>
            <asp:ListItem Value="en-US">English</asp:ListItem>
            <asp:ListItem Value="fr-CA">French</asp:ListItem>
        </asp:DropDownList>
        <asp:Label ID="lblText" runat="server" Text="<%$Resources:language, Name%>"></asp:Label>
    </div>
    </form>





Default.aspx.cs




.cs Code

protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["language"] != null)
        {
            drpLanguage.SelectedValue = Convert.ToString(Session["language"]);
        }
        Session["language"] = null;
    }
    protected void drpLanguage_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (drpLanguage.SelectedValue != "0")
        {
            Session["language"] = drpLanguage.SelectedValue;
            string value = Convert.ToString(drpLanguage.SelectedValue);
            Utility.DefaultLanguage = value;
            drpLanguage.SelectedItem.Value = Utility.DefaultLanguage;
            Server.Transfer(Request.Path);
        }
        else
        {
            Response.Write("<script>alert('Please select Language'); </script>");
            lblText.Text = "";
        }

    }





In App_GlobalResources Folder, Right Click and Select Add





Add->New Item



Give the Name as Language.resx and enter the following Details.



Again Add New Item 






Give the Name as Language.fr-CA.resx and enter the following Details.




Build the Solution and see the output.






SQL SERVER 2012 NEW FEATURE PART -II

Exceptions in SQL SERVER 2012

In C sharp we are having Exceptions(Try, Catch,throw). But in sql server 2008 we are having only Try, Catch. But in SQL SERVER 2012  , a new feature is introduced that is throw.


Syntax:

BEGIN TRY     
-----SELECT, INSERT, UPDATE, DELETE
 END TRY    
 BEGIN CATCH   
 throw  
 END CATCH 

Example:

BEGIN TRY   
DECLARE @VALUE INT   
SET @VALUE = 1/ 0   
END TRY    
BEGIN CATCH   
THROW   
END CATCH





New Functions:

IIF() Function:

The IIF function is used to check a condition.

Example : If we have two values with a,b. If the first expression is true, than it returns a value, if the second expression is true, it returns b value.

Example:


DECLARE @X INT;  
DECLARE @Y INT;  
SET @X=2
SET @Y=3;  
SELECT iif(@X>@Y, 'x is greater', 'y is greater') As IIFResult 

Choose() Function

It is similar to an Array, we can retrieve value using Index


Syntax

CHOOSE ( index, value1, value2.... [, valueN ] )

CHOOSE() Function excepts two parameters,
Index: It represent the index . Here index always starts with1. 
Value: List of values of any data type.



DECLARE @Index INT;  
SET @Index =5;  
Select Choose(@Index, 'A','B','C','D','E','F','G','H') As ChooseResult 
  

If an index value exceeds the number of Items, it returns NULL

Example:

DECLARE @Index INT;  
SET @Index =10;  
Select Choose(@Index, 'A','B','C','D','E','F','G','H') As ChooseResult 




If the value has a float data type , then the value is implicitly converted to an integer


DECLARE @Index INT;  
SET @Index =1.5;  
Select Choose(@Index, 'A','B','C','D','E','F','G','H') As ChooseResult 

Output:


TRY_PARSE()


If it is successfull, it returns the value, otherwise it returns Null

Syntax


TRY_PARSE ( string_value AS data_type [ USING culture ] ) 



Example

SELECT TRY_PARSE('Date' AS datetime USING 'en-GB');



SELECT Try_Parse ('Sunday, 13 Feb 2015' AS Datetime2 USING 'en-US') AS [Try_PARSE]



SELECT CASE WHEN TRY_PARSE('DATE' AS DATETIME2 USING 'EN-GB') IS NULL THEN
'PARSE FAIL'
ELSE
'PARSE SUCCESS'
END




TRY_CONVERT():

It returns , Null if fail, Else it returns the Output.

Example:


SELECT TRY_CONVERT(datetime, '2014/05/31');
SELECT TRY_CONVERT(datetime, '2042-05-31');
SELECT TRY_CONVERT(datetime, '20420434');
SELECT TRY_CONVERT(datetime, '31-12-2012');





DATEFROMPARTS Function

Syntax:

DATEFROMPARTS ( year, month, day)


DECLARE @YEAR AS INT=2015
DECLARE @MONTH AS INT=02  
DECLARE @DAY AS INT=13  

SELECT DATEFROMPARTS(@YEAR, @MONTH, @DAY)  






The Eomonth Function:

It returns the last date in the month

MONTH ( startdate [,month_to_add ] ) 

Example:


SELECT EOMONTH(GETDATE())ASMONTH










Kubernetes

Prerequisites We assume anyone who wants to understand Kubernetes should have an understating of how the Docker works, how the Docker images...