Things I see in student code | FOB

My CS300 professor at Portland State University just wrote a fantastic blog post about things he commonly sees in student source code – it’s a great read and helpful for reflecting on your own code and best practices:

I’ve read quite a lot of student code over the years. Some of it is quite good. A lot of it is full of predictable badnesses. These notes attempt to enumerate some of this badness, so that you may avoid it.

This is pretty C-centric in its current form. However, many of its lessons are multilingual. This is a living document, so don’t expect it to be the same next time you look at it. In particular, the numbering may change if something gets inserted in the middle. It is revisioned automatically by Drupal, so feel free to point at a particular revision if you care.

 

via Things I see in student code | FOB.

Quick Update: CSS/JS Auto-Minification in ASP.NET

I’ve been trying for weeks to write up a good technical article about a recent CSS/JavaScript minification handler for ASP.NET (ASHX/HttpHandler) that I whipped up, but our current release has been so busy, I haven’t had enough time to really put it all together.

Just wanted to post a quick update for everyone who mentioned they’d like to hear about it that I’ll be posting more info as soon as I can. =)

In the meantime, here are links to some of the articles that helped me construct the custom handler in the first place:

And, my own pride and joy (this damn code took me forever, only because I had to do all sorts of research and testing with Regex in C#), the function that will fix relative paths in the combined CSS files by replacing them with absolute paths based on your application root:

/// <summary>
/// CSS Only: Replaces relative paths in url(...) properties within the specified script.
/// </summary>
/// <param name="scriptBody">The pre-combined script, passed from CombineScripts().</param>
/// <param name="scriptPath">The relative path where scripts are located (ex: ~/CSS/).</param>
/// <param name="applicationPath">The absolute application path. (ex: /ApplicationRoot).</param>
/// <returns></returns>
private static String FixRelativePaths(String scriptBody, String scriptPath, String applicationPath)
{
 scriptPath = VirtualPathUtility.AppendTrailingSlash(scriptPath);
 String relativeRoot = VirtualPathUtility.Combine(applicationPath, scriptPath);

 Regex cssUrlReference = new Regex("(?<=url\\()(.+?)(?=\\))", RegexOptions.Singleline);
 Regex invalidPathChars = new Regex("[ '\"]+", RegexOptions.Singleline);

 MatchCollection urlMatches = cssUrlReference.Matches(scriptBody);
 foreach (Match m in urlMatches)
 {
 String oldPath = Regex.Replace(m.Value, "[ '\"]+", "");
 String newPath = VirtualPathUtility.Combine(relativeRoot, oldPath);
 newPath = VirtualPathUtility.ToAbsolute(newPath);
 scriptBody = scriptBody.Replace(m.Value, newPath);
 }

 return scriptBody;
}

I’d love to read your comments and/or questions about this code, so please feel free to post your thoughts in the comments on this post.

I’ll try to get you the full meal deal on this code as soon as I can. =)

C# Corner: How to get distinct rows from a DataSet or DataTable

Not without its typos, but quite a helpful article nonetheless… 😉

One of the common issues in data layer is avoiding duplicate rows from dataset or datatable. I saw many people are writing separate function and looping through the datatable to avoid the duplicates. There is more simple ways available in .Net but people are unaware about this. I thought of writing a blog about this because I saw many blogs which mislead the people from right path. Thers is no need of looping or no need of logic are required to avoid the duplicates.

Following single line of code will avoid the duplicate rows.

ds.Tables[“Employee”].DefaultView.ToTable(true,”employeeid”);

ds – Dataset object

dt.DefaultView.ToTable( true, “employeeid”);

dt – DataTable object

First option in ToTable is a boolean which indicates, you want distinct rows or not?

Second option in the ToTable is the column name based on which we have to select distinct rows.

Simple right, this option is the last one so most of the people didn’t got the time to find it. Now your code will look much cleaner without those junk codes.

via How to get [distinct] rows from a DataSet or Datatable? by shyju.

#region: Awesome or Horrible?

While coding in Java recently, I decided to do a little research to see if Java supported the #region directive (or something similar) and found a ton of articles knocking its usage as poor programming style.

Personally, I love the #region directive in C#, as it allows me to keep my code more organized (and yes, I am aware of the exisiting code-folding functionality in Visual Studio). In the files I work with, I’ve become pretty meticulous about organizing the code blocks into regions, partially because I like the organization, and partly because I was previously under the impression that it was good form to keep source files organized in this way. I use the following regions myself, generally:

  • Private/Protected Members
  • Public Accessors
  • Constructors
  • Public Methods
  • Protected Methods
  • Private Methods
  • (Anything class specific)

I agree with the sentiment in the articles I’ve read that it is *not* good practice to sweep bad code under the rug by hiding it from the developer in a folded #region, but I think that organizing relatively good code into regions like the ones I’ve mentioned above makes it a lot easier to get directly to the code I want to work on.

What do you think? I’m curious to see justifications for/against this directive, and as always, thanks for reading!

Additional links:

LoseThos: Programming As Entertainment

Pretty cool stuff:

LoseThos is for programming as entertainment.  It empowers programmers with kernel privilege because it’s fun.  It allows full access to everything because it’s fun.  It has no bureaucracy because it’s fun.  It’s the way it is by choice because it’s fun. LoseThos is in no way a Windows or Linux wannabe — that would be pointless. LoseThos is not trying to win a prize for low resource usage or run on pathetic hardware.  Low line count is a goal, though.  It’s 100,000 lines of code including a 64-bit compiler, tools and a graphics library.  It’s strictly 64-bit and could be configured to function with 32 Meg or less RAM, but who cares!   Where do you get a x86_64 machine with less than 32 Meg RAM?  With no multimedia, it’s hard to run out of memory on a modern home computer.

LoseThos was designed from scratch with a clean slate and has no compatibility with anything else. Source code is ASCII plus binary graphics data.  It has a new language roughly based C/C++.  It’s more than C and less than C++ so, maybe, it’s C+. I took every opportunity to improve things once I made a clean break with the past.  That’s another reason LoseThos has value — it is innovative.

I started with a command line like this:
Dir(“*.*”);

I added default parameters from C++:
Dir();

I said, “parentheses are stupid.”
Dir;

Now, I have a language which looks a little like pascal.  It also doesn’t have a main() routine — any statement outside a function executes immediately, in order. The command line feeds straight into the compiler (not an interpreter) and it doesn’t have that bullshit errno crap for return values — command line commands are regular C+ functions.

(via http://www.losethos.com/)


Wired: Bell Labs Kills Fundamental Physics Research

Another shitty move by (Alcatel-)Lucent, who wrecked Bell Labs and blew all of my stock money…

facepalm

Bell Labs Kills Fundamental Physics Research

By Priya Ganapati

After six Nobel Prizes, the invention of the transistor, laser and countless contributions to computer science and technology, it is the end of the road for Bell Labs’ fundamental physics research lab.

Alcatel-Lucent, the parent company of Bell Labs, is pulling out of basic science, material physics and semiconductor research and will instead be focusing on more immediately marketable areas such as networking, high-speed electronics, wireless, nanotechnology and software.

The idea is to align the research work in the Lab closer to areas that the parent company is focusing on, says Peter Benedict, spokesperson for Bell Labs and Alcatel-Lucent Ventures.

“In the new innovation model, research needs to keep addressing the need of the mother company,” he says.

That view is shortsighted and may drastically curtail the Labs’ ability to come up with truly innovative discoveries, respond critics.

“Fundamental physics is absolutely crucial to computing,” says Mike Lubell, director of public affairs for the American Physical Society. “Say in the case of integrated circuits, there were many, many small steps that occurred along the way resulting from decades worth of work in matters of physics.”

(continued at http://blog.wired.com/gadgets/2008/08/bell-labs-kills.html)

In case you weren’t previously aware, here’s a list of some of the great inventions to come out of Bell Labs in the past:

At its peak, Bell Laboratories was the premier facility of its type, developing a wide range of revolutionary technologies, including radio astronomy, the transistor, the laser, information theory, the UNIX operating system, and the C programming language. There have been six Nobel Prizes awarded for work completed at Bell Laboratories. [1]

(http://en.wikipedia.org/wiki/Bell_Labs)

Yes, that’s the transistor, the laser, UNIX, and the C programming language, let alone everything else they invented.

Thanks again, (Alcatel-)Lucent. Great job. 😦

ASP.NET: Starter Kits and Community Projects

In relation to the last post, here are some starter kits and projects officially listed at Microsoft’s own ASP.NET site (http://www.asp.net/community/projects/)

Starter Kits

 

DotNetNuke® Web Application Starter Kit

DotNetNuke is an open source web application framework ideal for creating, deploying and managing interactive web, intranet and extranet sites. The combination of an enterprise portal, built-in content management system, elegant skinning engine, and the ability to display static and dynamic content makes DotNetNuke an essential tool for ASP.NET developers.

TheBeerHouse: CMS and E-commerce Starter Kit

TheBeerHouse starter kit enables you to implement a website with functionality typically associated with a CMS/e-commerce site. This website demonstrates key features of ASP.NET 2.0 and is the sample used in the book, “ASP.NET 2.0 Website Programming / Problem – Design – Solution.”

Small Business Starter Kit

The Small Business Starter Kit provides a sample of a business promotion website suitable for small and medium-sized businesses. It provides a template for customizing and creating a site for your own business out-of-the-box, with advanced features including integration with SQL and XML data sources for content and data management.

Open Source

dasBlog

dasBlog is a blogging engine that offers elegant visual aesthetics, powerful easy to use features, and a unique application architecture. dasBlog requires no database engine, using file-based content management with an architecture that ensures excellent performance.

Visit the dasBlog Web Site

ScrewTurn Wiki

ScrewTurn Wiki is a fast, powerful and simple ASP.NET wiki engine, installs in a matter of minutes and it’s available in different packages, fitting every need. It’s even free and open source.

Visit the ScrewTurn Wiki Web Site

BlogFodder: List Of Free / Open Source ASP.NET Web Applications

I started looking for free/open-source ASP.NET applications to run on my development instance of IIS (since IIS is already running on my machine), and stumbled upon this list today:

As a big ASP.NET advocate, I’m loving the recent surge in open source / free ASP.NET applications that are hitting the web – And what’s more because Microsoft have given us some great building foundations with the frameworks like the ASP.NET Membership Provider, a lot of these open source programs are very high quality!  More so than some of the paid applications.

I thought it would be a good idea to create an ever growing list of all the open source ASP.NET applications I could find – Obviously I haven’t had chance to download or install every application so I can’t vouch for them

Notable applications:

Full list available at:
http://www.blogfodder.co.uk/post/2008/07/List-Of-Free–Open-Source-ASPNET-Web-Applications.aspx)

[C#] Open webform in new browser window from C# codebehind page

Found a great little snip of code online today from csharphelp.com about how to open a new browser window from a C# codebehind:

Response.Write("<SCRIPT language=javascript>var w=window.open('Rpt_OrderStatus_Form.aspx','OrderStatus','height=800,width=800');</SCRIPT>");

…but, one of the comments on that thread is that the Response.Write disrupts the page appearance. Any thoughts/suggestions on a better way to open a new browser window from a C# codebehind?

[g++] warning: deprecated conversion from string constant to ‘char*’

Just stumbled on to this problem/fix while writing some C++ code for my CS courses…

warning: deprecated conversion from string constant to ‘char*’

I hadn’t really thought about this much, as previous versions of g++ (such as the 3.4.3 version we’re using on our university systems) never complained about this issue, but g++ 4.2.3 does. The fix, as I found from multiple posts around the web, is to change all function arguments that will be expected to take a string constant from “char *” to “const char *”. For example:

Function Call:

class.someFunction("");

Original Function Prototype:

void class::someFunction(char *);

Updated Function Prototype:

void class::someFunction(const char *);

I’m somewhat new to C++ (OSU taught Java and I code in C# for the day job), so please give me a bit of slack on this one if you’re a seasoned pro. 😉

As always, comments and questions are welcome via my comment box. Thanks for reading!

Regarding Base-64: Trying to solve an ASP.NET issue…

Update: Thanks to WordPress.com automagically linking related posts to each other, I think I may have found a potential solution to this issue here: Invalid character in a Base-64 string (ASP.NET)

The problem seems to be with the ViewState. The ViewState is encrypted, and when an attempt is made to decrypt it on postback, the error is triggered.  The solution is actually quite simple: in the web.config file, set the ViewState not to be encrypted, like this:

<system.web>
<pages viewStateEncryptionMode=”Never”>
</pages>
</system.web>

You should really check out the rest of that article; it looks like it’s got a great explanation for what is actually occurring.

Also, this seems to be related to another message, “Invalid Viewstate.”

My original article is below the fold…

Continue reading “Regarding Base-64: Trying to solve an ASP.NET issue…”

Null-Coalescing Operator

While at a rather disappointing MSDN event yesterday, I came across one gem of C# 3.0 candy in the form of a null-coalescing operator. This is basically a short-cut for the oft seen:

string emailAddress = parsedValue != null ? parsedValue : “(Not provided)”;

OR

string emailAddress = String.Empty;
if (parsedValue != null) {
emailAddress = parsedValue;
}
else {
emailAddress = “(Not provided)”;
}

Using the Null-Coalescing Operator
These can now instead be re-written using the new null-coalescing operator as:

string emailAddress = parsedValue ?? “(Not provided)”;

This can roughly be read as “Set emailAddress equal to parsedValue unless it is null, in which case set it to the literal (Not Provided)”.

(via Null-Coalescing Operator)

Stroustrup and Sutter: C++ to run and run | Reg Developer

This is the conference (and super session) I attended last week. It was really cool. =)

Stroustrup and Sutter: C++ to run and run | Reg Developer

SD West 2008 For the second year in a row organizers at the Software Development Conference & Expo West felt the super sessions hosted by C++ legends Bjarne Stroustrup and Herb Sutter were worth some ink on the event agenda.

“There was a time in the late 1990s and early 2000s when they simply stopped advertising C++ sessions at this conference,” Sutter told attendees. “And yet they found a curious thing: every year for four years, C++ was the strongest track at the show. With zero advertising! That says something about the market. That says that there are problems that C++ is solving.”

The duo offered the C++ crowd day-long sessions at SD West. In fact, a session presented last year (Concepts and generic programming in C++0x”) was back by popular demand, alongside an additional day of new material covering the design and evolution of the grandpappy of object-oriented programming languages.

Sutter is the author of several books on software development, a lead architect at Microsoft, chair of the ISO C++ standards committee, and coiner of the phrase “concurrency revolution.” Stroustrup is also an author, a professor of computer science at the Texas A&M University’s college of engineering, and a research fellow at AT&T Labs.

Of course, the Danish computer scientist is best known as the creator and original implementer of C++.

Stroustrup doesn’t like to hear his brainchild referred to as an object-oriented programming (OOP) language, though he allowed that its main contribution was to make OOP mainstream. “Before C++, 99.9 per cent of programmers never even heard of it OOP,” he said during a post-session Q&A. “Those who’d heard of it believed that it was only for slow graphics written by geniuses.”