Simple example of configuring Enterprise library Caching Block.

Download the Enterprise Library 5 from here

http://www.microsoft.com/en-in/download/details.aspx?id=15104

Create a new windows application.

We need the configuration information to setup the caching.

Open the EntLib Configuration console.

Open the app.config file of the windows application created.

Select Blocks à Add Caching Settings

It will add the required configuration information to the config file of the windows application.

Sample code implementing Caching block to save dictionary object in Cache.


public static class Configuration
{
public static Dictionary<string, string> GetConfigSettings()
{
// get the cache manager
ICacheManager cacheManager = CacheFactory.GetCacheManager();
var configSettings = (Dictionary<string, string>)cacheManager["configSettings"];

if (configSettings == null)
{
configSettings = new Dictionary<string, string>();
configSettings.Add("key1", "value1");
configSettings.Add("key2", "value2");

// add the dictionary object
cacheManager.Add("configSettings", configSettings);
}
else
{
// get from the configsettings object from the cache
configSettings = (Dictionary<string, string>) cacheManager["configSettings"];
}

return configSettings;
}
}

Bye.

 

 

The type initializer for ‘System.Data.SqlClient.SqlConnection’ threw an exception

I was getting the above error in one of my windows application. Was because of some section getting repeated in the app.config file.

Removing the duplicate section information from the app.config resolved the issue.

Sample code for Inserting a lead record from a .NET application : Oracle CRM On Demand

First download the wsdl file for the lead record from Oracle CRM On Demand web application.

Add web references to it within a .NET windows application.

Use the following code for inserting the lead record.

We need to specify value for all the required field for the record to get inserted.

        String loginUrlString = "https://secure-ausomxapa.crmondemand.com/Services/Integration?command=login&quot;;
        String logoffUrlString ="https://secure-ausomxapa.crmondemand.com/Services/Integration?command=logoff&quot;;
        String siebelUserName = "username/password";
        String siebelPassword ="password";
        String opportunityUrl = "https://secure-ausomxapa.crmondemand.com/Services/Integration;jsessionid=&quot;;
        String sessionID = "";
      
        Private void Form1_Load(Object sender, EventArgs e)
        {            
            // Get the session from the helper Class ManageSession
             sessionID = ManageSession.Login(loginUrlString, siebelUserName, siebelPassword);

            //Create the New lead record instandce And Set its url With proper session id
             Lead myLead = New Lead();
             myLead.Url = "https://secure-ausomxapa.crmondemand.com/Services/Integration;jsessionid=&quot; + sessionID;

            // create arrary Of lead record To be inserted
             LeadData[] myLeadData = New LeadData[1];
             myLeadData[0] = New LeadData();
             myLeadData[0].LeadFirstName = "Nishant";
             myLeadData[0].LeadLastName = "Rana";
             myLeadData[0].Source = "Email";
             myLeadData[0].dLead_Generation_Date = Convert.ToDateTime("7/30/2010");
             myLeadData[0].LeadOwner = "Nishant Rana";
             myLeadData[0].dLead_Generation_dateSpecified = True;             

            // add lead data array To listofLeadData Class
             ListOfLeadData myLstLeadData = New ListOfLeadData();
             myLstLeadData.Lead = myLeadData;

            // create an instance Of leadinsert_input Class
            LeadInsert_Input myLeadRecordInput = New LeadInsert_Input();
            myLeadRecordInput.ListOfLead = myLstLeadData;
            LeadInsert_Output myLeadRecordOutput = myLead.LeadInsert(myLeadRecordInput);    
        }

 

 

The sample code for the ManageSession.cs class

 class ManageSession
    {
        public static string SessionID = "";
        public static String Login(String loginUrlString, String userName, String password)
        {
            try
            {
                // create a http request and set the headers for authentication
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(loginUrlString);
                HttpWebResponse myResponse;
                myRequest.Method = "POST";
                // passing username and password in the http header 
                // username format if it includes slash should be the forward slash /
                myRequest.Headers["UserName"] = userName;
                myRequest.Headers["Password"] = password;
                myResponse = (HttpWebResponse)myRequest.GetResponse();
                Stream sr = myResponse.GetResponseStream();
                // retrieve session id
                char[] sep = { ‘;’ };
                String[] headers = myResponse.Headers["Set-Cookie"].Split(sep);
                for (int i = 0; i <= headers.Length – 1; i++)
                {
                    if (headers[i].StartsWith("JSESSIONID"))
                    {
                        sep[0] = ‘=’;
                        SessionID = headers[i].Split(sep)[1];
                        break;
                    }
                }
                sr.Close();
                myResponse.Close();
            }
            catch (WebException webException)
            {
                return webException.Message;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            // send back the session id that should be passed to subsequent calls 
            // to webservices 
            return SessionID;
        }

        public static String Logoff(String logoffUrlString, string SessionID)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(logoffUrlString);          
            // set the session id in header
            req.Headers["JSESSIONID"] = SessionID;
            // make the HTTP call
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            return resp.StatusCode.ToString();

        }
    }

 

Hope it helps !

Bye..

Preventing your system from getting auto locked

Within most of the organization, there is a default setting that after a few minutes have escaped, the system gets locked itself, if system is left unattended. Well to prevent this i have written a small utility (windows application) which periodically sends user input to the system, making it to believe that some mouse movement has been made and thus stopping the system from getting locked.

Here we would be calling SendInput function within user32.dll

The SendInput function synthesizes keystrokes, mouse motions, and button clicks and that is what we need.

http://msdn.microsoft.com/en-us/library/ms646310.aspx

This is useful in case we are giving presentation or else reading some documents …

Following is the code for the same

1) Create a new windows application in C#

2) Add a button named btn_Unlock to it and a timer control named timer1.

3) Set enabled to false and interval to 120000 for timer control.

4) Put the following code to your form class


public partial class frmKU : Form

{

public
frmKU()

{

InitializeComponent();

}

[DllImport(“User32.dll”, SetLastError = true)]

public static extern int SendInput(int
nInputs, ref INPUT
pInputs, int cbSize);

public struct INPUT

{

public
int type;

public
MOUSEINPUT mi;

}

public struct MOUSEINPUT

{

public
int dx;

public
int dy;

public
int mouseData;

public
int dwFlags;

public
int time;

public
int dwExtraInfo;

}

// Call the
API

int
resSendInput;

private
void btnUnlock_Click(object
sender, EventArgs e)

{

timer1.Enabled = true;

INPUT
input = new INPUT();

resSendInput = SendInput(5, ref input, Marshal.SizeOf(input));

}

private
void timer1_Tick(object
sender, EventArgs e)

{

INPUT
input = new INPUT();

resSendInput = SendInput(5, ref input, Marshal.SizeOf(input));

}

}

 

Bye …

Unable to find a version of the runtime to run the application

I was facing the problem while trying to run one of my windows application created in Visual studio 2005 using .NET framework 2.0.

Few days back the application was running fine and today it on trying to run it i was getting the error.

The way it solved for me was to again open the project in solution explorer in visual studio and rebuilding it.

Bye,..

Creating Word document using C#

Create a new windows application project and add a button to it.

On click of that button, we will create a new document(word) and write a simple Hello World text in it.

To create a word document using C# we need to first reference the following DLL(com)

DLL

After adding reference, add this directive

using Microsoft.Office.Interop.Word;

Put this code on button click

    private void button1_Click(object sender, EventArgs e)

        {

            object missing = System.Reflection.Missing.Value;

            object Visible=true;

            object start1 = 0;

            object end1 = 0;

 

            ApplicationClass WordApp = new ApplicationClass();

            Document adoc = WordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);

            Range rng = adoc.Range(ref start1, ref missing);

 

            try

            {              

                rng.Font.Name = “Georgia”;

                rng.InsertAfter(“Hello World!”);

                object filename = @”D:\MyWord.doc”;

                adoc.SaveAs(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing,

                ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);

                WordApp.Visible = true;

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }        

        }

The easiest way to write code for office interoperability is to make use of VBA code.

Say you want to insert a picture in a word document what you can do is

open the word document – Go to Tools ->Macro-> Record New Macro

Now click on insert menu and insert the picture. Stop the recording, again go to Macro -Macros-> Select your Macro and click on edit

You will find the vba code over there

Sub Macro1()

Selection.InlineShapes.AddPicture FileName:= _
“C:\Documents and Settings\nishantr1\My Documents\My Pictures\untitled.bmp” _
, LinkToFile:=False, SaveWithDocument:=True
End Sub

Now to write the same code in c# you will do something like this

Range rngPic = adoc.Tables[1].Range;

rngPic.InlineShapes.AddPicture(@”C:\anne_hathaway.jpg”, ref missing, ref missing, ref missing);

Bye

Saving and Retrieving richtextbox control’s content (.rtf file) in database

Let’s start with a very simple application.

Form

Drop OpenFileDialog control in the application.

When user click on Pick File button using OpenFileDialog he will select a rtf file to display in richtextbox control.

The content of richtextbox control will be saved in the sql server table.

This is how our table looks like.

Table

File content is the image data type column where we will store our rtf content.

<!–[if gte vml 1]> <![endif]–>

Put the following code in Pick file button click.

if(openFileDialog1.ShowDialog() == DialogResult.OK)

{

try

{

rtfContent.LoadFile(openFileDialog1.FileName);

}

catch(Exception ex)

{

MessageBox.Show(ex.Message);

}

}

Put the following code in Save Button Click

SqlConnection conn=new SqlConnection(“Data Source=D-0824;Initial Catalog=WordInterOp; uid=sa;pwd=sa;”);

SqlCommand cmd=new SqlCommand();

cmd.CommandText = “Insert into RtfStore (fileName,fileContent) values ( @fname,@fcontent)”;

cmd.Connection=conn;

SqlParameter fileName=new SqlParameter(“@fname”,openFileDialog1.SafeFileName);

rtfContent.SaveFile(@”c:\temp.rtf”, RichTextBoxStreamType.RichText);

FileStream stream = new FileStream(@”c:\temp.rtf”, FileMode.Open, FileAccess.Read);

int size = Convert.ToInt32(stream.Length);

Byte[] rtf = new Byte[size];

stream.Read(rtf, 0, size);

SqlParameter fileContent=new SqlParameter();

fileContent.ParameterName=”@fcontent”;

fileContent.SqlDbType=SqlDbType.Image;

fileContent.Size=rtf.Length;

fileContent.Value=rtf;

cmd.Parameters.Add(fileName);

cmd.Parameters.Add(fileContent);

conn.Open();

int success=cmd.ExecuteNonQuery();

if(success==1)

{

MessageBox.Show(“Entered data successfully”);

}

openFileDialog1.SafeFileName- To get the name of file instead of the complete path.

rtfContent.SaveFile- Saving the content of the control in a rtf file.

RichTextBoxStreamType.RichText– This tells that we are saving richtext having some formatting and not just plain text.

Finally through filestream we are reading that file and saving it’s content in our sqlserver table.

Similary to read the rtf content from the database and display it in Richtextbox control, this is what we need to do

// cmd.commandText=”select fileContent from RtfStore where filename=’xyz’ “;

SqlDataReader dr =  cmd.ExecuteReader();

if (dr.Read())

{

Byte[] rtf = new Byte[Convert.ToInt32((dr.GetBytes(0, 0,

null, 0, Int32.MaxValue)))];

long bytesReceived = dr.GetBytes(0, 0, rtf, 0, rtf.Length);

ASCIIEncoding encoding = new ASCIIEncoding();

rtfContent.Rtf = encoding.GetString(rtf, 0, Convert.ToInt32(bytesReceived));

}

Bye

Working with ListBox in .Net Windows Application

Say we want to implement some functionality as shown in the image below in our windows formListBox

Using >> button we want to move values from optional sections to mandatory sections list box and vice versa using << button. But we don’t want the sections which are mandatory to move to optional list box.

Finally we can rearrange items in the Mandatory list box using up and down buttons.

Let’s see the code for all this

Our listboxes are named lstOptional and lstMandatory

>> button is named btnSelect

<< button is named btnDeSelect

When button >>(btnSelect is clicked)

private void btnSelect_Click(object sender, EventArgs e)
{

// if there are no item in lstOptional Listbox return

if (lstOptional.Items.Count == 0)
{

return;
}

// if some item is selected in the lstOptional Listbox check if we already have it in lstMandatory

// if it is there or nothing is selected than return

int g = lstMandatory.FindStringExact(lstOptional.Text);
if(g>-1||lstOptional.Text ==””)
{
return;
}

// finally add that item to lstMandatory, refresh it to make it appear and remove it from lstOptional

lstMandatory.Items.Add(lstOptional.Text );
lstMandatory.Refresh();
lstMandatory.Text = “”;
lstOptional.Items.Remove(lstOptional.Text);
}

When button << DeSelect is clicked

private void btnDeSelect_Click(object sender, EventArgs e)
{

// if nothing is selected in lstMandatory just put the focus over the listbox

if (lstMandatory.Text == “”)
{
lstMandatory.Focus();
return;
}

// checking if the selected item is mandatory on.

// Here we have saved the mandatory items in a hidden listbox on form load

int g = lstHidden.FindStringExact(lstMandatory.Text);
if (g > -1)
{
MessageBox.Show(“This section is mandatory”,”Information”);
}
else
{
lstOptional.Items.Add(lstMandatory.Text);
lstMandatory.Items.Remove(lstMandatory.Text);
}
}

When button Up is clicked we need to move the selected item in upward direction

int selectedItemIndex = lstMandatory .SelectedIndex;
String selectedItemText = lstMandatory .Text;
if (selectedItemIndex != 0)
{
lstMandatory .Items.RemoveAt(selectedItemIndex);
lstMandatory .Items.Insert(selectedItemIndex – 1, selectedItemText);
lstMandatory .SelectedIndex = selectedItemIndex – 1;
}
lstMandatory .Refresh();
lstMandatory .Focus();

Finally when button Down is clicked

int selectedItemIndex = lstMandatory.SelectedIndex;
String selectedItemText = lstMandatory.Text;
int total = lstMandatory.Items.Count;
if (selectedItemIndex < total – 1)
{
lstMandatory.Items.RemoveAt(selectedItemIndex);
lstMandatory.Items.Insert(selectedItemIndex + 1, selectedItemText);
lstMandatory.SelectedIndex = selectedItemIndex + 1;
}
lstMandatory.Refresh();

Bye

Create wizard like window application C#

Hi today we will see how to create wizard like window application in .NET 2.0.

1) Create a new window application.
2) Add three forms in it. I have named the form as FirstStep, SecondStep and ThirdStep.
3) In FirstStep add two button – Next and Cancel
4) In SecondStep add three button- Previous, Next and Cancel
5) In ThirdStep add two button- Previous and Cancel
6) Than add a new class file – name it WizardData.cs
7) Add following code to it

// this wizardData class will have a enumeration and a property to display the appropriate form
public class WizardData
{
public enum wizardForms
{
FirstStep =1, SecondStep=2, ThirdStep=3,Cancel =99
}
private wizardForms formToShow;
public wizardForms FormToShow
{
get
{
return formToShow;
}
set
{
formToShow=value;
}
}
}

8. Then go to program.cs and modify it in the following manner

[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MyInitialization();

//Replace Application.Run(…. ) with MyInitialization() – custom function
}

9) The code for MyInitialization() goes like this

// Create instances of all the forms to be displayed
private static void MyInitialization()
{
WizardData wData = new WizardData();
wData.FormToShow = WizardData.wizardForms.FirstStep;
Form step1 = new FirstStep(wData);
Form step2 = new SecondStep(wData);
Form step3 = new ThirdStep(wData);
while (wData.FormToShow != WizardData.wizardForms.Cancel)
{
switch (wData.FormToShow)
{
case WizardData.wizardForms.FirstStep:
{
step1.ShowDialog();
break;
}
case WizardData.wizardForms.SecondStep:
{
step2.ShowDialog();
break;
}
case WizardData.wizardForms.ThirdStep:
{
step3.ShowDialog();
break;
}
}
}
10) Now go to your FirstStep Form. Replace the constructor with this

public FirstStep(WizardData wd)
{
this.wData = wd;
InitializeComponent();
}

11) In the cancel button and next button click event handler write the following code

private void btnNext_Click(object sender, EventArgs e)
{
// to show the SecondStep form
wData.FormToShow = WizardData.wizardForms.SecondStep;
this.Close();
}
private void btnCancel_Click(object sender, EventArgs e)
{
wData.FormToShow = WizardData.wizardForms.Cancel;
this.Close();
}

12) Repeat the same step 11 for SecondStep and ThirdStep form.
for previous button click event handler add the following code
private void btnPrevious_Click(object sender, EventArgs e)
{
// replace the wizardForm.(…) with appropriate form to be displayed
wData.FormToShow = WizardData.wizardForms.FirstStep;
this.Close();
}


That’s it