You are currently browsing the category archive for the ‘programming’ category.

I ran into a styling issue last night and it is driving me nuts.  I have found a work-around, but I want to see if I can figure out how to do this way.

I have a span tag which I am using for a button.  This button calls a JavaScript function to test blog posting settings.  I am using a span because it was easy enough to style.

CSS:


#VerifyBlogClick {
/*#696969*/
color:#575757;
border:1px solid gray;
background-color:#eee;
padding:2px 5px 2px 5px;
margin:0 0 0 13px;
border-radius: 2px;
}
#VerifyBlogClick:hover {
color:Black;
background-color:#bbb;
cursor:pointer;
}
.verifierRunning {
padding-right:30px;
background-image:url(ajaxloaderBlue.gif);
background-repeat:no-repeat;
background-position:right;
}

HTML:


<span id="VerifyBlogClick" onclick="javascript:verifyBlog_click()" title="Tries to send an unpublished test post to your blog">Verify Blog</span>

JavaScript:


$('#VerifyBlogClick').addClass('verifierRunning');

// ... stuff

$('#VerifyBlogClick').removeClass('verifierRunning');

Basically what I have here is a span styled like a button.  When the button is clicked I add the class .verifierRunning to the span tag using jquery. This class changes border-right to 20px and defines a background image (a loading image).

The problem that I am running into is that any properties defined in the id selector are not overridden by the class.  It seems that id’s always have a higher precedence than a class.  I can’t believe that there isn’t a way around this, though I have not been able to find anything on the web which will work.

My work-around this is to change VerifyBlogClick to a class.  I don’t mind doing this, I would just like to find out a way to do this the other way.

I just took the long silly way around to return a json result to  a page.  I kept trying to send a json string back as just that, a string and it just wouldn’t work.  Whenever JavaScript received the string it didn’t know what to do with it, except treat it as a string of course.  I banged my head against this one for too many hours.  Though my persistence payed off.

As the night got later (I think it’s 03:00 about now) I decided to figure out how others are returning json object from ASP.NET MVC.  It isn’t as simple as it should be, but not too difficult.  The biggest issue, as with much in MVC land is the huge lack of documentation.  So looking up something like JsonResult, yields a pretty useless help page.  So more time had to go into discovering on how to actually use this cool new result type.

It turns out you can set up and action with a return type of JsonResult (it’s usually ActionResult) and have that action return a json object.  I am not even going to pretend I can do this from other objects like json.net (from James Newton-King).  I am using this to return a model as json which populates my form with on-demand instructions.  This library rocks, but I digress.

The basic structure I used is a dictionary object

public JsonResult MyAction()
{
  Dictionary<string, string> dict = new Dictionary<string, string>();
  dict.Add("keya", "valuea");
  dict.Add("keyb", "valueb");
  return Json(dict);
}

That’s pretty much it in a nutshell.  Json() is a new web helper in MVC3.  You can find it at System.Web.Helpers.

I saw one example where you can build an object on the fly, but I couldn’t get it to work.  It basically looks like this:


//....
return Json(new {keya = valuea, keyb = valueb};

The dictionary generic works for now.  If you know of a better way, please let me know.

While working on Blog by Email (http://blogbyemail.com) I came across the necessity to create my own HTML helper class.  For those who don’t know helper classes “…reduce the amount of tedious typing of HTML tags that you must perform to create a standard HTML page.”

The registration request form on the site was getting hit pretty hard by spam bots and I was getting tired of cleaning up the mess, so I decided to add a captcha.

ReCaptcha is what I decided on and started down the rabbit hole.  First of all there was only ASP.NET examples.  Since I was writing this in ASP.NET MVC, I wanted to use a more, “MVC” approach to it.  I came across an post on Devlicio.us named Using ReCaptcha with Asp.Net MVC.  The post covered exactly everything I need, what it was missing is details around its steps, specifically Step 5 – Create a Html Helper to build and render the Captcha control. It shows the current code and nothing else:

public static string GenerateCaptcha( this HtmlHelper helper )
{
  var captchaControl = new Recaptcha.RecaptchaControl
    {
      ID = "recaptcha",
      Theme = "blackglass",
      PublicKey = -- Put Public Key Here --,
      PrivateKey = -- Put Private Key Here --
    };
  var htmlWriter = new HtmlTextWriter( new StringWriter() );
  captchaControl.RenderControl(htmlWriter);
  return htmlWriter.InnerWriter.ToString();
}

My first thought, is cool, I can just add an HTML helper to the view to generate the captcha, this is a good approach.

First stumble, that is a method, that needs to go into a class–what class should it go in to?

No problem, I’ll just look up creating helper methods.  That was an easy search which rendered an ASP.Net site page, Creating Custom HTML Helpers.  Great, now I have my examples.  I matched it to an extension method; okay, I get that, I have used those before.  I learned the syntax and added it to my site.

It doesn’t come up in Inteli-sense.  What can it be.  I changed all kinds of things around, from renaming the class, to changing the method name.  I was wondering if it followed some naming scheme like controllers and models do.  I don’t recall it needing to.

I decided to browse though the comments, see if anyone else ran into this.  And there is was, someone named, ianchadwick mentioned a way to make the namespace global in the web.config.  Well, damn, that is it, the view doesn’t know about my namespace BlogByEmail.Helpers.  I added @using BlogByEmail.Helpers; to the top of the page, and everything fell into place.

To use the helper in the view simply use @Html.Raw(Html.GenerateCaptcha())

Html.Raw is needed to keep MVC from HTML Encoding the output.

Damn I feel dumb sometimes.  …back to my code!

For some time now I have wanted to post to a blog from an email account.  Some blog engines these days have this functionality, like WordPress and TypePad.  Some through plug-ins and some built in.  I have used the WordPress plug-in on a test installation, and it works pretty well.  Though WordPress is probably my most preferred blogging engine, most of the time when I am installing blogs, it’s on a Microsoft stack and I am not big on running PHP on Windows.  On the Windows stack I really like using Blogengine.NET.  I find it to be a very capable blogging engine.  The only problem is, at least to date, I have not found a plug-in for it to post by email.  What it does support though is XML-RPC.

With the Help of the XML-RPC.NET library and a few hours away from the family, I through together a rough blog posting application.

I added in OpenPop.NET, a popmail client library I have used in the past, and now have a way to collect emails.  Now all I needed to do is tie them all together.

The outcome is Blog by Email (http://blogbyemail.com).  An online service for setting up email accounts to post to blogging engines.  Besides looking like crap (I am using the generic MVC layout), it is functioning well. I am hoping my buddy will give me a hand coming up with a real design for the site.

The biggest challenge to setup posting to a blog is finguring out what XML-RPC entry point is, and what the blogging engine uses for the Blog Id.  The blog id is often the name of the blog, but I found in MovableType it uses the actual integer value assigned to that blog.  Bit of a pain to get that value.  A cool aspect of MovableType is that it generates a password to use for posting via XML-RPC.  A nice security feature.

Speaking of security, to protect the users entered credentials I am encrypting both usernames and passwords in the database.  Also, each user is given a unique key pair when the sign up with the service.  Little steps to make it harder to get this information in case someone does hack the application.

 

If you need to post to your blog from a POPMAIL email address, give Blog by Email a try.  The service is free (at least until it grows to the point where it needs a bigger web server).

While the site is getting off the ground and I get the code stable, registration is closed.  There is a form request an account.  I am looking for people to help test the system, so if you are interested please let me know.

Brett

http://blogbyemail.com

It has been /interesting/ working with Entity Framework (EF).  With my first couple of sites I used Linq to SQL, and I really liked it.  It’s pretty simple once you get the gist of it.  Though now Microsoft recommends the use of Entity Framework (EF) and Linq to Entities.  Well using Linq against EF is really no different then Linq to SQL so the transition was pretty simple.  Here is a good beginner walk-through I ran into.

The part I like most about EF is Code First.  I can define my classes, relationships and inheritance and EF creates the database for me.  Need to add some properties, no problem, add them and remap (or recreate) the database.

Sure there are a few short comings like no foreign key constraints on none primary keys.  This is a pretty big deal, but nothing that can’t be handled in code (at least for my small sites).  I wonder how it’s handled with database first models, I’ll have to experiment with that some day.

The other shortcoming I found is with date fields.  It seems EF automatically works with database datetime2 field types but only creates datetime field types in its database create scrips.  This perplexed me for some time until I discovered what was really going on, and the temporary fix is pretty darn simple.

Each time you create a new script by running “Generate database from model…”–the script which is created is opened in Visual Studio (eg. myModel.edmx.sql).  Before you run it or close it, do a find and replace on the file.  Yes you guessed it, find datatime and replace it with datetime2.  Simple straight forward and works like a charm, as long as you remember to do it.

Happy coding!

I just finished a new file hashing tool, BD File Hash, which is hosted on CodePlex under the Microsoft Public License (Ms-PL).

The goal behind this Windows tool is an easier way to verify files you download from the internet.  Many applications, ISO’s, and other files usually list a hash with them.  This hash is used to verify the file you downloaded is the same file the author meant you to download.  It prevents you from using corrupt or exploited downloads by allowing you to verify the file before you use it.

The problem I had with most file hashing tools, is that they needed to be run from a command line, or you had to open the hash value into a text editor and copy/paste it into the hashing application to be compared. So I wanted BD File Hash to be a convenient way to verify files using hashes.

BD File Hash has the following capabilities:

  • Right click any file and select BD File Hash from your Send To menu
  • Use a file picker to select the file with the authors hash value, it will automatically be parsed from the file and entered into the BD File has application
  • Easily hash to files to see if they are the same
  • Supports MD5, SHA-1, and SHA-256
    • Please recommend any other hashing algorithms you may need.
  • Save your default hash type to the one you use most often

BD File Hash requirements:

  • .NET 3.5 SP1
  • Windows Installer 3.1

Give BD File Hash a try today!

I hacking together a report today and discovered the Unicode text I received was actually in Unicode not ASCII.  I remembered that ChrW(int) will convert character codes to their associated character.  I really wasn’t in the mood to write parsing logic and test it, but luckily I came across a class which does this.  I ripped out the method I needed and it worked great in all it’s simplicity.  I have included this function below:

Public Function UnicodeToASCII(sText As String) As String
  Dim saText() As String, sChar As String
  Dim sFinal As String, saFinal() As String
  Dim x As Long, lPos As Long

  If Len(sText) = 0 Then
    Exit Function
  End If

  saText = Split(sText, ";") 'Unicode Chars are semicolon separated

  If UBound(saText) = 0 And InStr(1, sText, "&#") = 0 Then
    UnicodeToASCII = sText
    Exit Function
  End If

  ReDim saFinal(UBound(saText))

  For x = 0 To UBound(saText)
    lPos = InStr(1, saText(x), "&#", vbTextCompare)

    If lPos > 0 Then
      sChar = Mid$(saText(x), lPos + 2, Len(saText(x)) - (lPos + 1))

      If IsNumeric(sChar) Then
        If CLng(sChar) > 255 Then
          sChar = ChrW$(sChar)
        Else
          sChar = Chr$(sChar)
        End If
      End If

      saFinal(x) = Left$(saText(x), lPos - 1) & sChar
    ElseIf x < UBound(saText) Then
      saFinal(x) = saText(x) & ";" 'This Semicolon wasn't a Unicode Character
    Else
      saFinal(x) = saText(x)
    End If
  Next

  sFinal = Join(saFinal, "")
  UnicodeToASCII = sFinal

  Erase saText
  Erase saFinal
End Function

For months and months now I have asked myself, “Self, what language next, Ruby, Python, something else?” and has driven me crazy.  Someday I will ask myself why I spent so much time thinking about it instead of just digging in to something.  Well the real truth to that is time.  Sure I have spent time on the Ruby site going through browser-enabled 15 minute intro and some general reading.  It never really sticks until you throw together a couple of apps.

Over the last eight months I have been on a big web front end kick, getting myself up to speed on web display stuff like CSS, JavaScript, and jquery.  It’s been a lot of fun, but I really am not a good page designer, so besides reproducting current layouts there wasn’t a real lot for me to do.  

And there is always ASP.NET MVC which I have been following and learning off and on since August of 2008.  Having the web skills when putting together some learning MVC sites was really useful.  Don’t worry, I wont go on another, “I love MVC…”, rant.

Saturday morning I was in our local library with my two sons picking out movies reading some books, messing around and found myself at the card catalog computer screen.  Hey do you remember actual card catalogs, the rows and rows of drawers which contained cards of all the books in the library.  Here is one area computers help one-billion percent.  Anyway, I did my usual search for ASP.NET, came up with the same books as usual.  A 2008 book I had already checked out (and didn’t like too much) during my web learning, and some older stuff.  Oh hum I thought….

Than I had an idea and started typing

ruby programming

A match, wow a match and a recent book too.  I was was feeling a bit excited.  Okay, let’s try another

python programming

Ah, nothing on that one.  Well that settles it—right, wrong or indifferent, I will start with Ruby.  Well, I have always been leaning this way anyhow.  The exposure I have had, I have liked, now to come up with an app to put together.  Then of course if I get my arms around the language I will have to move on to Rails, and Iron Ruby (Uses .NET’s DLR).

Hey look, ASP.NET has made it’s first live-supported release!  This is great!

I have been using the MVC pattern for a good 8 months now and I just love it.  It just makes so much sence to the way I think. Sure there is a learning curve to get started with ASP.NET MVC, whatever, it’s worth the trip.

I read about it here first.  Phil Haack wrote about the release.
You can get the release from here.

Remember if you have a previous version of ASP.NET MVC loaded, you will have to unistall it first.  A short time ago, Phil Haack, Scott Hanselman, Rob Conery, and ScottGu release a FREE tutorial to MVC, as a fist “Chapter” to their upcomming book, ASP.NET MVC 1.0.

ASP.NET MVC 1.0

ASP.NET MVC 1.0

Just the other day I decided to sign up with dreamhost for SVN and web hosting.  This hosting service is setup really well.  They have one very reasonably priced plan, and charge for extras from there.  Not that I need any.  They are running an unlimmited storage and bandwidth special right now.  Normally 50G (not sure on bw);  5 MySql databases, unlimited email and shell/ftp users,unlimited mail, imap access, webmail client, etc., etc.  Truly full service hosting. You can setup a virtual private server for on $15 per month extra!

Programming support for PHP5, Perl, Python, Full Unix Shell (one of my favorite parts), Crontab access, Full CGI access, Ruby On Rails, SSI, CVS and SVN reopos, and they have mod_dav_svn installed!

Running on Debian Linux, friends have told me that they have had very little down time with the service.

You cannot go wrong with all they provide for the price they charge ($9/month?), easily the best Linux based hosting I have come across.  Only time will truly tell me how reliable the service is.  The word on the street is good!

http://dreamhost.com

Oh yeah, and they are a green hosting center :)

Twitter Updates

Follow

Get every new post delivered to your Inbox.

Join 74 other followers