Tuesday, March 22, 2016

Submit Buttons: More Useful than You Think

We all are familiar with using a submit button to post a html form back to the server; however, people often overlook their name attribution which can provide the server with additional information to give better context to the request and the user's intent.

I like to name all my submit buttons Action as a matter of protocol. But obviously, you can pick your poison. When you name your different submit buttons all the same thing, they sort of act like a select box with each button representing a submission option.


Client Side:
    <label for="MyFavQuote" >Fav Quote: </label> 
    <input id="MyFavQuote" name="MyFavQuote" type="text" />

    <input id="SaveDraftButton" name="Action" type="submit" value="Save as Draft" />

    <input id="SaveFinalButton" type="submit" name="Action" value="Save as Final" />


Server Side:
String quote = Request["MyFavQuote"];
String action = Request["Action"];
if (action == null)
{

      //Nothing needed for get request
}
else if (action == "Save as Draft")
{
     data.SaveDraft(userId, quote);
}
else if (action == "Save as Final")
{
     data.Publish(userId, quote);
}


Saturday, February 28, 2015

Delivering Software Value to your Business: Users per Line of Code

If you work inside a SAAS company objectively determining the value of your software and developer hours may not be easy, but it is certainly less difficult then determining the value of a internal business application. How important is this feature? Is it worth the level of effort in developer hours? Agile attempts to address these questions with story points effort points, but this metric is often hard to communicate to management and does not facilitate the justification of lowering technical debt.

The metric I am putting forward is Users per Line of code (Users/LOC). This is calculated by taking the users of an application and dividing it by all the lines of code that go into making a deployable binary, including files that do not compile such as configurations or stored procedures. This can give a team a rough estimate of their application's value to the business.

When multiple applications share code between them through a shared DLL or other means that do not involve manual copy and paste, the shared code's total lines can be divided by the number of applications sharing it. Conversely, if a team is trying to calculate their application suite's total value they can sum all of their applications' lines of code while only adding the shared code once.

The reason that lines of code factor in to this metric is because by only looking at an application's  total users no value is placed on a developer's time or productivity. Although, life seldom has absolutes, having less lines of code generally makes a modification of an existing feature easier. Additionally, if an application's architecture is conducive to code sharing adding a requested feature will not as negatively effect the lines of code. As far as bugs go, there is a direct relationship between an application's lines of code and the number of bugs that will occur.

I am not proposing Users/LOC as The One True Metric™, but rather an additional metric in the application developer's tool box. Focusing on any one metric can incentivize destructive behavior in any organization. Obviously, Users/LOC must be used in conjunction with other metrics; overemphasis may incentivize poorly readable code.  If your company's CEO is the primary user of Reporting Application X, obviously Users/LOC is not the most appropriate metric.

It is easy to imagine Users/LOC being used as a component of another metric; for example in an agile environment, (Story Points * Users) / LOC. Users/LOC can also be used on a feature basis as opposed to being used for an entire application for enhanced accuracy. There is high value in this metric because it can reduce both over-engineered code and under-engineered code. If Application A is used by one person to simply do basic data entry to one table with minimal validation rules is over-engineered with a 5-layered web service architecture an extremely poor Users/LOC score will result. If application B has the same complex business logic that must be repeated on five different pages but the developer under-engineers by not isolating the business logic in its own layer this metric's score will also be lower than expected.

In summary, Users/LOC can help lead developers and product managers increase their value to the business by both helping to direct resources appropriately and detecting poor architectural and allocation decisions after the fact. More users, more impact and visibility. Less lines of code, more impact potential per developer hour in the future. Maximize users per line of code and maximize your application suite's short-term and long-term value.

Friday, May 3, 2013

Asp.net Chart: Labels Not Showing Up

You might have noticed that when you are making your fancy little asp.net chart that quite a few of your x-axis labels are missing. This wasn't a major issue when you were making a line chart, but when you got to the column graph, missing those labels was kind of a big deal. Not to worry, the solution is fairly simple; although, hard to find if your googling skills are as bad as mine.

You merely have to set the Interval attribute to 1 in the LabelStyle tag. Markup sample below:
















I also set the Interval to 1 in MajorGrid to make sure every column had its own tick mark. Additionally, I set the Angle to 45 to give each label more room (and it looks cool); but, in order for this to take effect you have to set IsLabelAutoFit to false  in the AxisX tag.

Happy coding!

Tuesday, March 26, 2013

Linq to Entities, not wrong or right

At this point in my career, I have had the pleasure of having Linq to Entities be made both mandatory and forbidden by management decree. All I can say is, whether you want to ban L2E or mandate it, you are wrong.

If you have a simply structured application Linq to Entities can save you an absurd amount of time that can be used to do things like make your application more usable. For applications whose databases can be described by simple one to many, or many to many relationships, Linq to Entities can be quick to code against, have reasonable performance, and present a shallow learning curve. For more complex reporting pages, Linq to Entities can easily leverage stored procedures to increase performance. Yes, there are risks such as an ignorant programmer unintentionally doing multiple full table scans; however, it is unlikely that a programmer who can not be trusted with L2E could be also be trusted to remember to use the count(*) aggregation in SQL.

However, if your database schema is not so simple, you might run into issues with Linq to Entities. If your database has self referencing tables, is denormalized, very complex, or just generally misshapen from consultant raiders, L2E may not be worth the hassle. There is nothing wrong with straight up SQL, it has always worked, and it still does. In the hands of an experienced developer, by-passing Linq to Entities in favor regular SQL and Ado.net can give you access to some very powerful optimizations without sacrificing a robust code base. Although, stored procedures can also be used with L2E to increase performance, this sometimes adds business logic into the database.

In software architecture and patterns, there is no always best solution. Patterns need to be applied on an as needed basis by someone who actually understands the benefits and drawbacks of a given pattern. Linq to Entities is the same way; it has many benefits and drawbacks and therefore needs to be used as needed.

Software Engineer Job Titles (as I see them)

Everyone knows titles are not a big deal, at least when you are a measly software developer. However, the following is what I personally expect from different levels of developers, engineers, programmers, or what ever you call coders at your place of employ:

Intern/Entry (0) - Is analytically minded, but is still struggling with the basics of syntax, ect.

Junior Developer (1) - Has mostly mastered language syntax and constructs, but still needs a lot of guidance to effectively leverage his tools to create a usable piece of software that can be reasonably maintained.

[Mid] Developer (2) - Can work on assigned tasks with minimal guidance only occasionally needing to seek help. May still struggle with translating high level requirements into code. He can be unable to see patterns in a high level in the application, or see them when they are not there. May not be able to deal with ambiguity.

Senior Developer (3) - Able to develop and deploy most applications from to start to finish with no guidance. She has the ability to translate requirements and user feedback into actionable plans. Must also possess the ability to help delegate work. Can deal with ambiguity and make plans to work around it. May have some trouble distinguishing between different design patterns and applying them appropriately.

Okay, some pedants may say the next one clashes with a senior developer, may not be generally used, or claim that software architecture is it's own distinguishable field; but if I don't list it a mid-level developer will not be in the middle of the list!

Architect (4) - Has mastered his area of technology and can immediately spot the causes of obscure errors. Is an expert at translating requirements in to software, and can often understand user feedback even if the verbal feedback contradicts their true intentions or goals. Can head off issues before they become problems. Has very good working knowledge of design patterns and when to they are appropriate. Able to understand how to make larges gains in application performance. Experience is broad enough to know if a language/framework is not appropriate for the problem at hand and seek the necessary expertise. Might be able to write a book in their area of expertise.


How to render a select box with Zend Framework forms.

I was using Zend Framework 2 to make a quick form when I needed to render a quick select box for my user to select a month. I never thought I would be writing a blog post about something PHP related or something as simple as creating a dropdown so that a user could select a month; however, I ran into so much trouble doing so I think it is necessary for me to post my solution for posterity.

I was seriously scouring Google for over a hour; find a proposed solution, test, fail, repeat. The Zend documentation was fairly useless as per usual, so I was left searching random blog entries. Every time I came across something that looked promising I'd see something in the comments resembling the bellow remarks:
READER: This codez doesn't work dude!
AUTHOR: It totes does, you just got to download my custom library add-on first!

Anyway, my luck changed when I stumbled across this blog, it was the first one that had a solution that worked out of the box. However, his method for creating the element differed from the one I had used in the rest of my form. In a sane world this would not have mattered, but, in the real world this happened to make the select box look very different from the rest of the elements in my form. This still gave me a good jumping off point for this solution:

$this->addElement('select', 'Month', array(
      'label' => 'Month',
      'required' => true,
      'multiOptions' => $this->getMonths() ));


Just add an option key called 'multiOptions' and assign it an array where the key is the html value and the value is the html displayed text. Happy coding!

Friday, November 9, 2012

MySqlDataReader reading tinyint (byte) as bool

Regrettably, work has forced me to work with MySql as I have been working in a LAMP enviorment instead of my beloved .net. However, if I make a utility I go right back to C#.

While making a little utillity that interface with MySql I used the MySQL Connector Net 6.1.6 library and the included MySqlDataReader. It has a very strange behavior where it thinks tinyints are bool. It took me about a day to track this down.

reader.ReadByte to the rescue.

Thursday, February 23, 2012

Views Make The Entity Framework More Tolerable

As of late, I have been on the war path against The Entity Framwork, some of my peers and I have been bitten in the butt too many times. However, being less database focused, I have overlooked something very important; creating views in the database and then creating entities off of them can make your life much easier.

However, I still maintain that the best use of EF is when your DB consists of simple one-to-many relationships.

Wednesday, August 10, 2011

Sending a dynamic file to the client in ASP.Net

Sending a dynamic file (a file you either generate on the fly or have stored in the database) to the client in ASP.Net is fairly simple, but there are a few details to take into consideration if you want optimal results.

First, I would recommend avoiding sending files from a page with another purpose. If you send files or do redirects within an ASP.Net control event it can make your user's browser navigation buttons difficult to use. For example, if the user downloads the file then navigates to the next page then hits the back button, her browser will download the file a second time. To make the user's life as convenient as possible you will want to create dedicated download page.

Create a new Web Form (without a Master Page) and delete everything except the @ Page tag on the first line. Next, add the following attribute to your Page tag: Theme=""
The empty value will prevent your page from attempting to load a theme.

You will now want to go to the codebehind and add a Page_PreInit method; this is the best place to put your file download logic since you will not have to waste time parsing the markup. Before you add the following logic, do not forget to do your security checks if your files are not always publicly accessible.





Response.ClearContent();

This will clear any html generated in the request; it is probably not necessary if you followed all the above steps, however.

Response.ClearHeaders();

This will clear the HTTP headers.

Response.BinaryWrite(YourFileData);

Write the contents of the file to the response in the form of a byte array.

Response.ContentType = "application/octet-stream";

This tells the browser that it is dealing with a file as opposed to html. This generic MIME type should work for everything, but if you want to get more specific you can match the MIME type to your file here.

Response.AddHeader("Content-Disposition", "attachment; filename=" + YourFileName);

The content disposition is important for making the browser treat this as a normal file so it will not display as "FileDownload.aspx"

Response.AddHeader("Content-Length", YourFileSize.ToString());

This lets the involved parties know how large the file is; dot your "I"s and cross your "T"s

Response.End();

Finally, send the file to the client.



If you followed all the above steps, your client should have their file and have no idea that is was served dynamically. Happy coding!




Friday, July 8, 2011

ADO.Net

Once upon a time, there was a technology called "ADO.Net". It worked really well for retrieving data. Then programmers forgot how to use it because it wasn't hip; much to my own regret.

Monday, April 4, 2011

Some Additional Blogging

I doubt anyone actually reads this blog (although if I'm wrong, leave me a comment and let me know), but recently I've gotten some exciting news. Some executives at my company got a hold of some of my writing and invited to start blogging on the company's internal site.

I won't be able to write as technically and I will have to be much more careful about what I say, but the cool part is that people will actually read it.

To be fair, I really haven't done much to promote this blog, or even updated it frequently; but I will continue the occasional post here when it strikes my fancy in the hopes that the occasional passer-by will find some useful information or that my writing will give me a slight edge in future interviews.

Monday, March 21, 2011

A Practical Tutorial for the ASP.Net Event Model

There are likely a million guides on the web that detail the asp.net event model; however, many developers still do not grasp how to use the events properly. If you want a detailed guide to the events, try this resource. The goal of this post is to provide a guide to the actual use of the most important events; not to provide exhaustive details on everything. Also keep in mind the suggestions in this post apply most of the time; but as always, decisions have to be made on a case by case basis as your specific page may have circumstances that make it very different.



1. Page_Init



  • Populate lists, such as drop-downs

  • Set default/initial values for inputs

  • Inject content into literals

As the name implies, this event should be used for initialization of your controls. Setting default values here has several advantages. First, even if you forget to check whether the current request is a postback, your initializations will not overwrite values set by the users. Second, you get a performance boost because you do not clog up the view state. Many sources suggest using the view state to reduce database requests thereby increasing performance; however, I disagree as this is actually the duty of data-caching. One caveat to remember about Page_Init is that it cannot be used to initialize controls or populate lists when the initialization value is dependent on the value of another control. Resist the urge to set control visibility in Page_Init; it might seem to make sense at first, but will cause you trouble later.



2. Page_Load



  • Initialize controls (which might not have been visible prior to the postback) when their values are dependent on the values of other controls in the page

Page_Load is by far the least useful event on this list despite the fact that it is the event most commonly used by many developers. I cannot think of a good reason to put anything in Page_Load unless it is only used in a post back to vary page content based on user input. Resist the urge to put pretty much anything in this event. Above all else, avoid databinding in the Page_Load or you will regret it later!



3. Control Events


  • Save content changes to the database

  • Set flags on instance fields

  • Custom validation

  • Possibly redirects (try to avoid using POST requests to do redirects as it makes your site harder to use)

The control events are where data storage should be done whether it's to the database or some other medium; don't forget to check whether your page is valid. Control events are also a great place to execute business logic. Resist the urge to make UI changes in the control events (such as setting control visibility); instead set a flag and make the change in Page_PreRender. Some obvious exceptions to this rule are events like calendar DayRender or repeater DataBinding.



4. Page_PreRender



  • Set whether the control is visible

  • Set whether the control is enabled

  • Changes in content based on a varying mode or stage

  • Data-Binding!


First and foremost, this is where databinding should be triggered. This is because Page_PreRender is when your data will be in the state that you want the user to see. Prematurely triggering a databind can give users the impression that their changes did not go through. Page_PreRender is also where Visible and Enabled properties of controls should be set. Taking these steps here ensures your user gets the proper content if you're varying a page based on stage or mode in your business logic. Resist the urge to do resource cleanup in this event; that should be done in Page_Unload. If you are the type of developer that hates maintainable code and used a markup datasource, databinding can occur after the Page_PreRender event making resource clean up inappropriate here.

Wednesday, November 24, 2010

Get service of SVsBuildManagerAccessor fails

Output:
Get service of SVsBuildManagerAccessor fails

When this rather cryptic message is shown in Visual Studio 2010, it's because your one-click publish has failed (perhaps several seconds prior to your push deadline). Even worse, no webpages indexed by Google contain any mention of this obscure error.

The funny thing about Visual Studio publish is that it relies on some Internet Explorer assemblies; if one of these assemblies, specifically, ieproxy.dll, is missing or unregistered, you will get the error message "Get service of SVsBuildManagerAccessor fails" when you try to publish.

The quickest fix for this problem is to either update or reinstall Internet Explorer, alternatively, if you are sure the dll is present and you enjoy the command prompt, you can use regsvr32, to make sure ieproxy.dll is in the registry.

Credit is due to patthewebrat

Wednesday, October 6, 2010

jQueryTOOLS TOOLTIP

I was putting together a quick prototype, and decided to use jQueryTOOLS TOOLTIP. I had been looking around at different jQuery plugins the week prior and was impressed by their demo; it looks great. The good thing about the the jQueryTOOLS TOOLTIP is it is very configurable; read, "it does not look like it does in the demo out of the box so I hope you have a good graphics artist". For something as simple as a tooltip, it was also a little bit difficult to get working properly.

When I tried to use it for my table rows it was a bit choppy when you moused over, also if I did not set the "tip" option, it turned my row into the tooltip (after tearing the row out of the table permanently). For something as simple as a tooltip, if I was looking for a high level of configuration I would just make it myself; I want simple and works within seconds. I will not be using jQueryTOOLS TOOLTIP in any production applications.

Saturday, October 2, 2010

"class" is a Reserved Word in Internet Explorer

I'm a big fan of most of Microsoft's products, even Vista; but I loath Internet Explorer. If you are writing JavaScript make sure you avoid naming variables "class" as it is a reserved word in Internet Explorer (even IE8).

Thursday, September 30, 2010

Entity Framework Web Application Deployment

In retrospect, this seem painfully obvious, but when you deploy your Entity Framework web application, I would recommend that you script your database from SQL Management Studio as opposed to selecting "Generate Database from Model..." in the Visual Studio .edmx context menu.

Yes, I made the mistake of using the model generated SQL to create my production database, but it was a very small project and I had not gone into SQL Management Studio once during coding...

Happy Coding

Friday, September 10, 2010

What I wish I read a decade ago

In the field of software development two types of developers seem to be working their hardest to destroy you application and push back your release date. The first is the "Copy and Paste Kid", the second is "Over-Generalizing Gerry". The Copy and Paste Kid has never heard of functions or constants and makes numerous humorous mistakes. Over-Generalizing Gerry is the evil "genius" who will destroy your code-base by over-engineering you application into oblivion. Watch out, he'll leave no stone unturned because he will either try to anticipate every future situation imaginable or make sure your application conforms (insert buzz word paradigm) religiously. If you let your local evil "genius" gain too much self-confidence he might even try to create his own language or language extension! Pshhh, what the heck did the creators of JavaScript know?

The frustrating thing about talking to even a mild Over-Generalizing Gerry is he will often confuse you with the Copy and Paste Kid! I've finally found an article that articulates perfectly why there is an "over" in "over-generalize". I myself have been guilty of over-engineering all too often; that's why I wish I had read this article a while ago: Tips for maintainable Java code.

The preceding article is probably the best I have ever read as far as good practices outlines go. It applies to any language, not just Java.

Friday, July 30, 2010

Making a custom container control in ASP.Net (without templates)

If you're anything like me, you've tried to make your own ASP.Net server control that had container functionality, but were greeted with this exception when parsing:

"Type 'YourControlHere' does not have a public property named 'SomeHtmlElement'."

Next you goggled all possible permutations of "asp.net server control tutorial" and "child controls". Most of the solutions seemed to be either, "call EnsureChildControls", or "Use a template". However, you already called "EnsureChildControls", and if the ASP Panel control doesn't use a template, why would you?

To fix this inconvenience simply put the following attribute before your control class:
[ParseChildren(false)]

Now you are free to go about your business calling this.RenderChildren where ever and when ever you please!

Thursday, July 8, 2010

Problems with Telerick RadGrids inside a dynamic element?

I was working on a drag and drop system yesterday, but I had some problems in Firefox. When containers resized, the Telerick RadGrids inside of them would overflow instead of resizing properly like they do in IE8 (weird I know) and Chrome.

My first attempt at a work around was to allow dynamic resizing in the server-side RadGrid options. This was effective; however, it had the unfortunate, but not completely unexpected side-effect of allowing users to resize and distort the grid. Although, the main benefit of trying this fix was examining the resulting DOM and discovering an more effective solution:
<MasterTableView TableLayout="Fixed" />
When the table-layout style attribute of the table is changed from "auto" to "fixed" the problem seems to disappear.

It would not surprise me if there was a better solution to the problem out there; I can't claim to be an expert with Telerick controls. All the same, I hope someone finds the information in this post helpful.

Wednesday, November 25, 2009

Graviton?

I am a professional software developer, not a professional physicist; however, I have had a keen interest in physics since early childhood, and was seriously considering a career in the field upon entering college. I am open to constructive criticism from those in the field; please read the following post with the understanding that I am expressing my opinions and not putting forward a serious scientific paper. I do, however, feel I have a better understanding of physics than the average amateur physicist; but again, I would appreciate any qualified individual coming forward with perceived holes in my understanding.

Gauge bosons are the conveyers of the forces of nature. For example, a photon conveys the electro-magnetic force. The graviton is proposed to convey the force of gravity; however, although both particles are gauge bosons, there is a very big difference between a graviton and a photon. The key difference is that there is empirical evidence supporting the existence of photons. Even if one were for some reason mistrust the results of scientific experiments, the evidence for photons is all around us in everything we see. Our vision is the result of numerous photons colliding with the electrons in the photoreceptive cells of our retinas. However, despite the significant roll gravity plays in our universe, a graviton has yet to be detected in any way. Although, something not being detected at a certain point in time is not proof of non-existence; it is my personal position that gravitons have yet to be detected precisely because they do not exist.

Before I continue, I will mention that some might posit that the graviton is simply, “the quantity of which we measure the interaction of gravity with particles of mass.” It is hard to deny the existence of the graviton if it is given this definition; however, I feel like this is a semantic work around. The photon is said to be a particle because electro-magnetic radiation is observed to behave as a particle when coming into contact with an electron cloud. In addition, electro-magnetic energy has been observed to be quantized for a very long time; where is there is absolutely no evidence to support gravitational energy being quantized. That is to say, light only comes in discrete steps of energy. A light beam cannot be in whatever frequency one desires, but instead, its frequency is strictly limited to values allowed by the laws physics; hence, lending credence to calling the photon a particle.

I will admit a personal bias to not believing things that have yet to be proven both rationally and empirically; however, my disbelief in the graviton is not without rational basis. The hypothetical graviton appears to directly contradict the theory of relativity. Einstein’s relativity claims that gravity is the result of curved space-time, not some mystical gauge boson. Unlike the graviton, relativity has empirical evidence supporting it. Gravitational lensing, as well numerous other predictions of relativity, have been observed in the real world. It would be absurd to throw out a perfectly reasonable theory with evidence supporting it in favor of a theory with no evidence. However, I doubt many proponents of gravitons would favor throwing out relativity, but would probably prefer some strange work around akin to hammering a square peg into a round hole.

In order to reconcile relativity with the existence of gravitons we either have to demonstrate how gravitons can cause gravitational lensing, or assert prior observations of gravitational lensing were the result of some other natural phenomenon. In order to assert the graviton is the cause of gravitational lensing, a model of the interaction of the photon and the graviton must be proposed. Although, the results of my Google search for “graviton photon interaction” were a bit sparser than I would have liked, I came across an interesting article by Matthew R. Edwards. It was titled Photon-Graviton Recycling as Cause of Gravitation and was located in the third issue of volume 14 of the Apeiron publication. The publication date was July 2007 and the article can be found at the following URL, http://redshift.vif.com/JournalFiles/V14NO3PDF/V14N3EDW.pdf. According to this article, photons lose energy when traveling through space because of interactions with gravitons. I therefore deduce, perhaps wrongly, that in this model, gravitational lensing is caused by light refraction as the photon either slows down when entering an area of higher graviton concentration, or speeds up when entering an area of lower graviton concentration. If this is the case, my position has the potential to be falsified by comparing the speed of light at a point of high gravitation to the speed of light at a point of low gravitation. I am not sure how one would go about setting up this type of experiment, but if Edwards is correct, the speed of light after taking into account coronal gas density, should be slower near the sun than the speed of light at a point farther out in the solar system. I do, however, realize I may be straw-manning, as the Apeiron publication may not necessarily speak for the physics community at large.

Biologist Richard Dawkins has noted that humans have the tendency to make false positives in association recognition. That is to say, people will tend to see patterns where they do not exist. The desire of even extremely intelligent people to see patterns can be very strong; this tendency helped our ancestors survive in a vast and confusing world. I feel as if the graviton comes from the desire to fit gravity into the pattern of the other three known forces. It is reasonable to think that gravity might have a gauge boson because electro-magnetism does; however, there is no scientific reason why this must be the case.

I believe that attempts to combine gravity with the other three known forces have failed, and will continue to fail, because gravity is simply a very different “animal”. I also feel as if the tendency of some physicists to analyze the world in terms of symmetry is misguided and needs to be checked. The universe is not symmetrical and there absolutely no logical reason why it should be. Symmetry is like beauty, it is extremely subjective, and people tend to like it. In addition, the word “symmetrical” is ambiguous. When you say symmetrical, do you mean in terms of a vertical orientation? Or do you mean in terms of a horizontal one? Maybe, your perspective is not in terms of any spacial dimension at all?

Hopefully the activation of the Large Hadron Collider will help settle this issue. Perhaps the graviton will be found to be real and my position will be found to be incorrect. If that is the case, I will gladly change my mind in the spirit of truth finding and intellectual honesty. However, more than the graviton, the goal of this posting is to warn against the dangers of unscientific thinking disguised as rational means to obtaining knowledge. Symmetry is beautiful, and often part of our universe, but it is not a valid scientific approach.