Search This Blog

Wednesday, December 4, 2013

DataContractAttribute C# example

C# > Serialization > DataContractAttribute

DataContract Attribute specifies that the type defines or implements a data contract and is serializable by a serializer.
EnumMember Attribute specifies that the field is an enumeration member and should be serialized.

Example:


namespace WindowsFormsApplication
{
    public partial class Form1 : Form
    {
        [DataContract]
        public enum Country
        {
            [EnumMember(Value = "USA")]
            USA,
            [EnumMember(Value = "DE")]
            Germany,
            [EnumMember(Value = "FR")]
            France,
            NotASerializableEnumeration
        }

        [DataContract (Name = "Customer")]
        public class Customer : IExtensibleDataObject
        {
            public Customer(string name,  Country cnt)
            {
                Name = name;
                Country = cnt;
            }
            private ExtensionDataObject extensionDataValue;
            public ExtensionDataObject ExtensionData
            {
                get { return extensionDataValue; }
                set { extensionDataValue = value; }
            }
            [DataMember]
            internal string Name;
            [DataMember]
            internal Country Country;
        }
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            Customer p = new Customer("Microsoft", Country.USA );
            FileStream fs = new FileStream(@"C:\1.xml", FileMode.Create);
            try
            {
                DataContractSerializer ser = new DataContractSerializer(typeof(Customer));
                ser.WriteObject(fs, p);
            }
            catch (SerializationException exc)
            {
                 MessageBox.Show(exc.Message.ToString());   
            }
            finally
            {
                fs.Close();
            }
        }
     }
}





Monday, December 2, 2013

Search for files in directories and subdirectories C#

C# > Files > Search

GetDirectories: gets the names of subdirectories in a specified directory.
GetFiles: returns the names of files in a specified directory.

Example: Search for files in directories and subdirectories

          List<string> sfiles = new List<string>();
         FileDirSearch(@"C:\\", sfiles, "*.xml");

      void FileDirSearch(string sDir, List<string> sfiles, string pattern)
        {
            try
            {
                foreach (string d in Directory.GetDirectories(sDir))
                {
                    foreach (string f in Directory.GetFiles(d, pattern))
                    {
                        sfiles.Add(f);
                    }
                    FileDirSearch(d, sfiles, pattern);
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show (exc.Message);
            }
        }






Control of Flow Keywords SQL Server

SQL Server > Control of Flow

Control of Flow keywords in SQL Server:




PrintPreviewDialog C# Example

C# > Print  > PrintPreviewDialog

PrintPreviewDialog is a dialog box form for printing from a Windows Forms application.






Example

In this example we will create a print document and print using PrintPreviewDialog. We will print some text on Print Page event



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void btnPrint_Click(object sender, EventArgs e)
        {
            PrintDocument document = new System.Drawing.Printing.PrintDocument();
            PrintPreviewDialog ppd = new PrintPreviewDialog();
            ppd.ClientSize = new System.Drawing.Size(500, 400);
            ppd.Location = new System.Drawing.Point(0, 0);
            document.PrintPage += new PrintPageEventHandler(Doc_PrintPage);
            ppd.Document  = document;
            ppd.ShowDialog();
        }
        private void Doc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            string text = "Header";
            Font printFont = new  Font("Tahoma", 40, System.Drawing.FontStyle.Bold );
            e.Graphics.DrawString(text, printFont, Brushes.Blue, 0, 0);
            text = "Text";
            printFont = new Font("Tahoma", 30, System.Drawing.FontStyle.Regular);
            e.Graphics.DrawString(text, printFont, Brushes.Black , 0, 100);
        }
    }
}






Add operator SQL Server Example

SQL Server > Operators > Add

+ Operator adds two numbers.





Example

1. Add values from 2 numeric columns

create table #test(value int, fee int)
insert into #test(value, fee) values (500,50),(100,10)
  select
   value + fee as 'Total'
  from
   #test
drop table #test

Result:
 Total
   550
   110


2. Add values from 1 numeric value and 1 char value

DECLARE @int_value int = 100
DECLARE @str_value varchar(10) = '10'

SELECT @str_value + @int_value

Result:
(No column name)
110


3. Using + operator to concatenate string

DECLARE @str1 varchar(10) = 'Microsoft'
DECLARE @str2 varchar(10) = 'SQL Server'

SELECT @str1 + ' ' + @str2

Result:
(No column name)
Microsoft SQL Server





Rank DataTable with LINQ C# Example

C# > LINQ > Rank

Example: Using LINQ to implement RANK function with DataTable.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public  DataTable RankDt(DataTable dt, string fld)
        {
            var rankDt = (from row in dt.AsEnumerable()
                            orderby row.Field<int>(fld) descending
                            select row).CopyToDataTable();

            rankDt.Columns.Add("Rank");
            int rank = 1;
            for (int i = 0; i < rankDt.Rows.Count - 1; i++)
            {
                rankDt.Rows[i]["Rank"] = rank;
                if (rankDt.Rows[i][fld].ToString() != rankDt.Rows[i + 1][fld].ToString())
                    rank++;
            }
            rankDt.Rows[rankDt.Rows.Count - 1]["Rank"] = rank;
            return rankDt;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();
            ds.Tables.Add("Product");
            DataTable dt = ds.Tables[0];
            dt.Columns.Add("name", typeof(string));
            dt.Columns.Add("quantity", typeof(Int32));
 
            DataRow dr = dt.NewRow();
            dr[0] = "Product 1" ;
            dr[1] = 500;
            dt.Rows.Add(dr);
            dr = dt.NewRow();

            dr[0] = "Product 2";
            dr[1] = 500;
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr[0] = "Product 3";
            dr[1] = 50;
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr[0] = "Product 4";
            dr[1] = 100;
            dt.Rows.Add(dr);

            dataGridView1.DataSource = RankDt(dt, "quantity");
        }
     }
}