public class CSMain
{
private CSMain() { }
static CSMain()
{
mUID = "2c81068a-7828-4769-8112-36754b67cdc5";
}
[STAThread]
static void Main()
{
try
{
bool firstInstance;
mSingleInstanceLock = new Mutex(true, mUID, out firstInstance);
if (firstInstance == true)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmLogin());
}
}
catch (Exception ex)
{
string err = ex.ToString();
}
}
private static string mUID;
private static Mutex mSingleInstanceLock;
}
Search This Blog
Monday, October 14, 2013
Find the idle time of windows application
Find how much time application idle in windows application
public partial class Form1 : Form,IMessageFilter
{
Timer timer;
private DateTime _wentIdle;
private int _idleTicks;
public Form1()
{
InitializeComponent();
Application.AddMessageFilter(this);
timer = new Timer();
timer.Interval = 1000;
timer.Tick += timer_Tick;
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
TimeSpan diff = DateTime.Now - _wentIdle;
if (diff.TotalSeconds >= Settings.Default.IdleTimeout_Sec)
{
label1.Text = "Idle From - " + _wentIdle;
}
if (++_idleTicks >= Settings.Default.IdleTimeout_Sec)
{
label1.Text = "Idle From - " + _idleTicks;
}
if (_idleTicks > 100)
{ Application.Exit(); }
}
private void Form1_Load(object sender, EventArgs e)
{
Application.Idle += Application_Idle;
}
void Application_Idle(object sender, EventArgs e)
{
_wentIdle = DateTime.Now;
}
public bool PreFilterMessage(ref Message m)
{
if (isUserInput(m))
{
_wentIdle = DateTime.MaxValue;
_idleTicks = 0;
label1.Text = "We Are NOT idle!";
}
return false;
}
private bool isUserInput(Message m)
{
if (m.Msg == 0x200) { return true; }
if (m.Msg == 0x020A) { return true; }
if (m.Msg == 0x100) { return true; }
if (m.Msg == 0x101) { return true; }
return false;
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f = new Form2();
f.Show();
}
}
public partial class Form1 : Form,IMessageFilter
{
Timer timer;
private DateTime _wentIdle;
private int _idleTicks;
public Form1()
{
InitializeComponent();
Application.AddMessageFilter(this);
timer = new Timer();
timer.Interval = 1000;
timer.Tick += timer_Tick;
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
TimeSpan diff = DateTime.Now - _wentIdle;
if (diff.TotalSeconds >= Settings.Default.IdleTimeout_Sec)
{
label1.Text = "Idle From - " + _wentIdle;
}
if (++_idleTicks >= Settings.Default.IdleTimeout_Sec)
{
label1.Text = "Idle From - " + _idleTicks;
}
if (_idleTicks > 100)
{ Application.Exit(); }
}
private void Form1_Load(object sender, EventArgs e)
{
Application.Idle += Application_Idle;
}
void Application_Idle(object sender, EventArgs e)
{
_wentIdle = DateTime.Now;
}
public bool PreFilterMessage(ref Message m)
{
if (isUserInput(m))
{
_wentIdle = DateTime.MaxValue;
_idleTicks = 0;
label1.Text = "We Are NOT idle!";
}
return false;
}
private bool isUserInput(Message m)
{
if (m.Msg == 0x200) { return true; }
if (m.Msg == 0x020A) { return true; }
if (m.Msg == 0x100) { return true; }
if (m.Msg == 0x101) { return true; }
return false;
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f = new Form2();
f.Show();
}
}
Using statement to connect to database
use using keyword to connect to database.
using System.Data;
using System.Data.SqlClient;
String conString = "Data Source=SERVER;UID=user;PWD=passsword Integrated Security=True;";
using (SqlConnection sqlCon = new SqlConnection (conString))
{
sqlCon.Open();
DataTable tblDatabases = sqlCon.GetSchema ("Databases");
sqlCon.Close();
foreach (DataRow row in tblDatabases.Rows)
{
Console.WriteLine ("Database: " + row["database_name"]);
}
}
using System.Data;
using System.Data.SqlClient;
String conString = "Data Source=SERVER;UID=user;PWD=passsword Integrated Security=True;";
using (SqlConnection sqlCon = new SqlConnection (conString))
{
sqlCon.Open();
DataTable tblDatabases = sqlCon.GetSchema ("Databases");
sqlCon.Close();
foreach (DataRow row in tblDatabases.Rows)
{
Console.WriteLine ("Database: " + row["database_name"]);
}
}
Tuesday, August 13, 2013
Encryption and Decryption in c#.net
using System;
using System.Data;
using System.Configuration;
using System.Text;
using System.Security.Cryptography;
namespace Encription
{
class CryptorEngine
{
public static string Encrypt(string ToEncrypt, bool useHasing)
{
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(ToEncrypt);
//System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
string Key = "Bhagwati";
if (useHasing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(Key));
hashmd5.Clear();
}
else
{
keyArray = UTF8Encoding.UTF8.GetBytes(Key);
}
TripleDESCryptoServiceProvider tDes = new TripleDESCryptoServiceProvider();
tDes.Key = keyArray;
tDes.Mode = CipherMode.ECB;
tDes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tDes.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tDes.Clear();
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
public static string Decrypt(string cypherString, bool useHasing)
{
byte[] keyArray;
byte[] toDecryptArray = Convert.FromBase64String(cypherString);
//byte[] toEncryptArray = Convert.FromBase64String(cypherString);
//System.Configuration.AppSettingsReader settingReader = new AppSettingsReader();
string key = "Bhagwati";
if (useHasing)
{
MD5CryptoServiceProvider hashmd = new MD5CryptoServiceProvider();
keyArray = hashmd.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd.Clear();
}
else
{
keyArray = UTF8Encoding.UTF8.GetBytes(key);
}
TripleDESCryptoServiceProvider tDes = new TripleDESCryptoServiceProvider();
tDes.Key = keyArray;
tDes.Mode = CipherMode.ECB;
tDes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tDes.CreateDecryptor();
try
{
byte[] resultArray = cTransform.TransformFinalBlock(toDecryptArray, 0, toDecryptArray.Length);
tDes.Clear();
return UTF8Encoding.UTF8.GetString(resultArray,0,resultArray.Length);
}
catch (Exception ex)
{
throw ex;
}
}
}
}
using System.Data;
using System.Configuration;
using System.Text;
using System.Security.Cryptography;
namespace Encription
{
class CryptorEngine
{
public static string Encrypt(string ToEncrypt, bool useHasing)
{
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(ToEncrypt);
//System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
string Key = "Bhagwati";
if (useHasing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(Key));
hashmd5.Clear();
}
else
{
keyArray = UTF8Encoding.UTF8.GetBytes(Key);
}
TripleDESCryptoServiceProvider tDes = new TripleDESCryptoServiceProvider();
tDes.Key = keyArray;
tDes.Mode = CipherMode.ECB;
tDes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tDes.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tDes.Clear();
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
public static string Decrypt(string cypherString, bool useHasing)
{
byte[] keyArray;
byte[] toDecryptArray = Convert.FromBase64String(cypherString);
//byte[] toEncryptArray = Convert.FromBase64String(cypherString);
//System.Configuration.AppSettingsReader settingReader = new AppSettingsReader();
string key = "Bhagwati";
if (useHasing)
{
MD5CryptoServiceProvider hashmd = new MD5CryptoServiceProvider();
keyArray = hashmd.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd.Clear();
}
else
{
keyArray = UTF8Encoding.UTF8.GetBytes(key);
}
TripleDESCryptoServiceProvider tDes = new TripleDESCryptoServiceProvider();
tDes.Key = keyArray;
tDes.Mode = CipherMode.ECB;
tDes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tDes.CreateDecryptor();
try
{
byte[] resultArray = cTransform.TransformFinalBlock(toDecryptArray, 0, toDecryptArray.Length);
tDes.Clear();
return UTF8Encoding.UTF8.GetString(resultArray,0,resultArray.Length);
}
catch (Exception ex)
{
throw ex;
}
}
}
}
Indexer in C#.net
Indexer in c#, Indexers allow instances of a class or struct to be indexed just like arrays. for creating indexer we need to inherit System.Collection.CollectionBase.
example-
public class EmployeeCollection:System.Collection.CollectionBase
{
//adding class to indexer
public void Add(Employee obEmployee)
{
this.InnerList.aAdd(obEmployee);
}
//get the data
public Employee this[int i]
{
get
{
return
{
this.InnerList[i] as Employee;
}
}
}
}
for add data into collection create object of collection and call add method. For get data collection[index].
example-
public class EmployeeCollection:System.Collection.CollectionBase
{
//adding class to indexer
public void Add(Employee obEmployee)
{
this.InnerList.aAdd(obEmployee);
}
//get the data
public Employee this[int i]
{
get
{
return
{
this.InnerList[i] as Employee;
}
}
}
}
for add data into collection create object of collection and call add method. For get data collection[index].
Thursday, October 18, 2012
Upload Large Image Using WCF Services Using RESTFul WCF Services
How to upload large image in WCF service?
By default WCF service allow 64KB data to upload if you want to upload more data then 64K you need to change the configuration settings, need to change the buffer size for incoming and outgoing request size here is an example for upload large image through WCF service,
[OperationContract]
[WebInvoke(Method = "POST",UriTemplate = "/File")]
bool UploadImage(Stream obStream);
In Service implement interface method.
public bool UploadImage(Stream image)
{
if(image != null)
{
try
{
string ImageName = DateTime.Now.ToString().Replace(" ","").Replace(":","").Replace("/","") + ".jpeg";//define name of image.
if(!Directory.Exists(@"C:\Images"))//check folder exist or not.
Directory.CreateDirectory(@"C:\Images");
string strFilePath = @"C:\Images\" + ImageName;
FileStream targetStream = null;
Stream sourceStream = image;
string uploadFolder = @"C:\Images\";
string filename = ImageName;
string filePath = Path.Combine(uploadFolder,filename);
///write file using stream.
using(targetStream = new FileStream(filePath,FileMode.Create,FileAccess.Write,FileShare.None))
{
const int bufferLen = 4096;
byte[] buffer = new byte[bufferLen];
int count = 0;
int totalBytes = 0;
while((count = sourceStream.Read(buffer,0,bufferLen)) > 0)
{
totalBytes+=count;
Debug.WriteLine("Bytes Count="+totalBytes.ToString());
targetStream.Write(buffer,0,count);
}
targetStream.Close();
sourceStream.Close();
}
return true;
}
catch(Exception ex)
{
return false;
}
}
return false;
}
private byte[] StreamToByte(Stream stream)
{
byte[] buffer = new byte[16 * 1024];
using(MemoryStream ms = new MemoryStream())
{
int read;
while((read = stream.Read(buffer,0,buffer.Length)) > 0)
{
ms.Write(buffer,0,read);
}
return ms.ToArray();
}
}
and in Configration use webHttpbinding change the maxReceivedMessageSize.
<webHttpBinding>
<binding name="webHttpBindingStreamed" transferMode="StreamedRequest" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
</binding>
</webHttpBinding>
the max length for Receive buffer is 2147483647, also add the readerQuotas.
may be this will help you.
By default WCF service allow 64KB data to upload if you want to upload more data then 64K you need to change the configuration settings, need to change the buffer size for incoming and outgoing request size here is an example for upload large image through WCF service,
In IService Interface, declare method.
here Method is POST and we are using stream to upload a image.
[OperationContract]
[WebInvoke(Method = "POST",UriTemplate = "/File")]
bool UploadImage(Stream obStream);
In Service implement interface method.
public bool UploadImage(Stream image)
{
if(image != null)
{
try
{
string ImageName = DateTime.Now.ToString().Replace(" ","").Replace(":","").Replace("/","") + ".jpeg";//define name of image.
if(!Directory.Exists(@"C:\Images"))//check folder exist or not.
Directory.CreateDirectory(@"C:\Images");
string strFilePath = @"C:\Images\" + ImageName;
FileStream targetStream = null;
Stream sourceStream = image;
string uploadFolder = @"C:\Images\";
string filename = ImageName;
string filePath = Path.Combine(uploadFolder,filename);
///write file using stream.
using(targetStream = new FileStream(filePath,FileMode.Create,FileAccess.Write,FileShare.None))
{
const int bufferLen = 4096;
byte[] buffer = new byte[bufferLen];
int count = 0;
int totalBytes = 0;
while((count = sourceStream.Read(buffer,0,bufferLen)) > 0)
{
totalBytes+=count;
Debug.WriteLine("Bytes Count="+totalBytes.ToString());
targetStream.Write(buffer,0,count);
}
targetStream.Close();
sourceStream.Close();
}
return true;
}
catch(Exception ex)
{
return false;
}
}
return false;
}
private byte[] StreamToByte(Stream stream)
{
byte[] buffer = new byte[16 * 1024];
using(MemoryStream ms = new MemoryStream())
{
int read;
while((read = stream.Read(buffer,0,buffer.Length)) > 0)
{
ms.Write(buffer,0,read);
}
return ms.ToArray();
}
}
and in Configration use webHttpbinding change the maxReceivedMessageSize.
<webHttpBinding>
<binding name="webHttpBindingStreamed" transferMode="StreamedRequest" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
</binding>
</webHttpBinding>
the max length for Receive buffer is 2147483647, also add the readerQuotas.
may be this will help you.
Friday, April 6, 2012
Extension Methods in c#
You want to improve the syntax for calling common methods in your C# program, so that function names are shorter and easier to type. Extension methods provide a way to easily represent static methods as instance methods in the syntax of the C# language, which can be more intuitive and recallable for developers.
Here is an example.
using System;
public static class ExtensionMethods
{
public static string GetFirstThreeLatters(this string value)
{
if (value.Length > 0)
{
value=value.Substring(0,3);
}
return value;
}
}
class Program
{
static void Main()
{
string value = "dot net perls";
value = value.GetFirstThreeLatters(); // Called like an instance method.
Console.WriteLine(value);
}
}
OUTPUT:-
dot.
Description. In the first part of the program text, you can see an extension method declaration in the C# programming language. An extension method must be static and can be public so you can use it anywhere in your source code.
The extension method is called like an instance method, but is actually a static method. The instance pointer 'this' is received as a parameter. You must specify the 'this' keyword before the appropriate parameter you want the method to be called upon. In the method, you can refer to this parameter by its declared name.
This-keyword in parameter list. The only difference in the declaration between a regular static method and an extension method is the 'this' keyword in the parameter list. If you want the extension method to received other parameters as well, you can place those in the method signature's parameter list after the 'this' parameter.
Here is an example.
using System;
public static class ExtensionMethods
{
public static string GetFirstThreeLatters(this string value)
{
if (value.Length > 0)
{
value=value.Substring(0,3);
}
return value;
}
}
class Program
{
static void Main()
{
string value = "dot net perls";
value = value.GetFirstThreeLatters(); // Called like an instance method.
Console.WriteLine(value);
}
}
OUTPUT:-
dot.
Description. In the first part of the program text, you can see an extension method declaration in the C# programming language. An extension method must be static and can be public so you can use it anywhere in your source code.
The extension method is called like an instance method, but is actually a static method. The instance pointer 'this' is received as a parameter. You must specify the 'this' keyword before the appropriate parameter you want the method to be called upon. In the method, you can refer to this parameter by its declared name.
This-keyword in parameter list. The only difference in the declaration between a regular static method and an extension method is the 'this' keyword in the parameter list. If you want the extension method to received other parameters as well, you can place those in the method signature's parameter list after the 'this' parameter.
Thursday, March 22, 2012
Create Interface
for create Interface use keyword interface then name of the interface here is an example.
interface IEmployee
{
string FirstName{get;set;}
string EmpID{get;set;}
int Age{get;set;}
DateTime DateOfJoining { get; set; }
bool Save();
}
interface IEmployee
{
string FirstName{get;set;}
string EmpID{get;set;}
int Age{get;set;}
DateTime DateOfJoining { get; set; }
bool Save();
}
Create a class
for create a class use the keyword class then name of the class here is an example.
class Employee
{
public string FirstName
{
get;
set;
}
public string EmpID
{
get;
set;
}
public int Age
{
get;
set;
}
public bool Save()
{
return true;
}
public DateTime DateOfJoining
{
get;
set;
}
class Employee
{
public string FirstName
{
get;
set;
}
public string EmpID
{
get;
set;
}
public int Age
{
get;
set;
}
public bool Save()
{
return true;
}
public DateTime DateOfJoining
{
get;
set;
}
Socket Programming
private void btnRead_Click(object sender, EventArgs e)
{
string Query = "POST /test/service.asmx/HelloWorld HTTP/1.1\r\n" +
"Host: 192.168.1.25\r\n" +
"Content-Type: application/x-www-form-urlencoded\r\n" +
"Content-Length:0 \r\n";
byte[] byArrsend = System.Text.ASCIIEncoding.ASCII.GetBytes(Query);
try
{
IPAddress ipAddress = IPAddress.Parse("110.234.132.130");
IPEndPoint ipEnd = new IPEndPoint(ipAddress, 80);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(ipEnd);
if (socket.Connected)
{
socket.Send(byArrsend);
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnReceive), socket);
//MessageBox.Show(responceBuilder.ToString());
while (reading)
System.Threading.Thread.Sleep(200);
textBox1.Text = Responce;
StreamWriter sw = new StreamWriter("\\My Documents\\Socket1.xml");
sw.Write(Convert.ToString(responceBuilder));
}
else
{
MessageBox.Show("Not Connected");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
int bytesRead;
string Responce;
bool reading = true;
byte[] buffer = new byte[1024];
StringBuilder responceBuilder = new StringBuilder();
private void OnReceive(IAsyncResult ar)
{
try
{
//while (reading == true)
//{
Socket socket = (Socket)ar.AsyncState;
bytesRead = socket.EndReceive(ar);
if (bytesRead > 0)
{
Responce = Encoding.ASCII.GetString(buffer, 0, bytesRead);
//_Receive = true;
}
if (bytesRead > 0)
{
if (responceBuilder.Length == 0)
{
string tempString = Encoding.ASCII.GetString(buffer, 0, bytesRead);
//if (replace) ;
//{
// tempString = tempString.Remove(0, tempString.IndexOf("<?xml version="));
//}
responceBuilder.Append(tempString);
}
else
{
responceBuilder.Append(Encoding.ASCII.GetString(buffer, 0, bytesRead));
}
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnReceive), socket);
reading = true;
}
else
{
reading = false;
}
//}
Responce = responceBuilder.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
//responceBuilder = responceBuilder.Remove(0, 0);
//StreamWriter sw=new StreamWriter("\\My Documents\\Socket1.xml");
//sw.Write(Convert.ToString(responceBuilder));
}
Subscribe to:
Posts (Atom)