csharp 动态加载库

动态加载库

dynamicLoadLibrary.cs
AppDomainSetup appDomainSetup=new AppDomainSetup();
appDomainSetup.LoaderOptimization=LoaderOptimization.SingleDomain; 
System.Security.Policy.Evidence evidence = new System.Security.Policy.Evidence ();
AppDomain ad = AppDomain.CreateDomain("LabMapDotNetDomain", new System.Security.Policy.Evidence (),appDomainSetup); 



string DllPath = Application.StartupPath + @"\LabMapDotNet.dll ";
System.Reflection.Assembly assmble = System.Reflection.Assembly.LoadFile(DllPath);
Type tmpType = assmble.GetType("LabMapDotNet.LabMap");
System.Reflection.PropertyInfo proInfo = tmpType.GetProperty("Instance");
object obj = proInfo.GetValue(null, null);
labmap = obj as ILabMap;

Thread.Sleep(5000);
AppDomain.Unload(ad);

csharp 在.NET中显示DebuggerDisplay属性。

在.NET中显示DebuggerDisplay属性。

DebuggerDisplay.cs
[DebuggerDisplay("Rate - {InsuranceRate} Age (months) - {AgeInMonths}")]
public class Car
{
 public decimal InsuranceRate { get; set; }
 public int AgeInMonths { get; set; }
 public int NumberOfMiles { get; set; }
 public int NumberOfPreviousOwners { get; set; }
 public int NumberOfCollisions { get; set; }
}
CarWithToString.cs
[DebuggerDisplay("{ToString, nq}")]
public class Car
{
   public decimal InsuranceRate { get; set; }
   public int AgeInMonths { get; set; }
   public int NumberOfMiles { get; set; }
   public int NumberOfPreviousOwners { get; set; }
   public int NumberOfCollisions { get; set; }
 
   public override string ToString()
   {
      return string.Format("Rate - {0}. Age (months) - {1}.", this.InsuranceRate, this.AgeInMonths);
   }
}
CarClass.cs
public class Car
{
   public decimal InsuranceRate { get; set; }
   public int AgeInMonths { get; set; }
   public int NumberOfMiles { get; set; }
   public int NumberOfPreviousOwners { get; set; }
   public int NumberOfCollisions { get; set; }
}

csharp .NET文件,用于显示如何使用和配置TraceSource进行日志记录。

.NET文件,用于显示如何使用和配置TraceSource进行日志记录。

TraceSourceLogging.cs
namespace TraceSourceLogging
{
  using System.Diagnostics;

  class Program
  {
    private static TraceSource traceSource = new TraceSource("Log");

    static void Main(string[] args)
    {
       traceSource.TraceData(TraceEventType.Verbose, 1, "Now we're logging!");
       traceSource.Flush();
       traceSource.Close();
    }
  }
}
TraceSourceConfig.xml
<?xml version="1.0"?>
<configuration>
  <system.diagnostics>
    <sources>
      <source name="Log" switchValue="Information" switchType="System.Diagnostics.SourceSwitch">
        <listeners>
          <add name="myListener"/>
          <remove name="Default"/>
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add name="myListener"
        type="System.Diagnostics.TextWriterTraceListener"
        initializeData="myListener.log">
      </add>
    </sharedListeners>
  </system.diagnostics>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
</configuration>
SetTraceSourceConfigOff.xml
<source name="Log" switchValue="Off" switchType="System.Diagnostics.SourceSwitch">
  <listeners>
    <add name="myListener"/>
    <remove name="Default"/>
  </listeners>
</source>
MultipleTraceSourceConfig.xml
<system.diagnostics>
  <sources>
    <source name="Log" switchValue="Information" switchType="System.Diagnostics.SourceSwitch">
      <listeners>
        <add name="myListener"/>
        <remove name="Default"/>
      </listeners>
    </source>
    <source name="EmployeeLog" switchValue="Information" switchType="System.Diagnostics.SourceSwitch">
      <listeners>
        <add name="myListener"/>
        <remove name="Default"/>
      </listeners>
    </source>
    <source name="PersonLog" switchValue="Information" switchType="System.Diagnostics.SourceSwitch">
      <listeners>
        <add name="myListener"/>
        <remove name="Default"/>
      </listeners>
    </source>
  </sources>
  <sharedListeners>
    <add name="myListener"
      type="System.Diagnostics.TextWriterTraceListener"
      initializeData="myListener.log">
    </add>
  </sharedListeners>
</system.diagnostics>
CustomLoggingWithTraceSource.cs
public class Person
{
    private static readonly TraceSource traceSource = new TraceSource("PersonLog");

    public string FirstName { get; set; }
    public string LastName { get; set; }

    public bool IsValid()
    {
        var isValid = (!string.IsNullOrWhiteSpace(this.FirstName) || !string.IsNullOrWhiteSpace(this.LastName));
        traceSource.TraceInformation(string.Format("Is {0} {1} valid - {2}", this.FirstName, this.LastName, isValid));
        return isValid;
    }
}

public class Employee : Person
{
    private static readonly TraceSource traceSource = new TraceSource("EmployeeLog");

    public string Department { get; set; }
    public Person Manager { get; set; }
    public bool IsActive { get; set; }

    public bool IsDepartmentValid()
    {
        var isValid = !string.IsNullOrWhiteSpace(this.Department);
        traceSource.TraceInformation(string.Format("Is the {0} department valid - {1}", this.Department, isValid));
        return isValid;
    }
}

csharp 执行时间

执行时间

time_of_execution.cs
using System.Diagnostics; 

Stopwatch sWatch = new Stopwatch();

  sWatch.Start();

// some operations
  
  sWatch.Stop();

  MessageBox.Show(sWatch.ElapsedMilliseconds.ToString());

csharp GraphicTrackerを使用してRPG风シンボルの移动

GraphicTrackerを使用してRPG风シンボルの移动

GraphicTracker1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.EngineCore;

namespace MappingApplication_CS
{
    public partial class Form1 : Form
    {
        double g_X;
        double g_Y;

        IGraphicTracker g_pGraphicTracker;
        IGraphicTrackerSymbol g_pGraphicTrackerSymbol1;
        IGraphicTrackerSymbol g_pGraphicTrackerSymbol2;
        int g_ID;
        bool g_Flag;

        public Form1()
        {
            InitializeComponent();

            //GraphicTrackerの初期化
            g_pGraphicTracker = new GraphicTrackerClass();
            g_pGraphicTracker.Initialize(axMapControl1.Map as IBasicMap);

            string path = @".\saga.png";
            string path2 = @".\saga2.png";

            g_pGraphicTrackerSymbol1 = g_pGraphicTracker.CreateSymbolFromPath(path, path);
            g_pGraphicTrackerSymbol2 = g_pGraphicTracker.CreateSymbolFromPath(path2, path2);
            
            IPoint pPoint = new PointClass();
            pPoint.PutCoords(0, 0);
            g_X = 1278000;
            g_Y = 341000;
            g_ID = g_pGraphicTracker.Add(pPoint as IGeometry, g_pGraphicTrackerSymbol1);
            g_pGraphicTracker.SetOrientationMode(g_ID, esriGTOrientation.esriGTOrientationFixed);

            //Timerイベント
            Timer timer = new Timer();
            timer.Interval = 1000;
            timer.Tick += new EventHandler(timer1_Tick);
            timer.Start();
        }


        //現在のマウスカーソル位置の座標をステータスバーに表示する
        private void axMapControl1_OnMouseMove(object sender, ESRI.ArcGIS.Controls.IMapControlEvents2_OnMouseMoveEvent e)
        {
            string x = System.Convert.ToString(e.mapX);
            string y = System.Convert.ToString(e.mapY);
            toolStripStatusLabel1.Text = "X: " + x + "  " + "Y: " + y;
        }

        //タイマー イベント ハンドラ
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (g_Flag == true)
            {
                g_pGraphicTracker.SetSymbol(0, g_pGraphicTrackerSymbol1);
                g_Flag = !g_Flag;
            }
            else
            {
                g_pGraphicTracker.SetSymbol(0, g_pGraphicTrackerSymbol2);
                g_Flag = !g_Flag;
            }

            g_pGraphicTracker.MoveTo(g_ID, g_X, g_Y, 0.0);

        }

        private void axMapControl1_OnKeyDown(object sender, ESRI.ArcGIS.Controls.IMapControlEvents2_OnKeyDownEvent e)
        {
            switch (e.keyCode)
            {
                //8キー
                case (int)104:
                    g_Y += 50;
                    break;

                //2キー
                case (int)98:
                    g_Y -= 50;
                    break;
                //4キー
                case (int)100:
                    g_X -= 50;
                    break;

                //6キー
                case (int)102:
                    g_X += 50;
                    break;
            }
        }
    }
}

csharp 小类调用IronPython并使用它的参数执行传入的方法名称。

小类调用IronPython并使用它的参数执行传入的方法名称。

PythonEngine.cs
namespace PythonEnine
{
    using IronPython.Hosting;
    using Microsoft.Scripting.Hosting;

    /// <summary>
    /// Creates the Python engine and invokes methods
    /// </summary>
    public class PythonEngine
    {
        private ScriptSource scriptSource;
        private CompiledCode compiledCode;
        private ScriptScope scope;
        private ScriptEngine engine;

        public PythonEngine(string scriptPath)
        {
            this.Script = scriptPath;
        }

        public string Script { get; set; }

        public dynamic InvokeMethodWithParameters(string methodName, params object[] parameters)
        {
            engine = Python.CreateEngine();
            scriptSource = engine.CreateScriptSourceFromFile(this.Script);
            compiledCode = scriptSource.Compile();
            scope = engine.CreateScope();

            compiledCode.Execute(scope);

            dynamic pythonMethod = scope.GetVariable(methodName);

            return engine.Operations.Invoke(pythonMethod, parameters);
        }
    }
}

csharp C#:JsonResult替代ASP.NET MVC。

C#:JsonResult替代ASP.NET MVC。

JsonNetResult.cs
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace System.Web.Mvc
{
    internal class JsonNetResult : JsonResult
    {
        static IList<JsonConverter> DefaultConverters = new List<JsonConverter>()
        {
            new StringEnumConverter(), //new StringEnumConverter() { CamelCaseText = true },
            new IsoDateTimeConverter(),
        };

        public JsonSerializerSettings SerializerSettings { get; set; }
        public Formatting Formatting { get; set; }

        public JsonNetResult()
        {
            this.SerializerSettings = new JsonSerializerSettings()
            {
                Converters = DefaultConverters,
                //ContractResolver = new CamelCasePropertyNamesContractResolver(),
            };
        }

        public JsonNetResult(JsonResult original)
            : this()
        {
            this.ContentEncoding = original.ContentEncoding;
            this.ContentType = original.ContentType;
            this.JsonRequestBehavior = original.JsonRequestBehavior;
            this.Data = original.Data;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            HttpResponseBase response = context.HttpContext.Response;

            response.ContentType = !string.IsNullOrEmpty(ContentType)
                ? ContentType
                : "application/json";

            if (ContentEncoding != null)
                response.ContentEncoding = ContentEncoding;

            if (Data != null)
            {
                JsonTextWriter writer = new JsonTextWriter(response.Output) { Formatting = Formatting };

                JsonSerializer serializer = JsonSerializer.Create(this.SerializerSettings);
                serializer.Serialize(writer, Data);

                writer.Flush();
            }
        }
    }

    internal static class ControllerExtensions
    {
        public static JsonResult JsonNet(this Controller controller, JsonResult result)
        {
            return new JsonNetResult(result);
        }
    }
}
JsonNetAttribute.cs
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace System.Web.Mvc
{
    internal class JsonNetAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
            var result = filterContext.Result as JsonResult;
            if (result != null) filterContext.Result = new JsonNetResult(result);
        }
    }
}

csharp 从月份值获取月份名称

从月份值获取月份名称

Get-month-name.cs
string monthName = new DateTime(2010, monthValue, 1) .ToString("MMM", CultureInfo.InvariantCulture);

csharp 从月份值获取月份名称

从月份值获取月份名称

Get-month-name.cs
string monthName = new DateTime(2010, monthValue, 1) .ToString("MMM", CultureInfo.InvariantCulture);

csharp 适用于Windows Phone 8的1-File Robust RESTful API内部层

适用于Windows Phone 8的1-File Robust RESTful API内部层

RESTAPI.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
namespace RESTAPI
{
    /// <summary>
    /// Encapsulates functionality to make it possible to make
    /// RESTful API calls on web resources and services
    /// </summary>
    class RESTAPHandler
    {
        public delegate void RESTSuccessCallback(Stream stream);
        public delegate void RESTErrorCallback(String reason);

        public  void get(Uri uri, Dictionary<String,String> extra_headers, RESTSuccessCallback success_callback, RESTErrorCallback error_callback)
        {
            HttpWebRequest request = WebRequest.CreateHttp(uri);
            
            if(extra_headers != null)
            foreach (String header in extra_headers.Keys)
                try
                {
                    request.Headers[header] = extra_headers[header];
                }
                catch (Exception) { }

            request.BeginGetResponse((IAsyncResult result) => {
                HttpWebRequest req = result.AsyncState as HttpWebRequest;
                if (req != null)
                {
                    try
                    {
                        WebResponse response = req.EndGetResponse(result);
                        success_callback(response.GetResponseStream());                        
                    }
                    catch (WebException e)
                    {
                        error_callback(e.Message);
                        return;
                    }
                }
            }, request);
        }

        public void post(Uri uri,  Dictionary<String, String> post_params, Dictionary<String, String> extra_headers, RESTSuccessCallback success_callback, RESTErrorCallback error_callback)
        {
            HttpWebRequest request = WebRequest.CreateHttp(uri);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";

            if (extra_headers != null)
                foreach (String header in extra_headers.Keys)
                    try
                    {
                        request.Headers[header] = extra_headers[header];
                    }
                    catch (Exception) { }


            request.BeginGetRequestStream((IAsyncResult result) =>
            {
                HttpWebRequest preq = result.AsyncState as HttpWebRequest;
                if (preq != null)
                {
                    Stream postStream = preq.EndGetRequestStream(result);

                    StringBuilder postParamBuilder = new StringBuilder();
                    if (post_params != null)
                        foreach (String key in post_params.Keys)
                            postParamBuilder.Append(String.Format("{0}={1}&", key, post_params[key]));

                    Byte[] byteArray = Encoding.UTF8.GetBytes(postParamBuilder.ToString());

                    postStream.Write(byteArray, 0, byteArray.Length);
                    postStream.Close();


                    preq.BeginGetResponse((IAsyncResult final_result) =>
                    {
                        HttpWebRequest req = final_result.AsyncState as HttpWebRequest;
                        if (req != null)
                        {
                            try
                            {
                                WebResponse response = req.EndGetResponse(final_result);
                                success_callback(response.GetResponseStream());
                            }
                            catch (WebException e)
                            {
                                error_callback(e.Message);
                                return;
                            }
                        }
                    }, preq);
                }
            }, request);            
        }
    }
}