C# best practice for custom global packages/helper methods etc.? [closed] - c#

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I'm coming to C# from Python & JS and am enjoying it thoroughly so far. One of the quirks however is that it seems a lot of steps need to be taken to do some simple things. For instance if I have a 2D array and want to simply print out a 2D matrix to the console, this will require more code rather than calling a simple method like in Python. This is because printing the array will print the object type rather than its inner values. I've read one book so far and already know about method overriding, such as overriding .ToString() to do this, and know how to do this, so my question is more "what is the best practice to create and use your own global methods to do common tasks?" Or do any libraries exist that may already include many simple featurs like this?
What I'm looking to do is one of two things, and I'm curious which might be considered "better practice" -
1) Array is an object that has a lot of useful methods for manipulating arrays, but I'd like it if there was a method such as Array.PrintArray(arr) which would print the array and any inner arrays to the console. Since it seems there's no native method to do this, I'd like to write my own Array.PrintArray(arr) and make it available globally to all projects. Doing this seems like I'd need to extend the native Array object, and use this extension globally. I'm not sure how to do that, or if it's even a good idea to do that.
2) Alternatively if the above isn't good practice, I'd like to write my own helper object, lets call it "HelperSelf" with a list of my own methods, and make this helper object available globally to all projects. Eg, I could define a method HelperSelf.PrintArray so that I could type HelperSelf.PrintArray(arr) in any project in C# to print that array to the console in a way I define it.
So my question is twofold -
1) What is the best way to centrally define a way to do something via my own "helper" methods that I code so that the entire C# namespace has access to these helper methods?
2) Is doing something like this considered "best practice" or useful in C#? Does anyone else do something like this to print n-dimensional arrays to the console without having to manually write longer lines of code every time they wish to do so? Or is doing something like this considered highly unusual and it's better we just stick to writing multiple lines of code each time?
The printing n-dimensional array to console is an example of just one thing I want to do. In reality I'd like to code probably tens, or even 100+ of my own "helper" functions which I think would make things in C# much simpler coming from a Python background.
PS: The reason I want to use C# instead of Python is for projects that are better suited for C#, such as game development, systems operations, large scale projects where I find typing to be an incredibly useful feature, etc.

This is perhaps one of the reasons why languages like php, python etc get a bad rap, because they might have lots of these "semi useless" things built in. I don't personally regard "printing a 2d array to the console" as a particularly useful thing for the .net framework to contain because I don't recall, in the last 10 years, printing to the console in anything more than a scrappy test app of dotnetfiddle.com - none of the enterprise systems I work on write anything to the console though they can be configured to I suppose; they use NLog and custom loggers to write to Azure table storage etc but I could drop a console connector in there if I wanted to. Tend to just look up the logging output in Azure- we have a visualisation tool for it even
1)
make a static method or a static class that has your helpers, possibly in another project so you can import it and reference it. If you make the most amazing set of console drawing classes you can even package it as a NuGet offering and make it available to the world but on the simple level putting it in a NuGet serve (and you can easily host your own if your library isn't likely to find widespread use) means it's a few clicks to get it into your next project. Here's a simple one liner to flatten a 2d array Into a csv string for printing to the console, for example:
public static PrintArray(object [][] a){
var s = string.Join("\r\n", a.Select(inner => string.Join(",", inner));
Console.WriteLine(s);
}
Once this is written inside your helper class you can import the helper namespace to anywhere in your project and call it. You could even turn it into an extension method so that all arrays gain then ability to just say somearray.PrintArray rather than PrintHelper.PrintArray(x) though it wouldn't give expected results on arrays of other dimensions than 2
2)
whether it's unusual largely depend on your context. As noted for me it would be highly unusual to ever touch the console but if one day I went somewhere where there was some legacy cgi app that they couldn't replace with something better then it might well be that every project I wrote would have to output csv data in a very particular format to the console so the other app could consume it. It's not easy to say an answer that addresses this in all possible contexts but I do truly appreciate that Microsoft strive to keep the framework relatively bloat free, and resist adding methods that to a large extent would only be of interest to a narrow section of the population, instead preferring to focus on providing ways to make very generically capable methods to let you build the specific you want.
LINQ is one great example of this and a testament to its success in this regard is that once people discover it they tend to view it as a hammer and every problem is a nail; it ends up getting abused for all sorts of things, sometimes inappropriately - as generic, adaptable solutions often do. There is no question that it makes your developer life easier by cutting down the number of loops you have to write though. Once upon a time finding the max int in an array or calculating whether an array had a person whose last name was smith looked like:
int m = int.MinValue;
foreach(int x in array)
if(x>m)
x=m;
bool found = false;
foreach(var p in personarray)
if(p.LastName == "Smith"){
found = true;
break;
}
Now it's:
intarray.Max();
personarray.Any(p=>p.LastName == "Smith");
I do look at c# as more like a box full of Lego bricks where you build your own castles, where other languages have a lot of prebuilt castles floating around in with all the individual bricks. LINQ is one example of a fabulous prebuilt castle that does all sorts of wonderful things, but the way it's been able to be worked into the framework means it's still super generic and can be imported to create a set of extensions across all your arrays, lists, and other data containers, and in and of itself it doesn't do anything particular other than visit every element of a sequence and call a bit of code you provide so you're still tasked with making it specifically useful by crafting that code
The suggestion to look at NuGet.org is a good one; everyone has written everything. Your desire to write hundreds of helper classes may well have already been filled. I tend to find when it comes down to the brass tacks of actually doing my work, my job, I don't spend a lot of time writing helper classes because a lot of it is either on NuGet or turns out unnecessary because every project is different enough that curating a massive collection of helpers isn't actually helpful. One of the go to NuGet libraries that nearly every project I work on uses is Newtonsoft's JSON - interesting that it's an order of magnitude more downloaded than the rest of the top 100 (https://www.nuget.org/stats/packages) and that in itself is an indicator that the framework is fairly comprehensive in its ability to provide for most things you want to do without needing extra help. Coupled with the earlier points about it being relatively bloat free is probably an indicator of how well thought out it is in terms of "what do the majority of commercial applications need the framework to contain?"
I did also write a simple emailer helper some years ago that has found its way into many projects but by and large the company projects are bereft of suites of helpers created by our team, and have their own micro custom ones so don't spend a lot of time creating hundreds of them.. maybe let the work drive that one and only put in the library something that has been pasted into 3+ projects

You can use Generic and extension methods for that. For example, you can define Print extension method like this
public static class ArrayExtensions {
public static void Print<T> (this IEnumerable<T> items) {
foreach (var item in items) {
Console.WriteLine (item);
}
}
}
and the usage like this
var numbers = new[] { 1, 2, 3, 4, 5 };
numbers.Print();
var names = new string[] { "van", "ngan" };
names.Print();

Related

User Friendly way to use formula for calculation

I have an object model that I need the user to be able to create a formula based on, and also use some built-in functions. For example:
AddWorkDays(MyObject.StartDate, 3)
MyObject has various properties that the user may access. We may also need to do some If/Then statements. The users are very familiar with Excel formulas, because that is how they currently do their work.
I see two possible options:
create my own parser using one of the many available C# Libraries
Adapt an Excel-based parser to be context aware of my objects.
The issue with option 1 is I don't want to re-invent the wheel. I would expect someone has already built a parser that can handle basic functions and math operations and is context aware based on class(es) passed in. I can't seem to find something like this.
Option 2 would allow the user to re-use their existing Excel knowledge to build formulas like:
=if(MyObject.Type = "A", AddWorkDays(MyObject.StartDate, 3), AddWorkDays(MyObject.StartDate, 5)
I see XLParser is advertised as being great for parsing Excel formulas, but it seems I would need to add-on the Context-aware part for reading and validating properties on MyObject.
Any experience, examples, warnings, etc. on how to proceed are welcome
I solved this issue by using the FLEE library: https://github.com/mparlak/Flee
It supports "Context" where you can define variables that should be in context. Out of the box it supports regular syntax for things like addition, subtraction, and even a basic IF statement. It is easily extensible to add your own functions. I made it Excel-like by defining some of the common functions: AND, OR, MIN, MAX. This was less than 100 lines of code to do.
I use it to process relatively large data sets (200,000 items with 5 formulas for each item) and it processes in under 10 seconds if used correctly.

Bulk translation of C# to Objective C

Our department has inherited two new code bases. One is in C#, the other is in Objective C. The first has a bunch of functionality that we need in the second as well.
I realize that there isn't going to be a 1-to-1 relationship that we can run a simple translator to move from C# to Objective C, but is there some tool to do a rough conversion of the syntax.
We're mostly looking for a tool that would do some of the mindless part. I'm not looking forward to manually translating 1000 function headers, for example, when the format for both is so well defined.
EDIT
Even something we could run on an individual methods one at a time would speed up the process significantly.
Are you getting rid of the C# code base? If not then it seems like you can look at this from a different angle - rather than undertaking the huge effort of converting thousands of classes that rely on probably scores of API's, how about exposing your existing functionality as services that can be called from your Objective-C code? You can do this using web services.
Alternatively you can take a look at Mono/Cocoa#, though I doubt this is going to be a viable solution for your problem.

Using reflection for code gen?

I'm writing a console tool to generate some C# code for objects in a class library. The best/easiest way I can actual generate the code is to use reflection after the library has been built. It works great, but this seems like a haphazard approch at best. Since the generated code will be compiled with the library, after making a change I'll need to build the solution twice to get the final result, etc. Some of these issues could be mitigated with a build script, but it still feels like a bit too much of a hack to me.
My question is, are there any high-level best practices for this sort of thing?
Its pretty unclear what you are doing, but what does seem clear is that you have some base line code, and based on some its properties, you want to generate more code.
So the key issue here are, given the base line code, how do you extract interesting properties, and how do you generate code from those properties?
Reflection is a way to extract properties of code running (well, at least loaded) into the same execution enviroment as the reflection user code. The problem with reflection is it only provides a very limited set of properties, typically lists of classes, methods, or perhaps names of arguments. IF all the code generation you want to do can be done with just that, well, then reflection seems just fine. But if you want more detailed properties about the code, reflection won't cut it.
In fact, the only artifact from which truly arbitrary code properties can be extracted is the the source code as a character string (how else could you answer, is the number of characters between the add operator and T in middle of the variable name is a prime number?). As a practical matter, properties you can get from character strings are generally not very helpful (see the example I just gave :).
The compiler guys have spent the last 60 years figuring out how to extract interesting program properties and you'd be a complete idiot to ignore what they've learned in that half century.
They have settled on a number of relatively standard "compiler data structures": abstract syntax trees (ASTs), symbol tables (STs), control flow graphs (CFGs), data flow facts (DFFs), program triples, ponter analyses, etc.
If you want to analyze or generate code, your best bet is to process it first into such standard compiler data structures and then do the job. If you have ASTs, you can answer all kinds of question about what operators and operands are used. If you have STs, you can answer questions about where-defined, where-visible and what-type. If you have CFGs, you can answer questions about "this-before-that", "what conditions does statement X depend upon". If you have DFFs, you can determine which assignments affect the actions at a point in the code. Reflection will never provide this IMHO, because it will always be limited to what the runtime system developers are willing to keep around when running a program. (Maybe someday they'll keep all the compiler data structures around, but then it won't be reflection; it will just finally be compiler support).
Now, after you have determined the properties of interest, what do you do for code generation? Here the compiler guys have been so focused on generation of machine code that they don't offer standard answers. The guys that do are the program transformation community (http://en.wikipedia.org/wiki/Program_transformation). Here the idea is to keep at least one representation of your program as ASTs, and to provide special support for matching source code syntax (by constructing pattern-match ASTs from the code fragments of interest), and provide "rewrite" rules that say in effect, "when you see this pattern, then replace it by that pattern under this condition".
By connecting the condition to various property-extracting mechanisms from the compiler guys, you get relatively easy way to say what you want backed up by that 50 years of experience. Such program transformation systems have the ability to read in source code,
carry out analysis and transformations, and generally to regenerate code after transformation.
For your code generation task, you'd read in the base line code into ASTs, apply analyses to determine properties of interesting, use transformations to generate new ASTs, and then spit out the answer.
For such a system to be useful, it also has to be able to parse and prettyprint a wide variety of source code langauges, so that folks other than C# lovers can also have the benefits of code analysis and generation.
These ideas are all reified in the
DMS Software Reengineering Toolkit. DMS handles C, C++, C#, Java, COBOL, JavaScript, PHP, Verilog, ... and a lot of other langauges.
(I'm the architect of DMS, so I have a rather biased view. YMMV).
Have you considered using T4 templates for performing the code generation? It looks like it's getting much more publicity and attention now and more support in VS2010.
This tutorial seems database centric but it may give you some pointers: http://www.olegsych.com/2008/09/t4-tutorial-creatating-your-first-code-generator/ in addition there was a recent Hanselminutes on T4 here: http://www.hanselminutes.com/default.aspx?showID=170.
Edit: Another great place is the T4 tag here on StackOverflow: https://stackoverflow.com/questions/tagged/t4
EDIT: (By asker, new developments)
As of VS2012, T4 now supports reflection over an active project in a single step. This means you can make a change to your code, and the compiled output of the T4 template will reflect the newest version, without requiring you to perform a second reflect/build step. With this capability, I'm marking this as the accepted answer.
You may wish to use CodeDom, so that you only have to build once.
First, I would read this CodeProject article to make sure there are not language-specific features you'd be unable to support without using Reflection.
From what I understand, you could use something like Common Compiler Infrastructure (http://ccimetadata.codeplex.com/) to programatically analyze your existing c# source.
This looks pretty involved to me though, and CCI apparently only has full support for C# language spec 2. A better strategy may be to streamline your existing method instead.
I'm not sure of the best way to do this, but you could do this
As a post-build step on your base dll, run the code generator
As another post-build step, run csc or msbuild to build the generated dll
Other things which depend on the generated dll will also need to depend on the base dll, so the build order remains correct

Programming hire test - Test a developers knowledge in C# / ASP.NET [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
We're hiring a .NET developer soon, and I was assigned to create a test, which would take aprox: 1h to solve. A test which would test the programmers knowledge in (mainly) C# and ASP.NET.
This is what i've come up with so far:
Use project #1 to read data(HTML) from the specified URL and output all links(anchors) containing anchor name “xxxxxxxxx”. You are free to use 3rd party libraries. My main thought here was to test how the developer would go about solving the problem. For example:
Create a regex which would parse all the data needed.
Create a DOM-tree and use XPATH to find all anchor nodes.
Iterate the whole string and perform manual string compares.
Create a new solution where you demonstrate the usage of .NET masterpages.
Connect the solution to the ******** database. And output all customers from the “********_customers” table.
Create a new button which refreshes all users using AJAX.
Pretty basic stuff. Though, I also added the one below. Mainly to test the developers OO knowledge. Do you think this is too "overkill", or what kind of test would you suggest? If you were to hire a ASP.NET developer, what would your main focus be? ADO.NET? IO? string handling?
Create an interface/abstract class implementation demonstrating the functionallity of either the Factory, Factory Method, Command or Decorator pattern. You wont need to implement any functionallity, just use comments in your abstract class.
Thanks in advance!
The task you gave is essentially a day or two worth of coding if you want to have reasonably readable code. Within an hour I guess I would do it, but you'd have to read code that has cryptically named methods, unreadable regexes, weird callbacks, no error handling and overall is pretty darn ugly. Looking at it you would not hire me.
Before you give your question to candidates, first make sure that your peers/programmers can do it first. And that you can code it in less than 60 minutes in a way that would satisfy you.
That said, I do not know if test is the best choice for hiring anyone. A few interviewing bloggers wrote about their experience coming from conducting tons of interviews:
Guerilla Guide to Interviewing by Joel Spolksy
Truth about interviewing, Get that job at Google (and many others) by Steve Yegge
I totally agree with them. Having conducted about a gazillion of interviews myself, I find that asking basic technology related questions is not nearly as good as asking to implement a bit of recursion or pointers (if someone claims to know C/C++).
By hiring someone who understands recursion/algorithms you get a smart guy who can learn new technology. When you hire someone who knows how to connect to a database, who knows how to connect to a database but not necessarily qualified to do much more than that.
There are a few sources of good programming questions that are somewhere between coding and algorithms that may inspire you. They do not test .NET at all, but are very good indicator of smart programmers.
Top Coder
Google Code jam
Within 1 hour you can only test his programming skills, but it's not enough to write the code sample.
Take a look at this C# / ASP.NET MVC test:
http://tests4geeks.com/test/asp-net-mvc-c-sharp
After the applicant will pass the test and result will be good, then invite him to the interview and talk about his experience. Ask about most difficult features, that he implemented in his projects. In other words, you must understand, if he know and can do enough to take part in your project.
If you still want to ask him to write some code. That is some idea:
There are the students and subjects. Please ask to write 3 pages (asp .net mvc or web-forms). First and second - for editing the dictionary of students and subjects. Third form must contain be the table. The students are in left column. The subjects are in the top row. The marks are at the intersection. Each mark can be edited (text box) and saved. Saving could be implemented by clicking the common button "Save". Or it could save each cell automatically using the Ajax.
This is very simple example, but it would show you how user writes the code, what techniques does he use.
I would have thought that it would be better to simply create a test that would make it easy for you to put developers into different 'skill buckets'.
Why not have three or four sections or features that the developer must 'layer' features on top one another to show their programming and design skills.
Part 1: Implement x easy difficulty
features.
Part 2: Implement x medium difficulty
features.
Part 3: Implement x difficult
features.
Part 4: Implement x very difficult features.
And give the developer 1 hour to write the application. Make it realistic that they can implement the features in the given time frame.
As Joel and Jeff say on the Stackoverflow podcast, there is a direct correlation between developer skill and speed.
Think about the way exams are structured? We can all get 100% of the questions correct in any exam we sit if we had infinite time, but in 1 hour?
This way, If a developer takes your test and only implements features up to Section 2 in the time period, then you should have a safe indication that they are not suitable for the job. Section 3 features all done then they are good enough and section 4 complete would indicate that they are very experienced and a slight cut above the rest.
However I would also look at the overall polish that the developer has given to the code. If they implemented all features up to section 4, but poorly, then they are also not going to be someone you want. IF a developer only did up to section 3 but implemented everything very elegantly, then I would want to hire them.
I also think that 1 hour is perhaps a little too long. I would aim for 10-40 minutes obviously you may need to cut out section 4 that I proposed.
You should check
GeekInterview -- a good source for interview questions
There are hundreds of questions.
I think you would be much better off coming up with a single question that will allow you to see more than just development skills using your target technologies. Strong problem solving skills are as important as expertise in a specific technology stack.
I would even recommend that you explore the two aspects of a candidate in different parts of the process. I usually ask a bunch of questions about the technology stack we are using on our project to gauge the candidates level of knowledge as it relates to that stack.
Then I ask them a pure problem solving question and I allow them to use whichever technology they are most comfortable with to solve the problem (their choice of technology can be an important indicator).
I particularly like Graph Theory related problems. The candidates solutions will tell you a ton about how they approach, solve problems as well as how they validate their solutions.
As part of the problem solving portion of the interview you should be looking for:
Proper data structure design
Implementation of OO best practices
Proper solution (can they debug problems effectively... one great way to see this is do not allow them to use a computer, make them code on a whiteboard and debug in their heads)
Proper solution validation (do they come up with test cases)
My 2 cents:
We have a programming test in my company that is easy. Basically, you have to implement the listener pattern extending the ArrayList class, create unit tests for it (based on at least what we require), document the corner cases, document the program itself if you want to, and then send the test back to us.
A developer has 48 hours to complete that test. We ask for production quality in the test. We want to test the following items:
Was the developer smart enough to cover the corner cases?
Is the developer implementation of multi-threading satisfactory?
Are the unit tests good enough? Do they cover enough cases?
Is the code well written and documented? Will someone be able to maintain that code in the future?
Does he care about his code? Did he explain why he did "A" and not "B"?
I don't think short tests are capable of evaluating a developer. You may ask for a tool or technology that someone have not been using in the past months, and whoever is being tested for that technology will need sometime to get up to speed - but if a developer was working with that the day before, he will know by memory how to use it, and he/ she will seem smarter than the other developer, what may not be true.
But if you ask for something that is tricky and you are interviewing the developer, you can check how he is going to solve the problem - I don't think it really matters if he/ she cannot get the 100% right answer, as long as he/ she can talk about the problems that you found on the code and show that they actually understand whatever you explained to them.
In the past we have used problems from Google code jam. the problems in the early rounds are easier and they get gradually harder. They are kind of algorithmic in nature, you can solve them in whatever language you like. As they get harder there is often an obvious 'brute force' kind of answer that won't work because of the size of the data. So you have to think of something more optimal.
The first test you suggested should take 10min-40min for a basic dev - I would use a web-crawler I have in my library that converts HTML to XML then easily use Linq to XML.
I would test for lambda expressions, performance patterns maintain files, or writing an object to several files dynamically.
Maybe you would like to test unmanged code, pointers etc.
I donno, im just writing-jabbering while things are comin up to my mind, i wrote things that was hard for me to implement.
few days ago I was invited to pass C# programming test at skillbox website there was 30 questions quiz and 45 time to pass it. Below is some of them:
1) What will be printed by running the program?
#if DEBUG
Console.WriteLine("DEBUG");
#else
Console.WriteLine("RELEASE");
#endif
2) What will be the result of calling SomeMethod():
public static void SomeMethod()
{
string s1 = "a";
string s2 = "b";
Swap(ref s1, ref s2);
Console.WriteLine(s1);
Console.WriteLine(s2);
}
public static void Swap(ref Object a, ref Object b)
{
Object t = b;
b = a;
a = t;
}
Here is a link for reference, I think you can find more C# quezzes there http://skillbox.io

Rewriting Existing Functionality in the .NET Base Class Library

Relating to another question I asked yesterday with regards to logging I was introduced to TraceListeners which I'd never come across before and sorely wish I had. I can't count the amount of times I've written loggers needlessly to do this and nobody had ever pointed this out or asked my why I didn't use the built in tools. This leads me to wonder what other features I've overlooked and written into my applications needlessly because of features of .NET that I'm unaware of.
Does anyone else have features of .NET that would've completely changed the way they wrote applications or components of their applications had they only known that .NET already had a built in means of supporting it?
It would be handy if other developers posted scenarios where they frequently come across components or blocks of code that are completely needless in hindsight had the original developer only known of a built in .NET component - such as the TraceListeners that I previously noted.
This doesn't necessarily include newly added features of 3.5 per se, but could if pertinent to the scenario.
Edit - As per previous comments, I'm not really interested in the "Hidden Features" of the language which I agree have been documented before - I'm looking for often overlooked framework components that through my own (or the original developer's) ignorance have written/rewritten their own components/classes/methods needlessly.
The yield keyword changed the way I wrote code. It is an AMAZING little keyword that has a ton of implications for writing really great code.
Yield creates "differed invoke" with the data that allows you to string together several operations, but only ever traverse the list once. In the following example, with yield, you would only ever create one list, and traverse the data set once.
FindAllData().Filter("keyword").Transform(MyTransform).ToList()
The yield keyword is what the majority of LINQ extensions were built off of that gives you the performance that LINQ has.
Also:
Hidden Features of ASP.NET
Hidden Features of VB.NET?
Hidden Features of F#
The most frequently overlooked feature I came across is the ASP.net Health Monitoring system. A decent overview is here: https://web.archive.org/web/20210305134220/https://aspnet.4guysfromrolla.com/articles/031407-1.aspx
I know I personally recreated it on several apps before I actually saw anything in a book or on the web about it.
I spoke to someone at a conference one time and asked about it. They told me the developer at MS had bad communication skills so it was largely left undocumented :)
I re-wrote the System.Net.WebClient class a while back. I was doing some web scraping and started my own class to wrap HttpWebRequest/HttpWebReponse. Then I discovered WebClient part way through. I finished it anyway because I needed functionality that WebClient does not provide (control of cookies and user agent).
Something I'm thinking about re-writing is the String.Format() method. I want to reflect the code used to parse the input string and mimic it to build my own "CompiledFormat" class that you can use in a loop without having to re-parse your format string with each iteration. The result will allow efficient code like this:
var PhoneFormat = new CompiledFormat("({0}){1}-{2}x{3}");
foreach (PhoneNumber item in MyPhoneList)
{
Console.WriteLine(PhoneFormat.Apply(PhoneNumber.AreaCode, PhoneNumber.Prefix, PhoneNumber.Number, PhoneNumber.Extension));
}
Update:
This prompted me to finally go do it. See the results here: Performance issue: comparing to String.Format

Categories

Resources