views:

118

answers:

3

i have a file which will be used across many app projects. the only difference of these files is the webservice reference name. code like this:

public void Test(){
    Kevin.ServiceReference1.Service1Client client = new Kevin.ServiceReference1.Service1Client();
    // do something....
}

like code above, the 'Kevin.ServiceReference1' will be replace by specified app project namespace. so, according to DRY(don't repeat yourself), i shouldn't just copy the file to many projects and rename the specified part manually. is there any way i can easily replace some parts of my template file to something related to the project?

A: 

This isn't a question of DRY; while the files might look similar, you aren't repeating yourself because the one and only operation -- the declaration and assignment of a variable -- is different for every type*.

While you might want to look into giving your classes a common parent if they share a common purpose, there's nothing in your example that suggests that the classes are, in fact, related in any way.

If you're looking for ways to automate the process to make it easier on yourself, check out T4 Templates (free from Microsoft), or PostSharp. There are many other threads on here about code generation.

Adam Robinson
i dont agree with you adam. the logic is totally is same. and the web service these apps use is the same too, except the namespace of generated code.but i cant control the namespace of the generated service referrence code, can i? if i can, the problem may be solved using link file.
Kevin Yang
+1  A: 

Have you looked into Microsoft's T4 code templating system ? It might be just what you need.

Links: http://msdn.microsoft.com/en-us/vstudio/cc308634.aspx
http://visualstudiomagazine.com/articles/2009/05/01/visual-studios-t4-code-generation.aspx

RyBolt
i never heard T4 before. what a shame. i 'll check it out. and if that help, i 'll let you know.
Kevin Yang
A: 

If the only thing changing in the file is the namespace and class name, you can extract all of the other common functionality into a base class. Then, for each different usage, make a derived class inheriting from the base class. The derived class could just have a simple method that would return the specific namespace/class.

Paul Kearney - pk
yes, that's what i've done now. but the problem is, the code is relying on the web service generated entities, which come back to the namespace problem again.
Kevin Yang