Thursday 10 July 2014

Get all databases from SQL Server programatically using c#

 public class DatabasesDataContract
    {
        public int DBId { get; set; }
        public string DatabaseName { get; set; }
    }

public class ConnStringDataContract
    {
        [DataMember]
        public string Server { get; set; }
        [DataMember]
        public string InitialCatalog { get; set; }
        [DataMember]
        public string UserName { get; set; }
        [DataMember]
        public string Password{ get; set; }
    }

public List<DatabasesDataContract> GetAllDBinSQL(ConnStringDataContract objconn)
        {
            List<DatabasesDataContract> objGetDBs = new List<DatabasesDataContract>();
            DataSet _ds = new DataSet();
            SqlDataAdapter _sda = new SqlDataAdapter();
            try
            {
                string strConnString = string.Empty;
                string myServerAddress = objconn.Server;
                string myUsername = objconn.UserName;
                string myPassword = objconn.Password;

                strConnString = "Data Source=" + myServerAddress + ";User ID=" + myUsername + ";Password=" + myPassword;

                sqlcon = new SqlConnection(strConnString);
                string sqlcommand = "SELECT name, database_id FROM sys.databases";
                if (sqlcon.State == ConnectionState.Open)
                {
                    sqlcon.Close();
                }
                sqlcon.Open();
                _sda.SelectCommand = new SqlCommand(sqlcommand, sqlcon);
                _sda.Fill(_ds);
                sqlcon.Close();

                foreach (DataRow drow in _ds.Tables[0].Rows)
                {
                    DatabasesDataContract objddc = new DatabasesDataContract();
                    objddc.DatabaseName = drow["name"].ToString();
                    objddc.DBId = Convert.ToInt32(drow["database_id"].ToString());

                    objGetDBs.Add(objddc);
                }
            }
            catch (Exception ex) {

            }
            finally
            {
                if (sqlcon.State == ConnectionState.Open)
                {
                    sqlcon.Close();
                }
            }
            return objGetDBs;
        }

Get a table schema from a SQL table using C#

public List<TableDetailsDataContract> GetTableDetails(string tableName, string strConnString)
        {
            List<TableDetailsDataContract> ListTabledtls = new List<TableDetailsDataContract>();

            DataSet _ds = new DataSet();
            SqlDataAdapter _sda = new SqlDataAdapter();
            try
            {
                sqlcon = new SqlConnection(strConnString);
                string sqlcommand = "SELECT c.name AS 'Column Name', t.name AS 'Data type', c.max_length AS 'Max Length', c.is_nullable, ISNULL(i.is_primary_key, 0) AS 'Primary Key' FROM sys.columns AS c INNER JOIN sys.types AS t ON c.system_type_id = t.system_type_id LEFT OUTER JOIN sys.index_columns AS ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id LEFT OUTER JOIN sys.indexes AS i ON ic.object_id = i.object_id AND ic.index_id = i.index_id WHERE (c.object_id = OBJECT_ID('"+ tableName +"'))";
                if (sqlcon.State == ConnectionState.Open)
                {
                    sqlcon.Close();
                }
                sqlcon.Open();
                _sda.SelectCommand = new SqlCommand(sqlcommand, sqlcon);
                _sda.Fill(_ds);
                sqlcon.Close();

                foreach (DataRow drow in _ds.Tables[0].Rows)
                {
                    ListTabledtls.Add(new TableDetailsDataContract { Column = drow["Column Name"].ToString(), DataType = drow["Data type"].ToString(), IsNullable = Convert.ToBoolean(drow["is_nullable"]), size = Convert.ToInt32(drow["Max Length"].ToString()), isPrimaryKey = Convert.ToBoolean(drow["Primary Key"]) });
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (sqlcon.State == ConnectionState.Open)
                {
                    sqlcon.Close();
                }
            }
            return ListTabledtls;
        }

Get All table name from a sql server database using WCF

 public class ConnStringDataContract
    {
        [DataMember]
        public string Server { get; set; }
        [DataMember]
        public string InitialCatalog { get; set; }
        [DataMember]
        public string UserName { get; set; }
        [DataMember]
        public string Password{ get; set; }
    }
 -------------------------------------------------------------------------------------------------------
public List<TablesDataContract> GetTables(ConnStringDataContract objconn)
        {
            List<TablesDataContract> Tables = new List<TablesDataContract>();

            DataSet _ds = new DataSet();
            SqlDataAdapter _sda = new SqlDataAdapter();
            try
            {
                string strConnString = string.Empty;
                string myServerAddress = objconn.Server;
                string myUsername = objconn.UserName;
                string myPassword = objconn.Password;
                string myInitialCatalog = objconn.InitialCatalog;

                strConnString = "Data Source=" + myServerAddress + ";Initial Catalog=" + myInitialCatalog + ";User ID=" + myUsername + ";Password=" + myPassword;

                sqlcon = new SqlConnection(strConnString);
                string sqlcommand = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE (TABLE_TYPE = 'BASE TABLE')";
                if (sqlcon.State == ConnectionState.Open)
                {
                    sqlcon.Close();
                }
                sqlcon.Open();
                _sda.SelectCommand = new SqlCommand(sqlcommand, sqlcon);
                _sda.Fill(_ds);
                sqlcon.Close();
               
                foreach (DataRow drow in _ds.Tables[0].Rows)
                {
                    Tables.Add(new TablesDataContract { TableName = drow["TABLE_NAME"].ToString() });
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (sqlcon.State == ConnectionState.Open)
                {
                    sqlcon.Close();
                }
            }

            return Tables;
        }

Sunday 29 June 2014

LINQ - Set Operators

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.ComponentModel; 
using System.Xml.Linq; 
 
namespace SetOperators 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            LinqSamples samples = new LinqSamples(); 
 
            //Comment or uncomment the method calls below to run or not 
 
              samples.Linq46(); // This sample uses Distinct to remove  duplicate  elements in a sequence of factors of 300 
 
            //samples.Linq47(); // This sample uses Distinct to find the unique Category names 
 
            //samples.Linq48(); // This sample uses Union to create  one sequence that contains the unique values from both  
                                // arrays 
 
            //samples.Linq49(); // This sample uses the Union method to create  one sequence that contains the unique first  
                                // letter from both product and customer names. Union is only available through method  
                                // syntax 
 
            //samples.Linq50(); // This sample uses Intersect to create one sequence that contains the common values shared  
                                // by both arrays 
 
            //samples.Linq51(); // This sample uses Intersect  to create one sequence that contains the common first letter  
                                // from both product and customer names 
 
            //samples.Linq52(); // This sample uses Except to create a sequence that contains the values from numbersA that  
                                // are not also in numbersB 
 
            //samples.Linq53(); // This sample uses Except to create one  sequence that contains the 1st letters of product  
                                // names that are not also first letters of customer names 
        } 
 
        public class Product 
        { 
            public int ProductID { getset; } 
            public string ProductName { getset; } 
            public string Category { getset; } 
            public decimal UnitPrice { getset; } 
            public int UnitsInStock { getset; } 
        } 
 
        public class Order 
        { 
            public int OrderID { getset; } 
            public DateTime OrderDate { getset; } 
            public decimal Total { getset; } 
        } 
 
        public class Customer 
        { 
            public string CustomerID { getset; } 
            public string CompanyName { getset; } 
            public string Address { getset; } 
            public string City { getset; } 
            public string Region { getset; } 
            public string PostalCode { getset; } 
            public string Country { getset; } 
            public string Phone { getset; } 
            public string Fax { getset; } 
            public Order[] Orders { getset; } 
        } 
 
        class LinqSamples 
        { 
            private List<Product> productList; 
            private List<Customer> customerList; 
 
            [Category("Set Operators")] 
            [Description("This sample uses Distinct to remove duplicate elements in a sequence of " + 
                        "factors of 300.")] 
            public void Linq46() 
            { 
                int[] factorsOf300 = { 22355 }; 
 
                var uniqueFactors = factorsOf300.Distinct(); 
 
                Console.WriteLine("Prime factors of 300:"); 
                foreach (var f in uniqueFactors) 
                { 
                    Console.WriteLine(f); 
                } 
            } 
 
            [Category("Set Operators")] 
            [Description("This sample uses Distinct to find the unique Category names.")] 
            public void Linq47() 
            { 
                List<Product> products = GetProductList(); 
 
                var categoryNames = ( 
                    from prod in products 
                    select prod.Category) 
                    .Distinct(); 
 
                Console.WriteLine("Category names:"); 
                foreach (var n in categoryNames) 
                { 
                    Console.WriteLine(n); 
                } 
            } 
 
            [Category("Set Operators")] 
            [Description("This sample uses Union to create one sequence that contains the unique values " + 
                         "from both arrays.")] 
            public void Linq48() 
            { 
                int[] numbersA = { 0245689 }; 
                int[] numbersB = { 13578 }; 
 
                var uniqueNumbers = numbersA.Union(numbersB); 
 
                Console.WriteLine("Unique numbers from both arrays:"); 
                foreach (var n in uniqueNumbers) 
                { 
                    Console.WriteLine(n); 
                } 
            } 
 
            [Category("Set Operators")] 
            [Description("This sample uses the Union method to create one sequence that contains the unique first letter " + 
                         "from both product and customer names. Union is only available through method syntax.")] 
            public void Linq49() 
            { 
                List<Product> products = GetProductList(); 
                List<Customer> customers = GetCustomerList(); 
 
                var productFirstChars = 
                    from prod in products 
                    select prod.ProductName[0]; 
                var customerFirstChars = 
                    from cust in customers 
                    select cust.CompanyName[0]; 
 
                var uniqueFirstChars = productFirstChars.Union(customerFirstChars); 
 
                Console.WriteLine("Unique first letters from Product names and Customer names:"); 
                foreach (var ch in uniqueFirstChars) 
                { 
                    Console.WriteLine(ch); 
                } 
            } 
 
            [Category("Set Operators")] 
            [Description("This sample uses Intersect to create one sequence that contains the common values " + 
                        "shared by both arrays.")] 
            public void Linq50() 
            { 
                int[] numbersA = { 0245689 }; 
                int[] numbersB = { 13578 }; 
 
                var commonNumbers = numbersA.Intersect(numbersB); 
 
                Console.WriteLine("Common numbers shared by both arrays:"); 
                foreach (var n in commonNumbers) 
                { 
                    Console.WriteLine(n); 
                } 
            } 
 
            [Category("Set Operators")] 
            [Description("This sample uses Intersect to create one sequence that contains the common first letter " + 
                         "from both product and customer names.")] 
            public void Linq51() 
            { 
                List<Product> products = GetProductList(); 
                List<Customer> customers = GetCustomerList(); 
 
                var productFirstChars = 
                    from prod in products 
                    select prod.ProductName[0]; 
                var customerFirstChars = 
                    from cust in customers 
                    select cust.CompanyName[0]; 
 
                var commonFirstChars = productFirstChars.Intersect(customerFirstChars); 
 
                Console.WriteLine("Common first letters from Product names and Customer names:"); 
                foreach (var ch in commonFirstChars) 
                { 
                    Console.WriteLine(ch); 
                } 
            } 
 
            [Category("Set Operators")] 
            [Description("This sample uses Except to create a sequence that contains the values from numbersA" + 
                         "that are not also in numbersB.")] 
            public void Linq52() 
            { 
                int[] numbersA = { 0245689 }; 
                int[] numbersB = { 13578 }; 
 
                IEnumerable<int> aOnlyNumbers = numbersA.Except(numbersB); 
 
                Console.WriteLine("Numbers in first array but not second array:"); 
                foreach (var n in aOnlyNumbers) 
                { 
                    Console.WriteLine(n); 
                } 
            } 
 
            [Category("Set Operators")] 
            [Description("This sample uses Except to create one sequence that contains the first letters " + 
                         "of product names that are not also first letters of customer names.")] 
            public void Linq53() 
            { 
                List<Product> products = GetProductList(); 
                List<Customer> customers = GetCustomerList(); 
 
                var productFirstChars = 
                    from prod in products 
                    select prod.ProductName[0]; 
                var customerFirstChars = 
                    from cust in customers 
                    select cust.CompanyName[0]; 
 
                var productOnlyFirstChars = productFirstChars.Except(customerFirstChars); 
 
                Console.WriteLine("First letters from Product names, but not from Customer names:"); 
                foreach (var ch in productOnlyFirstChars) 
                { 
                    Console.WriteLine(ch); 
                } 
            } 
 
            public List<Product> GetProductList() 
            { 
                if (productList == null) 
                    createLists(); 
 
                return productList; 
            } 
 
            public List<Customer> GetCustomerList() 
            { 
                if (customerList == null) 
                    createLists(); 
 
                return customerList; 
            } 
 
            private void createLists() 
            { 
                // Product data created in-memory using collection initializer: 
                productList = 
                    new List<Product> { 
                    new Product { ProductID = 1, ProductName = "Chai", Category = "Beverages", UnitPrice = 18.0000M, UnitsInStock = 39 }, 
                    new Product { ProductID = 2, ProductName = "Chang", Category = "Beverages", UnitPrice = 19.0000M, UnitsInStock = 17 }, 
                    new Product { ProductID = 3, ProductName = "Aniseed Syrup", Category = "Condiments", UnitPrice = 10.0000M, UnitsInStock = 13 }, 
                    new Product { ProductID = 4, ProductName = "Chef Anton's Cajun Seasoning", Category = "Condiments", UnitPrice = 22.0000M, UnitsInStock = 53 }, 
                    new Product { ProductID = 5, ProductName = "Chef Anton's Gumbo Mix", Category = "Condiments", UnitPrice = 21.3500M, UnitsInStock = 0 }
                }; 
 
                // Customer/Order data read into memory from XML file using XLinq: 
                customerList = ( 
                    from e in XDocument.Load("Customers.xml"). 
                              Root.Elements("customer") 
                    select new Customer 
                    { 
                        CustomerID = (string)e.Element("id"), 
                        CompanyName = (string)e.Element("name"), 
                        Address = (string)e.Element("address"), 
                        City = (string)e.Element("city"), 
                        Region = (string)e.Element("region"), 
                        PostalCode = (string)e.Element("postalcode"), 
                        Country = (string)e.Element("country"), 
                        Phone = (string)e.Element("phone"), 
                        Fax = (string)e.Element("fax"), 
                        Orders = ( 
                            from o in e.Elements("orders").Elements("order") 
                            select new Order 
                            { 
                                OrderID = (int)o.Element("id"), 
                                OrderDate = (DateTime)o.Element("orderdate"), 
                                Total = (decimal)o.Element("total") 
                            }) 
                            .ToArray() 
                    }) 
                    .ToList(); 
            } 
        } 
    } 
} 

How to find a string within a jQuery or javascript string

Sometimes, you required to find a the existence of a small string with in a string. This article will  demonstarte , how could you do by...