分类目录归档:.Net

.Net

Using the ASP.NET MVC 3 Logon returnUrl Parameter

razor:

@{
  ViewBag.Title = "登陆";
  Layout = "~/Views/Shared/_LoginLayout.cshtml";
  string retUrl = "";
  if (Request["ReturnUrl"] != null)
  {
    retUrl = ViewContext.HttpContext.Request["ReturnUrl"];
  }
}
@using (Html.BeginForm("Logon", "Account", new { model = this.Model, ReturnUrl = retUrl }))
{
//form
}

controller:

[HttpPost]
public ActionResult LogOn(LogOnModel model, string ReturnUrl)
{
  ViewBag.UserLogOut = true;
  if (!ModelState.IsValid)
    return View("Logon");
  if (ModelState.IsValid)
  {
    try
    {
      //login
    }
    catch (Exception e)
    {
      ModelState.AddModelError("", e.Message);
      return View(model);
    }
  }
  if (!string.IsNullOrEmpty(ReturnUrl))
    return Redirect(ReturnUrl);//return
  return RedirectToAction("Index", "Product");
}

UserSessionAuthorizeAttribute:

public class UserSessionAuthorizeAttribute : AuthorizeAttribute
{
  public override void OnAuthorization(AuthorizationContext  filterContext)
  {
    base.OnAuthorization(filterContext);
    if(//check session)
    {
      filterContext.Result = new RedirectToRouteResult(
        new System.Web.Routing.RouteValueDictionary
            {
              { "controller", "Account" },
              { "action", "LogOn" },
              { "ReturnUrl", filterContext.HttpContext.Request.RawUrl }
            });
    }
  }
}

Umbraco中生成Breadcrumb,create Breadcrumb in Umbraco

 
我的Breadcrumb是用Partial
首先新建一个Partial:Breadcrumb
2012-01-19_17-33-33
在里面插入代码:

@inherits RenderViewPage
@using Umbraco.Cms.Web
@using System
 @{
     var Homepage = @DynamicModel;
     var lis = string.Empty;
     lis = string.Format("
  • {0}
  • ", Homepage.Name) + lis; while (Homepage.ContentType.Alias != "homePage";) { Homepage = Homepage.Parent; lis = string.Format("
  • {1}
  • ", Homepage.Url, Homepage.Name) + lis; } }
      @Html.Raw(lis)

    这样就行了
    在使用的地方:
    @Html.Partial(“Breadcrumb”)
     
    效果如下:
    2012-01-19_17-33-52
    当然必要的css还是需要的,这里就不贴了.

    MVC3-Razor输出Html

    输出HTML代码(包含标签):直接输出,

    string html = "文本";
    @html

    输出HTML内容(不包含标签):有两种方法,

    第一种:

    IHtmlString html=new HtmlString("文本");
    @html ;

    第二种:

    string html = "文本";
    @Html.Raw(html);

    C#中实现单实例

    
    public class SingletonDemo
    {
        private static SingletonDemo theSingleton = null;
        private SingletonDemo() { }
        public static SingletonDemo Instance()
        {
            if (theSingleton == null)
            {
                theSingleton = new SingletonDemo();
            }
            return theSingleton;
        }
        static void Main(string[] args)
        {
            SingletonDemo s1 = SingletonDemo.Instance();
            SingletonDemo s2 = SingletonDemo.Instance();
            if (s1.Equals(s2))
            {
                Console.WriteLine("see, only one instance!");
            }
        }
    }
    

    .net mvc 中使用ActionFilterAttribute过滤器

    过滤器是mvc中常用的
    在.net mvc 中直接继承和实现ActionFilterAttribute类就可以了
    很简单
    下面贴出一个例子
    过滤器:

    
    public class UseStopwatchAttribute : ActionFilterAttribute
    {
      public override void OnActionExecuting(ActionExecutingContext filterContext)
      {
        Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start();
        filterContext.Controller.ViewData["stopWatch"] = stopWatch;
      }
      public override void OnResultExecuting(ResultExecutingContext filterContext)
      {
        Stopwatch stopWatch = (Stopwatch)filterContext.Controller.ViewData["stopWatch"];
        stopWatch.Stop();
        Random r = new Random();
        filterContext.Controller.ViewData["elapsedTime"] = stopWatch.ElapsedMilliseconds
        + " milliseconds -   Rand  " + r.Next(1000).ToString();
      }
    }
    

    这的话这个过滤器就写好了
    在使用的时候只要在controller上写上就行了

    
    [UseStopwatch]
    public class ProductsController : Controller
    {
      //
      // GET: /Store/Products/
      public ActionResult List()
      {
        return View();
      }
      public ActionResult Details()
      {
        return View();
      }
      public ActionResult AddReview()
      {
        return View();
      }
    }
    

    C#中同步、异步读取进程输出信息

    1、异步的:

    p.StartInfo.RedirectStandardError = true;
    p.ErrorDataReceived += new DataReceivedEventHandler(OutputInfo);
    p.Start();
    p.BeginErrorReadLine();
    
    private void OutputInfo(object sendProcess, DataReceivedEventArgs output){
      if (!String.IsNullOrEmpty(output.Data))
      {
        //处理方法...
      }
    }

    2、同步的

    p.StartInfo.RedirectStandardError = true;
    p.Start();
    StreamReader sr = ffmpeg.StandardError;
    p.WaitForExit();//之后就可以从sr里读了
    

    C#中枚举类型enum的使用

    1、关于enum的定义

    enum Fabric
    {
      Cotton = 1,
      Silk = 2,
      Wool = 4,
      Rayon = 8,
      Other = 128
    }
    

    2、符号名和常数值的互相转换

    Fabric fab = Fabric.Cotton;
    int fabNum = (int)fab;//转换为常数值。必须使用强制转换。
    Fabric fabString = (Fabric)1;//常数值转换成符号名。如果使用ToString(),则是((Fabric)1).ToString(),注意必须有括号。
    string fabType = fab.ToString();//显示符号名
    string fabVal = fab.ToString ("D");//显示常数值
    

    3、获得所有符号名的方法(具体参见Enum类)

    public enum MyFamily
    {
      YANGZHIPING = 1,
      GUANGUIQIN = 2,
      YANGHAORAN = 4,
      LIWEI = 8,
      GUANGUIZHI = 16,
      LISIWEN = 32,
      LISIHUA = 64,
    }
    foreach (string s in Enum.GetNames(typeof(MyFamily)))
    {
      Console.WriteLine(s);
    }
    

    4、将枚举作为位标志来处理

    根据下面的两个例子,粗略地说,一方面,设置标志[Flags]或者[FlagsAttribute],则表明要将符号名列举出来;另一方面,可以通过强制转换,将数字转换为符号名。说不准确。看下面的例子体会吧。注意:

    • 例一:
    Fabric fab = Fabric.Cotton | Fabric.Rayon | Fabric.Silk;
    Console.WriteLine("MyFabric = {0}", fab);//输出:Fabric.Cotton | Fabric.Rayon | Fabric.Silk;
    
    • 例二:
    class FlagsAttributeDemo
    {
      // Define an Enum without FlagsAttribute.
      enum SingleHue : short
      {
        Black = 0,
        Red = 1,
        Green = 2,
        Blue = 4
      };
      // Define an Enum with FlagsAttribute.
      [FlagsAttribute]
      enum MultiHue : short
      {
        Black = 0,
        Red = 1,
        Green = 2,
        Blue = 4
      };
      static void Main( )
      {
        Console.WriteLine(
        "This example of the FlagsAttribute attribute n" +
        "generates the following output." );
        Console.WriteLine(
        "nAll possible combinations of values of an n" +
        "Enum without FlagsAttribute:n" );
        // Display all possible combinations of values.
        for( int val = 0; val <= 8; val++ )
        Console.WriteLine( "{0,3} – {1}",  val, ( (SingleHue)val ).ToString( ) );
        Console.WriteLine(  "nAll possible combinations of values of an n" + "Enum with FlagsAttribute:n" );
        // Display all possible combinations of values.
        // Also display an invalid value.
        for( int val = 0; val <= 8; val++ )
        Console.WriteLine ( "{0,3} – {1}",  val, ( (MultiHue)val ).ToString( ) );
      }
    }
    /*
    This example of the FlagsAttribute attribute
    generates the following output.
    All possible combinations of values of an
    Enum without FlagsAttribute:
    0 – Black
    1 – Red
    2 – Green
    3 – 3
    4 – Blue
    5 – 5
    6 – 6
    7 – 7
    8 – 8
    All possible combinations of values of an
    Enum with FlagsAttribute:
    0 – Black
    1 – Red
    2 – Green
    3 – Red, Green
    4 – Blue
    5 – Red, Blue
    6 – Green, Blue
    7 – Red, Green, Blue
    8 – 8
    */
    

    5、枚举作为函数参数。经常和switch结合起来使用。下面举例

    public static double GetPrice(Fabric fab)
    {
      switch (fab)
      {
        case Fabric.Cotton:
          return (3.55);
        case Fabric.Silk:
          return (5.65);
        case Fabric.Wool:
          return (4.05);
        case Fabric.Rayon:
          return (3.20);
        case Fabric.Other:
          return (2.50);
        default:
          return (0.0);
      }
    }
    

    6、上面三点一个完整的例子

    //enum的定义
    public enum Fabric : short
    {
      Cotton = 1,
      Silk = 2,
      Wool = 3,
      Rayon = 8,
      Other = 128
    }
    //将枚举作为参数传递
    public static double GetPrice(Fabric fab)
    {
      switch (fab)
      {
        case Fabric.Cotton: return (3.55);
        case Fabric.Silk : return (5.65);
        case Fabric.Wool: return (4.05);
        case Fabric.Rayon: return (3.20);
        case Fabric.Other: return (2.50);
        default: return (0.0);
      }
    }
    public static void Main()
    {
      Fabric fab = Fabric.Cotton;
      int fabNum = (int)fab;
      string fabType = fab.ToString();
      string fabVal = fab.ToString ("D");
      double cost = GetPrice(fab);
      Console.WriteLine("fabNum = {0}nfabType = {1}nfabVal = {2}n", fabNum, fabType, fabVal);
      Console.WriteLine("cost = {0}", cost);
    }
    

    7、Enum类的使用

    Enum.IsDefindeEnum.Parse两种方法经常一起使用,来确定一个值或符号是否是一个枚举的成员,然后创建一个实例。Enum.GetName打印出一个成员的值;Enum.GetNames打印出所有成员的值。其中注意**“`typeof“`**的使用。这一点很重要。

    public enum MyFamily
    {
      YANGZHIPING = 1,
      GUANGUIQIN = 2,
      YANGHAORAN = 4,
      LIWEI = 8,
      GUANGUIZHI = 16,
      LISIWEN = 32,
      LISIHUA = 64,
    }
    string s = "YANGHAORAN";
    if (Enum.IsDefined(typeof(MyFamily), s))
    {
      MyFamily f = (MyFamily)Enum.Parse(typeof(MyFamily), s);
      GetMyFamily(f);
      Console.WriteLine("The name is:" + Enum. GetName(typeof(MyFamily), 2));
      string[] sa = Enum.GetNames(typeof(MyFamily));
      foreach (string ss in sa)
      {
        Console.WriteLine(ss);
      }
    }
    

    list contains 类

    Subscription sub = new Subscription();
    sub.Appname = subName;
    if (this.Subscriptions.Contains(sub,new SubcriptionComparer<Subscription>()))
      return true;
    else
      return false;
    class SubcriptionComparer<T> : IEqualityComparer<T>
    where T : Subscription
    {
      public int GetHashCode(T obj)
      {
        return obj.GetHashCode();
      }
      public bool Equals(T t1, T t2)
      {
        return t1.Appname == t2.Appname;
      }
    }