Enum naming to avoid name clashes - asp.net

I'm trying to standardise the way I name things, but as a newbie I always seem to come up with an issue somewhere further down the line.
Case in point - I have a user control and enum that clash. The UC is very specific and contains a form dropdownlist/validation for customer input - the name relates to the type of input so the class is named EmploymentStatus.
However, the dropdownlist is populated via an enum - ideally this would be called EmploymentStatus too as I've adopted the recommended singular form for enums.
No doubt everyone has come across this issue at some point, but what is a good solution?

I think namespaces would be the way to go here. Just put the enum in a separate namespace then refer to fully qualified e.g.
MyCompany.MyApplication.AnotherNamespacePart.EmploymentStatus
If this is a bit verbose then you can use namespace aliases to make things a bit more readable.
using myEnum = MyCompany.MyApplication.AnotherNamespacePart;
... some code
myEnum.EmploymentStatus
Please note I've assumed C# here but the principle will hold for other asp.net languages
In my humble opinion and all that

Related

Comparison between ViewBag and ViewData? [duplicate]

This question already has answers here:
What's the difference between ViewData and ViewBag?
(17 answers)
Closed 7 years ago.
Which is better to bring data from controller to view in .net MVC amongst ViewBag and ViewData ?
Both the ViewData and ViewBag objects are great for accessing data between the controller and view.
The ViewBag objects lets you add dynamic properties to it which makes it a very verstile tool.So dynamic object, meaning you can add properties to it in the controller.It achieves the same goal as ViewData and should be avoided in favour of using strongly typed view models.
ViewBag is a dynamic wrapper around ViewData.
So with ViewData you can do
ViewData["MyData"] = "Hello World"
You can achieve the same result using
ViewBag.MyData = "Hello World"
Since ViewBag is dynamic, you can access properties that may not actually exist e.g. ViewBag.NothingToSeeHere and the code will still compile. It may hit an exception when you run that line of code, but the property is not resolved until runtime.
More information can be found here
How ViewBag in ASP.NET MVC works
As Jason mentioned, "ViewBag is a dynamic wrapper around ViewData".
For the most part, there isn’t a real technical advantage to choosing one syntax over the other.ViewBag is just syntactic sugar that some people prefer over the dictionary syntax. Although there might not be a technical advantage to choosing one format over the other, there are some critical differences to be aware of between the two syntaxes.
One obvious difference is that ViewBag works only when the key being accessed is a valid C# identifi er. For example, if you place a value in ViewData["Key With Spaces"], you can’t access that value using ViewBag because the code won’t compile.
Another key issue to be aware of is that dynamic values cannot be passed in as parameters to extension methods. The C# compiler must know the real type of every parameter at compile time in order for it to choose the correct extension method.
If any parameter is dynamic, compilation will fail. For example, this code will
always fail: #Html.TextBox("name", ViewBag.Name). To work around this, either use ViewData["Name"] or cast the value to a specifi c type: (string) ViewBag.Name.

Servlet Initialization parameters using annotation

I am trying to learn Servlet annotations and came across this snippet
#WebServlet(urlPatterns="/MyPattern", initParams={#WebInitParam(name="ccc", value="333")})
This makes sense to me. However, I don't understand why it is not like this
#WebServlet(urlPatterns="/MyPattern", initParams={(name="ccc", value="333"), (name="abc", value="1")})
So, the question is why we need to put #WebInitParam annotation when we already declared the attribute as initParams. It seems redundant to me, or am I missing something?
The alternative you suggest would not even compile.
When you look at the JLS, it states this:
It is a compile-time error if the return type of a method declared in
an annotation type is not one of the following: a primitive type,
String, Class, any parameterized invocation of Class, an enum type
(§8.9), an annotation type, or an array type (§10) whose element type
is one of the preceding types.
So in order to group name and value together, which represent the initialization parameter the only option is to use annotation (#WebInitParam in this case) with corresponding values set as its parameters.
As with most questions about language design choices we can only speculate here. I think some reasons for this are:
Keeping the language simple.
It is kind of redundant, but the syntax for annotations can be reused and does not require new language constructs. This makes it easier to parse and to read. Sure, It's longer, but it's also more explicit to write the annotation's name.
Don't restrict possible future language enhancements.
The proposed syntax would not work if annotations would support inheritance. I don't know if that's even a planned feature but it would not be possible to implement straightforward it if the type can be omitted.
In many cases an array of annotations seems like a workaround anyway. It can be avoided in Java 8, where you can add multiple annotations of the same type:
#WebServlet(urlPatterns="/MyPattern")
#WebInitParam(name="ccc", value="333")
#WebInitParam(name="abc", value="1")
(I don't know if the servlet api actually supports this yet though)

what is the difference between System.Net.Cookie and System.Web.HttpCookie?

I obtain a HTTPCookie, but need a Net.Cookie. Are they just something you can recast, or how would i go about it?
Actually you have two questions:
Difference between System.Web.HttpCookie and System.Net.Cookie
How to convert from HTTPCookie to a Cookie.
Part 1)
This question is really interesting ,I'm still thinking why there are two classes which looks pretty same ,My initial thought was System.Web.HttpCookie inherits System.Net.Cookie but this isn't true both directly inherit from Object so they are distinct classes ,but the properties matches a lot ,so this gives a hope for the solution of part 2.
Part 2)
I think its possible to convert one into another theoretically since both are just objects if you populate them the right way it will work , here a little analysis when I compared the two classes.
Click to open in new tab to enlarge
Update:
The System.Web is made to be used in server-based apps and System.Net can be used for client based apps.
Some Thoughts:
Write a method or a static class which can convert one object into another, I haven't check all of them but properties whose names match, there signature also matches.
Properties which don't exists in the another object you can stuff some constant or a value which you know matches the scenario like Port number.
Good luck ,let me know how you came up with the final solution ,post the code or link.
Some Links
this post has some related code

Utility class or Common class in asp.net

Do anyone knows about the class which has the common function which we generally use while developing web application. I have no idea what you may call it, it may be the utility class or common function class. Just for reference, this class can have some common function like:
Generate Random number
Get the file path
Get the concatinated string
To check the string null or empty
Find controls
The idea is to have the collection of function which we generally use while developing asp.net application.
No idea what you are really asking, but there already are ready-made methods for the tasks you write in various library classes:
Random.Next() or RNGCryptoServiceProvider.GetBytes()
Path.GetDirectoryName()
String.Concat() or simply x + y
String.IsNullOrEmpty()
Control.FindControl()
Gotta love the intarwebs - An endless stream of people eager to criticize your style while completely failing to address the obvious "toy" question. ;)
Chris, you want to inherit all your individual page classes from a common base class, which itself inherits from Page. That will let you put all your shared functionality in a single place, without needing to duplicate it in every page.
In your example it looks like utility class - it is set of static functions.
But I think that you should group it in few different classes rather than put all methods in one class - you shouldn't mix UI functions(6) with string functions(3,4), IO functions (2) and math(1).
As Mormegil said - those functions exists in framework, but if you want to create your own implementations then I think that for part of your function the best solution is to create extension method.

How do you decide on the means of passing model data from asp.net mvc controllers to views?

There seem to be multiple means of passing model data from controllers in asp.net mvc to views. Its not clear to me if there's a recommended approach in the mvc v1 and v2 releases or if like most things in life, it depends. I've seen several approaches:
Option 1 - Populate the controller's ViewData dixtionary in either an icky string-based indexing way with casting in the view, or the in a strongly typed way by creating a strongly typed custom model class and passing that via ViewData.
Option 2 - Use ViewData.Model, which I'm not sure I even understand.
Option 3 - Use ViewPage.Model, in which case I'm not sure how you pass the model data from the controller.
I've seen a number of posts poo-pooing options 1 and 2 but I don't understand why. These posts seem to highly recommend 3 in most cases.
How do you approach this? Is there a standard way?
Every view 'should' have a specific model. This is sometimes more work so people use short cuts like ViewData, which works but is just not as clean and type safe in my opinion, so I prefer to have everything in the view's model.
You can then make all your views stongly typed. This is a very clean way to do so. Then in your controller you just call the view like:
YourViewModel model = new YourViewModel()
{
// initialize the data here
};
View(model);
Then in your views you can access all the data via ViewPage Model and it is all type safe and enforced from the controller as well.
EDIT from comments:
You don't need to use ViewData at all if you don't want. You can encapsulate all the data your view needs in a model. Just like the example you quoted with ProductsListViewData. It's just a model that contains all the items that were going to be stored in the ViewData. Both ways work but when you encapsulate it in a class (preferred method where everything is in the model) then all the bits and pieces are strongly typed.
ViewData is a generic container so even though you can just put anything you want into it, it is not type safe and therefore not as 'clean'. It comes down to preference and maintainability. There is only option 1 and 3. Your option 2 is misunderstood and is just option 3 in reality. There is no ViewData.Model just ViewPage.Model.
One approach you may wish to consider as your views become more complex, is to reserve the use of Models for input fields, and use ViewData to support anything else the View needs to render.
There are at least a couple of arguments to support this:
You have a master-page that requires some data to be present (e.g. something like the StackOverflow user information in the header). Applying a site-wide ActionFilter makes it easy to populate this information in ViewData after every action. To put it in model would require that every other Model in the site then inherit from a base Model (this may not seem bad initially, but it can become complicated quickly).
When you are validating a posted form, if there are validation errors you are probably going to want to rebind the model (with the invalid fields) back to the view and display validation messages. This is fine, as data in input fields is posted back and will be bound to the model, but what about any other data your view requires to be re-populated? (e.g. drop-down list values, information messages, etc) These will not be posted back, and it can become messy re-populating these onto the model "around" the posted-back input values. It is often simpler to have a method which populates the ViewData with the..view data.
In my experience I have found this approach works well.
And, in MVC3, the dynamic ViewModels means no more string-indexing!
This might be of some help:
When is it right to use ViewData instead of ViewModels?
(I know the following answer is highly arguable, but it's just the way I like to do it)
I would say use ViewData for simple data-tasks, and use the Model for the main purpose of the View. Check out Rob Conerys ViewData helper-classes here to give them a bit more Strongly typed feel:
http://blog.wekeroad.com/2010/01/20/my-favorite-helpers-for-aspnet-mvc
Using Models for absolubtely everything will bloat your project with hundreds of models just to achieve the smallest thing. I mean if you have a User-setting page, you would normally pass a User-model into the view, but if you decide to show some related data like Customers related to this User. You're stuck with the following solutions
You might have to add a List property to the User-model in order to expose the customers to the view. This leads to the Customer-property always being applied to the User-model everywhere else in the project - or make a new simpler User-model.
Make a new action that returns a partial of customers, which you can use with Html.RenderAction.
OR
you could do ViewData["Customers"] = myRepo.GetCustomersRelatedTo(user); // or something like that.
and (if using Robs helpers) in your view:
<%= Html.RenderPartial("CustomerList", Html.ViewData("Customers")) %>
add a PartialView called CustomerList that takes IEnumerable
In my humble opinion this is a cleaner solution and sure - you end up with a magic string here and there, but I'll stick to this approach until someone shows me a project with not a single magic string.
Use the tools we have in the Framework to get the job done. and Keep it simple s... ;)

Resources