Microsoft.Win32.SystemEvents in Winform

September 10, 2014 Leave a comment

You can catch You machine logon\logoff event in .Net

using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;
using System.IO;
namespace WindowsFormsApplication1
{
public class SessionEvent
{
public SessionEvent()
{
SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch);
Microsoft.Win32.SystemEvents.SessionEnding += SystemEvents_SessionEnding;
}

void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
{
string path = @”C:\Datafeed\Example.txt”;
if (!File.Exists(path))
{
File.Create(path);
TextWriter tw = new StreamWriter(path);
tw.WriteLine(e.Reason + ” ” + DateTime.Now.ToString());
tw.Close();
}
else if (File.Exists(path))
{
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine(e.Reason + ” ” + DateTime.Now.ToString());
}
}
}

~SessionEvent()
{
//Do this during application close to avoid handle leak
Microsoft.Win32.SystemEvents.SessionSwitch -= new SessionSwitchEventHandler(SystemEvents_SessionSwitch);
}

private void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
if (e.Reason == SessionSwitchReason.SessionLogon ||
e.Reason == SessionSwitchReason.SessionLogoff ||
e.Reason == SessionSwitchReason.SessionLock ||
e.Reason == SessionSwitchReason.SessionUnlock)
{
string path = @”C:\Datafeed\Example.txt”;
if (!File.Exists(path))
{
File.Create(path);
TextWriter tw = new StreamWriter(path);
tw.WriteLine(e.Reason + ” ” + DateTime.Now.ToString());
tw.Close();
}
else if (File.Exists(path))
{
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine(e.Reason + ” ” + DateTime.Now.ToString());
}
}
}

}

}
}

Advertisements
Categories: C#

Export DataGridView into Excel without using COM

August 7, 2014 Leave a comment

This feature will allow to you export data into excel without using or refering any COM

static Boolean ExportToExcel(string FilePath, DataGridView dataGridView, out Exception ex)
{
ex = null;
string strFileNameWithPath = FilePath;
try
{
string connectionString = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” + strFileNameWithPath + “;Extended Properties=Excel 8.0”;
OleDbConnection objConnection = new OleDbConnection(connectionString);
objConnection.Open();
OleDbDataAdapter objAdapter = new OleDbDataAdapter();
//Dim objCommand As New OleDbCommand(“CREATE TABLE [Employees] ( EmployeeID int,LastName nvarchar(20),FirstName nvarchar(10),Title nvarchar(30))”, objConnection)
//generate command
string createText = “CREATE TABLE [” + dataGridView.Name + “] (“;
for (int i = 0; i <= dataGridView.Columns.Count – 1; i++)
{
createText += dataGridView.Columns[i].HeaderText +” varchar(255), “;
}
if (createText.EndsWith(“, “))
{
createText = createText.Substring(0, createText.Length – 2);
}
createText +=”)”;
OleDbCommand objCommand = new OleDbCommand(createText, objConnection);
objCommand.ExecuteNonQuery();
//Dim objExportCommand As New OleDbCommand(“INSERT INTO Employees (EmployeeID, LastName,FirstName,Title) VALUES (@EmployeeID,@LastName, @FirstName,@Title)”, objConnection)
string insertText = “INSERT INTO [” + dataGridView.Name + “] (“;
for (int i = 0; i <= dataGridView.Columns.Count – 1; i++)
{
insertText += dataGridView.Columns[i].HeaderText +”,”;
}
insertText = insertText.Substring(0, insertText.Length – 1) +
“)”;
//’ add parameter
for (int i = 0; i < dataGridView.Rows.Count; i++)
{
string commandInsert = “”;
for (int j = 0; j < dataGridView.Columns.Count; j++)
{
commandInsert +=”‘” + Convert.ToString(dataGridView.Rows[i].Cells[j].Value).Trim() + “‘,”;
}
if (commandInsert.EndsWith(“,”))
{
commandInsert = commandInsert.Substring(0, commandInsert.Length – 1);
}
commandInsert = insertText +” VALUES(” + commandInsert + “)”;
OleDbCommand objCommandInsert = new OleDbCommand(commandInsert, objConnection);
objCommandInsert.ExecuteNonQuery();
}
objConnection.Dispose();
return true;
}
catch (Exception exc)
{
ex = exc;
return false;
}
}

Sample how to use it.

saveFileDialog1.ShowDialog();
Exception ex;
ExportToExcel(saveFileDialog1.FileName, dataGridView1, out ex);

Categories: C#

Print file without open it in c#

January 22, 2014 Leave a comment

In this method you can put condition of file printing as per file type with attached executable

public static Boolean PrintFile(string fileName)
{
try
{
Process proc = new Process();
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.Verb = “print”;

//Define location of adobe reader/command line
//switches to launch adobe in “print” mode
proc.StartInfo.FileName = “Your application executable path”;
proc.StartInfo.Arguments = String.Format(@”/p /h {0}”, fileName);
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;

proc.Start();
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
if (proc.HasExited == false)
{
proc.WaitForExit(10000);
}

proc.EnableRaisingEvents = true;

proc.Close();
return true;
}
catch
{
return false;
}

Categories: C#

How to Disable a button click on client side and fire event on server side in ASP.Net

September 30, 2013 Leave a comment

Returns a string that can be used in a client event to cause postback to the server. The reference string is defined by the specified control that handles the postback and a string argument of additional event information

ControlName.Attributes.Add(“onclick”, “this.disabled=true;” + Page.ClientScript.GetPostBackEventReference(ControlName, “”));

Categories: ASP.Net

Dataset Search with LINQ

Search in datatable with relation

DataTable dt1 = GetDataTable(students);
IEnumerable seq1 = dt1.AsEnumerable();
DataTable dt2 = GetDataTable2(classDesignations);
IEnumerable seq2 = dt2.AsEnumerable();
string anthonysClass = (from s in seq1 where s.Field(“Name”) == “Anthony Adams”
from c in seq2 where (int)c[“Id”] == (int)s[“Id”]
select (string)c[“Class”]). SingleOrDefault();

Search in field

int id; id = (from s in seq1 where s.Field(“Name”) == “Anthony Adams”
select s.Field(“Id”, DataRowVersion.Current)). Single();

Update values back to dataset

DataRow row = (from s in seq1 where s.Field(“Name”) == “Anthony Adams”
select s).Single();
row.SetField(“Name”, “George Oscar Bluth”);
row.AcceptChanges();

Categories: LINQ

Important principles of SOA (Service oriented Architecture)

SOA is based on four important concepts:-

1) Services share only schemas and contracts

Services use Schemas to represent data and contracts to understand behavior. They do not use language dependent types or classes in order to understand data and behavior. XML is used to define schemas and contracts. Due to this, there is not heavy coupling between environments.

 2) Services evolve

Change is the law of nature and services will evolve. In SOA, services can be versioned and you can host those services in new ends. For instance, you have a service called as “Search Client “which gives details based on Ticket Number and its exposed on end point “endpoint1”. Tomorrow you want make your Search Tickets service more useful by also providing an extra option of allowing him to search by passenger name. Therefore, you just declare a new end “endpoint2” with service “Search Client with phone number”. So the client who is consuming the service at end endpoint1 continues and at the other end, we have evolved our service by adding new ends endpoint2.

3)Service compatibility is policy based

Policy describes the capabilities of the system. Depending on policies, the service can degrade to match the service for the client. For instance your service needs to be hosted for two types of client one which uses Remoting as the communication methodology while other client uses DCOM. An ideal SOA service can cater to both of them according to there communication policies.

4)Boundaries are well defined

In SOA, everything is formalized. The client who is consuming the service does not need to know how the implementation of the service is done. If you look at some old methodologies of communication like DCOM. Any changes at server level the client also has to change. Therefore, the server and client implementation was so much bound that changes need to be done at all places. In SOA, the rule is if you do enhancement you do not need to change anything at the client. SOA based application only understands that there is an end point, contract, and bindings.

Note: – Just to clarify shortly about end point and contract. Any SOA service is exposed through an end point. End point defines three important aspects What, Where and How. We will understand more details of the same in the later questions.

Is Web services are the base for SOA. The answer is 50 % supported. What web services lack is the policy based Service compatibility. If you host a web service it can only serve with HTTP communication channel and SOAP message. Any other type of client trying to communicate he will not degrade it self. This is what is provided by WCF. You can host the service in one or more mode. For instance you can host a WCF service using remoting and ASMX.

Categories: .Net, WCF

Dynamic grouping in crystal report from code

Here CRRep is a crystal reort object

Hide Section

For X = 1 To CRRep.Sections.Count
If CRRep.Sections.Item(CInt(X)).Name = “SectionName” Then
CRRep.Sections.Item(CInt(X)).Suppress = True
End If
Next

Change Sorting

Set CRField = CRRep.Database.Tables(SortTable).Fields.GetItemByName(CStr(“SortByColumn”))
CRRep.RecordSortFields.Item(1).Field = CRField

Change Grouping

Dim GroupTable
Dim GroupDBFieldName
Set CRField = CRRep.Database.Tables(GroupTable).Fields.GetItemByName(CStr(GroupDBFieldName))
CRRep.Areas.Item(“GH1”).GroupConditionField = CRField

Paassing parameter in sub report

For Each Section In CRRep.Sections
For Each RepObject In Section.ReportObjects
If RepObject.Kind = 5 Then
Set SubRep = RepObject.OpenSubReport
‘ Replaceable Parameters in Sub Reports
For Each ParamDef In SubRep.ParameterFields
”’ If ParamDef.ParameterFieldName = “Date” Then
”’ ParamDef.SetCurrentValue CDate(“date”)
”’ End If
Next
Set SubRep = Nothing
End If
Next
Next

Categories: Other