Archive

Archive for the ‘C#’ Category

Fire Custom event with custom EventArgs

Step 1- Create Custom EventArgs

public class ExtendedEventArgs : EventArgs
{
public string Message { get; set;}
public ExtendedEventArgs(string message)
{
Message = message;
}
}

Step 2 – Create Delegate to handle Which will accept this argument

public delegate int ExtendedEvent(object sender, ExtendedEventArgs e);

Step 3 – Create and attach this delegate to event

public event ExtendedEvent OnExtendEvent;

Step 4 – Attach a method to delgate

this.OnExtendEvent += ExtendedEventRaised;

Step 5 – Create handler method to get requried parameter in EventAgrs

private int ExtendedEventRaised(object sender, ExtendedEventArgs e)
{
return e.Message.Length;
}

Step 6 – Fire event on your condition

if (OnExtendEvent != null)
OnExtendEvent(null, new ExtendedEventArgs(“Saresh”));

Categories: .Net, C#

Compare two object and get changes made in their values

Here we can compare values of a DataRow of DataTable or compare two object of same class. It will return you name of properties with differance in string.

string GetUpdatedHistory(DataRow orignalRecord, DataRow updatedRecord)
{
if (orignalRecord.Table.Columns.Count != updatedRecord.Table.Columns.Count)
{
return string.Empty;
}
StringBuilder text = new StringBuilder();
for (int i = 0; i < orignalRecord.Table.Columns.Count; i++)
{
if (Convert.ToString(orignalRecord[i]) != Convert.ToString(updatedRecord[i]))
{
text.Append("Column " + orignalRecord.Table.Columns[i].ColumnName +
string.Format(" changed from to ,”, Convert.ToString(orignalRecord[i]), Convert.ToString(updatedRecord[i])));
}
}
return text.ToString().Substring(0, text.ToString().Length – 1);
}
string GetUpdatedHistory(object type1, object type2)
{
StringBuilder text = new StringBuilder();
PropertyInfo[] instance1 = type1.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
PropertyInfo[] instance2 = type2.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
// Display information for all properties.
foreach (var propInfo in instance1)
{
PropertyInfo propInfo2 = (PropertyInfo)instance2.Where(x => x.Name == propInfo.Name).FirstOrDefault();
string value1 = Convert.ToString(propInfo.GetValue(type1, null));
string value2 = Convert.ToString(propInfo2.GetValue(type2, null));
if (value1 != value2)
{
text.Append(“Property ” + propInfo.Name +
string.Format(” changed from to ,”, Convert.ToString(value1), Convert.ToString(value2)));
}
}
return text.ToString().Substring(0, text.ToString().Length – 1);
}

Categories: .Net, C#

String type to ENum (Generic)

October 21, 2014 Leave a comment

///

/// Allows the discovery of an enumeration value based on the EnumTextValueAttribute
///

/// The type of the enum to get the value for.
/// The text of the EnumTextValueAttribute.
/// boxed representation of the enum value

public static T GetEnumValue(string text)
{
Type enumType = typeof(T);

MemberInfo[] members = enumType.GetMembers();
foreach (MemberInfo mi in members)
{
object[] attrs = mi.GetCustomAttributes(typeof(EnumTextValueAttribute), false);
if (attrs.Length == 1)
{
if (((EnumTextValueAttribute)attrs[0]).Text == text)
return (T) Enum.Parse(enumType, mi.Name);
}
}
throw new ArgumentOutOfRangeException(“text”, text, “The text passed does not correspond to an attributed enum value”);
}

Categories: C#

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());
}
}
}

}

}
}

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#

Remove attributes from xml

public void IntermediateProcess(string xmlFilePath)
{

XmlDocument xmlDoc = new XmlDocument();
FileInfo fileInfo = new FileInfo(_xmlFilePath);
if (fileInfo.Exists)
{
xmlDoc.Load(_xmlFilePath);

XmlNodeList listFormField = xmlDoc.GetElementsByTagName(“TagName”);
foreach (XmlNode node in listFormField)
{
node.Attributes.RemoveNamedItem(“attributename”);
}
xmlDoc.Save(_xmlFilePath);
}
}

Categories: C#