Search This Blog

Monday, March 25, 2013

Handle NetworkAvailabilityChanged event in C# Windows Forms

C# > System.Net > NetworkInformation > NetworkChange > NetworkAvailabilityChanged

NetworkAvailabilityChanged occurs when the availability of the network changes.

Example

Check network available.

Edit Program.cs: Add event to check network is available






using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    static class Program
    {
        ///
        /// The main entry point for the application.
        ///

        private static void NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
        {
            if (e.IsAvailable)
            {
                MessageBox.Show ("Network Available");
            }
            else
            {
                MessageBox.Show("Network Unavailable");
            }
        }

        [STAThread]
        static void Main()
        {
            NetworkChange.NetworkAvailabilityChanged += NetworkAvailabilityChanged;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

Check network availability c#

C# >System.Net > NetworkInformation > NetworkInterface > GetIsNetworkAvailable


GetIsNetworkAvailable indicates whether any network connection is available.

Example
System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();





base keyword C#

C# > Keywords > Base

Base is used to access members of the base class from within a derived class

Example

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


namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        public class Animal
        {
            protected string type = "";
            public virtual string GetAnimalInfo()
            {
               return(type); 
            }
        }
        class Dog : Animal
        {
            private string name = "";
            public Dog(string name)
            {
                base.type = "dog";
                this.name = name;
            }
            public string GetAnimalInfo()
            {
                // Calling the base class GetInfo method:
                string type = base.GetAnimalInfo();
                return (name + " is a " + type);
            }
        }
        public Form2()
        {
            InitializeComponent();
        }
        private void Form2_Load(object sender, EventArgs e)
        {
            Dog dog = new Dog("Tashi");
            string AnimalInfo = dog.GetAnimalInfo(); // "Tashi is a dog"
         }
    }
}










this C#

C > Keywords > This

Refers to the current instance of the class.

Example

1.This is used to qualify the FirstName and LastName

class Person
{
            private string FirstName;
            private string LastName;
            
            public Person(string FirstName, string LastName)
           {
                this.FirstName = FirstName;
                this.LastName = LastName;
            }









Thursday, March 21, 2013

Insert values and create a temporary table from a dynamic query SQL Server

SQL Server > Scripts > Insert dynamic temp table

Global temporary tables are visible to any user and any connection after they are created, and are deleted when all users that are referencing the table disconnect from the instance of SQL Server

DECLARE @sql varchar(max)
IF object_id('tempdb.dbo.##MyTemp') Is Not Null
       DROP TABLE ##MyTemp
SET @sql =
'SELECT * INTO ##MyTemp FROM (select name from sys.all_objects ) as tbl'
Exec (@sql)
go
SELECT * FROM ##MyTemp





Modulo operator SQL Server

SQL Server > Operators > Modulo

Modulo operator (%)
Returns the remainder of one number divided by another


Example:

SELECT 39 % 7 AS Remainder

Result:
4





DATALENGTH SQL Server

SQL Server > Built-In Functions > DATALENGTH

Returns the number of bytes used to represent any expression
Example:

IF EXISTS(SELECT name FROM sys.tables
      WHERE name = 'test')
   DROP TABLE test;
GO

CREATE TABLE test
(
 c1 varchar(5),
 c2 char(5),
 c3 nvarchar(5)
);
GO

INSERT INTO test VALUES ('1', '1','1'), ('22', '22', '22'),('333', '333', '333');
GO
SELECT 
    DATALENGTH(c1) AS 'Varchar Column',
    DATALENGTH(c2) AS 'Char Column',
    DATALENGTH(c3) AS 'NVarChar Column'
FROM
    test;
GO

Result:

Varchar Column      Char Column  NVarChar Column
1                   5             2
2                   5             4
3                   5             6





Replicate SQL Server

SQL Server > Built-In Functions > REPLICATE

Repeats a string with specified number of times.





Example:

SELECT REPLICATE ('a',5)

Result:
aaaaa




STUFF function SQL Server

SQL Server > Built-in Functions > STUFF

STUFF inserts a string into another string
STUFF ( expression , start , length , replaceWith )

Example:
 
SELECT STUFF('abcdef', 1, 2, 'hg');

Result:
hgcdef

Wednesday, March 20, 2013

EXCEPT and INTERSECT SQL Server

SQL Server > Operators > EXCEPT AND INTERSECT

EXCEPT returns any distinct rows from the left query that are not also found on the right query.
INTERSECT returns any distinct rows that are returned by both the query on the left and right.

Example

 create table #t(name varchar(50))
insert into #t(name) values ('1')
insert into #t(name) values ('2')
insert into #t(name) values ('3')

create table #t1(name varchar(50))
insert into #t1(name) values ('1')
insert into #t1(name) values ('2')
insert into #t1(name) values ('5')

select * from #t
except
select * from #t1

--Result:
--name
--3

select * from #t
intersect
select * from #t1

--Result:
--name
--1
--2

drop table  #t
drop table  #t1





Union SQL Server

SQL Server > Operators > Union

Union combines the results of queries into a single result set.

The number of the columns must be the same in all queries.
The data types must be compatible.

All incorporates all rows into the results and includes duplicates. If not specified, duplicate rows are removed.

Example

create table #t(name varchar(50))
insert into #t(name) values ('1')
insert into #t(name) values ('2')
insert into #t(name) values ('3')

create table #t1(name varchar(50))
insert into #t1(name) values ('1')
insert into #t1(name) values ('4')
insert into #t1(name) values ('5')

select * from #t
union
select * from #t1

Result:
name
1
2
3
4
5

select * from #t
union all

select * from #t1

Result:
name
1
2
3
1
4
5

 





How to format datetime and date in Sql Server

SQL Server > Built-in Functions CONVERT

Examples to display date/time data in different formats.

SELECT convert(varchar, getdate(), 100) -- mon dd yyyy hh:miAM (or PM)
SELECT convert(varchar, getdate(), 101) -- mm/dd/yy
SELECT convert(varchar, getdate(), 102) -- yy.mm.dd
SELECT convert(varchar, getdate(), 103) -- dd/mm/yy
SELECT convert(varchar, getdate(), 104) -- dd.mm.yyyy
SELECT convert(varchar, getdate(), 105) -- dd-mm-yyyy
SELECT convert(varchar, getdate(), 106) -- dd mon yyyy
SELECT convert(varchar, getdate(), 107) -- mon dd, yyyy
SELECT convert(varchar, getdate(), 108) -- hh:mm:ss
SELECT convert(varchar, getdate(), 109) -- mon dd yyyy hh:mm:ss:mmmAM (or PM)
SELECT convert(varchar, getdate(), 110) -- mm-dd-yyyy
SELECT convert(varchar, getdate(), 111) -- yyyy/mm/dd
SELECT convert(varchar, getdate(), 112) -- yyyymmdd
SELECT convert(varchar, getdate(), 113) -- dd mon yyyy hh:mm:ss:mmm
SELECT convert(varchar, getdate(), 114) -- hh:mm:ss:mmm
SELECT convert(varchar, getdate(), 120) -- yyyy-mm-dd hh:mm:ss
SELECT convert(varchar, getdate(), 121) -- yyyy-mm-dd hh:mm:ss.mmm
SELECT convert(varchar, getdate(), 126) -- yyyy-mm-ddThh:mm:ss.mmm





Open Excel file C#

C# > Diagnostics > Process > Start


Starts a process resource.


Example


using System.Diagnostics;
Process.Start("Excel.exe", @"C:\MyExcelfile.xlsx");

Populating a DataSet and table from a DataAdapter C#

C# > Data >  Populating DataSet and DataTable

SQL Adapter to executes the SQL statement or stored procedure referenced in its SelectCommand and put the results into a table in the dataset.
Than you call data adapter's Fill method.  
If the dataset contains multiple tables, you should have separate data adapters for each table and must therefore fill each table separately.

Example:

SqlConnection con = new SqlConnection("connString");
SqlCommand com = new SqlCommand("exec your_stored_procedure", con);
com.CommandTimeout = 30;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = com;
con.Open();
DataSet ds = new DataSet();
da.Fill(ds, "Data");
DataTable dt = ds.Tables[0];
con.Close();