Windows service MVC @html.raw () usage file stream read-write simple factory and Factory mode comparison

Source: Internet
Author: User
Tags readfile actionlink

public partial class Service1:servicebase
{

System.Threading.Timer Recordtimer;
Public Service1 ()
{
InitializeComponent ();
}

protected override void OnStart (string[] args)
{
TODO: Add code here to start the service.
Intialsaverecord ();
}

protected override void OnStop ()
{
TODO: Add code here to perform the close operation required to stop the service.
if (Recordtimer! = null)
{
Recordtimer.dispose ();
}
}

<summary>
Timed check, and execution method
</summary>
<param name= "source" ></param>
<param name= "E" ></param>
private void Intialsaverecord ()
{
10000 milliseconds = 10 seconds
TimerCallback TimerCallback = new TimerCallback (callbacktask); Load Events
AutoResetEvent autoevent = new AutoResetEvent (false);
Recordtimer = new System.Threading.Timer (timerCallback, autoevent, 0, 1800000);//Where parameter 10000 indicates the time interval for deferred service execution, in milliseconds

or (timed service)

System.Timers.Timer t = new System.Timers.Timer ();//Instantiate Timer class, set interval time is 1000 milliseconds;
t.elapsed + = new System.Timers.ElapsedEventHandler (ordertimer_tick);//Time to execute the event;
T.autoreset = true;//Whether the setting is executed once (false) or always executed (true);

t.interval=1000;

t.enabled = true;//Whether the System.Timers.Timer.Elapsed event is performed;


}
Method
private void Callbacktask (Object stateInfo)
{
Writefile.saverecord (String. Format (@ "DSC current record time: {0}, Condition: The program is working properly! ", DateTime.Now));
}

}

Windows Service installation steps:
1. CD C:\Windows\Microsoft.NET\Framework\v4.0.30319
2. InstallUtil.exe EXE's path
Unloading:
installutil.exe/u EXE's path

----@html.raw () Usage of MVC

The @Html. Raw () method outputs a string with Html tags,

such as: @Html. Raw ("<div style= ' color:red ' > Output string </div>")

Result: output string (string in red font)

Use Html.raw in razor (this way is recommended)

Summary of usage of Html.ActionLink1, Html.ActionLink ("LinkText", "ActionName") the first parameter: The text to be displayed, the second parameter: view name for example: <%=html.actionlink ("Jump to About page", "about") ;%>→ <a href= "/home/about" > Jump to About Page </a> 2, Html.ActionLink ("LinkText", "ActionName", " ControlName ") First parameter: The text to be displayed, the second parameter: view name, third parameter: Controller name for example: <%= html.actionlink (" Jump to Other Controler "," Index "," Home ");%> →<a href= "/ home/index" > Jump to other Controler </a> 3, Html.ActionLink ("LinkText", "ActionName", routevalues) The first parameter: The text to be displayed, the second argument: The view name, the third parameter: A parameter in the URL such as: <%=html.actionlink ("Jump to About page", "about", new {id = "1", name = "X"})%>→<a href= "/home/about/1?name=x" > Jump to About Page </a> 4,  html.actionlink ("LinkText", " ActionName ", routevalues,htmlattributes) First parameter: The text to be displayed, the second parameter: view name, third parameter: parameter in URL, fourth parameter: Set label properties for example: <%= Html.ActionLink ("Jump to About page", "about", new {id = "1", name = "x"}, new {disabled = "disabled", @class = "About"})%> & Nbsp;→ <a class= "about" disabled= "disabled" href= "/home/about/1?name=x" > Jump to About page &LT;/A&Gt;  Note: When setting the Class property of a label, you should precede the class with @, because class is the keyword.    ---   read and write   file streams

Read the file

public static string ReadFile ()
{

string basepath = System.AppDomain.CurrentDomain.BaseDirectory;
String Strtempdir = String. Format ("{0}", DateTime.Now.ToString ("YyyyMMdd"));
String path3 = Path.Combine (BasePath, Strtempdir);
FileStream fs = new FileStream (path3, FileMode.Open);
StreamReader sr = new StreamReader (FS,ENCODING.UTF8);
String line = Sr. ReadLine ();//read a line directly
Sr. Close ();
Fs. Close ();
return line;
}

public static string ReadFile (String surl)
{

StringBuilder builder = new StringBuilder ();
using (FileStream fs = File.Open (sURL, FileMode.OpenOrCreate))
{
using (StreamReader sr = new StreamReader (FS, Encoding.UTF8))
{
Builder. Append (Sr. ReadToEnd ());
}
}
Return builder. ToString ();
}

Write a file

public static void WriteFile ()
{

string basepath = System.AppDomain.CurrentDomain.BaseDirectory;
String Strtempdir = String. Format ("{0}", DateTime.Now.ToString ("YyyyMMdd"));
String path3 = Path.Combine (BasePath, Strtempdir);
FileStream fs = new FileStream (path3, filemode.append);
StreamWriter SW = new StreamWriter (FS);
Sw. WriteLine ("Hello World");
Sw. Close ();
Fs. Close ()///Here to be aware that FS must be closed behind the SW, otherwise it will throw an exception
}

----Simple factory and factory model comparison one, Factory mode

In Factory mode, we create the object without exposing the creation logic to the client, and by using a common interface to point to the newly created object.

Second, introduce

Intent: Define an interface that creates an object, letting its subclasses decide which factory class to instantiate, and the factory pattern to defer its creation to subclasses.

Main solution: The main solution to the problem of interface selection.

When to use: we explicitly plan to create different instances under different conditions.

How to solve: let its sub-class implement the Factory interface, return is also an abstract product.

Key code: The creation process executes in its subclasses.

Application Examples:
1, you need a car, you can pick up directly from the factory, without having to control how the car is done, and the specific implementation of the car.
2, Hibernate Exchange database only need to change dialect and drive.

Advantages:
1. A caller wants to create an object, as long as it knows its name.
2, high scalability, if you want to add a product, as long as the expansion of a factory class can be.
3, the specific implementation of shielding products, the caller only care about the interface of the product.

Disadvantages:
Each time you add a product, you need to add a specific class and object implementation of the factory, so that the number of classes in the system multiplied, to a certain extent, increase the complexity of the system, but also increase the system specific class dependency. That's not a good thing.

Usage scenarios:
1, Logger: Records may be recorded to the local hard disk, system events, remote servers, etc., the user can choose where to log logs.
2, database access, when the user is not aware of the last system to use which type of database, and the database may change.
3, design a connection server framework, requires three protocols, "POP3", "IMAP", "HTTP", you can use these three as product classes, together to implement an interface.

Precautions:
As a way to create a class pattern, you can use the factory method pattern in any place where complex objects need to be generated. One thing to keep in mind is that complex objects are suitable for Factory mode, and simple objects, especially those that can be created only through new, do not need to use Factory mode. If you use Factory mode, you need to introduce a factory class that increases the complexity of the system.

Three, simple Factory mode

The simple factory model consists of the following 3 roles:

    1. Factory (Factory role)
    2. Product (abstract products role)
    3. Concreteproduct (Specific product role)
    Typical abstract Product class codeAbstract class Product {Public business approach for all product classesPublicvoidMethodsame () {Implementation of public methods}Declaring abstract business methodsPublicAbstractvoidMethoddiff (); }Typical specific product Class code class Concreteproducta:product {Implementing Business methodsPublicOverridevoidMethoddiff () {Implementation of the Business Method}} class Concreteproductb:product {Implementing Business methodsPublicOverridevoidMethoddiff () {Implementation of the Business Method}} class Factory {Static Factory methodPublic Productgetproduct (string Arg) {Product Product = null; if (Arg. Equals ( "A")) {Product = new concreteproducta (); //initialization set Product} else if (Arg. Equals ( "B")) {Product = new CONCRETEPRODUCTB (); //initialization set Product} return product;}} Class Program {static void Main (new Factory (); Product Product = Factory. GetProduct ( "A"); product. Methoddiff (); } } 

The method used to create an instance in the simple Factory mode is sometimes a static method, so it is occasionally called the Static factory methods (static Factory method) mode

Four, factory method mode

Improved button factory using factory method mode:

Improved button factory using factory method mode:

Factory method Mode:

    1. Instead of providing a button factory class to unify the creation of all products, the process of creating a specific button is given to a dedicated factory subclass to complete.
    2. If a new button type appears, you can create an instance of the new button simply by defining a specific factory class for this new type of button.

Definition of the factory method pattern
Referred to as Factory mode (Factory pattern).
It can also be called Virtual constructor mode (Constructor pattern) or polymorphic Factory mode (polymorphic Factory pattern).
The factory parent is responsible for defining the public interface that creates the product object, while the factory subclass is responsible for generating the specific product object.
The purpose is to defer the instantiation of the product class to the factory subclass, which is to determine exactly which specific product class should be instantiated by the factory sub-class.

The factory method pattern consists of the following 4 roles:

    1. Product (abstract products)
    2. Concreteproduct (Specific products)
    3. Factory (Abstract Factory)
    4. Concretefactory (Factory specific)
    Typical abstract Product class codeAbstractClassProduct {Public business approach for all product classesPublicvoid Methodsame () {Implementation of public methods}Declaring abstract business methodsPublicAbstractvoid Methoddiff (); }Typical specific product class codeClassConcreteproducta:Product {Implementing Business methodsPublicOverridevoid Methoddiff () {Implementation of the Business Method}}ClassCONCRETEPRODUCTB:Product {Implementing Business methodsPublicOverridevoid Methoddiff () {Implementation of the Business Method}}Typical Abstract factory class codeInterfaceFactory {Product factorymethod ();}Typical specific factory class codeClassconcreteafactory: factory {public Product FactoryMethod () {return new concreteproducta ();} Span class= "Hljs-class" >class concretebfactory: factory {public Product FactoryMethod () {return Span class= "Hljs-keyword" >new CONCRETEPRODUCTB (); }} class program {static void Main (string[] args) {Factory Factory = new concreteafactory (); Product Product = Factory. FactoryMethod (); Product. Methoddiff (); } } 

Windows service MVC @html.raw () usage file stream read-write simple factory and Factory mode comparison

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.