You are currently browsing the category archive for the ‘programming’ category.
All my main development machines are now running Visual Studio 2012. I have a few new projects in VS2012 and have begun updating my old projects to it as well. I ran into an annoying issue today that I need to post.
My Blog by Email site was built using VS2010 and ASP.NET MVC 3. My new machine, which I am working on right now, is running Windows 8 and VS2012. Recently a new user started using the site and discovered a few bugs I needed to get fixed. I cloned the repo from Bitbucket and opened the solution in VS2012.
My first tip-off that there was an issue is when the Migration Report displayed 7 errors all on the _bin_deployableAssemblies\ folder.
BlogByEmail\_bin_deployableAssemblies\Microsoft.Web.Infrastructure.dll: Failed to backup file as C:\vsp2k12\BlogByEmail\Backup\BlogByEmail\_bin_deployableAssemblies\Microsoft.Web.Infrastructure.dll BlogByEmail\_bin_deployableAssemblies\System.Web.WebPages.Razor.dll: Failed to backup file as C:\vsp2k12\BlogByEmail\Backup\BlogByEmail\_bin_deployableAssemblies\System.Web.WebPages.Razor.dll (... Plus 5 more files)
My second is when I went to run the project and the build failed for the same 7 files.
If you recall the _bin_deployeableAssemblies folder is used to aid in bin deploying MVC 3 applications to [shared] hosts which don’t have ASP.NET MVC 3 loaded. You can read more about it here [@haacked.com].
It turns out this isn’t required in VS2012 as I found here :
Starting with MVC 3 Tools Update we are now using Nuget package references, which means that your project is automatically bin-deployable. Since the tooling gesture is no longer necessary it was removed from VS 11.
The fix here is really simple. Remove the files and _bin_deployableAssemblies folder from your project. Everything should compile just fine.
Now the one part I have not figured out is where or how we get the files that used to be in _bin_deployableAssemblies. I don’t see them in the bin folder as I assumed they would be. I will need to do some test deployments at my host, Arvixe (I think they didn’t have MVC 3 loaded). Add a comment below if you h ave some knowledge around this.
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
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!
Unicode Characters converted to ASCII string
I hacking together a report today and discovered the Unicode text I received was actually in Unicode not ASCII.
Basically I have this: こんにちは
By using AscW(Char) you can convert a Unicode character into an integer value. Add some delimiters to encode the string and you have a Unicode HTML Entity Reference. It isn’t perfect, as AscW(Char) sometimes returns a negative number, which isn’t allowed, though this is an easy work around explained here. It is used below.
Public Function UnicodeToAscii(sText As String) As String
Dim x As Long, sAscii As String, ascval As Long
If Len(sText) = 0 Then
Exit Function
End If
sAscii = ""
For x = 1 To Len(sText)
ascval = AscW(Mid(sText, x, 1))
If (ascval < 0) Then
ascval = 65536 + ascval ' http://support.microsoft.com/kb/272138
End If
sAscii = sAscii & "&#" & ascval & ";"
Next
UnicodeToAscii = sAscii
End Function
Now lets go the other way: ASCII string to Unicode
And I want this: こんにちは
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 AsciiToUnicode(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
AsciiToUnicode = 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, "")
AsciiToUnicode = sFinal
Erase saText
Erase saFinal
End Function
I didn’t always understand why you wouldn’t just want to work with the Unicode characters themselves. Well is seems that not all applications treat Unicode the same way and the characters may be changed. If you are storing and passing around a text representation of the characters there is no way for them to misinterpreted.
One of the neatest things I like about this is that I can just put the text represented Unicode in a web page and the browser will automatically convert it to Unicode characters. This is the reason I needed to use an image above to show what the text represented Unicode looks like. If I just put the string there, it is converted by the browser when displayed.
If you have been to this post in the past, you have probably noticed that it has changed a bit. That is because I had it all backwards! Yeah well it happens. I said I want wanted to change Unicode characters to Ascii string, but the code actually was for the other way around. Well I finally got around to fixing this and made sure that code worked before displaying it. I hope this helps someone out there.
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.


