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!

Friday, August 1, 2014

SQL SERVER CLR stored procedure

Short notes regarding how to begin with the CLR store procedure and help full reference links in the bottom.

View/Set the Database setting :

 select * from sys.dm_clr_properties  
 select * from sys.dm_clr_appdomains  
 select * from sys.dm_clr_loaded_assemblies  
 select * from sys.dm_clr_tasks  

Enabling the Clr in SQL Server.

 sp_configure 'show advanced options', 1;  
 GO  
 RECONFIGURE;  
 GO  
 sp_configure 'clr enabled', 1;  
 GO  
 RECONFIGURE;  
 GO

Creating StoreProcedure.

 USE database_name  
 GO  
 EXEC sp_changedbowner 'sa'  
 ALTER DATABASE database_name SET TRUSTWORTHY ON  
 CREATE ASSEMBLY Database2 FROM 'C:\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\Database2.dll';  
 create PROCEDURE SqlStoredProcedure11 AS EXTERNAL NAME Database2.StoredProcedures.SqlStoredProcedure1;  
 EXEC dbo.SqlStoredProcedure11  


Code Snippet:

using System;  
 using System.Data;  
 using System.Data.SqlClient;  
 using System.Data.SqlTypes;  
 using Microsoft.SqlServer.Server;  
 using DataTracker;  
 using System.Text;  
 public partial class StoredProcedures  
 {  
   [Microsoft.SqlServer.Server.SqlProcedure]  
   public static void SqlStoredProcedure1 ()  
   {  
     // Put your code here  
     SqlPipe sp;  
     sp = SqlContext.Pipe;  
     String strCurrentTime = "Current System DateTime is: "  
     + System.DateTime.Now.ToString();  
     sp.Send(strCurrentTime);  
   }  
 }  

Reference Link








Monday, July 21, 2014

REST vs SOAP

REST stands for REpresentational State Transfer (REST) which enforces a stateless client server design where web services are treated as resource and can be accessed and identified by there URL unlike SOAP web services which were defined by WSDL.
Web services written by applying REST Architectural concept are called RESTful web services which focus on System resources and how state of Resource should be transferred over http protocol.

SOAP
SOAP, originally defined as Simple Object Access Protocol, is a protocol specification for exchanging structured information in XML form.SOAP is protocol which relies on XML, that defines what is in the message and how to process it,set of encoding rules for data types, representation for procedure calls and responses.


REST vs SOAP

Before going for differences between two lets first see the differences in request header :

Sample SOAP & REST Request message for Weather Web Service :


 


SOAP vs REST Key Differences
Here are some of Key differences between SOAP and REST web Service :

  •  REST uses HTTP/HTTPS, SOAP can use almost any transport to send the request(for example we can have SOAP Messages over SMTP),  SOAP is a XML based messaging protocol.
  • REST is totally stateless operations where as SOAP supports statefull calls too. 
  • SOAP has more strict contract in the form of WSDL between applications, no such contract exists in case of REST.
  • AS REST APIs can be consumed using simple GET requests, RESTresponse can be cached, this is not possible with SOAP.
  • REST is Lighter, SOAP requires an XML wrapper around every request and response(SOAP Headers, XML tags etc). Thats why REST is preferred choice in mobile devices and PDA's
  •  SOAP message format is restricted to XML only where as REST supports other formats too for example JSON.  
  • REST is simpler in terms of development as compared to SOAP.
  • Browsers can handle REST easily as compared to SOAP as REST is based on HTTP where SOAP is another wrapper over HTTP.

Why to use SOAP ? 
SOAP provides some features like Security, Reliable Messaging, Atomic transaction which are not available in REST API.

  • WS-Security  & WS-SecureConversation  Provide support for using security tokens like Kerberos, and X.509.
  • WS-ReliableMessaging   Reliable messages delivery between distributed applications in case of failures.
  • WS-AtomicTransaction, two-phase commit across distributed transactional resources
  • In case where exact specification  of exchange format need to agreed between applications SOAP is better suitable.

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