On the database index, interfaces and abstract classes, MVC interceptors, URL parameters pass the basic implementation of simple instructions

Disclaimer: The road has a lot to learn referral of place, hope to help you on it! https://blog.csdn.net/mingzaiwang/article/details/83657583

Write the code for four years, and then manage the team for two years, every interview I want to say why always ask book knowledge, then one would like to forget our society is such that we do not deliberately go to tangle on this knowledge, but we have to adapt to the times, we should also ask them firmly grasp the knowledge points. Start my show

1, the role of index databases, as well as the stated method?

         We do it with: "directory index is like the book, it accurately locate the specific content of the books through the catalog of the book." These words to describe affirm called index.

Construction of the table when the primary key so there will be corresponding will be corresponding clustered index, so there will be a tree-structured data tables. It is formed between each of the main key from a master to a temporary association database (we will generally have a primary key, thereby forming a corresponding balanced tree.)

So the question comes up that we know clustered index, and thus began what is called non-clustered index doubt it?

Non-clustered index leaf node is still inode, but there is a pointer to the corresponding data block, use a non-clustered index if this query, and the query column contains a list of other indexes that are not covered, then he will have a second query, the query node data corresponding to the data lines.

If the following Table t1:

id username score
1 Hsiao Ming 90
2 Red 80
3 Xiaohua 92
.. .. ..
256 Xiaoying 70

And a clustered index clustered index (id), a non-clustered index index (username).

Use the following statement to query, the second query does not require, you can you can get directly from the non-clustered index node to which the data query column.

select id, username from t1 where username = '小明'
select username from t1 where username = '小明'

But the following statement to query, you need to go to the second query data to obtain the original line score:

select username, score from t1 where username = '小明'

Composite Index (covering index)

The establishment of more than two of the index, you can query the data in the columns of a composite index without the need for secondary queries back to the table, such as index (col1, col2), execute the following statement

select col1, col2 from t1 where col1 = '213';

To pay attention to the use of a composite index required to meet the principles of the leftmost index, that is, when queried if the conditions where there is no one to many of the leftmost column, the index will not work.

Also include the usage of SQL Server, you can put a non-clustered index contains columns include it, but do not necessarily need to build composite index.

2, on the difference between the actual code in c # interfaces and abstract classes?

Abstract classes and interfaces have

1, can be inherited

2, not be instantiated

3, can contain method declarations

4, the derived class must be implemented method is not implemented

Interface is the interface (interface) is a specification, defined the work of the rest of the specification will be simple and convenient.

This is a practical example of the interface I wrote in 2016:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<IShow> list = new List<IShow>();
            list.Add(new Map());
            list.Add(new Voice());
            list.Add(new Video());
            list.Add(new ThreeD());
            foreach (IShow ishow in list)
            {
                ishow.Show();
                Console.ReadKey();
            }
        }
    }
    interface IShow
    {
        void Show();
    }
    public class Map : IShow
    {
        public void Show()
        {
            Console.WriteLine("显示图片");
        }
    }
    public class Voice : IShow
    {
        public void Show()
        {
            Console.WriteLine("播放声音");
        }
    }
    public class Video : IShow
    {
        public void Show()
        {
            Console.WriteLine("显示视频");
        }
    }
    public class ThreeD : IShow
    {
        public void Show()
        {
            Console.WriteLine("3D交互");
        }
    }
    
}
public class Vm : IShow
{
        public void Show()
        {
            Console.WriteLine("vm感观");
        }
}

Then came a VM that is, with VR.

If you anticipate there will be versions of the problem, you can create "an abstract class." For example, create a dog (Dog), chicken (Chicken) and ducks (Duck), then you should consider abstract animal (Animal) to deal with things that may arise after the wind horse cattle. The new members are added to the interface will be mandatory for all derived classes to modify and recompile, version-ended questions so the best abstract class to achieve.

abstract keyword can only be used in a method of modifying an abstract class , and no specific implementation. Implement abstract methods must be implemented using the override keyword in the derived class.
The most fundamental difference interfaces and abstract classes: abstract class is an incomplete class is an abstract object, and the interface is a code of conduct.

Abstract class:

public abstract class Fruit
{
        public string  vendor { get; set; }   //默认为private
        
        public abstract float Price { get; }  //抽象属性必须是公有的

        public abstract void GrowInArea();    //抽象方法必须是公有的
}
public class Apple : Fruit
{
        public override float Price
        {
            get
            {
                if (vendor == "红富士")
                    return 100;
                else
                    return 0;

            }
        }

        public override void GrowInArea()
        {
            Console.WriteLine("我在南方北方都能生长,我的生产商是:" + vendor + ",我现在的价格        
            是:" + Price);
        }
}
static void Main(string[] args)
{
            Fruit f = new Apple();
            f.vendor = "红富士";
            f.GrowInArea();

            f = new Orange();
            f.vendor = "柑橘";
            f.GrowInArea();

            Console.ReadKey();

}

3, on the use of the MVC interceptors?

     In ASP.NET MVC, there are three interceptor: Action interceptors, Result interceptors and interceptor Exception. I want to first and third. In fact, the so-called ASP.NET MVC interceptors, nothing mysterious, it is an ordinary class. FilterAttribute just need to inherit a base class, Action interceptors but also to achieve IActionFilter interface, and Exception interceptors need to implement IExceptionFilter interface.
      We first look to achieve: Let's create a new directory under Filters Controllers directory, and then create two classes under Filters, called LoggerFilter called ExceptionFilter. The first is LoggerFilter code.

1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using System.Web;
 5using System.Web.Mvc;
 6using System.Web.Mvc.Ajax;
 8namespace MVCDemo.Controllers.Filters
 9{
   public class LoggerFilter : FilterAttribute, IActionFilter
   {
       void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
       {
           filterContext.Controller.ViewData["ExecutingLogger"] = "正要添加公告,已以写入日志!时间:" + DateTime.Now; 
       }
17        void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
       {
           filterContext.Controller.ViewData["ExecutedLogger"] = "公告添加完成,已以写入日志!时间:" + DateTime.Now;
       }
   }
22}

 You can see, this class inherits FilterAttribute and implements IActionFilter. The key is IActionFilter, it has two methods, OnActionExecuting execution before being intercepted Action, OnActionExecuted executed after being intercepted Action. Two methods have a parameter, although different types, but are in fact a role: intercepted the context of the Action.
      I have to explain this place, you interceptor intercepted Action, when making process will inevitably use to be intercepted Action related things, such as in our case, we need to want to be where the interception ViewData Action Controller added content, Therefore, the interceptor method has a parameter indicates intercepted Action context is a matter of course.
      Look below ExceptionFilter this interceptor, which is to play the role of an abnormality occurs in Action.
ExceptionFilter.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
namespace MVCDemo.Controllers.Filters
{
   public class ExceptionFilter : FilterAttribute,IExceptionFilter
   {
       void IExceptionFilter.OnException(ExceptionContext filterContext)
       {
           filterContext.Controller.ViewData["ErrorMessage"] = filterContext.Exception.Message;
           filterContext.Result = new ViewResult()
           {
               ViewName = "Error",
               ViewData = filterContext.Controller.ViewData,
           };
           filterContext.ExceptionHandled = true;
       }
   }
}

Complete example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using MVCDemo.Models;
using MVCDemo.Models.Interfaces;
using MVCDemo.Models.Entities;
using MVCDemo.Controllers.Filters;
namespace MVCDemo.Controllers
{
   public class AnnounceController : Controller
   {
       public ActionResult Release()
       {
           ICategoryService cServ = ServiceBuilder.BuildCategoryService();
           List<CategoryInfo> categories = cServ.GetAll();
           ViewData["Categories"] = new SelectList(categories, "ID", "Name");
           return View("Release");
       }
       [LoggerFilter()]
       [ExceptionFilter()]
       public ActionResult DoRelease()
       {
           AnnounceInfo announce = new AnnounceInfo()
           {
               ID = 1,
               Title = Request.Form["Title"],
               Category = Int32.Parse(Request.Form["Category"]),
               Content = Request.Form["Content"],
           };
           IAnnounceService aServ = ServiceBuilder.BuildAnnounceService();
           aServ.Release(announce);
           ViewData["Announce"] = announce;
           System.Threading.Thread.Sleep(2000);
           ViewData["Time"] = DateTime.Now;
           System.Threading.Thread.Sleep(2000);
           return View("ReleaseSucceed");
       }
   }
}

4, the gap between session and cookie, why use the session, a specific method for each cookie actual operation, and said the next token?

  1. cookie data is stored on the customer's browser, session data on the server.
  2. cookie is not very safe, people can analyze stored locally and COOKIE COOKIE cheat, taking into account the security should be used session.
  3. session will be saved on the server for a certain time. When accessing the increase would be more take up the performance of your server
  4. Taking into account mitigating server performance, you should use COOKIE.
  5. Single cookie saved data can not exceed 4K, many browsers are limited to a maximum of 20 sites saved cookie.
  6. So My advice:
  7.    The login information and other important information is stored as SESSION
  8.    Additional Information If you want to keep, you can be placed in COOKIE

oauth token session and not contradictory, as the authentication token security better than the session, because each request signature also prevents eavesdropping and replay attacks, and the session would have to rely on the link layer to protect the security of communications. As mentioned above, if you need to implement stateful session, you can still increase the session to save some of the state on the server side

App usually dealing with a restful api with the server. Rest is stateless, that is not like the app browser as a cookie to store the session, hence the session token to mark themselves enough, session / state by the logic api server processing. If you are not stateless backend of rest api, then you may need to save the session in the app. Webkit can be embedded in the app, with a hidden browser to manage the cookie session.

token is a token landing, to avoid duplication and landed repeatedly get pressure to bring the server session and so on.

5, each corresponding page parameters are passed between those methods and the corresponding advantages and disadvantages of these methods?

1, url way http://abc.com?name=xiaoming&age=18&gender=man

2, use the cookie to save:

//1、保存一条数据
document.cookie="name=abc";
document.cookie="age=18";
//2、获取所有数据
var cookie=document.cookie;
console.log(cookie);  //"name=abc; age=18; PHPSESSID=fr1njdv6apf3neoj5nehntrps7"
//之后可以解析字符串,获取指定的数据内容
//3、设置cookie的有效期
document.cookie="id=666;expires="+new Date("2017-10-22 08:00");
 //第一种类型:会话cookie
//    //1、设置值
    $.cookie("phone","13188886666");
    $.cookie("email","[email protected]");
//    //2、获取值
    var phone=$.cookie("phone");
    console.log(phone);
    var email=$.cookie("email");
    console.log(email);
    //第二种类型:设置长期cookie(具有指定有效期)
    $.cookie("address","广东深圳市",{
        expires:7               //expires不仅仅可以是日期类型的对象,也可以是以天为单位的数字
    });
    $.cookie("tel","0755-88888888",{
        expires:1/24              //该cookie值就会保存一小时
    });
    $.cookie("birthday","1.1",{
        expires:new Date("2018-01-01 08:00")        //对于这样的过期时间,已经在内部处理好了时区问题
    });
//删除指定的cookie
$.removeCookie("birthday");

3, using the localStorage h5, or stored object type sessionStorage

存储对象的正确的方式:
var p2={name:"周瑜",age:16};
var s2=JSON.stringify(p2);      //将对象"序列化"为JSON数据(字符串格式)
localStorage.setItem("p2",s2);  //以字符串格式存储信息
var s2_2=localStorage.getItem("p2");    //获取存储的信息,也是字符串格式
var p2_2=JSON.parse(s2_2);      //将JSON数据反序列化为对象

localStroage和sessionStorage使用大致相同,他们的不同之处在于,localstroage是永久保存,而sessionstroage是会话存在,
当会话结束,sessionstroage保存值也会清空。

 

Guess you like

Origin blog.csdn.net/mingzaiwang/article/details/83657583