csharp 资源Getresource

资源Getresource

LoadEmbeddedText.cs
var assembly = Assembly.GetExecutingAssembly();
var stream = assembly.GetManifestResourceStream("Cbb.Smms.EMH.ZRXPExport.ZrxpTemplate.txt");
using (StreamReader reader = new StreamReader(stream))
{
  return reader.ReadToEnd();
}
GetResource.cs
 var value = Properties.Resources.ResourceManager.GetString("R1");

csharp 使用参数启动流程。

使用参数启动流程。

StartProcess.cs


starter.exe
var process = new Process
{
    StartInfo = new ProcessStartInfo
    {
        FileName = "target.exe",
        Arguments = "xxxx xxxx xxxx",
        WindowStyle = ProcessWindowStyle.Hidden
    }
};
process.Start();
process.WaitForExit();
MessageBox.Show("Test");



/////////////////////////////////////
/////////////////////////////////////
////////////////////////////////////

target.exe
static void Main(string[] args)
{

    Console.WriteLine("Start");
    Thread.Sleep(5000);

    foreach (var item in args)
    {
        Console.WriteLine(item);
    }

    Console.WriteLine("Done");

}

csharp 透过した色を绮丽に表示できるパネル

透过した色を绮丽に表示できるパネル

PanelEx.cs
  class PanelEx : Panel
  {
    protected override void OnCreateControl()
    {
      base.OnCreateControl();
      this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.CacheText, true);
    }

    protected override CreateParams CreateParams
    {
      get
      {
        CreateParams cp = base.CreateParams;
        cp.ExStyle |= NativeMethods.WS_EX_COMPOSITED;
        return cp;
      }
    }

    public void BeginUpdate()
    {
      NativeMethods.SendMessage(Handle, NativeMethods.WM_SETREDRAW, IntPtr.Zero, IntPtr.Zero);
    }

    public void EndUpdate()
    {
      NativeMethods.SendMessage(Handle, NativeMethods.WM_SETREDRAW, new IntPtr(1), IntPtr.Zero);
      Parent.Invalidate(true);
    }
  }

  class TableLayoutPanelEx : TableLayoutPanel
  {
    protected override void OnCreateControl()
    {
      base.OnCreateControl();
      this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.CacheText, true);
    }

    protected override CreateParams CreateParams
    {
      get
      {
        CreateParams cp = base.CreateParams;
        cp.ExStyle |= NativeMethods.WS_EX_COMPOSITED;
        return cp;
      }
    }

    public void BeginUpdate()
    {
      NativeMethods.SendMessage(Handle, NativeMethods.WM_SETREDRAW, IntPtr.Zero, IntPtr.Zero);
    }

    public void EndUpdate()
    {
      NativeMethods.SendMessage(Handle, NativeMethods.WM_SETREDRAW, new IntPtr(1), IntPtr.Zero);
      Parent.Invalidate(true);
    }
  }

  static class NativeMethods
  {
    public static int WM_SETREDRAW = 0x000B; //uint WM_SETREDRAW
    public static int WS_EX_COMPOSITED = 0x02000000;


    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam); //UInt32 Msg
  }

csharp パラパラしないTableLayoutPanel中

パラパラしないTableLayoutPanel中

TableLayoutPanelEx.cs
  class TableLayoutPanelEx : TableLayoutPanel
  {
    protected override void OnCreateControl()
    {
      base.OnCreateControl();
      this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.CacheText, true);
    }

    protected override CreateParams CreateParams
    {
      get
      {
        CreateParams cp = base.CreateParams;
        cp.ExStyle |= NativeMethods.WS_EX_COMPOSITED;
        return cp;
      }
    }

    public void BeginUpdate()
    {
      NativeMethods.SendMessage(Handle, NativeMethods.WM_SETREDRAW, IntPtr.Zero, IntPtr.Zero);
    }

    public void EndUpdate()
    {
      NativeMethods.SendMessage(Handle, NativeMethods.WM_SETREDRAW, new IntPtr(1), IntPtr.Zero);
      Parent.Invalidate(true);
    }
  }

  static class NativeMethods
  {
    public static int WM_SETREDRAW = 0x000B; //uint WM_SETREDRAW
    public static int WS_EX_COMPOSITED = 0x02000000;


    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam); //UInt32 Msg
  }

csharp Topshelf与Windsor的基本用法

Topshelf与Windsor的基本用法

HostFactoryMethod.cs
        private static void RunTheHostFactory(IWindsorContainer container)
        {
            HostFactory.Run(config =>
            {
                config.Service<ITopshelfService>(settings =>
                {
                    // use this to instantiate the service
                    settings.ConstructUsing(hostSettings => container.Resolve<ITopshelfService>());
                    settings.WhenStarted(service => service.Start());
                    settings.WhenStopped(service =>
                    {
                        service.Stop();
                        container.Release(service);
                        container.Dispose();
                    });
                });

                config.RunAsLocalSystem();

                config.SetDescription("This is an example service.");
                config.SetDisplayName("My Example Service");
                config.SetServiceName("MyExampleService");
            });
        }

csharp 让Windsor将连接字符串注入原语。取自http://blog.ploeh.dk/2012/07/02/PrimitiveDependencies/。

让Windsor将连接字符串注入原语。取自http://blog.ploeh.dk/2012/07/02/PrimitiveDependencies/。

ConnectionStringConventions.cs
namespace NAMESPACE
{
    using System.Configuration;

    using Castle.Core;
    using Castle.MicroKernel;
    using Castle.MicroKernel.Context;

    public class ConnectionStringConvention : ISubDependencyResolver
    {
        public bool CanResolve(
            CreationContext context,
            ISubDependencyResolver contextHandlerResolver,
            ComponentModel model,
            DependencyModel dependency)
        {
            return dependency.TargetType == typeof(string)
                && dependency.DependencyKey.EndsWith("ConnectionString");
        }

        public object Resolve(
            CreationContext context,
            ISubDependencyResolver contextHandlerResolver,
            ComponentModel model,
            DependencyModel dependency)
        {
            var name = dependency.DependencyKey.Replace("ConnectionString", "");
            return ConfigurationManager.ConnectionStrings[name].ConnectionString;
        }
    }
}

csharp 用于以所选元素阵列的词典顺序生成所有排列的扩展方法。

用于以所选元素阵列的词典顺序生成所有排列的扩展方法。

AllPermutationsWithSelector.cs
// http://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order
public static IEnumerable<TRes> AllPermutationsWithSelector<TSource, TRes>(this TSource[] seq, Func<IEnumerable<TSource>, TRes> selector)
{
	int n = seq.Length;
	var arr = Enumerable.Range(0, n).ToArray();

	while (true)
	{
		// Building result string, then generating next permutation
		yield return selector(arr.Select(i => seq[i]));

		// Finding largest k such that a[k] > a[k - 1]
		int k = n;
		while (--k > 0 && (arr[k] < arr[k - 1])) { }
		if (k == 0) yield break;
		int temp = arr[k - 1];

		// Finding largest l such that a[l] > a[k]
		int l = seq.Length;
		while (arr[--l] < temp) { }

		// Swap values
		arr[k - 1] = arr[l];
		arr[l] = temp;

		// Reversing the sequence from a[k] up to a[n]
		for (int i = 0; i < (n - k) / 2; i++)
		{
			temp = arr[i + k];
			arr[i + k] = arr[n - 1 - i];
			arr[n - 1 - i] = temp;
		}
	}
}

csharp BetterDefaultModelBinder意味着所有集合属性都被实例化为空集合而不是null。

BetterDefaultModelBinder意味着所有集合属性都被实例化为空集合而不是null。

Global.cs
ModelBinders.Binders.DefaultBinder = new BetterDefaultModelBinder();
BetterDefaultModelBinder.cs
    public class BetterDefaultModelBinder : DefaultModelBinder
    {
        protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
        {
            var model = base.CreateModel(controllerContext, bindingContext, modelType);

            if (model == null || model is IEnumerable)
                return model;

            foreach (var property in modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                object value = property.GetValue(model);
                if (value != null)
                    continue;

                if (property.PropertyType.IsArray)
                {
                    value = Array.CreateInstance(property.PropertyType.GetElementType(), 0);
                    property.SetValue(model, value);
                }
                else if (property.PropertyType.IsGenericType)
                {
                    Type typeToCreate;
                    Type genericTypeDefinition = property.PropertyType.GetGenericTypeDefinition();
                    if (genericTypeDefinition == typeof(IDictionary<,>))
                    {
                        typeToCreate = typeof(Dictionary<,>).MakeGenericType(property.PropertyType.GetGenericArguments());
                    }
                    else if (genericTypeDefinition == typeof (IEnumerable<>) ||
                             genericTypeDefinition == typeof (ICollection<>) ||
                             genericTypeDefinition == typeof (IList<>))
                    {
                        typeToCreate = typeof(List<>).MakeGenericType(property.PropertyType.GetGenericArguments());
                    }
                    else
                    {
                        continue;
                    }

                    value = Activator.CreateInstance(typeToCreate);
                    property.SetValue(model, value);
                }
            }

            return model;
        }
    }

csharp 一种主要方法

一种主要方法

Program.cs
    class Program
    {
        static void Main()
        {
            try
            {
                var container = WindsorFactory.Create();

                RunTheHostFactory(container);
            }
            catch (Exception exception)
            {
                var assemblyName = typeof(Program).AssemblyQualifiedName;

                if (!EventLog.SourceExists(assemblyName))
                    EventLog.CreateEventSource(assemblyName, "Application");

                var log = new EventLog { Source = assemblyName };
                log.WriteEntry(string.Format("{0}", exception), EventLogEntryType.Error);
            }
        }

        private static void RunTheHostFactory(IWindsorContainer container)
        {
            HostFactory.Run(config =>
            {
                config.Service<IIrisMonitorService>(settings =>
                {
                    // use this to instantiate the service
                    settings.ConstructUsing(hostSettings => container.Resolve<IIrisMonitorService>());
                    settings.WhenStarted(service => service.Start());
                    settings.WhenStopped(service =>
                    {
                        service.Stop();
                        container.Release(service);
                        container.Dispose();
                    });
                });

                config.UseNLog();

                config.RunAsLocalSystem();

                var description = container.Resolve<ServiceDescription>();
                config.SetDescription(description.Description);
                config.SetDisplayName(description.DisplayName);
                config.SetServiceName(description.ServiceName);
            });
        }
    }

csharp Guard异常助手

Guard异常助手

Expressions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Ormazabal.PanelMonitoring.Helpers
{
    static class Expressions
    {
        public static string GetMemberName<T>(Expression<Func<T>> expression)
        {
            var memberExpression = expression.Body as MemberExpression;

            if (memberExpression == null)
                throw new ArgumentException("Expression must be a field or property accessor", "expression");

            return memberExpression.Member.Name;
        }
    }
}
Guard.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Ormazabal.PanelMonitoring.Helpers
{
    public static class Guard
    {
        public static void NotNull<T>(Expression<Func<T>> parameter)
        {
            if (parameter.Compile()() != null)
                return;

            string parameterName = Expressions.GetMemberName(parameter);

            throw new ArgumentNullException(parameterName);
        }

        public static void NotValid<T>(Expression<Func<T>> parameter, Func<T, bool> constraint)
        {
            Guard.NotNull(parameter);

            string parameterName = Expressions.GetMemberName(parameter);

            if (constraint(parameter.Compile()()))
                return;

            throw new ArgumentException("The supplied parameter does not satisfy conditions", parameterName);    
        }

        public static void NotNullOrEmpty(Expression<Func<string>> parameter)
        {
            Guard.NotNull(parameter);

            if (parameter.Compile()() != String.Empty)
                return;

            string parameterName = Expressions.GetMemberName(parameter);

            throw new ArgumentException("The string cannot be empty", parameterName);
        }
        
    }
}
Usage.cs
public Usage1(object someObject)
{
    Guard.NotNull(() => someObject);
    
}

public UsageWithStrings(string someString)
{
  Guard.NotNullOrEmpty(() => someString);
  
}

public UsageForValidation(int someInt)
{
  Guard.NotValid(() => someInt, p => p > 0 && p <= 10);
  
}