I have a WinForms app written in C# which has a lot of custom Classes.
Many of those Clases share similar Properties and Methods, and I have been able to cut down on the Coding by using Inheritance.
However, my Classes also have a lot of similar Static Methods (often the only thing that differs from one implementation to another between Classes is the reference to the Class itself. A very dumbed down example of this might be -
public class MyClass1()
{
public string IdentifyYourself()
{
return "This is the IdentifyYourself method in " + typeof(MyClass1).Name;
}
}
public class MyClass2()
{
public string IdentifyYourself()
{
return "This is the IdentifyYourself method in " + typeof(MyClass2).Name;
}
}
Is there a way to generalize the code in the IdentifyYourself() method so that there is no need to keep restating the Class in each implementation?
If these were not Static Methods then I could do something like
this.GetType().Name;
But of course the 'this' keyword is unavailable in a Static Method.
You may be wondering why these need to be Static methods. However the above example is not my actual code but a simplified version of the issue I am having. An actual example from my code (but still one of the shorter examples) is as follows -
public static DataTable List(bool active = true)
{
try
{
string table = typeof(MyClass).Name;
string sqlText = "SELECT * FROM [" + table + "] WHERE Active = #Active;";
SqlCommand sqlCom = new SqlCommand(sqlText);
sqlCom.Parameters.AddWithValue("#Active", active);
DataTable results = Express.GetTable(sqlCom);
return results;
}
catch (Exception eX)
{
...
}
}
The Code for the List() implementation differs from one Class to the next only in the first line
string table = typeof(MyClass).Name;
I'm thinking that if I could generalize this in some way, I could re-factor the code as follows -
public static DataTable List(bool active = true)
{
try
{
string nameOfClass = //...some generalized way of obtained the Name of the class...//
return UtilityClass.List(nameOfClass);
}
...
}
It is then a straight copy and paste of just a couple of lines of code each time I want to implement this in a new class and all the more detailed code can be placed in a Utility Class. The advantage of this isn't just avoiding having to type the name of each Class in each implementation, but also, if the details of the SQL operations need to change, it only has to be changed in one place.
The classic way to do that would be generics:
public static DataTable List<T>(bool active = true)
{
try
{
string table = typeof(T).Name;
// ...
} ....
and
var table = YourStaticClass.List<MyClass1>();
Frankly, however, I would also recommend making it return List<T> rather than DataTable. That depends a bit on what Express is, however (but: "dapper" would be trivial to use to do the query into a List<T>)
Related
Ok so I have ZERO idea how to word it in a title so I will explain what I am looking to achieve here.
I have a .cs file that houses a connection code utilizing dapper listed below.
namespace DBConnector
{
public static class Helper
{
public static string CnnVal(string name)
{
return ConfigurationManager.ConnectionStrings[name].ConnectionString;
}
}
public class DataAccess<T>
{
public List<T> GetInfo(string query, object parameters = null)
{
using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(Helper.CnnVal("ProxyRPDB")))
{
return connection.Query<T>(string, object);
}
}
}
}
What I am trying to achieve, is have a query executed from a DIFFERENT .cs file through the above code. BUT! I am trying to make it so that above code accepts query executions from multiple .cs files that all need different data from different tables. I have tried forever to find the information... so this is truly last resort. I am using Dapper for .NET 4.5.2.
First, we need to fix the basic syntax errors in the GetInfo() method:
public static class DataAccess
{
public static IEnumerable<T> GetInfo<T>(string query, object parameters = null)
{
using (var connection = new System.Data.SqlClient.SqlConnection(Helper.CnnVal("ProxyRPDB")))
{
return connection.Query<T>(query, parameters);
}
}
}
Now, assuming you have the proper reference and using directives in other *.cs files, you can do things like this inside those files:
var results = DataAccess.GetInfo<MyTableType>("SELECT * FROM [MyTable]");
foreach(var record in results)
{
//...
}
Dapper will now try to map the query results to instances of the MyTableType class, so make sure you've created such a class.
Note this works with IEnumerable instead of List. If you really need a List (hint: you usually don't, and IEnumerable can perform much better) you can always put a .ToList() at the end of the function call:
var results = DataAccess.GetInfo<MyTableType>("SELECT * FROM [MyTable]").ToList();
Please feel free to modify the title, I couldn't come up with any better one =\
Given the following example class
public class Person
{
public string Name;
public int ID;
public string City;
}
I need to create another mirror class, where every field is actually a wrapper of the original class:
public class PersonMirror
{
public FieldWrapper<string> Name;
public FieldWrapper<int> ID;
public FieldWrapper<string> City;
}
public class FieldWrapper<T>
{
public T Value;
public bool someBool;
public int someCounter;
// ..whatever
}
The thing is, I have many classes to mirror, and some of them have many fields! Moreover, the original class may be changed from time to time (add / remove / rename field), and every change must be applied to the mirrored class - not a good practice for maintainability.
My question is - is there a type safe way automate the decleration (rather then creation, such as generated code) of such mirrored classes?
EDIT:
Let's start from the beginning. In our SOA system, there is a resource access service (serviceX) responsible for updating items in the DB. Other services send it the modifications they would like to perform - in json that would be something like: {ID: 123, name : "myNewName"}. serviceX would then build an update query to send to the DB. However, there is a requirement that serviceX will expose a POCO interface, so that the interface will be language independent, so expressions such as (p=> p.name, "MyNewName") are not allowed. Another requirement is type safety, so json is not allowed either. Currently, the above solution is the best one we came up to answer all the requirements. Any better solutions are more then welcome!
IMO, there's no way to do what you want, except code generation.
Approaches for code generation could differ (this maybe source code generation + compilation, emitting IL code, either your own or existing one), but this is the only way.
use T4 to autogenerate your "WrapperClass".
Below, a proposition of how you could implement your FieldWrapper.
public class FieldWrapper<T, O>
{
private T _item;
private O _owner;
private PropertyInfo _setter;
public T Value
{
get { return _item; }
set {
if (!EqualityComparer<T>.Default.Equal(_item, value))
{
_item = value;
// do some personal check
_setter.SetValue(_owner, value);
}
}
}
public bool someBool;
public int someCounter;
// ..whatever
// CTOR
public FieldWrapper(O owner, Expression<Func<T, O>> propertyExpressionInTheOwner)
{
_owner = owner;
propertyName = (propertyExpressionInTheOwner.body as MemberExpression).Member.Name;
// get PropertyInfo using the owner and propertyName
}
}
Using the expression behavior permits you to create your fieldWrapper this way.
var p = new Person();
new FieldWrapper(p, (pers) => pers.Name);
The good point with this technique it is that if you person class change you will directly receive a compilation error.
With T4 the must is to load the assembly where all you class are, tag you class model with a specific attribute. Look into the assembly to found every class that have this attribute and generate the wrapper class associate.
You would have to run it after every code change, but you could create a code parsing application.
List desired keywords to substitute, such as " string ", " int ". Read the file, line by line. Find definition of classes (line contains "class"), then replace every instance of any given keyword in it with:
"FieldWrapper<" + keyword + ">"
You might want to drop keyword substitution inside methods (and perhaps in the method signatures / return types themselves) of by checking for "(" and ")", and the opening curly brace. Resume operation when you reach the closing curly brace. You can achieve that by storing the nesting level in an integer, incrementing it when hitting '{' and decrementing it when reaching '}'.
I'm beating my head against the wall pretty severely with this. I have several variables inside a C# console application that I would like to re-use. However, I cannot for the life of me re-use the variables in another class. I would love any help or pointers you could provide - I've searched for quite some time and I'm completely stumped.
EDIT: Yes, the variables are inside my Main function. Sorry for leaving this out.
EDIT: Heavily redacted code below. The variable values I'd like to re-use in another class are in the middle. There are more but those 3 should be sufficient for the sample. Thanks for the assistance!!!
public static class MyApp
{
static void Main(string[] args)
{
// loads XML doc
foreach (XmlNode node in nodes)
{
try
{
// does a bunch of stuff
// Parses variables from REST API
XDocument docdetailxml = XDocument.Parse(xmldoc);
XNamespace ns = docdetailxml.Root.GetDefaultNamespace();
var buid = docdetailxml.Root.Element(ns + "busid").Value;
var bname = docdetailxml.Root.Element(ns + "busname").Value;
var bcount = docdetailxml.Root.Element(ns + "buscount").Value;
// Invoke SQL connection string
// Trigger Stored Procedure and write values to database
// If needed, trigger email notification
// Close connections
}
catch (Exception e)
{
Console.WriteLine("Error encountered: " + e.Message);
// Exit the application
System.Environment.Exit(1);
}
finally
{
// Exit the application
// System.Environment.Exit(0);
}
}
}
private static void GetConnectionString()
{
throw new NotImplementedException();
}
private static void GetConnectionStrings()
{
throw new NotImplementedException();
}
}
}
you should define public property or public field
public class Student
{
public string Name {get;set;}
}
and when you want to pass value you can assign this value to property
Student st = new Student();
st.Name = "your value";
or you can use class constructor too.
If the variable denote some information about an object (like name, id, etc.) then they should be encapsulated in a class. The instance of the class (called an object) should be used to access this information.
As you already have the variables that represent an object, the next step would be to group these variables into classes. These variables are represented as properties in the class. The operations performed on these members should be available as methods. Furthermore the access modifiers decide the visibility of the members.
Going through your example, I can identify 3 variables that represent a Customer (assumption, I am not sure of the exact use case). These will form the Customer class.
class Customer
{
// You can either pass the UID through the constructor or
// expose a public setter to allow modification of the property
public Customer(string uid)
{
this.UID = uid;
}
public string UID { get; private set; }
public string Name { get; set; }
public string Count { get; set; }
}
Furthermore, the foreach loop can be split into 2 parts for resuablity
Read from the xml nodes and create a list of customers
Perform the database operations (like trigger stored procedures, write values, etc.) on the list of customers
Additionally, you can create another class that does the operations (business logic) that you are performing in the console application. This will allow you to reuse the same logic in case you move it to another application (like winforms or web service).
More information
Object oriented programming
Object oriented concepts in C#
Principles Of Object Oriented Design
I think there's a dedicated forum for struts on this site, best look there for more info.
Quick answer: the primary way of passing values from one action to another (I think you are working with struts Action classes?) is to put the values into the request or session (so, first job for you would be to read up on those topics: HttpServletRequest and HttpSession). Struts action classes do their work in the execute() method, and that method has a parameter of type HttpServletRequest. From the request you can get a handle to the session.
And both request and session offer methods getAttribute() and setAttribute(). So, to pass data from one action to another, set that data as a (request or session) attribute, then read out the attribute in the next action again.
The Program class is probably Static so you'll have to access those fields by class name instead of instance.
class Program
{
public string Name = "a name";
static void Main(string[] args)
{
Name = "Hello"; //You can't do this, compile error
Program p = new Program();
p.Name = "Hi"; //You can do this
SecondName = "Sn"; //You can do this
Program.SecondName = "Tr"; //You can do this too
}
public static string SecondName = "Peat";
}
I created a class where the main task is get data from the DB and mapping it to some object. The problem is the same class needs to map different datareader to different object. So, what I tried to do is to get out the mapping method using delegates.
Here is part of my code. See the important rows in bold.
public class GetDetails<T>
{
**public delegate void DelegateMapping(T position, IDataReader reader);**
**public DelegateMapping mappingMethod;**
public T Get(T instance)
{
//Get IDs and Add to list
_db.ExecuteReader(storedProcedure.ToString(), CommandType.StoredProcedure, reader =>
{
while ( reader.Read() )
{
**mappingMethod(instance, reader);**
}
}, parameterList.ToArray());
return instance;
}
}
And this is the class which is calling and using the "GetDetails" class
public class PositionDB : DbBase
{
public Position GetPositionDetails(string IDs)
{
GetDetails<Position> getIDs = new GetDetails<Position>(base.db);
getIDs.storedProcedure = StoredProcedure.NET_ADM_GetPositionDetails;
//Set the Delegated Method
**getIDs.mappingMethod = MappingPositionDetails;**
//Set Parameters
getIDs.parameterList.AddInParam("PositionIds", DbType.String, IDs);
//Return the PositionId Collection
return getIDs.Get(new Position());
}
**private void MappingPositionDetails(Position position, IDataReader reader)
{
position.Id = reader["CompPositionId"];
position.Description = reader["Description"];
position.ExpirationDate = reader["ExpirationDate"];
position.Title = reader["Title"];
}**
}
The code is working OK.
The questios are:
Did I use delegate correctly?
This kind of solution can cause problems in the future (performance)?
There is another better solution?
Thank you very much
Sebastian
To specifically answer your questions:
Yes, you did use delegates correctly
Yes, it can cause problems due to concurrency issues while multithreading
I think so, I detailed one possible solution below
I would propose three changes:
Move the delegate call into the method (concurrency issues, one thread could change the mapping delegate while another thread tries to access it, now trying to map a reader to completely different object than provided)
Use the already present generic Action/Func delegates, no need to define your own.
Use lambda expressions to define the mapping, no need for extra methods
Notice: 2 and 3 will need at least .net 3.5.
Employing these two proposals, your code would look like this:
public class GetDetails<T>
{
public T Get (T instance, Action<T, IDataReader> mappingMethod)
{
//Get IDs and Add to list
_db.ExecuteReader(storedProcedure.ToString(), CommandType.StoredProcedure, reader =>
{
while ( reader.Read() )
{
mappingMethod(instance, reader);
}
}, parameterList.ToArray());
return instance;
}
}
Now you can use this method in a multi-threaded environment as well.
Edit
just realized it's just part of the code. I corrected my proposal to take this into account.
Yes (There's some improvements you could make, see 3)
Not performance wise, maybe some issues in discoverability.
I would use polymorphism to eliminate the delegate completely for discoerability. Perhaps using an abstract method/class. Also depending on which .NET version you're developing for you can use lambdas and simpler types.
public Action<Position, IDataReader> Mapping { get; set; }
Then
getIDs.Mapping = (position, reader) =>
{
position.Id = reader["CompPositionId"];
position.Description = reader["Description"];
position.ExpirationDate = reader["ExpirationDate"];
position.Title = reader["Title"];
};
I am thinking to create a filter object which filters and delete everything like html tags from a context. But I want it to be independent which means the design pattern I can apply will help me to add more filters in the future without effecting the current codes. I thought Abstract Factory but it seems it ain't gonna work out the way I want. So maybe builder but it looks same. I don't know I am kinda confused, some one please recommend me a design pattern which can solve my problem but before that let me elaborate the problem a little bit.
Lets say I have a class which has Description field or property what ever. And I need filters which remove the things I want from this Description property. So whenever I apply the filter I can add more filter in underlying tier. So instead of re-touching the Description field, I can easily add more filters and all the filters will run for Description field and delete whatever they are supposed to delete from the Description context.
I hope I could describe my problem. I think some of you ran into the same situation before.
Thanks in advance...
Edit :
I actually want to create filters as types/classes instead of regular methods or whatever. Like :
class TextFilter : IFilter
{
private string something;
public string Awesome {get;set;}
public string FilterYo(string textFiltered)
{
// Do filtering
}
}
class HtmlFilter : IFilter
{
private string something;
private string iGotSomething;
public string Awesome {get;set;}
public string FilterYo(string textFiltered)
{
// Do filtering
}
}
class Main
{
protected void Main(object sender, EventArgs e)
{
InputClass input = new InputClass();
string filtered = new StartFiltering().Filter(input.Description); // at this moment, my input class shouldn't know anything about filters or something. I don't know if it makes any sense but this is what in my mind.
}
}
At this point if I want to apply Abstract Factory which would be meaningless or Builder as well. Because I don't want a particular thing, I need all of them kinda.
Thanks for your answers by the way.
Edit 2 - Possible Answer for Me
Okay lets think about strategy pattern with interfaces rather than delegates.
interface IFilter //Strategy interface
{
string Filter(string text);
}
class LinkFilter:IFilter //Strategy concrete class
{
public string Filter(string text)
{
//filter link tags and return pure text;
}
}
class PictureFilter:IFilter //Strategy concrete class
{
public string Filter(string text)
{
//filter links and return pure text;
}
}
class Context
{
private IFilter _filter;
private string _text;
public Context(IFilter filter,string text)
{
this._filter = filter;
this._text = text;
}
public void UpdateFilter(IFilter filter)
{
this._filter = filter;
}
public string RunFilter()
{
this._text = _filter.Filter(this._text);
return this._text;
}
}
class MainProgram
{
static void Main()
{
MyObject obj = new MyObject();
LinkFilter lfilter = new LinkFilter();
PictureFilter pfilter = new PictureFilter();
Context con = new Context(lfilter,obj.Description);
string desc = con.RunFilter();
con.UpdateFilter(pfilter);
desc = con.RunFilter();
}
}
Why don't you just go light weight: Define your filter as a Func<string, string>. If you keep these in a collection (List<Func<string, string>>), you can just do:
var text = myObject.DescriptionProperty
foreach (var func in myFuncList)
{
text = func(text);
}
You can also use Linq to shorten the above loop:
var text = myFuncList.Aggregate(text, (seed, func) => func(seed));
This way, you don't have to define a class hierarchy for filtering. This is good for the environment, since we will be running out of classes and namespaces very soon!
To wrap things up, I suggest you subclass List:
public class FilterCollection : List<Func<string, string>>
{
public string Filter(string text)
{
return this.Aggregate(text, (seed, func) => func(seed));
}
}
Have you looked at the strategy pattern? It allows you to swap algorithms.
If that is not what you are looking for, perhaps the decorator pattern will be more suitable. This will allow you to wrap filters and apply multiple ones if needed.
To me this sounds like the Strategy pattern.
Could be something like this (the code is in VB):
Function GetFilteredDescription(ByVal iSpecificFilterFunction As AbstractFilterFunction) As Result
Return iSpecificFilterFunction.Filter(Me.description)
End Function
Note: the GetFilteredDescription is member function of your class.
You can use below patterns:
Strategy Pattern for different Filter types
Chain of Responsibility for your filter stack (You can add Command Pattern here for different chains in a multitasking environment, or you can implement priority based chain or so on )
Builder or Abstract Factory for Filter instance creations.
What about Provider pattern? http://msdn.microsoft.com/en-us/library/ms972319.aspx
It is similar to Strategy, and is used in Microsoft products thoroughly.