Friday 19 April 2013

Calling Oracle Procedure which returns Ref Cursor AS output PARAMETER in ado.net

Calling Oracle Procedure which returns Ref Cursor AS output PARAMETER in ado.net



Step 1)  Create a Oracle Procedure which returns Ref cursor.


Creating a Procedure which returns Ref cursors as Output Parameter.


   CREATE OR REPLACE Procedure REFSP(p_orders OUT sys_refcursor)
  as
  begin
  open p_orders for select * from pearson.orders;
 end;
 

Step 2)   Calling  Oracle Procedure with ouput param IS Ref Cursor in ADO.NET

               Using   ExecuteReader.

        protected void  CallingOracleProcedure ()
        {
            try{
                String connString = ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString;
                OracleConnection conn = new OracleConnection(connString);
                conn.Open();


                OracleCommand cmd = new OracleCommand();
                cmd.Connection = conn;
                cmd.CommandType = System.Data.CommandType.StoredProcedure;                                 

                cmd.CommandText = "scott.refsp";
                OracleParameter oraP = new OracleParameter();
                oraP.OracleDbType = OracleDbType.RefCursor;
                oraP.Direction = System.Data.ParameterDirection.Output;

                cmd.Parameters.Add(oraP);


               OracleDataReader reader = cmd.ExecuteReader(); ;
                    while (reader.Read())
                    {
                       Console.WriteLine(reader.GetValue(0).ToString());
                       Console.WriteLine(reader.GetValue(1).ToString());
                       //repeat for remaining  fields.
                    }
                reader.Close();
}
            catch (OracleException ex)
            {

            }

        }

Method 2: Calling  Oracle Procedure with Return Type as Ref Cursor in ADO.NET

               Using   OracleDataAdapter.

        protected void CallingOracleProcedure ()
        {
            try{                String connString = ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString;
                OracleConnection conn = new OracleConnection(connString);
                conn.Open();


                OracleCommand cmd = new OracleCommand();
                cmd.Connection = conn;
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
              
                cmd.CommandText = "scott.refsp";
                OracleParameter oraP = new OracleParameter();
                oraP.OracleDbType = OracleDbType.RefCursor;
                oraP.Direction = System.Data.ParameterDirection.Output;
                cmd.Parameters.Add(oraP);

                 OracleDataAdapter ad = new OracleDataAdapter(cmd);
                OracleCommandBuilder cb = new OracleCommandBuilder(ad);
               
                System.Data.DataSet ds = new System.Data.DataSet();
                ad.Fill(ds);
            }
            catch (OracleException ex)
            {
            }

        }
Tags:Calling Oracle Procedure which returns Ref Cursor in ado.net,Calling Oracle Procedure which returns Ref Cursor in ado.net using ExecuteReader,Calling Oracle Procedure which returns Ref Cursor in ado.net using OracleDataAdapter, Calling Oracle Procedure s in ADO.NET,Executing Oracle Procedure s in ado.net.oracle 11g



Calling Oracle function which returns Ref Cursor in ado.net

Calling Oracle function which returns Ref Cursor in ado.net


Step 1)  Create a Oracle function which returns Ref cursor.


Creating a Function which returns Ref cursors.

CREATE OR REPLACE function reff1
return sys_refcursor
is
v_t sys_refcursor;
begin
open v_t for select * from pearson.orders;
return v_t;
end;
 
 

Step 2)   Calling  Oracle Function with Return Type as Ref Cursor in ADO.NET

               Using   ExecuteReader.


        protected void  CallingOracleFunction()
        {
            try{
                String connString = ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString;
                OracleConnection conn = new OracleConnection(connString);
                conn.Open();


                OracleCommand cmd = new OracleCommand();
                cmd.Connection = conn;
                cmd.CommandType = System.Data.CommandType.StoredProcedure;                                  cmd.CommandText = "scott.reff1";
                OracleParameter oraP = new OracleParameter();
                oraP.OracleDbType = OracleDbType.RefCursor;
                oraP.Direction = System.Data.ParameterDirection.ReturnValue;
                cmd.Parameters.Add(oraP);

               

                OracleDataReader reader = cmd.ExecuteReader(); ;

                {
                    while (reader.Read())
                    {
                        Console.WriteLine (reader.GetValue(0)).ToString();
                       Console.WriteLine (reader.GetValue(1)).ToString();
                         //repeat  for remaining fields.
                    }
                }

                reader.Close();            
}
            catch (OracleException ex)
            {

            }

        }
 

Method 2: Calling  Oracle Function with Return Type as Ref Cursor in ADO.NET

               Using   OracleDataAdapter.


        protected void CallingOracleFunction()
        {
            try{
                String connString = ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString;
                OracleConnection conn = new OracleConnection(connString);
                conn.Open();


                OracleCommand cmd = new OracleCommand();
                cmd.Connection = conn;
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.CommandText = "scott.reff1";
                OracleParameter oraP = new OracleParameter();
                oraP.OracleDbType = OracleDbType.RefCursor;
                oraP.Direction = System.Data.ParameterDirection.ReturnValue;
                cmd.Parameters.Add(oraP);

                 OracleDataAdapter ad = new OracleDataAdapter(cmd);
                OracleCommandBuilder cb = new OracleCommandBuilder(ad);
               
                System.Data.DataSet ds = new System.Data.DataSet();
                ad.Fill(ds);
            }
            catch (OracleException ex)
            {
            }

        }
Tags:Calling Oracle function which returns Ref Cursor in ado.net,Calling Oracle function which returns Ref Cursor in ado.net using ExecuteReader,Calling Oracle function which returns Ref Cursor in ado.net using OracleDataAdapter, Calling Oracle functions in ADO.NET,Executing Oracle functions in ado.net.

Friday 22 March 2013

convert list to xml asp.net VB.NET using LINQ

convert list to xml asp.net VB.NET using LINQ

This example explains how to convert list type to XML using LINQ .

Create a class called Student

  Class Student
        Public Name As String,Grade As String
        Public year As Integer
  End Class

Add List items of type Student

             Dim stuList As List<Student> =  New List<Student>()
            stuList.Add(New Student
            {
                 Name="Shyam", Grade="A",year=1990
            }
)
            stuList.Add(New Student
            {
                 Name = "Raghu", Grade = "B", year = 2010
            }
)
            stuList.Add(New Student
            {
                 Name = "Paul", Grade = "C", year = 2001
            }
)
            stuList.Add(New Student
            {
                 Name = "murthy", Grade = "D", year = 2010
            }
)
            stuList.Add(New Student
            {
                 Name = "madam", Grade = "E", year = 2000
            }
)


Create XML from List

Dim root As New XElement("root")

For i As Integer = 0 To stuList.Count - 1
    Dim ele As New XElement("Student", New XElement("Name", stuList(i).Name), New XElement("Grade", stuList(i).Grade), New XElement("Year", stuList(i).year))
    root.Add(ele)
Next
Console.WriteLine(root)
OUTPUT:
<root>
  <Student>
    <Name>Shyam</Name>
    <Grade>A</Grade>
    <Year>1990</Year>
  </Student>
  <Student>
    <Name>Raghu</Name>
    <Grade>B</Grade>
    <Year>2010</Year>
  </Student>
  <Student>
    <Name>Paul</Name>
    <Grade>C</Grade>
    <Year>2001</Year>
  </Student>
  <Student>
    <Name>murthy</Name>
    <Grade>D</Grade>
    <Year>2010</Year>
  </Student>
  <Student>
    <Name>madam</Name>
    <Grade>E</Grade>
    <Year>2000</Year>
  </Student>
</root>
Tags:convert list to xml asp.net VB.NET using LINQ,convert list to xml asp.neT,convert list to xml VB.NET,LINQ to XML XElement usage.

convert list to xml asp.net C# using LINQ

convert list to xml asp.net C# using LINQ


This example explains how to convert list type to XML using LINQ .

Create a class called Student


    class Student
    {
        public String Name, Grade;
        public int year;
    }

Add List items of type Student


            List<Student> stuList = new List<Student>();
            stuList.Add(new Student { Name="Shyam", Grade="A",year=1990 });
            stuList.Add(new Student { Name = "Raghu", Grade = "B", year = 2010 });
            stuList.Add(new Student { Name = "Paul", Grade = "C", year = 2001 });
            stuList.Add(new Student { Name = "murthy", Grade = "D", year = 2010 });
            stuList.Add(new Student { Name = "madam", Grade = "E", year = 2000 });

Create XML from List


            XElement root = new XElement("root");

            for (int i = 0; i < stuList.Count; i++)
            {
                XElement ele = new XElement("Student", new XElement("Name", stuList[i].Name),
                                                        new XElement("Grade", stuList[i].Grade),
                                                        new XElement("Year", stuList[i].year));
                root.Add(ele);
            }
            Console.WriteLine(root);

OUTPUT:
<root>
  <Student>
    <Name>Shyam</Name>
    <Grade>A</Grade>
    <Year>1990</Year>
  </Student>
  <Student>
    <Name>Raghu</Name>
    <Grade>B</Grade>
    <Year>2010</Year>
  </Student>
  <Student>
    <Name>Paul</Name>
    <Grade>C</Grade>
    <Year>2001</Year>
  </Student>
  <Student>
    <Name>murthy</Name>
    <Grade>D</Grade>
    <Year>2010</Year>
  </Student>
  <Student>
    <Name>madam</Name>
    <Grade>E</Grade>
    <Year>2000</Year>
  </Student>
</root>

Tags:convert list to xml asp.net C# using LINQ,convert list to xml asp.ne,convert list to xml C#,LINQ to XML XElement usage.

Tuesday 5 March 2013

Get Maximum Date using VB.NET LINQ


 Get Maximum Date using VB.NET LINQ

This example gets maximum/highest date from list of dates.

DateTime.Parse,  is used to Parse Date Strings  converts it into DateTime Object.
DateTime Custom Format:
         yyyy   is for four digit year
         MMM for  Month in Short form
         dd  is for Day . %d is for single digit/double digit day.


  Private  Sub GetMaxDate()
           String() szDates = New String() { "2013-jan-12",
               "2013-Mar-12", "2013-Feb-12",
               "2013-Apr-12", "2013-Oct-12","2013-Oct-12","2013-Nov-1",
               "2012-DEC-31"
               }



           var MaxDate = from dt in szDates
                          let custDt = DateTime.ParseExact(dt, "yyyy-MMM-%d",
                       System.Threading.Thread.CurrentThread.CurrentCulture)
                       orderby  custDt.Date descending
                       Dim dt As select

            Dim u As var
            For Each u In MaxDate
           Console.WriteLine("{0}",u)
            Next

            Console.WriteLine("Maxdate={0}",MaxDate.FirstOrDefault())
End Sub


OUTPUT:

2013-Nov-1
2013-Oct-12
2013-Oct-12
2013-Apr-12
2013-Mar-12
2013-Feb-12
2013-jan-12
2012-DEC-31
Maxdate=2013-Nov-1
LINQ let clause allows us to store temporary results in query sequence evaluation.
Tags:Get Maximum Date using VB.NET LINQ, LINQ Orderby on DateTime,LINQ LET CLAUSE,LINQ ORDERBY descending.How to get maximum date from selected dates.

Get Maximum Date using C# LINQ

 Get Maximum Date using C# LINQ

This example gets maximum/highest date from list of dates.

DateTime.Parse,  is used to Parse Date Strings  converts it into DateTime Object.
DateTime Custom Format:
         yyyy   is for four digit year
         MMM for  Month in Short form
         dd  is for Day .


  void GetMaxDate()
       {
           String[] szDates = new String[] { "2013-jan-12",
               "2013-Mar-12", "2013-Feb-12",
               "2013-Apr-12", "2013-Oct-12","2013-Oct-12","2013-Nov-1",
               "2012-DEC-31"};
         
          
           var MaxDate = from dt in szDates
                          let custDt = DateTime.ParseExact(dt, "yyyy-MMM-%d",
                       System.Threading.Thread.CurrentThread.CurrentCulture)
                       orderby  custDt.Date descending
                       select dt;

            foreach(var u in MaxDate)
           Console.WriteLine("{0}",u);

            Console.WriteLine("Maxdate={0}",MaxDate.FirstOrDefault());
       }

OUTPUT:

2013-Nov-1
2013-Oct-12
2013-Oct-12
2013-Apr-12
2013-Mar-12
2013-Feb-12
2013-jan-12
2012-DEC-31
Maxdate=2013-Nov-1
LINQ let clause allows us to store temporary results in query sequence evaluation.
Tags:Get Maximum Date using C# LINQ, LINQ Orderby on DateTime,LINQ LET CLAUSE,LINQ ORDERBY descending.How to get maximum date from selected dates.

Sunday 3 March 2013

Reverse Words in a Sentence using VB.NET


Reverse Words in a Sentence using VB.NET

               This example explains how to get words by using delimiter ' ' and then reverse each word using String>reverse.
String.Split(new char{' '});//  Splits sentence  into an array words
String.Reverse  Reverses each word ,but returns IEnumerator<char> need to convert it into an Array of char. then re-create String with Array of characters.
 
Shared  Sub ReverseWordsInString()
          Dim original As String = "But,in a larger sense,we can not dedicate - 1
not consecrate = not consecrate - 1
          String()words=original.Split(New Char()
          {
              " "c
          }
)
          Dim i As Integer
          For  i = 0 To  words.Length- 1  Step i + 1
              Char()cWords = words(i).Reverse().ToArray()
              words(i) = New String(cWords)
          Next

          Dim word As String
          For Each word In words
              Console.WriteLine(word)
          Next

        original=String.Join(" ", words)
          Console.WriteLine(original)

 End Sub
 
String.Join static function joins by array of words into a String. 
Note: We used same delimiter for splitting and joining words.

OUTPUT

Input:But, in a larger sense, we can not dedicate-- we can
not consecrate-- we can not hallow-- this ground.
Output:,tuB ni a regral ,esnes ew nac ton --etacided ew ton
nac --etarcesnoc ew nac ton --wollah siht .dnuorg
Tags:  Reverse Words in a Sentence using VB.NET, Reverse word in VB.NET ,String.Reverse ,String.Join,Create new String using char array VB.NET.

Reverse Words in a Sentence using C#

Reverse Words in a Sentence using C#


               This example explains how to get words by using delimiter ' ' and then reverse each word using String>reverse.

String.Split(new char{' '});//  Splits sentence  into an array words
String.Reverse  Reverses each word ,but returns IEnumerator<char> need to convert it into an Array of char. then re-create String with Array of characters.
 
 static void ReverseWordsInString()
      {
          string original =@"But, in a larger sense, we can not dedicate-- we can
not consecrate-- we can not hallow-- this ground.";
          String[]words=original.Split(new char[] {' '});
          for(int i=0; i < words.Length;i++)
          {
              char[]cWords = words[i].Reverse().ToArray();
              words[i] = new String(cWords);
          }

          foreach (String word in words)
          {
              Console.WriteLine(word);
          }
        original=String.Join(" ", words);
          Console.WriteLine(original);
}


String.Join static function joins by array of words into String. 
Note: We splitted by delimter space ' ', same delimiter used for joining words.

OUTPUT

Input:But, in a larger sense, we can not dedicate-- we can
not consecrate-- we can not hallow-- this ground.

Output:,tuB ni a regral ,esnes ew nac ton --etacided ew ton
nac --etarcesnoc ew nac ton --wollah siht .dnuorg

Tags:  Reverse Words in a Sentence using C#, Reverse word in C# ,String.Reverse ,String.Join,Create new String using char array C#.

Generate Random Date using VB.NET

Generate Random Date using  VB.NET

 
 
This example generates random date from 1900 to 9999.   
DaysInMonth will be returned appropriate Days, based on Leap year also.




Private Function GenererateRandomDate() As DateTime

            Dim year As Integer =  rnd.Next(1900,9999)
            Dim month As Integer =  rnd.Next(1,12)
            Dim day As Integer =  DateTime.DaysInMonth(year,month)

            Dim Day As Integer =  rnd.Next(1,day)

            Dim dt As DateTime =  New DateTime(year,month,Day)
            Return dt
 End Function


Construct Random Class object Outside of the function,Make n number of calls.




OUTPUT:
Random Date=10/11/5427 12:00:00 AMRandom Date=6/22/4602 12:00:00 AMRandom Date=9/7/7710 12:00:00 AMRandom Date=10/12/7657 12:00:00 AMRandom Date=8/23/2410 12:00:00 AM
 

Note: User can apply  Standard Date Formats on this.
for ex:  rndDate.ToString("d")   displays short date:  2/18/5335 
other available formats are: o,O,g,G,d,D,s,u,U,f,F,Y,y .


Tags:Generate Random Dates in Vb.NET,  Generate Random Dates in various format,Random Date in Vb.NET.Generate Random Month,Generate random Day,Generate Random Year,How to Generate Random DateTime Object,Generate Random UTC Dates

Generate Random Date using C#

Generate Random Date using C#


This example generates random date from 1900 to 9999.   
if Month is February checks for Leap year so days will 29 otherwise 28.

        DateTime GenererateRandomDate()
        {
          
            int year = rnd.Next(1900, 9999);
            int month = rnd.Next(1, 12);
            int day = DateTime.DaysInMonth(year,month);
          
            int Day = rnd.Next(1, day);

            DateTime dt = new DateTime(year,month,Day);
            return dt;
        }

Construct Random Class object Outside of the function,Make n number of calls.




OUTPUT:

Random Date=10/11/5427 12:00:00 AMRandom Date=6/22/4602 12:00:00 AMRandom Date=9/7/7710 12:00:00 AMRandom Date=10/12/7657 12:00:00 AMRandom Date=8/23/2410 12:00:00 AM
 

Note: User can apply  Standard Date Formats on this.

for ex:  rndDate.ToString("d")   displays short date:  2/18/5335 

other available formats are: o,O,g,G,d,D,s,u,U,f,F,Y,y .


Tags: Generate Random Dates in C#,  Generate Random Dates in various format,Random Date in C#.Generate Random Month,Generate random Day,Generate Random Year,How to Generate Random DateTime Object,Generate Random UTC Dates

Generate Random String using VB.NET


Generate Random String using VB.NET


This tutorial generates Random Strings may be suitable for Password generation/Captcha etc.,

// This example uses Random class generates sequence of bytes and then converts those bytes to
//String, picks only Alphabets.
//
        Private Function GenerateRandomString() As String           
           Dim bytes() As Byte =  New Byte(255) {}
            rnd.NextBytes(bytes)
            Dim szRandom As String =  System.Text.Encoding.ASCII.GetString(bytes)
            Dim c() As Char =  szRandom.ToCharArray()
            Dim sb As StringBuilder =  New StringBuilder()
            Dim cc As Char
            For Each cc In c
                If Char.IsLetter(cc) Then
                    sb.Append(cc)
                End If
            Next
            Return sb.ToString()
        End Function
 
Dim rnd As Random =  New Random
Console.WriteLine("RandomPassword={0}",GenerateRandomString());

Output:
RandomPassword=WTdavEYQqzBekgKkqgJalgQGsgSJVdiQgnJzwwrlbJe
RandomPassword=dJpjgBczezrQSMLzkYhLoZRJdStitRFoHdmJikqhfGcxlrniKChEkI
RandomPassword=DGaYmSvZuHoHRMjVfvQrrVzxoDiQdvwkjDgKjAQXRGUEx
RandomPassword=mZABWuDFUHHEzVVmSchQHFnbOfXPpBMcxRfrFKqtzvJNTnurjHYz
RandomPassword=IzYTMyvMpmNaDqXRNFVtIgnHfVVEioYbUTkyIRSASDvbgcGoYlJBpuqp
RandomPassword=SLkyLRSLhDOkXztdIGIOVRkjqwTdfkqYUMQszCtnTNWiwcWVPngmBxRge


For Random AlphaNumeric  Strings


Change the Logic to
   Char.IsLetterOrDigit(cc)

Output:a6Nna0eeJaXW2K8LNAfBMTBmgSd2YoezGODa1v37sWlsAlL19CpQwkGVdDmdwIdzKbX

For Random Numbers.

  U can use same Random class,Each time it generates new number, otherwise,
Chanage the Logic like this
Char.IsNumber(cc)
Output:
2752175506
6767
578799
89989878
Tags:    Generate Random String using VB.NET,Generate Random Passwords,Generate Random Numbers VB.NET, Random String Vb.NET,Generate Random Alphanumeric String VB.NET,How to Generate Random String in VB.NET

Generate Random String using C#

Generate Random String using C#


This tutorial generates Random Strings may be suitable for Password generation/Captcha etc.,

// This example uses Random class generates sequence of bytes and then converts those bytes to
//String, picks only Alphabets.
//
        String GenerateRandomString()
        {            
           byte[] bytes = new byte[255];
            rnd.NextBytes(bytes);
            String szRandom = System.Text.Encoding.ASCII.GetString(bytes);
            char[] c = szRandom.ToCharArray();
            StringBuilder sb = new StringBuilder();
            foreach (char cc in c)
            {
                if (Char.IsLetter(cc))
                {
                    sb.Append(cc);
                }
            }            return sb.ToString(); ;
        }
Random rnd = new Random();
Console.WriteLine("RandomPassword={0}",GenerateRandomString());

Output:
RandomPassword=WTdavEYQqzBekgKkqgJalgQGsgSJVdiQgnJzwwrlbJe
RandomPassword=dJpjgBczezrQSMLzkYhLoZRJdStitRFoHdmJikqhfGcxlrniKChEkI
RandomPassword=DGaYmSvZuHoHRMjVfvQrrVzxoDiQdvwkjDgKjAQXRGUEx
RandomPassword=mZABWuDFUHHEzVVmSchQHFnbOfXPpBMcxRfrFKqtzvJNTnurjHYz
RandomPassword=IzYTMyvMpmNaDqXRNFVtIgnHfVVEioYbUTkyIRSASDvbgcGoYlJBpuqp
RandomPassword=SLkyLRSLhDOkXztdIGIOVRkjqwTdfkqYUMQszCtnTNWiwcWVPngmBxRge


For Random AlphaNumeric  Strings


Change the Logic to

   Char.IsLetterOrDigit(cc)

Output:a6Nna0eeJaXW2K8LNAfBMTBmgSd2YoezGODa1v37sWlsAlL19CpQwkGVdDmdwIdzKbX


For Random Numbers.


  U can use same Random class,Each time it generates new number, otherwise,

Chanage the Logic like this

Char.IsNumber(cc)

Output:
2752175506
6767
578799
89989878

Tags:    Generate Random String using C#,Generate Random Passwords,Generate Random Numbers C#, Random String C#,Generate Random Alphanumeric String C#,How to Generate Random String in C#

Sunday 17 February 2013

SQL SERVER DATATYPES and .NET Framework Datatypes mapping

SQL SERVER DATATYPES and .NET Framework Datatypes mapping

datetime
SQL SERVER DATA TYPES.NET CLR DATATYPES
bigintint64
intint32
smallintint16
tinyintbyte
decimalSqlDecimal
numericSqlDecimal
floatdouble
realshort
smallmoneydecimal
moneydecimal
datedatetime
datetimedatetime
timetimespan
smalldatetimedatetime
datetime2datetime
datetimeoffsetdatetimeoffset


tags: SQL DATA TYPES mapping in .NET Data types,SQL Data types  equivalent in C#,SQL Data types  equivalent in Vb.net, SQL Data types and .net data types mapping.

Friday 15 February 2013

String split by Newline in VB.NET


String split by Newline in VB.NET

if String is in this format
     Dim  str as String = "1)ABS
2)SIGN
3)MOD
4)FLOOR
5)CEIL
6)ROUND
7)EXP
8)LOG
9)LOG10
10)POW
11)POWER
12)SQRT
13)PI
14)COS
15)SIN
16)TAN"

Split string by new line -> then  by  ')'  get exact Strings 


1) Split by Newline
            User can split by  "\r\n"   or System.Environment.NewLine

        Dim final As String = String.Empty
           Dim array() As String = str.Split(New String() {"\r\n"}
, StringSplitOptions.RemoveEmptyEntries)
           Dim s As String
           For Each s In array
               Console.WriteLine(s)
               final+=s.Split(New Char()
               {
                   ")"c
               }
, StringSplitOptions.RemoveEmptyEntries)(1)+" "
           Next
 
 OUTPUT
1)ABS
2)SIGN
3)MOD
4)FLOOR
5)CEIL
6)ROUND
7)EXP
8)LOG
9)LOG10
10)POW
11)POWER
12)SQRT
13)PI
14)COS
15)SIN
16)TAN
 
2) Split String by  ')'  character

            Dim finalwords() As String = final.Split(New String() {" "}
, StringSplitOptions.RemoveEmptyEntries)
           Array.Sort(finalwords)
           Dim i As Integer =  0
           Dim f As String
           For Each f In finalwords
               Console.Write(f + "\t")
           Next

FINAL OUTPUT:
ABS SIGN MOD FLOOR CEIL ROUND EXP LOG LOG10 POW POWER SQRT PI COS SIN TAN
ABS     CEIL    COS     EXP     FLOOR   LOG     LOG10   MOD     PI      POW
POWER   ROUND   SIGN    SIN     SQRT    TAN

Tags:String split by Newline in VB.NET,String split by '\r\n',String Split by System.Environment.NewLine. Split Strings in VB.NET,Split a String on Line Breaks,Split a String on carriage Return

String split by Newline in C#

String split by Newline in C#

if String is in this format
          String str = @"1)ABS
2)SIGN
3)MOD
4)FLOOR
5)CEIL
6)ROUND
7)EXP
8)LOG
9)LOG10
10)POW
11)POWER
12)SQRT
13)PI
14)COS
15)SIN
16)TAN";

Split string by new line -> then  by  ')'  get exact Strings 


1) Split by Newline
            User can split by  "\r\n"   or System.Environment.NewLine

          String final=String.Empty;
           String[] array=str.Split(new String[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
           foreach (String s in array)
           {
               Console.WriteLine("--"+s+"--");
               final+=s.Split(new char[] {')'}, StringSplitOptions.RemoveEmptyEntries)[1]+" ";
           }

OUTPUT
1)ABS
2)SIGN
3)MOD
4)FLOOR
5)CEIL
6)ROUND
7)EXP
8)LOG
9)LOG10
10)POW
11)POWER
12)SQRT
13)PI
14)COS
15)SIN
16)TAN
 
2) Split String by  ')'  character

           String[] finalwords=final.Split(new String[] { " " }, StringSplitOptions.RemoveEmptyEntries);
           Array.Sort(finalwords);
           int i = 0;
           foreach (String f in finalwords)
           {
               Console.Write(f + "\t");
           }

FINAL OUTPUT:

ABS SIGN MOD FLOOR CEIL ROUND EXP LOG LOG10 POW POWER SQRT PI COS SIN TAN
ABS     CEIL    COS     EXP     FLOOR   LOG     LOG10   MOD     PI      POW
POWER   ROUND   SIGN    SIN     SQRT    TAN

Tags:String split by Newline in C#,String split by '\r\n',String Split by System.Environment.NewLine. Split Strings in C#,Split a String on Line Breaks,Split a String on carriage Return

Tuesday 12 February 2013

Using ArrayList in VB.NET


Using ArrayList in  VB.NET

This example explains how to insert items into array list and fetch them based on type.

ArrayList is used for dynamic length 

Add namespace  System.Collections;

Create an Array List

Dim arrayList As ArrayList =  New ArrayList()

Add items to an array list


            arrayList.Add(1)
            arrayList.Add(2)
            arrayList.Add(3)
            arrayList.Add(1.1f)
            arrayList.Add(0.5f)
            arrayList.Add("Hello")
            arrayList.Add("World!")

It has integers and float values and string values also/

Get All values from Array List

            Console.WriteLine("Display All Values in Array List")
            Dim item As var
            For Each item In arrayList
                Console.Write(item+"\t")
            Next
Output: 1       2       3       1.1     0.5 Hello World!

Get Only Integers from Array List

            Console.WriteLine("Get Only Integers")
            Dim item As var
            For Each item In arrayList.OfType<int>()

                Console.Write(item+"\t")
            Next
Output:1       2       3
Get Only Float values from Array List

            Console.WriteLine("Get Only float")
            Dim item As var
            For Each item In arrayList.OfType<float>()

                Console.Write(item+"\t")
            Next
Output:1.1 0.5
Get Only String values from Array List

            Console.WriteLine("Get Only String Values")
            Dim item As var
            For Each item In arrayList.OfType<String>()

                Console.Write(item+"\t")
            Next
Output:Hello World!

Tags: using ArrayList in VB.NET,VB.NET ArrayList,ArrayList in VB.NET, ArrayList OfType method usage,Insert elements into Array List, Dynamic Array in VB.NET

Using ArrayList in C#

Using ArrayList in C#

This example explains how to insert items into array list and fetch them based on type.

ArrayList is used for dynamic length 

Add namespace  System.Collections;

Create an Array List

ArrayList arrayList = new ArrayList();

Add items to an array list

            arrayList.Add(1);
            arrayList.Add(2);
            arrayList.Add(3);
            arrayList.Add(1.1f);
            arrayList.Add(0.5f);
            arrayList.Add("Hello");
            arrayList.Add("World!");
It has integers and float values and string values also/

Get All values from Array List

            Console.WriteLine("Display All Values in Array List");
            foreach (var item in arrayList)
            {
                Console.WriteLine(item);
            }
Output: 1       2       3       1.1     0.5 Hello World!

Get Only Integers from Array List

            Console.WriteLine("Get Only Integers");
            foreach (var item in arrayList.OfType<int>())
            {
               
                Console.Write(item+"\t");
            }
Output:1       2       3

Get Only Float values from Array List

            Console.WriteLine("Get Only float");
            foreach (var item in arrayList.OfType<float>())
            {
               
                Console.Write(item+"\t");
            }
Output:1.1 0.5

Get Only String values from Array List

            Console.WriteLine("Get Only String Values");
            foreach (var item in arrayList.OfType<string>())
            {
               
                Console.Write(item+"\t");
            }
Output:Hello World!

Tags: using ArrayList in C#,C# ArrayList,ArrayList in C#, ArrayList OfType method usage,Insert elements into Array List, Dynamic Array in C#

Monday 11 February 2013

VB.NET Remove duplicate numbers/records from an array


  VB.NET Remove duplicate numbers/records from an array


Suppose array has series of numbers, if user wants to extract/find duplicated number in an array.
Here is the Logic.
Private Shared Sub RemoveDuplicateNumbersInArray()
    Dim a As Integer() = New Integer() {10, 20, 10, 30, 30, 20, _
        40, 40, 12, 14, 12, 14}

    Dim query =


    a = New Integer(query.Count() - 1) {}
    For i As Integer = 0 To query.Count() - 1
        a(i) = query.ElementAt(i).Key
    Next

    For Each i As Integer In a
        Console.WriteLine(i)
    Next
End Sub
Note :  1.Group each number by that number, so that duplicates will be under same group.
            2.if any group has more than one element          
                    query.Count() returns unique elements count.
            3. Then assign this values to existing array.

Input : int[] a = new int[] { 10, 20, 100, 100, 100, 10, 30, 20, 40, 50, 12, 14 };
Output:10      20      100     30      40      50      12      14


i.e 10,20,100 repeated more than once . so these are extra values removed from the array.

Input:  int[] a = new int[] { 10, 20,  10,30, 30, 20, 40, 40, 12, 14,12,14 };
Output: 10      20      30      40      12      14
 i.e 10 ,20,30,40,12,14 numbers repeated more than one time in an array a.

Tags:
  VB.NEt Remove duplicate numbers/records from an array,vb.net Remove duplicate records from an array,vb.net get unique elements array,vb.net get unique array,IGrouping LINQ,LINQ Count,LINQ Select on IGrouping,vb.net Find only Duplicate Values in an Array using LINQ

C# Remove duplicate numbers/records from an array

C# Remove duplicate numbers/records from an array


Suppose array has series of numbers, if user wants to extract/find duplicated number in an array.
Here is the Logic.

static void RemoveDuplicateNumbersInArray()
        {
            int[] a = new int[] { 10, 20, 10, 30, 30, 20, 40, 40, 12, 14, 12, 14 };





            var query = from d in a
                        group d by d into da
                        select da;


            a = new int[query.Count()];
            for (int i = 0; i < query.Count(); i++)
            {
                a[i] = query.ElementAt(i).Key;
            }

            foreach (int i in a)
            {
                Console.WriteLine(i);
            }
      }

Note :  1.Group each number by that number, so that duplicates will be under same group.
            2.if any group has more than one element          
                    query.Count() returns unique elements count.
            3. Then assign this values to existing array.

Input : int[] a = new int[] { 10, 20, 100, 100, 100, 10, 30, 20, 40, 50, 12, 14 };
Output:10      20      100     30      40      50      12      14


i.e 10,20,100 repeated more than once . so these are extra values removed from the array.

Input:  int[] a = new int[] { 10, 20,  10,30, 30, 20, 40, 40, 12, 14,12,14 };
Output: 10      20      30      40      12      14
 i.e 10 ,20,30,40,12,14 numbers repeated more than one time in an array a.

Tags:
C# Remove duplicate numbers/records from an array,C# Remove duplicate records from an array,C# get unique elements array,C# get unique array,IGrouping LINQ,LINQ Count,LINQ Select on IGrouping,C# Find only Duplicate Values in an Array using LINQ

VB.NET Find only Duplicate Values in an Array


VB.NET Find only Duplicate Values in an Array

Suppose array has series of numbers, if user wants to extract/find duplicated number in an array.
Here is the Logic.


Private Shared Sub GetDuplicateElementsInArray()
    Dim a As Integer() = New Integer() {10, 20, 100, 100, 100, 10, _
        30, 20, 40, 50, 12, 14}

    Dim query =

    For Each i As var In query.[Select](Function(ab, bc) ab).Where(Function(ab, bc) ab.Count() <> 1)
        Console.WriteLine(i.Key)
    Next



End Sub

Note :  1.Group each number by that number, so that duplicates will be under same group.
            2.if any group has more than one element          
                    query.Select((ab, bc) => ab.Count()) will be be greater than 1.
            3. Then filter the groups which has counter != 1  in step 2.
                 i.e this process may result more than one element.

Input : int[] a = new int[] { 10, 20, 100, 100, 100, 10, 30, 20, 40, 50, 12, 14 };
Output:
10
20
100



i.e 10,20,100 repeated more than once . so these are duplicate values in an array.

Input:  int[] a = new int[] { 10, 20,  10,30, 30, 20, 40, 40, 12, 14,12,14 };
Output: 10
20
30
40
12
14
 i.e 10 ,20,30,40,12,14 numbers repeated more than one time in an array a.

Tags:
VB.NET  Find only Duplicate Values in an Array,get repeated elements in an array,get non-unique values from an array,IGrouping LINQ,LINQ Count,LINQ Select on IGrouping,C# Find only Duplicate Values in an Array using LINQ

C# Find only Duplicate Values in an Array

C# Find only Duplicate Values in an Array

Suppose array has series of numbers, if user wants to extract/find duplicated number in an array.
Here is the Logic.


      static void GetDuplicateElementsInArray()
        {
            int[] a = new int[] { 10, 20, 100, 100, 100, 10, 30, 20, 40, 50, 12, 14 };

              



               var query = from d in a
                           group d by d into da
                           select da;

               foreach (var i in query.Select((ab, bc) => ab).Where((ab, bc) => ab.Count() != 1))
                   Console.WriteLine(i.Key);

         

        }

Note :  1.Group each number by that number, so that duplicates will be under same group.
            2.if any group has more than one element          
                    query.Select((ab, bc) => ab.Count()) will be be greater than 1.
            3. Then filter the groups which has counter != 1  in step 2.
                 i.e this process may result more than one element.

Input : int[] a = new int[] { 10, 20, 100, 100, 100, 10, 30, 20, 40, 50, 12, 14 };
Output
10
20
100



i.e 10,20,100 repeated more than once . so these are duplicate values in an array.

Input:  int[] a = new int[] { 10, 20,  10,30, 30, 20, 40, 40, 12, 14,12,14 };
Output: 10
20
30
40
12
14
 i.e 10 ,20,30,40,12,14 numbers repeated more than one time in an array a.

Tags:
C# Find only Duplicate Values in an Array,get repeated elements in an array,get non-unique values from an array,IGrouping LINQ,LINQ Count,LINQ Select on IGrouping,