public class GenericConverter
{
public static T Parse<T>(string sourceValue) where T : IConvertible
{
return (T)Convert.ChangeType(sourceValue, typeof(T));
}
public static T Parse<T>(string sourceValue, IFormatProvider provider) where T : IConvertible
{
return (T)Convert.ChangeType(sourceValue, typeof(T), provider);
}
}
using System.Diagnostics;
if (Process.Getprocessbyname(Process.Getcurrentprocess().ProcessName).Length >1)
{
MessageBox.show("Another instance of this process is already running");
Application.Exit();
}
public int CalculateTotalFileSize(string[] path)
{
int sumFileSize = 0;
foreach(string onePath in path)
{
FileInfo info = new FileInfo(onePath);
sumFileSize += Convert.ToInt32(info.Length);
}
return sumFileSize;
}
using System.Threading;
private void btnStart_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(this.AsyncGetResults));
t.Start();
}
private void AsyncGetResults()
{
// Do some not-GUI-touching stuff
// ...
// So some GUI-touching stuff
if (panellWait.InvokeRequired)
{
panelWait.Invoke(new MethodInvoker(delegate
{
panelWait.Visible = true;
}));
}
// Do some other not-GUI-touching stuff
// ...
}
/// <summary>
/// When calling a WCF service it is not possible to use a using(...) statement to close
/// the connection after the service call. A call to Dispose may cause an exception
/// which is against MS recommendation. As such when calling a WCF Service you can
/// us the Using method to correctly close the connection after your request or requests.
///
/// <remarks>This can be used with the following code <br/>
/// <code>
/// IMyService service = new MyService(); // Gets a proxy to WCF service
/// service.Using(()=>
/// {
/// service.DoSomthing();
/// service.DoSomethingElse("Hello World");
/// Console.WriteLine();
/// });
/// </code>
/// </remarks>
/// </summary>
/// <param name="service">The IService instance you wish will close after invocation</param>
/// <param name="action">The Action delegate to execute before the service is closed.</param>
public static void Using(this IService service, Action action)
{
ICommunicationObject communicationObject = service as ICommunicationObject;
try
{
action();
service.SafeDispose();
}
catch (CommunicationException cex)
{
Log.Error(String.Format("CommunicationException occured calling service method on {0}", service.GetType().Name), cex);
if (communicationObject != null)
communicationObject.Abort();
throw;
}
catch (TimeoutException tex)
{
Log.Error(String.Format("TimeoutException occured calling service method on {0}", service.GetType().Name), tex);
if (communicationObject != null)
communicationObject.Abort();
throw;
}
}