简体   繁体   中英

c# class generation for storing values in the session state

What I want is a class (or a list or whatever) where I can say:

String ClientName;
String DealerID;

And it would generate the code for me like

public static string ClientName
{
    get
    {
        object obj = HttpContext.Current.Session["clientName"];

        if (obj != null)
        {
            return (string)obj;
        }

        return null;
    }

    set
    {
        HttpContext.Current.Session["clientName"] = value;
    }
}

One way may be to use reflections but I don't know how.
Another solution maybe to use typed datasets but again I don't know how.
Another Way may be to use T4 templates but I do´t know how.

You can create code snippet . Save this code to file propsession.snippet and put file to directory %USERPROFILE%\\Documents\\Visual Studio 2012\\Code Snippets\\Visual Basic\\My Code Snippets

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
      <Title>propsession</Title>
      <Author>Lazy</Author>
      <Description>Code snippet for creating property stored in session</Description>
      <HelpUrl></HelpUrl>
      <Shortcut>propsession</Shortcut>
    </Header>
    <Snippet>
      <Declarations>
        <Literal Editable="true">
          <ID>type</ID>
          <ToolTip>Property type</ToolTip>
          <Default>string</Default>
          <Function>
          </Function>
        </Literal>
        <Literal Editable="true">
          <ID>Name</ID>
          <ToolTip>Property name</ToolTip>
          <Default>Name</Default>
          <Function>
          </Function>
        </Literal>
        <Literal Editable="true">
          <ID>key</ID>
          <ToolTip>Key</ToolTip>
          <Default>key</Default>
          <Function>
          </Function>
        </Literal>
      </Declarations>
      <Code Language="csharp"><![CDATA[public static $type$ $Name$
{
    get
    {
        object obj = HttpContext.Current.Session["$key$"];

        if (obj != null)        
            return ($type$)obj;        

        return null;
    }

    set { HttpContext.Current.Session["$key$"] = value;  }
}]]></Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

Start typing propsession in Visual Studio, and select this snippet. It will insert code for storing property value in session.

T4 sample:

<#
    // Here is the model
    Model = new []
        {
            P ("string", "ClientName"),
            P ("string", "DealerID"),
        };
#>

<#
    // Here is the "view", this can be extracted into a ttinclude file and reused
#>
namespace MyNameSpace
{
    using System.Web;

    partial class SessionState
    {
<#
    foreach (var propertyDefinition in Model)
    {
#>
        public static <#=propertyDefinition.Type#> <#=propertyDefinition.Name#>
        {
            get
            {
                object obj = HttpContext.Current.Session["<#=propertyDefinition.SessionName#>"];

                if (obj != null)
                {
                    return (<#=propertyDefinition.Type#>)obj;
                }

                return null;
            }

            set
            {
                HttpContext.Current.Session["<#=propertyDefinition.SessionName#>"] = value;
            }
        }    
<#
    }
#>
    }
}
<#+

    PropertyDefinition[] Model = new PropertyDefinition[0];

    class PropertyDefinition
    {
        public string Type;
        public string Name;

        public string SessionName
        {
            get
            {
                var name = Name ?? "";
                if (name.Length == 0)
                {
                    return name;
                }

                return char.ToLower(name[0]) + name.Substring(1);

            }
        }
    }

    static PropertyDefinition P (string type, string name)
    {
        return new PropertyDefinition
        {
            Type = type ?? "<NoType>",
            Name = name ?? "<NoName>",
        };
    }

#>

It generates the following code:

namespace MyNameSpace
{
    using System.Web;

    partial class SessionState
    {
            public static string ClientName
        {
            get
            {
                object obj = HttpContext.Current.Session["clientName"];

                if (obj != null)
                {
                    return (string)obj;
                }

                return null;
            }

            set
            {
                HttpContext.Current.Session["clientName"] = value;
            }
        }    
            public static string DealerID
        {
            get
            {
                object obj = HttpContext.Current.Session["dealerID"];

                if (obj != null)
                {
                    return (string)obj;
                }

                return null;
            }

            set
            {
                HttpContext.Current.Session["dealerID"] = value;
            }
        }    
        }
}

If you do extract the "view" the model file would look like this:

<#
    // Here is the model
    Model = new []
        {
            P ("string", "ClientName"),
            P ("string", "DealerID"),
        };
#>

<#@ include file="$(SolutionDir)\GenerateSessionState.ttinclude"#>

Regarding CodeSnippets vs T4

Sometimes it is thought that CodeSnippets (and Resharper code templates) are equivalent to T4. They are not.

CodeSnippets (and others) promotes code redundancy and is basically CopyPaste programming with extra tool support.

T4 (or CodeSmith) are MetaProgramming Tools which helps you reduce code redundancy in the code you maintain (they might generate redundant code but you don't need to maintain that code).

A thought experiment around CodeSnippets; you have used a snippet extensively but you realize there's an issue in the code it generated.

How do you resolve it? You have to find all instances where you used the snippet and adjust the code but run into problems; how do you find all instances? How do you merge the Changes when someone modified the snippeted code?

With MetaProgramming Tools like T4 or CodeSmith you fix the template and regenerate the code.

This is why I die a litte bit inside everytime someone mentions code snippets.

I work for CodeSmith Tools and you can do this with CodeSmith Generator very easily. We have a feature called ActiveSnippets . You can create a new ActiveSnippet by registering a template. It took me about 30 seconds to create the following template which accomplishes this:

<%@ Template Language="C#" TargetLanguage="C#" Description="http://stackoverflow.com/questions/13406669/c-sharp-class-generation-for-storing-values-in-the-session-state" %>
<%@ Property Name="PropertyName" Default="SomeValue" Type="System.String" %>
<%@ Property Name="SystemType" Default="string" Type="System.String" %>

public static <%= SystemType %> <%= PropertyName %>
{
    get
    {
        object obj = HttpContext.Current.Session["<%= PropertyName %>"];
        if (obj != null)
        {
            return (string)obj;
        }

        return null;
    }

    set
    {
        HttpContext.Current.Session["<%= PropertyName %>"] = value;
    }
}

To use the ActiveSnippet, you would need to create a new template with the content above and register the ActiveSnippet (EG, MySnippetName) by following the steps in the link above. Then just enter in MySnippetName ClientName String on a new line inside of a code document in Visual Studio and press control+e twice to execute the snippet. The generated code will be outputted to the document window where you typed MySnippetName ClientName String,

If you have any questions, please let us know!

PS, You'll find that we have a much better template syntax/API, integration story and Template Editor than T4 (They stole a bunch from us :). Also, unlike snippets, Generator Templates can render any text based content from any metadata (database/xml....) and consume any .NET API including third party libraries.

MS有一个关于如何使用T4模板的视频: http//msdn.microsoft.com/en-us/vstudio/cc308634.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM