Saturday, November 7, 2015

Filling a combobox on selection of another combo box

This example code will explains how to fill a combo box on the selection of another combo box and also explains about the MVVM architecture pattern.

Simple way to understand the  MVVM architecture pattern.
Let us split the MVVM as
      M                     V                       VM
  (model)             (View)               (ViewModel)
(model.cs)        (XAML file)          (ViewModel.cs)

For an example let us consider , there are two combo box , in one combo box we are filling list of countries and on selection of first combobox second combobox will be filled with the country specific languages. In addition to it let us have one text box which is going to show the country currency.

Take a look on Designing the classes.
MODEL : We are going to write methods which brings countries lists.
VIEWMODEL: An another class which contains the Property of display member of MODEL class to show on UI (VIEW)
VIEW: XAML binding of VIEWMODEL.

XAML file
<?xml version="1.0" encoding="utf-8"?>  
 <Window  
   x:Class="MvvmCombo.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
   Title="MvvmCombo"  
   Height="417"  
   Width="496">  
   <Grid  
     Name="mGrid"  
     HorizontalAlignment="Left"  
     VerticalAlignment="Top"  
     Width="479"  
     Height="374">  
     <ComboBox        
       ItemsSource="{Binding Countries}"         
       SelectedItem="{Binding SelectedCountry}"  
       DisplayMemberPath="DisplayName"  
       Grid.Column="1"  
       Grid.Row="1"  
       HorizontalAlignment="Left"  
       VerticalAlignment="Top"  
       Margin="10.99999999687,1.5,0,0"  
       Width="208"  
       Height="27"  
       SelectedIndex="0" />  
     <ComboBox  
       ItemsSource="{Binding Lang}"  
       Grid.Column="1"  
       Grid.Row="2"  
       HorizontalAlignment="Left"  
       VerticalAlignment="Top"  
       Margin="10.99999999687,3.50000000000006,0,0"  
       Width="208"  
       Height="26"  
       SelectedIndex="{Binding SelectedIndex}" />  
     <TextBox  
       Name="txtCur"  
       Text="{Binding Currency}"  
       IsReadOnly="True"  
       Height="29"  
       Width="208"  
       Margin="10.99999999687,3.50000000000007,0,0"  
       VerticalAlignment="Top"  
       HorizontalAlignment="Left"  
       Grid.Row="3"  
       Grid.Column="1" />  
     <Label  
       Content="Countries"  
       Grid.Column="0"  
       Grid.Row="1"  
       HorizontalAlignment="Left"  
       VerticalAlignment="Stretch"  
       Margin="8,1.5,0,5.49999999999994"  
       Width="65"  
       Height="27" />  
     <Label  
       Content="Language"  
       Grid.Column="0"  
       Grid.Row="2"  
       HorizontalAlignment="Left"  
       VerticalAlignment="Stretch"  
       Margin="8,5.00000000000006,0,5.49999999999993"  
       Width="65"  
       Height="24.5" />  
     <Label  
       Grid.Column="0"  
       Grid.Row="3"  
       HorizontalAlignment="Left"  
       VerticalAlignment="Stretch"  
       Margin="8,3.50000000000007,0,8.50000000000004"  
       Width="54"  
       Height="29"  
       Content="Currency" />  
     <TextBox  
       Name="txtCurSym"  
       IsReadOnly="True"  
       Text="{Binding CurrencySym}"  
       Grid.Column="1"  
       Grid.Row="3"  
       HorizontalAlignment="Stretch"  
       VerticalAlignment="Top"  
       Margin="251.635641460119,3.50000000000009,94.1004888627257,0"  
       Width="46"  
       Height="30" />  
     <Grid.ColumnDefinitions>  
       <ColumnDefinition  
         Width="0.182179268637068*" />  
       <ColumnDefinition  
         Width="0.817820731362932*" />  
     </Grid.ColumnDefinitions>  
     <Grid.RowDefinitions>  
       <RowDefinition  
         Height="0.0971428571428572*" />  
       <RowDefinition  
         Height="0.106124505217704*" />  
       <RowDefinition  
         Height="0.0992443324937027*" />  
       <RowDefinition  
         Height="0.102439726520331*" />  
       <RowDefinition  
         Height="0.0988269161568912*" />  
       <RowDefinition  
         Height="0.0856423173803527*" />  
       <RowDefinition  
         Height="0.410579345088161*" />  
     </Grid.RowDefinitions>  
   </Grid>  
 </Window>  


MODEL FILE
 using System;  
 using System.Collections;  
 using System.Collections.Generic;  
 using System.Globalization;  
 using System.Linq;  
 using System.Text;  
 using System.Threading.Tasks;  
 namespace MvvmCombo  
 {  
   class Model  
   {  
     public Model()  
     {  
     }  
     public List<RegionInfo> GetCountries()  
     {  
       RegionInfo country = new RegionInfo(new CultureInfo("en-US", false).LCID);  
       List<RegionInfo> countryNames = new List<RegionInfo>();  
       foreach (CultureInfo cul in CultureInfo.GetCultures(CultureTypes.SpecificCultures))  
       {  
         country = new RegionInfo(new CultureInfo(cul.Name, false).LCID);  
         countryNames.Add(country);          
       }  
       return countryNames.OrderBy(names => names.DisplayName).Distinct().ToList();  
     }  
     public List<CultureInfo> GetCountriesAll()  
     {  
       List<CultureInfo> list = new List<CultureInfo>();  
       foreach (System.Globalization.CultureInfo ci in   
         System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.AllCultures))  
       {         
         list.Add(System.Globalization.CultureInfo.CreateSpecificCulture(ci.Name));  
       }  
       return list;  
     }  
   }  
 }  
\
ViewModel File
using System;  
 using System.Collections.Generic;  
 using System.Globalization;  
 using System.Linq;  
 using System.Text;  
 using System.Threading.Tasks;  
 using System.ComponentModel;  
 using System.Collections.ObjectModel;  
 namespace MvvmCombo  
 {  
   class ViewModel :INotifyPropertyChanged  
   {  
     public event PropertyChangedEventHandler PropertyChanged;   
     private RegionInfo _ri;  
     private Model _m;  
     private void OnPropertyChanged(string propertyName)  
     {  
       if (PropertyChanged != null)  
         PropertyChanged(this, new PropertyChangedEventArgs(propertyName));  
     }  
     public ViewModel(Model m)  
     {  
       _m = m;  
     }  
     private List<CultureInfo> _allCul;  
     public List<RegionInfo> Countries  
     {  
       get  
       {  
         _allCul = _m.GetCountriesAll();  
         return _m.GetCountries(); ;  
       }  
     }  
     private List<string> _lang;  
     public List<string> Lang  
     {  
       get  
       {  
         return _lang;  
       }  
     }  
     public List<string> FillLanguage()  
     {  
       return _lang =  
         _allCul.Where(c => c.EnglishName.Contains(_ri.EnglishName))  
         .Select(c=>c.EnglishName.IndexOf("(")>-1?c.EnglishName.Substring(0,c.EnglishName.IndexOf("(")):  
           c.EnglishName).Distinct().ToList();  
     }  
     private string _currencySym;  
     public string CurrencySym  
     {  
       get  
       {  
         return _currencySym;  
       }  
       set  
       {  
       }  
     }  
     public object SelectedCountry  
     {  
       set  
       {  
         _ri = value as RegionInfo;  
         FillLanguage();          
         _currencySym = _ri.CurrencySymbol;  
         OnPropertyChanged("Lang");  
         OnPropertyChanged("CurrencySym");  
       }  
     }  
   }  
 }  

Friday, October 30, 2015

When and how to use Delegate?

A delegate is a reference to a method. Whereas objects can easily be sent as parameters into methods, constructor or whatever, methods are a bit more tricky. But every once in a while you might feel the need to send a method as a parameter to another method, and that's when you'll need delegates.

 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 using MyLibrary;  

 namespace DelegateApp {  
  /// <summary>  
  /// A class to define a person  
  /// </summary>  
  public class Person {  
   public string Name { get; set; }  
   public int Age { get; set; }  
  }  

  class Program {  
    //Our delegate  
    public delegate bool FilterDelegate(Person p);  
    static void Main(string[] args) {  
    //Create 4 Person objects  
    Person p1 = new Person() { Name = "John", Age = 41 };  
    Person p2 = new Person() { Name = "Jane", Age = 69 };  
    Person p3 = new Person() { Name = "Jake", Age = 12 };  
    Person p4 = new Person() { Name = "Jessie", Age = 25 };  
    //Create a list of Person objects and fill it  
    List<Person> people = new List<Person>() { p1, p2, p3, p4 };  
    DisplayPeople("Children:", people, IsChild);  
    DisplayPeople("Adults:", people, IsAdult);  
    DisplayPeople("Seniors:", people, IsSenior);  
    Console.Read();  
   }  
   /// <summary>  
   /// A method to filter out the people you need  
   /// </summary>  
   /// <param name="people">A list of people</param>  
   /// <param name="filter">A filter</param>  
   /// <returns>A filtered list</returns>  
   static void DisplayPeople(string title, List<Person> people, FilterDelegate filter) {  
     Console.WriteLine(title);  
     foreach (Person p in people) {  
     if (filter(p)) {  
       Console.WriteLine("{0}, {1} years old", p.Name, p.Age);  
     }  
    }  
    Console.Write("\n\n");  
   }  
   //==========FILTERS===================  
   static bool IsChild(Person p) {  
    return p.Age <= 18;  
   }  
   static bool IsAdult(Person p) {  
    return p.Age >= 18;  
   }  
   static bool IsSenior(Person p) {  
    return p.Age >= 65;  
   }  
  }  
 }  

Monday, August 31, 2015

Brief about Multithreading

Asynchronous processing and background processing was always a must for serious programs serving complex user needs.

Threading design guidelines.
  1. Avoid providing static methods that mutate static state
  2. Design for server environment
  3. Instances do not need to be thread safe
  4. Static states must be thread safe
Timer threads
A common use of threads is for all kinds of periodical updates. Under Win32 we have two different ways: window timers and time limited waiting for events. .NET offers three different ways:

Windows timers with the System.WinForms.Timer class
Periodical delegate calling with System.Threading.Timer class (works on W2K only)
Exact timing with the System.Timers.Timer class

System.Timers.Timer class is the most complete solution for all time fired events. It gives you the most precise control and timing and is surprisingly simple to use.
  1. Create the Timer object. You can a use constructor with interval setting.
  2. Add your event handler (delegate) to the Tick event
  3. Set the Interval property to the desired number of milliseconds (default value is 100 ms)
  4. Set the AutoReset property to false if you want the event to be raised only once (default is true – repetitive raising)
  5. Start the ticking with a call to the Start() method, or by setting Enabled property to true.
  6. Stop the ticking with call to the Stop() method or by setting the Enabled property to false.

  using System.Timers ;   
  void TickHandler( object sender, EventArgs e ){   
    // do some work   
  }   
  // usage block   
  {   
    ...   
    // create timer   
    Timer kicker = new Timer() ;   
    kicker.Interval = 1000 ;   
    kicker.AutoReset = false ;   
    // add handler   
    kicker.Tick += new EventHandler( TickHandler ) ;   
    // start timer   
    kicker.Start() ;   
    // change interval   
    kicker.Interval = 2000 ;   
    // stop timer   
    kicker.Stop() ;   
    // you can start and stop timer againg  
      kicker.Start() ;  
      kicker.Stop() ;  
      ...  
 }  

I should mention a few things about using the Timers.Timer class:
  1. In VS Beta 1 you must add a reference to System.Timers namespace by hand.
  2. Whenever you use the Timers namespace together with System.WinForms or System.Threading, you should reference the Timer classes with the full name to avoid ambiguity.
  3. Be careful when using Timers.Timer objects. You may find them a lot faster than the old windows timers approach (think why). Do not forget synchronize data access.

Thread pooling

The idea for making a pool of threads on the .NET framework level comes from the fact that most threads in multithreaded programs spend most of the time waiting for something to happen. It means that thread entry functions contain endless loops which calls real working functions. By using the ThreadPool type object preparing working functions is simpler and for bonus we get better resource usage.

There are two important facts relating to ThreadPool object.
  1. There is only one ThreadPool type object per process
  2. There is only one working thread per thread pool object
The most useful use of a ThreadPool object is to add a new thread with a triggering event to the thread pool. i.e.. "when this event happens do this". For using ThreadPool this way you must perform following steps:
  1. Create event
  2. Create a delegate of type WaitOrTimerCallback
  3. Create an object which will carry status information to the delegate.
  4. Add all to thread pool
  5. Set event
// status information object
public class StatusObject{ // some information } // thread entry function public void someFunc( object obj, bool signaled ){ // do some clever work } // usage block { ... // create needed objects AutoResetEvent myEvent = new AutoResetEvent( false ) ; WaitOrTimerCallback myThreadMethod = new WairOrTimerCallback( someFunc ) ; StatusObject statusObject = new StatusObject() ; // decide how thread will perform int timeout = 10000 ; // timeout in ms bool repetable = true ; // timer will be reset after event fired or timeout // add to thread pool ThreadPool.RegisterWaitForSingleObject( myEvent, myThreadMethod, statusObject, timeout, repetable ) ; ... // raise event and start thread myEvent.Set() ; ... }

A less common use of a thread pool will be (or at least should be, be aware of misuse) adding threads to be executed when the processor is free. You could think of this kind of usage as "OK, I have this to do, so do it whenever you have time". Very democratic way of handling background processing which can stop your program quickly. Remember that inside the thread pool you have only one thread working (per processor).

Using thread pool this way is even simpler:
  1. Create a delegate of type WaitCallback
  2. Create an object for status information, if you need it
  3. Add to thread pool

// status information object  
 public class StatusObject{  
      // some information  
 }  
 // thread entry function  
 public void someFunc( object obj, bool signaled ){  
      // do some clever work  
 }  
 // usage block  
 {  
      ...  
      // create needed objects  
      WaitCallback myThreadMethod = new WairOrTimerCallback( someFunc ) ;  
      StatusObject statusObject = new StatusObject() ;  
      // add to thread pool  
      ThreadPool.QueueUserWorkItem( myThreadMethod, statusObject ) ;  
      ...  
 }  

Some notes on thread pool:
  1. Don’t use a thread pool for threads that perform long calculations. You only have one thread per processor actually working.
  2. System.Thread.Timer type objects are one thread inside thread pool
  3. You have only one thread pool per process

Thursday, May 28, 2015

EBCDIC To ASCIIFile Converter Code C#


This code is written in C# to convert EBCDIC  to ASCII



using System;  
 using System.Collections.Generic;  
 using System.Text;  
 using System.IO;  
 using System.Text.RegularExpressions;  
 namespace ConsoleApplication1  
 {  
   class Program  
   {  
     static void Main()  
     {  
       StreamReader sr = new StreamReader("d:\\LAB\\CXAR2.block.txt");  
       StreamWriter sw = new StreamWriter("d:\\LAB\\CXAR2.DAT.ascii");  
       EBCDIC2ASCII obj = new EBCDIC2ASCII();  
       string line = "";  
       //char[] buffer=new char[256];  
       //byte[] bufferByte = new byte[256];   
       int i = 0;  
       while (!(sr.EndOfStream))  
       {  
         line = sr.ReadLine();  
         byte[] bufferByte = obj.EBCDIC_1(line);  
         char[] buffer = new char[bufferByte.Length - 1];  
         for (i = 0; i < bufferByte.Length - 1; i++)  
         {  
           buffer[i] = (char)bufferByte[i];  
         }  
         sw.WriteLine(buffer);  
       }  
       sr.Close();  
       sw.Close();  
     }  
   }  
   class EBCDIC2ASCII  
   {  
     public byte[] EBCDIC_1(string line)  
     {  
       string ebcdicTable = "@KMNPZ[\\]^_`akloz{|}ÀÁÂÃÄÅÆÇÈÉÑÒÓÔÕÖ×ØÙàâãäåæçèéðñòóôõö÷øùЁ‚ƒ„…†‡ˆ‰‘’“”•–—˜™¢£¤¥¦§¨©¬mjnLº»°~";  
       string asciiTable = " .(+&!$*); -/,%?:#@'\"{ABCDEFGHIJKLMNOPQR\\STUVWXYZ0123456789}abcdefghijklmnopqrstuvwxyzD_|><[]^=";  
       const byte space = (byte)32;  
       const byte tilde = (byte)126;  
       Regex rx = new Regex("");  
       string[] inBufChar = rx.Split(line);  
       List<char> lstInBuff = new List<char>();  
       List<byte> lstInBuff_Byte = new List<byte>();  
       char chrInBuff;  
       int i = 0;  
       for (i = 0; i < inBufChar.Length - 1; i++)  
       {  
         if (inBufChar[i] == "") { continue; }  
         chrInBuff =char.Parse(inBufChar[i]);  
         lstInBuff_Byte.Add((byte)chrInBuff);            
       }  
       //char[] inBufChar1 = new char[256];  
       byte[] inBuf = lstInBuff_Byte.ToArray();  
       byte[] outBuf = new byte[inBuf.Length-1];   
       for ( i = 0; i < line.Length-1; i++)  
       {  
         int inCharPos = ebcdicTable.IndexOf((char)inBuf[i]);  
         if (inCharPos == -1)  
         {  
           // Unknown EBCDIC character  
           outBuf[i] = space;  
         }  
         else  
         {  
           outBuf[i] = (byte)asciiTable[inCharPos];  
           if (outBuf[i] < space ||  
             outBuf[i] > tilde)  
           {  
             // Out of range ASCII character.  
             // Should never happen, as the translation table  
             // has no control or high-order characters on the  
             // output side ... but, just in case.  
             outBuf[i] = space;  
           }  
         }  
       }  
       return outBuf;  
     }  
     public byte[] EBCDICToASCIIFile(byte[] buffer,int recordLength)  
     {  
       byte[] outBuffer = BuildRecord(buffer, recordLength);  
       //fsOut.Write(outBuffer, 0, outBuffer.Length);           
       return outBuffer;  
     }  
     protected byte[] BuildRecord(byte[] buf, int record)  
     {  
       byte[] outBuf = new byte[256]; // Output record length  
       int outPos = 0;  
       outPos += CopyRange(buf, outBuf, 0, 12, outPos);              // Cust ID, district  
       if (outPos != outBuf.Length - 2)  
       {  
         //throw new ApplicationException(String.Format("BuildRecord(): Internal error at record {0}: {1} bytes have been written to output record, should be {2}.",  
         //record,  
         //outPos,  
         //outBuf.Length - 2));  
       }  
       // Add CR/LF  
       outBuf[outBuf.Length - 2] = (byte)13;  
       outBuf[outBuf.Length - 1] = (byte)10;  
       return outBuf;  
     }  
     protected int CopyRange(byte[] inBuf,  
          byte[] outBuf,  
          int start,  
          int length,  
          int outStart)  
     {  
       string ebcdicTable = "@KMNPZ[\\]^_`akloz{|}ÀÁÂÃÄÅÆÇÈÉÑÒÓÔÕÖ×ØÙàâãäåæçèéðñòóôõö÷øùЁ‚ƒ„…†‡ˆ‰‘’“”•–—˜™¢£¤¥¦§¨©¬mjnLº»°~";  
       string asciiTable = " .(+&!$*); -/,%?:#@'\"{ABCDEFGHIJKLMNOPQR\\STUVWXYZ0123456789}abcdefghijklmnopqrstuvwxyzD_|><[]^=";  
       const byte space = (byte)32;  
       const byte tilde = (byte)126;  
       for (int i = 0; i < length; i++)  
       {  
         int outPos = outStart + i;  
         int inCharPos = ebcdicTable.IndexOf((char)inBuf[start + i]);  
         if (inCharPos == -1)  
         {  
           // Unknown EBCDIC character  
           outBuf[outPos] = space;  
         }  
         else  
         {  
           outBuf[outPos] = (byte)asciiTable[inCharPos];  
           if (outBuf[outPos] < space ||  
             outBuf[outPos] > tilde)  
           {  
             // Out of range ASCII character.  
             // Should never happen, as the translation table  
             // has no control or high-order characters on the  
             // output side ... but, just in case.  
             outBuf[outPos] = space;  
           }  
         }  
       }  
       return length;  
     }  
   }  
 }  

Thursday, May 7, 2015

DataBinding WPF


Here we look an example of simple data binding in WPF. In this example I use a class for Data Binding. Here we look at the program.

Step1: First we create a Grid in our project:
<Grid x:Name="StuInfo">
     <Grid.ColumnDefinitions>
          <ColumnDefinition Width="Auto" MinWidth="77"></ColumnDefinition>
          <ColumnDefinition></ColumnDefinition>
     </Grid.ColumnDefinitions>
     <Grid.RowDefinitions>
          <RowDefinition></RowDefinition>
          <RowDefinition></RowDefinition>
          <RowDefinition></RowDefinition>
          <RowDefinition></RowDefinition>
          <RowDefinition></RowDefinition>
     </Grid.RowDefinitions>
</Grid>

Step2: After that we create two TextBlocks and Two TextBoxes in our program and we also create a Button (Next) to see the Next Record according to the program.
 
<TextBlock Text="First Name" Margin="10"></TextBlock>
<TextBlock Text="Last Name" Margin="10" Grid.Row="1"></TextBlock>
<TextBox Text="{Binding fname}" Margin="10" Grid.Column="1"></TextBox>
<TextBox Text="{Binding lname}" Margin="10" Grid.Column="1"  Grid.Row="1"></TextBox>
<Button HorizontalAlignment="Left" Margin="0,12,0,9" Name="button1" Width="75"Grid.Column="1" Grid.Row="2">Next</Button>

1.png

Step3: Now we add a Loaded Event handler in the .cs page. This event will be called when the client wants to load the application:
 
public partial class Window1 : Window
{
   
public Window1()
   {
        InitializeComponent();
        this.Loaded += new RoutedEventHandler(Page_Loaded);
   }
   void Page_Loaded(object sender, RoutedEventArgs e)
   {

   }
}

Step4: Now we add a class to our program:
public class Stu{
    public string fname { getset; }
    public string lname { getset; }
}  


Step5: Now we write the following code in the Loded Event Handler:
 
void Page_Loaded(object sender, RoutedEventArgs e)
{
   Stu s = new Stu();
    {
      s.fname = "Viji";
      s.lname = "Karg";
    };
      this.StuInfo.DataContext = s;
}

As we mention Binding in TextBox in .xaml page :
 
<TextBox Text="{Binding fname}" Margin="10" Grid.Column="1"></TextBox>
<TextBox Text="{Binding lname}" Margin="10" Grid.Column="1"  Grid.Row="1"></TextBox>



Step6: Now we add another Event Handler, which is for the Next Button:
 
public Window1()
{
   InitializeComponent();
   this.Loaded += new RoutedEventHandler(Page_Loaded);
   this.button1.Click += new RoutedEventHandler(button1_Click);
}
void
 button1_Click(object sender, RoutedEventArgs e)
{
   Stu s = new Stu();
    {
       s.fname = "Sid";
       s.lname = "hari";
    };
   this.StuInfo.DataContext = s;
}

Here we add another data in our program. When we click on the Next Button, the output will be:

Thursday, March 12, 2015

Database models

List of Database models is available from this url.

http://databaseanswers.org/data_models/

Friday, February 6, 2015

Dynamically create insert statement to insert records of DataTable into DataBase table


Useful when exporting the records from one Database(Oracle) to another Database(Oracle) table .


 using Oracle.DataAccess.Client;  

public static void Create_ORA_Entry(string connStr, DataTable dataTable, string tableName)  
     {  
       DataTable dt_dest = Db.ExecuteDataTable_ORACLE(connStr, "select * from tableName where [column_ID]=" + dataTable.Rows[0]["COLUMN_ID"].ToString(), "tableName");  
       if (dt_dest.Rows.Count > 0)  
       {  
         return; //record already exists! no action taken.   
       }  
       string columns = string.Join(","  
       , dataTable.Columns.Cast<DataColumn>().Where(c => dt_dest.Columns.Contains(c.ColumnName)).Select(c => c.ColumnName));  
       string values = string.Join(","  
       , dataTable.Columns.Cast<DataColumn>().Where(c => dt_dest.Columns.Contains(c.ColumnName)).Select(c => string.Format(":{0}", c.ColumnName)));  
       String sqlCommandInsert = string.Format("INSERT INTO {0} ({1}) VALUES ({2})", tableName, columns, values);  
       using (var con = new OracleConnection(connStr))  
       using (var cmd = new OracleCommand(sqlCommandInsert, con))  
       {  
         con.Open();  
         foreach (DataRow row in dataTable.Rows)  
         {  
           cmd.Parameters.Clear();  
           foreach (DataColumn col in dataTable.Columns.Cast<DataColumn>().Where(c=>dt_dest.Columns.Contains(c.ColumnName)))  
           {  
             cmd.Parameters.Add(col.ColumnName, row[col]);  
           }  
           int inserted = cmd.ExecuteNonQuery();  
         }  
       }  
     }  


public static DataTable ExecuteDataTable_ORACLE(string dataConnectionString,  
               string sql, string tableName)  
     {  
       OracleDataAdapter oraAD = new OracleDataAdapter(sql, dataConnectionString);  
       DataTable dt = new DataTable(tableName);  
       try  
       {  
         oraAD.Fill(dt);  
       }  
       catch (Exception ex)  
       {  
         throw ex;  
       }  
       finally  
       {  
         oraAD.Dispose();  
       }  
       return dt;  
     }  




Wednesday, February 4, 2015

Office Update breaks ActiveX controls

It seems that a recent Office update has broken ActiveX controls on worksheets. The symptoms include (but are probably not limited to):
  1. the program used to create this object is forms. that program is not installed on your computer
  2. Being unable to use or change properties of any active controls on worksheets
  3. Error messages saying “Can’t insert object”
  4. Error 438 when trying to refer to an activex control as a member of a worksheet in code
To fix it, do this:


  1. Close all Office applications.
  2. Do a search in Windows Explorer – make sure to include hidden and system files and folders – for *.exd files (note: that’s not *.exe !!) and delete any you find Or run this script by doing copy to text file then rename .txt to .bat. 
  3.  DEL %appdata%\microsoft\forms\MSForms.exd  
     DEL %temp%\excel8.0\MSForms.exd  
     DEL %temp%\word8.0\MSForms.exd  
     DEL %temp%\PPT11.0\MSForms.exd  
     DEL %temp%\vbe\MSForms.exd  
     PAUSE  
  4. Restart your Office apps and test the controls again.

Please note that the .exd files will be recreated when you next use a workbook with an embedded active control – this is quite normal and should not cause you a problem!

Code Formater

Paste Here Your Source Code
Source Code Formatting Options
1) Convert Tab into Space :
2) Need Line Code Numbering :
3) Remove blank lines :
4) Embeded styles / Stylesheet :
5) Code Block Width :
6) Code Block Height :
7) Alternative Background :
Copy Formatted Source Code
 
Preview Of Formatted Code