CAT | Software
18
HTML Unencoding for Razor View Engine on ASP.Net MVC 3 Preview 1
No comments · Posted by A.K. in Blog, Software
I have been using the Razor engine for a few days now, and I am liking it a lot. I noticed one big problem right from the start, all strings are HTML encoded. For our uses, this becomes quite an annoying “feature” when we deal with JSON strings. For example, given a simple JSON string,
The actual HTML encoded output of this became,
The quotes have been escaped, which is not the desired output. If we need to send HTML back out, or XML, we would have to then individually escape those. Overall, I find this quite annoying as we would have to wrap it inside of an HtmlString as shown in this StackOverflow post.
In our scenario, we are generating JSON/XML from C#, so most of the time, our serialized data is inside of the ViewModel. Which would result in us doing things like,
@(new HtmlString(View.Bar))
As you can see, this can become quite cumbersome. So I decided to plagiarized part of MVC to create a RawView. In the end, the usage will be,
@RawView.Bar
I also went ahead to allow the usage of the index operator as well in case there’s a need to loop over it with a list of keys.
@{
List<string> keys = new List<string> { "Foo", "Bar", "Baz" };
foreach (var key in keys) {
@RawView[key]
}
}
To achieve this, I would need to duplicate DynamicViewDataDictionary. Naturally, I named it DynamicRawViewDataDictionary,
{
private readonly Func<ViewDataDictionary> viewThunk;
public DynamicRawViewDataDictionary(Func<ViewDataDictionary> viewThunk)
{
this.viewThunk = viewThunk;
}
private ViewDataDictionary ViewData
{
get
{
ViewDataDictionary viewData = this.viewThunk();
return viewData;
}
}
public object this[string key]
{
set { setData(key, value); }
get { return getData(key); }
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return ViewData.Keys;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = getData(binder.Name);
return true;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
setData(binder.Name, value);
return true;
}
private object getData(string key)
{
object value = ViewData[key];
if (value is string)
{
return new HtmlString(value.ToString());
}
return value;
}
private void setData(string key, object value)
{
ViewData[key] = value;
}
}
The reason for the duplication is because the DynamicViewDataDictionary is an internal sealed class. There was no way I could get around this restriction other than copying and pasting. The obvious change I made to this class is the getData method. I checked to see if the object is a string, if it is, I wrapped it with an HtmlString().
Now I need to use this inside of a WebViewPage, since all views , I have to have a customized version of a WebViewPage as well. Good thing that MS didn’t make this class internal sealed, so I can easily inherit from it. I needed to make a generic and a non-generic version, I just plopped both of this inside of one file.
{
private DynamicRawViewDataDictionary _rawData;
public dynamic RawView
{
get
{
if (_rawData == null)
{
_rawData = new DynamicRawViewDataDictionary(() => ViewData);
}
return _rawData;
}
}
}
public abstract class CustomWebViewPage : WebViewPage
{
private DynamicRawViewDataDictionary _rawData;
public dynamic RawView
{
get
{
if (_rawData == null)
{
_rawData = new DynamicRawViewDataDictionary(() => ViewData);
}
return _rawData;
}
}
}
For the final touch to actually make this work, at the top of the cshtml file, you should have something like,
//or
@inherits Namespace.To.CustomWebViewPage<dynamic>
Now that the cshtml file inherits from the new CustomWebViewPage, it should have access to RawView, which will wrap all strings with an HtmlString.
Once you have this in place, you’ll still need to make sure that all of your new views inherits from CustomWebViewPage. I highly recommend using custom code templates in your MVC project to generate the view. This will help with automating a lot of the mundane tasks.
asp.net mvc 3 razor view engine · html encoded · html encoded strings · razor engine html encoded · razor view engine
4
Migrating project from ASP.NET MVC 2.0 to 3.0 Preview 1
No comments · Posted by A.K. in Software, Web Development
I just downloaded ASP.NET MVC 3.0 to test out the new Razor view engine. The problem is that the previous project created in MVC 2.0 needed to be changed as well. This step is nearly identical to the process in migrating from 1.0 to 2.0. The following content is blatant plagiarism with a few details modified,
To manually upgrade an existing ASP.NET MVC 1.0 application to version 2, follow these steps:
- Make a backup of the existing project.
- In a text editor, open the project file (the file with the .csproj or .vbproj file extension) and find the ProjectTypeGuid element. As the value of that element, replace the GUID {F85E285D-A4E0-4152-9332-AB1D724D3325} with {E53F8FEA-EAE0-44A6-8774-FFD645390401}. When you are done, the value of that element should be as follows:
{E53F8FEA-EAE0-44A6-8774-FFD645390401};{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}
- In the Web application root folder, edit the Web.config file. Search for System.Web.Mvc, Version=2.0.0.0 and replace all instances with System.Web.Mvc, Version=3.0.0.0.
- Repeat the previous step for the Web.config file located in the Views folder. (Additional note: There are 4 places that you need to change to 3.0.0.0 in this file.)
- Open the project using Visual Studio, and in Solution Explorer, expand the References node. Delete the reference to System.Web.Mvc (which points to the version 1.0 assembly). Add a reference to System.Web.Mvc (v3.0.0.0).
- Add the following bindingRedirect element to the Web.config file in the application root under the configuraton section:
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>(Additional note: I just replaced this entire section in my old Web.Config. Unless you have other elements, I would recommend doing the same thing.)
- Create a new empty ASP.NET MVC 2 application. Copy the files from the Scripts folder of the new application into the Scripts folder of the existing application.
- Update the existing application’s CSS file with the CSS style definitions in the Site.css file.
- Good luck!
Ah yes, the famous Fred Brooks quote. How does a software project get to be one year late? You guessed it, one day at a time. The project that I had embarked on at my company for the past 14 months was supposed to have taken 5. Imagine that, it was 9 months over the deadline, which is 180% late. When factoring in the fact that we had about 1/4 of the features, it actually was closer to 700% late. How could this have happened? Were we all sleeping? These are hard questions to answer, but I know that given a choice, we would not repeat this again. If we learn from our mistakes then we might have a fighting chance on preventing this from happening again. To start, how did this all happen?
It all happened so quickly (lol), I didn’t know what hit me until it did. It was a combination of many things that led to this huge delay,
- Project scope was constantly changing.
- Overly optimistic estimation of completion time.
- Inexperienced team.
- No code reviews.
- No set priorities.
We could have easily mitigated most of these by identifying problems earlier on and dealt with them as needed. Of course, hindsight is always 20/20, but our foresight, blind as a bat.
The elusive scope
I’ve read about this topic in papers and even heard it on various audio and podcasts. I even took a class on project management and we had a section on project scope, but none of it translated to reality for me and I had to find out the hard way. I didn’t know what a scope creep looked like until it snuck up and smacked me upside the head. Inexperience was one of the largest culprits for our downfall. Why was the scope creep in this project so elusive? The lack of a clear requirement specification.
We did not have much in terms of documentation but a simple PowerPoint slideshow. It was a very basic, naive specification that had a lot of missing requirements. To make up for it, the management pushed the responsibilities onto the developers. The developers were to apply “common sense” liberally. Yes, you heard it right, common sense (funny, my blog name). A word of caution, if you hear your manager state that the team/group/company doesn’t have enough common sense, take extra precautions and document everything you do in case you need it. Eventually, the word was thrown around so much where, to me, it felt that we should have gotten a degree “telepathy” instead. How can you quantify common sense? One person’s common sense does not necessarily apply to another person. If you decide/have to rely on common sense to produce a piece of software, I really pity you.
Don’t get me wrong, writing software requires a lot of common sense, but should never rely on it. You should rely on specific documentations, clear objectives, and frequent verifications/validations of the software. If the validation process seems to fail at a high rate, like it did in our scenario, then your requirement specification is weak and poorly developed. Each time we had accomplished some milestone, we checked back with our “customer,” who happens to be the boss, there was always something missing. Sure, some of it were the developers’ fault, but more often than not, it was the lack of specification requirements. In management’s words, “we did not apply enough common sense to fill in the missing pieces.”
We had specifications, but we didn’t have enough. We should have been spent more time on the planning stage. More discussions and debates regarding the product features and its priorities. Parallel with this planning stage should be prototyping of the new system’s infrastructure and implementation details such as file organization, data modeling, interfaces, etc. Since we were a new team, this would have been a good time to also sketch out basic coding standards to adhere to. A structured approach would have given us some foundation to give a strong start.
Sadly, we did not take this route. Our team dove right into the feature list without the slightest thought of refactoring anything. We had limited time and a huge, unprioritized todo list. The boss wanted to see results, and our direct manager pushed us to get features done. Right from the start, we were in a rat race. Naive were we, we happily chipped away at that insurmountable list. We were able to get some of the bigger features done and thought we were making headway. Each time, we pat ourselves on the back for the accomplishment. Without any milestone party, discussion, or thorough testing, we jumped right back on the treadmill, going full speed ahead onto that next feature.
Four months in and we weren’t even close to the halfway mark. Bugs started popping up left and right, but it seemed like we had more than our fair share of bugs. Bugs that I swore I had fixed kept on coming back. Something did not feel quite right, did we have zombie bugs? Unsquishable, unstoppable, undead bugs? So I put on my dumpster diving suit, closed my eyes, plugged my nose, and jumped into our code base. My heart sank, or to use my dumpster diving metaphor, I had major gag reflex. Copied and pasted code were everywhere, blocks of nearly 200 lines of code were identical. It was at this very moment that I felt I was entering a world of hurt.
To be continued…
late software · late software project · prevent late software projects · preventing late projects · requirement specification · software documentation
I’ve had the “luck” recently in having been in an environment where serious micromanagement was occurring. From this experience, I find that micromanagement not only demoralizes the entire development team, but it also puts the project at risk of failure. In this particular circumstance, the project is barely hopping along with the micromanager dragging it every inch of the way. It seems to be a very unproductive way to get to feature complete. Let me recap my experience.
I was contacted out of the blue by a former boss of mine to introduce me to a young, ambitious entrepreneur . This entrepreneur, whom I will call Bob, wanted to capitalize on the social networking trend and he had a great idea. His idea has been recognized by TechCrunch for its great potential. Everything seemed like it would work well and I agreed to work with him. At first, Bob seemed very on top of things. As a matter of fact, too much on top of things.
After the third day of working with Bob, I was uncomfortable because it felt like I was being dictated to on what I should be doing. I should fix this bug, then after which I should fix that bug. Once a bug was marked as fixed, almost always that bug was reopened with a feedback. The feedback was usually in the form of telling me that the fix wasn’t quite right because Bob had imagined the fix to be this way or that. Nearly a week had gone by and suffocation settles in. I dreaded having any contact with Bob, whether it be email, phone, or IM. I decided to consult my loving and supportive wife.
After some serious talking, we decided that despite the opportunities, it was not worth my trouble. So I told Bob that I will find a replacement and I will step down from my position. It took a couple weeks’ worth of interviewing candidates and I was lucky to find a replacement. But it was not meant to last. A few weeks later, I was once again contacted by Bob to help him look for another person. Apparently, my replacement had quit as well. I investigated further, and thus born this blog post.
Peopleware explored this idea greatly under chapter 20, Teamicide. This chapter listed ways in which you can kill your team and its effectiveness. The first of which fits into my scenario, Defensive Management. This section noted what I felt, that is only Bob’s “own judgment was competent; anyone else’s was suspect.” He fitted this profile to the T. He had a hard time allowing people to make their own mistakes or do what they think is necessary. He had to be “on top” of everyone’s work at any given time. So much so that he began to want direct report from everyone everyday of the things they had accomplished and the amount of time it took.
I don’t want to bash the micromanagement strategy. It may work in other scenarios and circumstances that I am not familiar with, but I can say that it will not work in software development. For a piece of software to be successful, you need to have smart, competent developers that can get things done. Once you have acquired your talents, let them know of the objective and let them loose (with periodic checkups). If you cannot trust your developers, then you have not found the right people.
Good developers will want to show that they are smart and that they can get things done the right way. If they are stuck, they will ask you to clarify the problem. Software building needs very specific requirements, if those requirements are not met or are fuzzy, you as the manager, will have an opportunity to make it clear. It is never a good idea to butt yourself into a developer’s work and interrupt their flow.
Peopleware noted that letting your software developers do whatever they want is a scary feeling. You will feel out of control, you will feel helpless. The good thing is, your developers will get more done, I can attest to that. Keep in mind this only applies to good software developers, otherwise, your mileage may vary. As you may know, The Mythical Man-Month pointed out that a “good” software developer is about five to ten times more productive than an average one. Peopleware confirmed this notion through observation of many “Coding War Games”. So, find good developers and let them do their job.
Once you have yourself a good team, it all boils down to trust. Do you trust your team? Do you have confidence in your team’s ability to deliver? Have they proven that they can deliver in the past? If the answer to all of these questions is a resounding yes, then you really have nothing to worry about. Go take care of other things for your business. You can have a great piece of software, but if you can’t sell it, then what is it really worth?
micromanagement · micromanagement death · software team · successful software · successful software team
No, I don’t mean how to be a good programmer, but how to be a successful one. Although these two qualities almost always go hand in hand, but not everyone that can program will become successful doing it.
Keep up to date
I cannot stress enough how important it is to keep up with technology. Being in a field where things are always changing at a fast pace, you will not be able to keep up with everything, but you should do your best to keep an eye out for new things. Keep in mind that I am not suggesting that you have to jump on that next coolest programming language. Far from it, I am suggesting that you learn the basics, write a simple sort or binary tree.
If it is a new programming language, understand some of the basic concepts. If it is the next coolest touchscreen coffee mug, find out if it has an API. The point is not to know everything, it is more pertinent to know what is possible.
Be passionate
My career as a developer is not long at all, but I have witnessed many of my peers picking this profession for the wrong reason. While I was in school, I would see many of my fellow students take no initiative in learning anything outside of the classroom. I remember one occasion where a simple regular expression would have sufficed, the student turned into a recursive function that was 30 lines long. On top of that, they take no time in commenting their code or even bother to refactor their functions.
Unless these are extremely talented people, I cannot see any of them becoming successful as a programmer. You have to be passionate. Every line of code is written with the intention that it can be improved upon. If you find yourself copying and pasting, stop immediately and find a better way. Refactor your code, use good variable names, have proper white spacing, indent neatly. Everything should be done with a reason and not just slapped together.
A passionate developer will make his code clean and understandable. Learn to comment your code. “But good code should tell you exactly what it is that you are doing.” I have heard this argument many times, and I cannot say how wrong it is. Comments not only tells you what the snippet of code does, but it also tells you why it’s there. Many programmers do not comment while coding, which is understandable, but good programmers will almost always comment their code after they are done. Dot your i’s and cross your t’s, other developers you work with will appreciate it.
Have side projects
This should be included in the previous section, but I think it needs to be on its own.
Unless you work for a company that does not value employees’ contribution, creativity, and passion, you need to have a side project. A side project not only tells your (future) employer that you can program, but it tells them that you love to program. I have spoken to a few people for tips on how to look for job candidates, the common theme is that they always look for people that have projects that are not school or work related. They want to look for people who eat and breathe this stuff.
Even big companies like Google allow their employees to spend 20% to do things outside of their job description. Or 3M’s more relaxed version, their 15% culture, that allows their employees to do anything they want (side projects of course) 15% of their time. Successful companies realize that by enabling their employees to work on something they are passionate about, they get more out of the employee. As a software developer, the company you work for should allow you to be passionate about what you do. If you are stuck with a company that does not allow for it, you should seriously consider another job. Life is too short to waste it on a job that restricts your ability to grow professionally.
Read programming books
Why read programming books? Isn’t it true that computer technology changes so often that what you know today may not apply tomorrow? That is true in some sense like programming languages. Languages change from year to year or job to job. It is not true for other aspects like concepts. For instance, OOP applies in C++, C#, Python, PHP, and many other languages. Understand concepts and not syntax, although syntax is a plus but it is not necessary. This is why we read programming books, understanding functional programming and design patterns are much more important than any single language. Pick up a book, here are some of my recommendations,
The Pragmatic Programmer: From Journeyman to Master
Code Complete: A Practical Handbook of Software Construction
Head First Design Patterns
These books are not listed in any order since I feel that they are all equally important to read. I just started on Code Complete myself and I find it fascinating.
Communication
As much as programmers hate to write and talk, it is an important skill to acquire. If you are anything like me, your writing probably falls into the bottom (lower?) quartile. That is why I have decided to start up my blog again. It has always been my focus to use this blog as a way for me to improve my writing skills. If you have communication problems, you should do the same thing as well. Writing allows you to verbalize your ideas effectively. Since I am not a master communicator by any stretch of the imagination, I cannot help you much in this aspect. What I can help you with is this observation from my limited experience.
People, in the same job position, with better communication skills and higher vocabulary are nearly always approached first by their management. This results in more responsibilities and when given the opportunity, they are more likely to be promoted. These people are more likely to take on the role of a technical lead because they can effectively communicate ideas with the team.
If you have any ideas that can be improved upon, I am more than happy to hear from you. Or if you think that I am wrong I would love to hear your thoughts.
side projects · software developer · software engineeeing · successful programmer
I first heard about Chrome this morning from a friend whose wife works with Google on this Chrome project. Indeed, I went to the website right away to check it out and I was blown away by what I read about it. If you want to read more about it, I recommend the Google Chrome comic strip that they put out on their website. I must warn you, unless you are into development stuff, the comic is pretty darn boring.
I’ve finally gotten version 2.0 stable enough for a release, maybe it should be a 2.0b1? I have completely rewritten and restructure the code so that it wouldn’t crash (as often), especially among those players with long, arcane directories for their War2. However, if your directory is long enough, it may still cause such a crash. Additionally, since the program is better structured now, you also benefit with having a smaller executable. Although, it’s not like 10kb means that much anyway
. One thing I should have made clear previously, this is for the latest English version of War2 only! (more…)
I’ve finally made some fixes for War2Observe and is now available for download HERE. If there are any serious bugs, please let me know immediately so I can fix it. These are changes that I’ve made to this version of War2Observe:
- The selected player’s color is now displayed on the left side of the menu
- The barrack’s HP is now shown while training units
- Ogre-mage is now shown in the barracks (more…)
Let me make it clear that War2Observe is NOT a malicious hack. It is not intended to give any player an unfair advantage over another. It simply gives Warcraft 2 a new sense of wonder. Here’s a grocery list of what it is, and what it is not:
IS:
- An improvement to a very old game
- As LoThaR. puts it, "real time insight"
- My attempt to showoff the raw power and sexiness of my brain…..
- To give back to the community I love so much
IS NOT:
- A malicious hack designed to give unfair advantage
- A maphack
- A trojan (as The_G0D thought it was)
No tags
Q: Why do I get the error "The application has failed to start because…"?
A: In an attempt to show my leetness coding skills, I have chosen to use Visual Studio 2008 as my IDE. This was a poor choice as it results in an executable file that does not work on most machines. To get it working, you need to download Microsoft Visual C++ 2008 Redistributable Package. If you are running x64 operating systems, there’s a link at the bottom of that page redirecting you to the proper download.
Q: I have Windows 98/ME, can you help me run version 2 of this program?
A: I have used a few memory functions that are available only to Windows 2000 and above. However, you are in luck because there exists an open source project called KernelEx which adds NT functions to the Windows 98/ME. Although this is a workaround, I cannot guarantee that it will work for you or it will be stable for you.
Q: How does this thing work?
A: It just makes War2 thinks you’re all the player. (more…)
war2observe · war2observe faq · war2observe frequently asked questions
