csharp IsNullOrEmpty反编译源

IsNullOrEmpty反编译源

NullOrEmpty.cs
public static bool IsNullOrEmpty(string value)
    {
      if (value != null)
        return value.Length == 0;
      else
        return true;
    }

csharp apiSignature.cs

apiSignature.cs
var apiKey = "apikey";
var secretKey = "secretkey";
 
// Generate a new globally unique identifier for the salt
var salt = System.Guid.NewGuid().ToString();
 
// Initialize the keyed hash object using the secret key as the key
HMACSHA256 hashObject = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
 
// Computes the signature by hashing the salt with the secret key as the key
var signature = hashObject.ComputeHash(Encoding.UTF8.GetBytes(salt));
 
// Base 64 Encode
var encodedSignature = Convert.ToBase64String(signature);
 
// URLEncode
encodedSignature = System.Web.HttpUtility.UrlEncode(encodedSignature);

csharp 解析通过T-SQL从连接子句推断外键 - 注意:不完整。只支持seroc中的sprocs和一些语法结构

解析通过T-SQL从连接子句推断外键 - 注意:不完整。在搜索中仅支持sprocs和一些语法结构(例如,它对游标和while循环无视)。也忽略复合键。将其扩展到其他语言的对比不应该那么难,但超出我的需要。

gistfile1.cs
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Data.Schema.ScriptDom;
using Microsoft.Data.Schema.ScriptDom.Sql;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Joins
{
    class ForeignKey
    {
        public string Table1 { get; set; }
        public string Key1 { get; set; }
        public string Table2 { get; set; }
        public string Key2 { get; set; }
    }

    class StatementContext
    {
        public Dictionary<string, string> Aliases {get;set;}
        public List<ForeignKey> FKs { get; set; }
        
        public StatementContext()
        {
            Aliases = new Dictionary<string, string>();
            FKs = new List<ForeignKey>();
        }

        public void Alias(TableSource ts)
        {
            if (ts.GetType() == typeof(SchemaObjectTableSource))
            {
                var source = ts as SchemaObjectTableSource;
                if (source.Alias != null)
                {
                    var alias = source.Alias.Value.ToLower();
                    if (!Aliases.ContainsKey(alias))
                        Aliases.Add(alias, source.SchemaObject.BaseIdentifier.Value);
                }
            }
        }


        public string UnAlias(string s)
        {
            if (Aliases.ContainsKey(s.ToLower()))
                return Aliases[s.ToLower()];
            else
                return s;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            string filePath = args[0];
            string Script = string.Empty;
            //System.Diagnostics.Debugger.Break();

            using (StreamReader streamReader = new StreamReader(filePath))
            {
                Script = streamReader.ReadToEnd();
            }

            IList<string> errorsList;
            var TSqlScript = ParseScript(Script, out errorsList);

            foreach (var b in TSqlScript.Batches)
                SearchStatmentList(b.Statements);

        }

        private static void SearchStatement(TSqlStatement s)
        {
            if (s != null)
            {
                var t = TextFrom(s);
                var st = s.GetType();

                if (st == typeof(AlterProcedureStatement))
                    SearchStatmentList((((AlterProcedureStatement)s).StatementList.Statements));
                else if (st == typeof(CreateProcedureStatement))
                    SearchStatmentList((((CreateProcedureStatement)s).StatementList.Statements));
                else if (st == typeof(BeginEndBlockStatement))
                    SearchStatmentList((((BeginEndBlockStatement)s).StatementList.Statements));
                else if (st == typeof(InsertStatement))
                {
                    var i = (InsertStatement)s;
                    if (i.InsertSource.GetType() == typeof(SelectStatement))
                        SearchStatement(i.InsertSource as SelectStatement);
                }

                else if (st == typeof(IfStatement))
                {
                    var i = s as IfStatement;

                    SearchStatement(i.ThenStatement);
                    SearchStatement(i.ElseStatement);

                }
                else if (st == typeof(SelectStatement))
                {

                    FindFromClauses(((SelectStatement)s).QueryExpression);
                }
            }
        }

        private static void SearchStatmentList(IList<TSqlStatement> statements)
        {
            foreach (var s in statements)
                SearchStatement(s);
        }

        private static void FindFromClauses(QueryExpression q)
        {
            if (q.GetType() == typeof(BinaryQueryExpression))
            {
                var binary = q as BinaryQueryExpression;


                FindFromClauses(binary.FirstQueryExpression);
                FindFromClauses(binary.SecondQueryExpression);
            }
            else if (q.GetType() == typeof(QuerySpecification))
            {
                var qs = q as QuerySpecification;

                var t = TextFrom(q);
                foreach (var from in qs.FromClauses)
                {
                    if (from.GetType() == typeof(QualifiedJoin))
                    {
                        StatementContext ctx = new StatementContext();
                        WalkJoin(from as QualifiedJoin, ctx);

                        foreach (var r in ctx.FKs)
                        {
                            Console.WriteLine(string.Format("{0}.{1} = {2}.{3}", ctx.UnAlias(r.Table1), r.Key1, ctx.UnAlias(r.Table2), r.Key2));
                        }
                    }
                }
            }
        }

        private static void WalkJoin(QualifiedJoin j, StatementContext context)
        {
            var t = TextFrom(j);
            if (j.SearchCondition.GetType() == typeof(BinaryExpression))
            {
                var b = j.SearchCondition as BinaryExpression;
                t = TextFrom(b);
                context.Alias(j.FirstTableSource);
                context.Alias(j.SecondTableSource);
                if (b.BinaryExpressionType == BinaryExpressionType.Equals)
                {
                    if (b.FirstExpression.GetType() == typeof(Column) &&
                        b.SecondExpression.GetType() == typeof(Column))
                    {
                        context.FKs.Add(new ForeignKey()
                        {
                            Table1 = ((Column)b.FirstExpression).Identifiers[0].Value,
                            Key1 = ((Column)b.FirstExpression).Identifiers[1].Value,
                            Table2 = ((Column)b.SecondExpression).Identifiers[0].Value,
                            Key2 = ((Column)b.SecondExpression).Identifiers[1].Value
                        });
                    }
                }
                if (j.FirstTableSource.GetType() == typeof(QualifiedJoin))
                {
                    WalkJoin((QualifiedJoin)j.FirstTableSource, context);
                }
                if (j.SecondTableSource.GetType() == typeof(QualifiedJoin))
                {
                    WalkJoin((QualifiedJoin)j.SecondTableSource, context);
                }
            }
        }

        private static string TextFrom(TSqlFragment f)
        {
            if (f == null) return null;

            var sb = new StringBuilder();
            for (int i = f.FirstTokenIndex; i <= f.LastTokenIndex; i++)
            {
                sb.Append(f.ScriptTokenStream[i].Text);
            }
            return sb.ToString();
        }

        public static TSqlScript ParseScript(string script, out IList<string> errorsList)
        {
            IList<ParseError> parseErrors;
            TSql100Parser tsqlParser = new TSql100Parser(true);
            TSqlFragment fragment;
            using (StringReader stringReader = new StringReader(script))
            {
                fragment = (TSqlFragment)tsqlParser.Parse(stringReader, out parseErrors);
            }
            errorsList = new List<string>();
            if (parseErrors.Count > 0)
            {
                var retMessage = string.Empty;
                foreach (var error in parseErrors)
                {
                    retMessage += error.Identifier + " - " + error.Message + " - position: " + error.Offset + "; ";
                }

            }
            return (TSqlScript)fragment;
        }
    }
}

csharp 测试C#内联方法(框架4.5)

测试C#内联方法(框架4.5)

Inlining.cs
/*
 * Following code for test an method will be inlined by JIT or not
 * Tested on Framework 4.5, Win8 x64
 * 
 * http://blogs.msdn.com/b/ericgu/archive/2004/01/29/64717.aspx
 * http://blogs.microsoft.co.il/blogs/sasha/archive/2012/01/20/aggressive-inlining-in-the-clr-4-5-jit.aspx
 */

using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Fa(1)); // Main
        Console.WriteLine(Fb(1)); // Fb
        Console.WriteLine(Fc(1)); // Main
        Console.WriteLine(Fd(1)); // Main
        Console.WriteLine(Fe(1)); // Fe if Platform target is x86, Main if x64
        Console.WriteLine(Ff(1)); // Ff
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    static string Fa(int a)
    {
        var s = a.ToString();
        var b = uint.Parse(s);
        var c = (a + b) / 2;
        var ss = c.ToString();
        var d = int.Parse(ss);
        return new StackFrame().GetMethod().Name;
    }

    static string Fb(int a)
    {
        var s = a.ToString();
        var b = uint.Parse(s);
        var c = (a + b) / 2;
        var ss = c.ToString();
        var d = int.Parse(ss);
        return new StackFrame().GetMethod().Name;
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    static string Fc(int a)
    {
        return new StackFrame().GetMethod().Name;
    }

    static string Fd(int a)
    {
        return new StackFrame().GetMethod().Name;
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    static string Fe(int a)
    {
        a += 1;
        return new StackFrame().GetMethod().Name;
    }

    static string Ff(int a)
    {
        a += 1;
        return new StackFrame().GetMethod().Name;
    }
}

csharp 使用带有.net的ffmpeg从视频创建缩略图图像

使用带有.net的ffmpeg从视频创建缩略图图像

CreateThumbFromVideo.cs
using System;
using System.Diagnostics;
using System.IO;
using System.Web;

namespace WebApp.HelperClass
{
    public class CreateThumbFromVideo
    {
        /// <summary>
        /// created by ~kad1r
        /// send files without mappath
        /// like "/video/videolink1.avi"
        /// function puts mappath itself
        /// download ffmpeg.exe - http://www.speedyshare.com/mRbUN/ffmpeg.rar
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static string generateThumb(string file)
        {
            string thumb = "";

            try
            {
                FileInfo fi = new FileInfo(HttpContext.Current.Server.MapPath(file));
                string filename = Path.GetFileNameWithoutExtension(fi.Name);
                Random random = new Random();
                int rand = random.Next(1, 9999999);
                string newfilename = "/video/" + filename + "___(" + rand.ToString() + ").jpg";
                var processInfo = new ProcessStartInfo();
                processInfo.FileName = "\"" + HttpContext.Current.Server.MapPath("/video/ffmpeg.exe") + "\"";
                processInfo.Arguments = string.Format("-ss {0} -i {1} -f image2 -vframes 1 -y {2}", 5, "\"" + HttpContext.Current.Server.MapPath(file) + "\"", "\"" + HttpContext.Current.Server.MapPath(newfilename) + "\"");
                processInfo.CreateNoWindow = true;
                processInfo.UseShellExecute = false;
                using (var process = new Process())
                {
                    process.StartInfo = processInfo;
                    process.Start();
                    process.WaitForExit();
                    thumb = newfilename;
                }
            }
            catch (Exception ex)
            {
                string error = ex.Message;
            }

            return thumb;
        }
    }
}

csharp 将当前请求重定向回当前页面

将当前请求重定向回当前页面

RedirectSelf.cs
/// <summary>
/// Redirect the current request back to the current page = full page reload
/// </summary>
public static void RedirectSelf(this HttpResponse response)
{
    response.Redirect(HttpContext.Current.Request.RawUrl);
}

csharp AppDomain中的CreateProxy实例

AppDomain中的CreateProxy实例

Remote.cs
public sealed class Remote<T> where T : MarshalByRefObject
{
    private readonly AppDomain domain;
    private readonly T remoteObject;

    private Remote(AppDomain domain, T remoteObject)
    {
        this.domain = domain;
        this.remoteObject = remoteObject;
    }

    public T RemoteObject
    {
        get { return remoteObject; }
    }

    public AppDomain Domain
    {
        get { return domain; }
    }

    public static Remote<T> CreateProxy(AppDomain domain, params object[] constructorArgs)
    {
        if (domain == null)
        {
            throw new ArgumentNullException("domain");
        }

        var type = typeof(T);

        var proxy = (T)domain.CreateInstanceAndUnwrap(
            type.Assembly.FullName,
            type.FullName,
            false,
            BindingFlags.CreateInstance,
            null,
            constructorArgs,
            null,
            null);

        return new Remote<T>(domain, proxy);
    }
}

csharp 将NameValueCollection转换为Querystring

将NameValueCollection转换为Querystring

NVC2QueryString.cs
/// <summary>
/// Constructs a NameValueCollection into a query string.
/// </summary>
/// <remarks>Consider this method to be the opposite of "System.Web.HttpUtility.ParseQueryString"</remarks>
/// <param name="parameters">The NameValueCollection</param>
/// <param name="delimiter">The String to delimit the key/value pairs</param>
/// <returns>A key/value structured query string, delimited by the specified String</returns>
public static string ToQueryString(this NameValueCollection parameters, String delimiter, Boolean omitEmpty)
{           
    if (String.IsNullOrEmpty(delimiter))
        delimiter = "&";

    Char equals = '=';
    List<String> items = new List<String>();

    for (int i = 0; i < parameters.Count; i++)
    {
        foreach (String value in parameters.GetValues(i))
        {
            Boolean addValue = (omitEmpty) ? !String.IsNullOrEmpty(value) : true;
            if (addValue)
                items.Add(String.Concat(parameters.GetKey(i), equals, HttpUtility.UrlEncode(value)));
        }
    }

    return String.Join(delimiter, items.ToArray());
}

//much easier:

public static string ToQueryString(this NameValueCollection parameters)
{
    var items = parameters.AllKeys
        .SelectMany(parameters.GetValues, (k, v) => k + "=" + HttpUtility.UrlEncode(v))
        .ToArray();
        
    return String.Join("&", items);
}

HttpContext context = HttpContext.Current;

string formValues = "";
for (int i = 0; i < context.Request.Form.Count; i++)
{
    string strValues = "";
    foreach (var strValue in context.Request.Form.GetValues(context.Request.Form.Keys[i]))
    {
        strValues += strValue + ",";
    }
    formValues += context.Request.Form.Keys[i] + " - " + strValues + Environment.NewLine;
}

csharp 将选择项目设置为下拉列表

将选择项目设置为下拉列表

Helpers.cs
using System;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;

using MiniRideAndDrive.Web.Data;

public static partial class Helpers {

    public static string BaseUrl {
        get { return HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/"); }
    }

    public static void SetSelectedListItem(this DropDownList ddl, string value) {
        ListItem li;

        li = ddl.Items.FindByValue(value);
        if (li != null) li.Selected = true;
    }

    public static void PopulateItems(this DropDownList ddl, object dataSource, string dataTextField, string dataValueField, string firstItemText) {
        if (ddl == null)
            return;

        ddl.DataTextField = dataTextField;
        ddl.DataValueField = dataValueField;
        ddl.DataSource = dataSource;
        ddl.DataBind();
        
        if(!string.IsNullOrEmpty(firstItemText))
            ddl.Items.Insert(0, new ListItem(firstItemText, "null"));
    }
}

csharp 拖曳

拖曳

ShuffleExtension.cs
public static void Shuffle<T>(this T[] array, Random random)
  {
		int n = array.Length;
		while (n > 1)
		{
			int k = random.Next(n--);
			T temp = array[n];
			array[n] = array[k];
			array[k] = temp;
		}
	}
	
	public static void Shuffle<T>(this IList<T> collection, Random random = null)
	{
		random = random ?? new Random();
		
		int n = collection.Count();
		
		while (n > 1)
		{
			int k = random.Next(n--);
			T temp = collection[n];
			collection[n] = collection[k];
			collection[k] = temp;
		}
	}