Tuesday 23 December 2014

set value in combobox in C#

 if (cmbHRU.Items.Count > 0)
                    {
                        // Search the Item that matches the string
                        int index = cmbHRU.FindString(_dtExistingStdata.Rows[0]["hru_id"].ToString());
                        // Select the Item in the Combo
                        cmbHRU.SelectedIndex = index;
                    }

Wednesday 10 December 2014

get single record from table in C# with where condition

 DataTable dtDataStation = objStationMaster.GetStationDetails();
                var stDetailId = (from DataRow dr in dtDataStation.Rows
                                  where Convert.ToString(dr["Station"]) == txtStation.Text
                                  select (string)dr["Identifier"]).FirstOrDefault();

Thursday 27 November 2014

Default binding in WCF

When you add Wcf service library then  wsHttp
ans when you add Wcf Service Appllication then basicHttp

so we can basicHttp is dedault binding

Tuesday 11 November 2014

Get Distinct Record only from datatable in C# Linq



    //----------Get Distinct Record only
                                

                    var distinctNames = (from row in dtGridSeries.AsEnumerable()
                                                      select row.Field<string>("Parameter Type")).Distinct();

        List<string> lstSelectedParamList = distinctNames.ToList();  // Get data in List
                                
       DataTable dtUnique = dtGridSeries.DefaultView.ToTable(true, "ColName");

Tuesday 30 September 2014

compute expression in C#



string strEq="-517*13+522*(312)-234*(34)+71";
  StringBuilder sbModifiedExp = new StringBuilder(strEq);
 object result = new DataTable().Compute(string.Format(sbModifiedExp.ToString()), "");
  double dCalcValue = Convert.ToDouble(result) > 0 ? Convert.ToDouble(result) : 0;

update colmn value in C# datatable

var rowsToUpdate = 
    dt1.AsEnumerable().Where(r => r.Field<decinmal?>("Series1") == -999);

foreach(var row in rowsToUpdate)
{
    row.SetField("Series1", DBNull.Value);    row.SetField("Series2", DBNull.Value);}

Sunday 28 September 2014

merge two array in one array in C#, Factorial in C#

 // make an array of strings. Note that we have included spaces
            string[] H1 = { "hello ", "and ", "welcome ", "to ", "this ", "demo! " };

            // put all the strings together
            Console.WriteLine(string.Concat(H1));

            // sort the strings, and put them together
            Array.Sort(H1);
            Console.WriteLine(string.Concat(H1));
            //*****************************************************//
            //In C# 3.0 you can use LINQ to accomplish this easily:

            int[] front = { 1, 2, 3, 4 };
            int[] back = { 5, 6, 7, 8 };
            int[] combined = front.Concat(back).ToArray();

            //In C# 2.0 you don't have such a direct way, but Array.Copy is probably the best solution:

            int[] front1 = { 1, 2, 3, 4 };
            int[] back1 = { 5, 6, 7, 8 };

            int[] combined1 = new int[front1.Length + back1.Length];
            Array.Copy(front1, combined1, front1.Length);
            Array.Copy(back1, 0, combined1, front1.Length, back1.Length);


            //Program that uses Array to Revers Word
            const string s2 = "This is Reverse word";
            string rev1 = Words.RWords(s2);
            Console.WriteLine(rev1);
         

            //----------Reverse String----------------------------

            string text = "HAMID ALI";
            StringBuilder reverse = new StringBuilder();

            for (int i = text.Length - 1; i >= 0; i--)
            {
                reverse.Append(text[i]);
            }
            Console.WriteLine(reverse);

            //----------------------Reverse string--------------------------------//
            string s = "HAMID ALI";
            char[] charArray = s.ToCharArray();
            Array.Reverse(charArray);
            Console.WriteLine(charArray);
            string s1 = charArray.ToString();
            Console.ReadKey();
            //-----------------------------------------------------//

            MatrixMultiplication MM = new MatrixMultiplication();
            MM.ReadMatrix();
            MM.MultiplyMatrix();
            MM.PrintMatrix();

            int[] ArrStr = new int[] { 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 3, 1, 4, 6, 7, 6, 4, 3 };
            Array.Sort(ArrStr);
            Array.Reverse(ArrStr);
            foreach (var str in ArrStr)
            {
                Console.WriteLine(str);
            }
            Console.ReadLine();


            //  clsA objA = new clsC();


            Console.WriteLine("Enter a number");
            int number1 = Convert.ToInt32(Console.ReadLine());
            long fact1 = GetFactorial(number1);
            Console.WriteLine("{0} factorial is {1}", number1, fact1);
            Console.ReadKey();








private static long GetFactorial(int number)
        {
            if (number == 0)
            {
                return 1;
            }
            return number * GetFactorial(number - 1);
        }








Friday 26 September 2014

Revers Word in C#

namespace demo_arraylist
{
    class Program
    {
        static void Main(string[] args)
        {
            //Program that uses Array to Revers Word
            const string s1 = "This is Reverse word";   
            string rev1 = Words.RWords(s1);
            Console.WriteLine(rev1);
            Console.ReadKey();
        }
        //This is a method of Reverse
        static class Words
        {
            public static string RWords(string strword)
            {
                string[] words = strword.Split(' ');
                Array.Reverse(words);
                return string.Join(" ", words);
            }
        }
    }
}

how to Rverse string

public static void ReverseFast(string x)
{
    string text = "HAMID ALI";
    StringBuilder reverse = new StringBuilder();

    for (int i = text.Length - 1; i >= 0; i--)
    {
        reverse.Append(text[i]);
    }
      Console.WriteLine(reverse);
}

Tuesday 23 September 2014

copy array to other array in C#

 //private double[][] CopyArrayBuiltIn(double[][] source, double[] arrStSubBasin)
        //{
        //    var len = source.Length;
        //    double[][] destination = new double[source.Length][];
        //    //  double[][] dest = new double[len][];

        //    for (var x = 0; x < len; x++)
        //    {
        //        var inner = source[x];
        //        var ilen = inner.Length;
        //        var newer = new double[ilen];
        //        Array.Copy(inner, newer, ilen);
        //        destination[x] = newer;
        //    }
        //    MatrixProduct(destination, arrStSubBasin);
        //    return destination;
        //}

Matrix Multiplication in C#



        #region Matrix Multiplication
        public double[] MatrixProduct(double[][] matrixA, double[] vectorB)
        {
            int aRows = matrixA.Length;
            int aCols = matrixA[0].Length;
            int bRows = vectorB.Length;
            if (aCols != bRows)
            {
                throw new Exception("Non-conformable matrices in MatrixProduct");
            }
            double[] result = new double[aRows];
            for (int i = 0; i < aRows; ++i) // each row of A
                for (int k = 0; k < aCols; ++k)
                    result[i] += matrixA[i][k] * vectorB[k];
            return result;
        }
        #endregion

Monday 22 September 2014

How to convert DataTable to 2D Object Array?

Array materialArray = dTable.AsEnumerable().Select(x => x.ItemArray).ToArray();
Array myArray = testDataSet.Tables[0].Columns.OfType<DataColumn>().Select(c => c.ColumnName.ToString()).ToArray();

Saturday 20 September 2014

Types of Templates in WPF


  1. Control Template

    This template specifies the appearance of a Control; if a control does not have a Control Template, the Control will not appear in your application.
    For Example - When you will add the template defines as below to your application as a resource then all the buttons in the application will appear as ellipses but will still function as buttons.
    1. <Style TargetType="Button">
    2. <!--Set to true to not get any properties from the themes-->
    3. <Setter Property="OverridesDefaultStyle" Value="True"/>
    4. <Setter Property="Template">
    5. <Setter.Value>
    6. <ControlTemplate TargetType="Button">
    7. <Grid>
    8. <Ellipse Fill="{TemplateBinding Background}"/>
    9. <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
    10. </Grid>
    11. </ControlTemplate>
    12. </Setter.Value>
    13. </Setter>
    14. </Style>
  2. Data Template

    This template specifies a group of characteristics for how data should be displayed. This template is particularly useful when you are binding an ItemsControl such as a ListBox to an entire collection.
    For Example – The Template defined as below, is used to display the items of a ListBox. The data template contains TextBlock controls that bind to the FirstName, LastName, and Address properties.
    1. >Grid>
    2. >Grid.Resources>
    3. >src:Customers x:Key="customers"/>
    4. >/Grid.Resources>
    5. >ListBox ItemsSource="{StaticResource customers}" Width="350" Margin="0,5,0,10">
    6. >ListBox.ItemTemplate>
    7. >DataTemplate>
    8. >StackPanel Orientation="Horizontal">
    9. >TextBlock Padding="5,0,5,0"
    10. Text="{Binding FirstName}" />
    11. >TextBlock Text="{Binding LastName}" />
    12. >TextBlock Text=", " />
    13. >TextBlock Text="{Binding Address}" />
    14. >/StackPanel>
    15. >/DataTemplate>
    16. >/ListBox.ItemTemplate>
    17. >/ListBox>
    18. >/Grid>

Friday 19 September 2014

cursor vs while loop in sql


Here's a short post regarding the use of CURSOR vs WHILE LOOP in T-SQL. I often hear from colleagues and read from articles that it's best to use while loops and avoid cursors as much as possible since cursor has some performance issues specially when looping on huge amount of data.

We'll, only one way to find out is to put these two solutions on a test!

To start with, start creating this table below; we will be using this to loop through records:

CREATE TABLE FamousCharacter
        (
           NameID int IDENTITY(1,1) PRIMARY KEY CLUSTERED, 
           Name nvarchar(50)
        )

Then, let's put some data and loop through these records. Run this script below to insert records to theFamousCharacter table we just created.

INSERT INTO FamousCharacter VALUES('Bart Simpson')
INSERT INTO FamousCharacter VALUES('Homer Simpson')
INSERT INTO FamousCharacter VALUES('Beast')
INSERT INTO FamousCharacter VALUES('Belle')
INSERT INTO FamousCharacter VALUES('Scooby Doo')
INSERT INTO FamousCharacter VALUES('Shaggy')
INSERT INTO FamousCharacter VALUES('Tom')
INSERT INTO FamousCharacter VALUES('Jerry')
INSERT INTO FamousCharacter VALUES('Sylvester')
INSERT INTO FamousCharacter VALUES('Tweety')
INSERT INTO FamousCharacter VALUES('Garfield')
INSERT INTO FamousCharacter VALUES('John')
INSERT INTO FamousCharacter VALUES('Mickey')
INSERT INTO FamousCharacter VALUES('Minnie')
INSERT INTO FamousCharacter VALUES('Peter Pan')
INSERT INTO FamousCharacter VALUES('Tinkerbell')
INSERT INTO FamousCharacter VALUES('Fred Flintstone')
INSERT INTO FamousCharacter VALUES('Wilma Flintstone')
INSERT INTO FamousCharacter VALUES('Daffy Duck')
INSERT INTO FamousCharacter VALUES('Bugs Bunny')
INSERT INTO FamousCharacter VALUES('Tarzan')
INSERT INTO FamousCharacter VALUES('Jane')
INSERT INTO FamousCharacter VALUES('Popeye')
INSERT INTO FamousCharacter VALUES('Olive')
INSERT INTO FamousCharacter VALUES('Mr. Potato head')
INSERT INTO FamousCharacter VALUES('Mrs. Potato head')
INSERT INTO FamousCharacter VALUES('Stitch')
INSERT INTO FamousCharacter VALUES('Lilo')
INSERT INTO FamousCharacter VALUES('Jack')
INSERT INTO FamousCharacter VALUES('Jill')
INSERT INTO FamousCharacter VALUES('Batman')
INSERT INTO FamousCharacter VALUES('Robin')
INSERT INTO FamousCharacter VALUES('Woody')
INSERT INTO FamousCharacter VALUES('Buzz')
INSERT INTO FamousCharacter VALUES('Pooh')
INSERT INTO FamousCharacter VALUES('Piglet')
INSERT INTO FamousCharacter VALUES('Shrek')
INSERT INTO FamousCharacter VALUES('Donkey')
INSERT INTO FamousCharacter VALUES('Road Runner')
INSERT INTO FamousCharacter VALUES('Wile E. Coyote')
INSERT INTO FamousCharacter VALUES('Superman')
INSERT INTO FamousCharacter VALUES('Ultimateman')
INSERT INTO FamousCharacter VALUES('Eric Theodore Cartman')
INSERT INTO FamousCharacter VALUES('Kenny McCormick')
INSERT INTO FamousCharacter VALUES('Casper')
INSERT INTO FamousCharacter VALUES('Richie Rich')
INSERT INTO FamousCharacter VALUES('Professor X')
INSERT INTO FamousCharacter VALUES('Magneto')
INSERT INTO FamousCharacter VALUES('Wolverine')
INSERT INTO FamousCharacter VALUES('Sabretooth')
INSERT INTO FamousCharacter VALUES('Jughead')
INSERT INTO FamousCharacter VALUES('Archie')
INSERT INTO FamousCharacter VALUES('Linus van Pelt')
INSERT INTO FamousCharacter VALUES('Lucy van Pelt')

These scripts inserts a total of 54 rows that we can test. Our objective is to see the performance difference between cursor and while loop. The small difference on scanning these set of rows would mean huge performance hits on larger tables having millions of rows.

Let's start!

Approach #1: Cursor
Run this script below and see the execution time it spent on the lower right corner of SQL Server status bar:

SET NOCOUNT ON
DECLARE my_cursor CURSOR FOR SELECT NameID,Name FROM FamousCharacter
DECLARE @id INT
DECLARE @name NVARCHAR(50)
OPEN my_cursor
FETCH NEXT FROM my_cursor INTO @id,@name
    WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT  (CAST(@id AS VARCHAR(5)) + '.)' + @name)       
        FETCH NEXT FROM my_cursor
    END
CLOSE my_cursor   
DEALLOCATE my_cursor









Total execution time using cursor:



Approach #2: While Loop
Run this script below and again, let's check the execution time spent using WHILE loop.
DECLARE @Rows INT, @id1 INT
DECLARE @name1 NVARCHAR(50)
SET @Rows = 1
SET @id1 = 0

WHILE @Rows > 0
BEGIN
    SELECT TOP 1 @id1 = NameID, @name1 = Name FROM FamousCharacter WHERE NameID >= @id1
    SET @Rows = @@ROWCOUNT
    PRINT  (CAST(@id1 AS VARCHAR(5)) + '.)' + @name1)
    SET @id1 += 1
END

Total execution time:


While loop obviously completed the execution in less than a second! Now to exaggerate a bit, I tried re-inserting the rows and duplicated it up to 379 rows. Here's the result:

Cursor completed execution in 29 seconds!

While completed in 16 seconds!

Thursday 18 September 2014

DataTable to array in c#

DataTable dtResult;
//Populate Datatable
int[] firstRow = dtResult.AsEnumerable()
                       .Take(1)
                       .ToArray();
DataRow[] dr = dt.AsEnumerable().Take(1).ToArray();
object[] dr1 = dr[0].ItemArray;
int[] dr2 = Array.ConvertAll(dr1, (p => Convert.ToInt32(p)));

Monday 15 September 2014

Calculate difference between two dates in C#

DateTime endDate= new DateTime(2009, 12, 25);
double daysUntilChristmas = xmas.Subtract(DateTime.Today).TotalDays;

Thursday 11 September 2014

Negative Value Condition in C# linq

Negative Value Condition
////////
var results = (from row in tb1.AsEnumerable()
               where row.Field<double>("ColumnNameHere").<0)
               select row).Count();
            OR  var results = (from row in DataSetInstance.Table[0].AsEnumerable()
               where row.Field<double>("Order_num").ToString().Contains("-")
               select row).Count();  
if( results == 0 )
{
    // Do the processing
}
else
{
    //Negative value not allow.
}
/////////

Wednesday 10 September 2014

Difference Between Const, ReadOnly and Static ReadOnly in C#

These are very common keywords and are quite confusing. So today we will discuss these keywords and try to understand them.
  1. Const: Const is nothing but "constant", a variable of which the value is constant but at compile time. And it's mandatory to assign a value to it. By default a const is static and we cannot change the value of a const variable throughout the entire program.

    Csharp-Const-ReadOnly-and-StaticReadOnly1.jpg

    Here I have created a class named Variables and defined all three variables, so first let's play with const.

    Csharp-Const-ReadOnly-and-StaticReadOnly2.jpg

    Here I tried to de-initialize the const variable, it gaves me an error like "A const field requires a value to be provided".  Ok now I initialize a value for this variable and try to change it further in the class.

    Csharp-Const-ReadOnly-and-StaticReadOnly3.jpg

    Here I have created a static constructor, default constructor, parameterized constructor and a Simple Method. I tried to change the value of the const variable everywhere but once I assign the value, I am unable to change it again since when I do it gives me a compile time error as you can see in the snapshot above.

    Now let's on to the readonly keyword.
     
  2. Readonly: Readonly is the keyword whose value we can change during runtime or we can assign it at run time but only through the non-static constructor. Not even a method. Let's see:

    Csharp-Const-ReadOnly-and-StaticReadOnly4.jpg

    Here first I try to initialize the value in the static constructor. It gives me an error. Which you can see above.
    Now I try to change the value in a method, see what happened:

    Csharp-Const-ReadOnly-and-StaticReadOnly5.jpg
     
    Here, it is also giving an error that you can only assign a value either through a variable or a constructor.
    Now try to change the value in the default constructor.

    Csharp-Const-ReadOnly-and-StaticReadOnly6.jpg
     
    Now in the snapshot above you can see it's built successfully without an error, warning or messages. Let's check if there is a runtime error. OK.

    Csharp-Const-ReadOnly-and-StaticReadOnly7.jpg
     
    Now here we can see that there is not a runtime error and the value was assigned successfully to the Readonly variable.
    Now one gotcha is, now that you have assigned the value, can you change this value again ??? 
    Let's try to change the value again.

    Csharp-Const-ReadOnly-and-StaticReadOnly8.jpg

     
    Here I created  a parameterized constructor and created a new object, and passing a value as "Hello Frend'z" and as I built it, it gave me the result "Build Succeeded".  Now let's move ahead and check for a runtime error:

    Csharp-Const-ReadOnly-and-StaticReadOnly9.jpg
     
    See guys. There is no runtime error !!  And the value can be changed again and again through a constructor.
     
    Now move ahead to Static Readonly variables.
     
  3. Static ReadOnly: A Static Readonly type variable's value can be assigned at runtime or assigned at compile time and changed at runtime. But this variable's value can only be changed in the static constructor. And cannot be changed further. It can change only once at runtime. Let's understand it practically.

    Csharp-Const-ReadOnly-and-StaticReadOnly10.jpg

    Now in the preceding you can see that I used two variables, one is not assigned and another is assigned, and the static constructor.  Now in the static constructor you can see that the unassigned variable is being assigned and the assigned value is being changed. And there is no compile time error. Further I try to again change this variable's value.  See what happened:

    Csharp-Const-ReadOnly-and-StaticReadOnly11.jpg
     
    As you can see in the above, I created Default, Parameterized Constructor and Method and tried to change the value again here. But I am getting a compile time error for all.