DennyDotNet

Awesome ASP.NET C# and other cool coding stuff

About the author

Denny Ferrassoli
Developer at Casting Networks. MCP / .NET
E-mail me Send mail
Add to Technorati Favorites

Recent posts

Recent comments

Authors

Categories

None


Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010

NoRM MongoDB and Distinct on an array

A little gotcha for anyone using NoRM MongoDB provider and running Distinct on an array.

MongoDB versions earlier than 1.5.0 will return distinct arrays as values. Any version of MongoDB 1.5.0 and above will return distinct values of the arrays. Let me demonstrate:

 

Object Person:

1. Name: "Joe", Friends: ["Tom", "Chuck"]
2. Name: "Tom", Friends: ["Joe", "Chuck"]
3. Name: "Bill", Friends: ["Tom", "Chuck"]

Now our NoRM code:

MongoCollection<Person> _collection = ...;

// MongoDB < 1.5.0

var results = _collection.Distinct<string>("Friends");

// above code throws an exception

var results = _collection.Distinct<string[]>("Friends");

// results = [ ["Tom", "Chuck"], ["Joe", "Chuck"] ]

 

// MongoDB >= 1.5.0

var results = _collection.Distinct<string>("Friends");

// results = ["Tom", "Chuck", "Joe"]

So keep an eye out when upgrading MongoDB!

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:
Posted by Denny on Friday, May 14, 2010 11:11 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Pre Apps

A buddy of mine has made two Pre (phone) apps and I wanted to give him a shout out!

Go and check out his apps!

http://developer.palm.com/appredirect/?packageid=com.pascharllc.audioblaster

http://developer.palm.com/appredirect/?packageid=com.pascharllc.fantasychat

Thanks!

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by Denny on Friday, May 07, 2010 8:24 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Analyze Your IIS Logs

So today I peeked at my IIS log and out of luck I spotted some funny behavior. Plenty of 404 errors for pages with names like admin, login, database, mdb, etc... Clearly someone looking for admin access / free databases. I decided to further analyze my logs using the IIS Log Analyzer. Since IIS Log Analyzer is a command-line utility, which I am not to fond of, I also downloaded Log Parser Lizard (free / donate) which is a great GUI interface for not only IIS logs but plenty more, like event logs, active directory, file system, etc...

The log parser allows you to use SQL syntax to parse the log files. Anyways... I wrote a short script to list all 404 errors grouping them by Uri and IP address to see what I could find. Since I don't get a ton of traffic it was fairly easy to filter out the normal 404 requests and the bad ones. However I would suggest further filtering until you get down to a more manageable data set. Here's my initial SQL:


SELECT c-ip, cs-uri-stem, Count(*) AS Total
FROM C:\logs\u_ex*.log
WHERE sc-status = 404
GROUP BY c-ip, cs-uri-stem
ORDER BY c-ip, Total DESC

Since I had quite a bit of data I further refined my search by removing records that I knew were not an issue:


SELECT c-ip, cs-uri-stem, Count(*) AS Total
FROM C:\logs\ddn\u_ex*.log
WHERE sc-status = 404 AND NOT cs-uri-stem LIKE '%favicon%' AND NOT cs-uri-stem LIKE '%.xml%'
GROUP BY c-ip, cs-uri-stem
HAVING COUNT(c-ip) > 1
ORDER BY c-ip, Total DESC

And I ended up with enough results that it was easy to quickly scan and see that there was something funny going on with these requests... such as:

/editor/admin_login.asp
/admin/eWeb/admin_login.asp
/admin/htmledit/admin_login.asp
/admin888/ewebeditor/admin_login.asp
/database/snowboy.mdb
/KS_Data/KesionCMS4.mdb
/msmir_net.mdb
/sql.rar

etc... etc... What you do with the results is completely up to you.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by Denny on Thursday, February 04, 2010 10:54 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Continuous Integration with TeamCity

I just started looking into TeamCity from JetBrains and wow this CI stuff is pretty cool! "TeamCity is a continuous integration and build management system." I've really been meaning to do more unit testing and now that I'm running TeamCity I feel the need to write tests even more to get the full benefits. They have a lot of neat features, support various build configurations, various triggers and they have a few add-ins that make managing your project very streamlined. Having never messed with any type of CI tools it was a little difficult to understand how to integrate my project but I actually didn't end up needing to read any of the documentation and was able to get going in about an hour from install to finish.

TeamCity has a free version (limited) as well as paid versions. I'm currently using the free version since I'm working on small projects.

If you're curious about CI or want to give yourself a real reason to start up your unit test writing then check out TeamCity.

Update:

Here's some more info and a tutorial to get you started.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by Denny on Wednesday, January 13, 2010 6:38 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Attaching to W3WP.exe by Process Name and User

A lot of the "attach debugger" macros I found only show you how to attach to the W3WP.exe process for debugging. Well  I run multiple sites under different app pools so I sometimes have multiple W3WP.exe's running and need to debug a specific one. In this case I wanted to attach to a specific IIS process.

First off note that I am using Windows Server 2008 R2 / IIS 7.5 and I have separate application pools for each site with different User Names for each process:

 

So I want to target the "test.testsite.com" process... Here's the Macro code:

(Code is in VB.NET)

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics

Public Module Attach_W3WP
    Public Sub AttachToIIS()
        Try
            Dim dbg2 As EnvDTE80.Debugger2 = DTE.Debugger
            Dim trans As EnvDTE80.Transport = dbg2.Transports.Item("Default")
            Dim dbgeng(2) As EnvDTE80.Engine
            dbgeng(0) = trans.Engines.Item("Managed")
            Dim proc2 As EnvDTE.Processes = _
                dbg2.GetProcesses(trans, Environment.MachineName)

            For Each proc As EnvDTE80.Process2 In proc2
                If proc.UserName <> Nothing Then
                    Dim name As String = System.IO.Path.GetFileName(proc.Name)
                    If name = "w3wp.exe" AndAlso proc.UserName.Contains("test.testsite.com") Then
                        proc.Attach2(dbgeng)
                        Exit For
                    End If
                End If
            Next
        Catch ex As System.Exception
            MsgBox(ex.Message)
        End Try
    End Sub
End Module

The important line is:

If name = "w3wp.exe" AndAlso proc.UserName.Contains("test.testsite.com") Then

Just replace "test.testsite.com" with the user of the process you want to target.

Run the macro and it should attach to the correct W3WP.exe process.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags: , ,
Posted by Denny on Thursday, October 29, 2009 5:15 AM
Permalink | Comments (0) | Post RSSRSS comment feed

New Open Source Project: BackTypeSharp

BackTypeSharp is a C# library that allows querying of BackType's API (www.backtype.com)

It was written in a fluent manner (or attempted) so that you can easily query BackType for information.

I started BackTypeSharp for a personal project and decided it could be useful to others and so I've decided to share it on CodePlex. I first saw BackType being used on Mashable.com. If you go to any story on Mashable's website and scroll towards the bottom you'll see a section called "Reactions" with comments from people posted via "BackType." A little research on BackType and a few days later I thought the "Reactions" was a neat idea and wanted to implement it into my own project. Since there were no libraries written in .NET to support interaction with the BackType API I created one.

I've used TweetSharp quite a bit and really enjoyed the fluent manner in which you execute requests so I attempted to model BackTypeSharp in a similar manner.

BackTypeSharp is far from a complete library and I will continue to work on it over time. If you'd like to help please feel free to contact me. There are some "tests" in the solution but I have no experience writing unit tests or doing TDD so I wouldn't rely on them. I would love to have someone who is experienced with writing unit tests help. If anything the test project shows how to query and get results using the library.

For more information on BackType you can visit the developer site here: BackType API Documentation

Check out the project on CodePlex here: BackTypeSharp

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by Denny on Tuesday, September 22, 2009 6:31 AM
Permalink | Comments (1) | Post RSSRSS comment feed

Talk like a pirate day!

September 19 is talk like a pirate day and in honor I've translated the site, thanks to Yahoo, into Piratespeak! Enjoy!

More info on doing this to your blog here. And straight from Yahoo here.

 

Arrrr!!!

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by Denny on Thursday, September 17, 2009 5:23 PM
Permalink | Comments (0) | Post RSSRSS comment feed

jQuery returns only 1 element even though there are many

I was so frustrated by this issue today. I simply could not figure out why jQuery would return only 1 element for $("a") when I clearly had multiple anchor tags!

No matter what I did the length would always return 1.

I nearly missed the answer to the issue in a StackOverflow post. But it helped me find that jquery.validator was causing the issue. After going to the plug-in's website and downloading the latest version all was back to normal.

It's just unfortunate when you KNOW something is supposed to work right and you waste an hour trying to figure out why :(

Hopefully this post will help anyone with the same problem in the future and help them avoid any wasted time.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by Denny on Monday, September 07, 2009 6:25 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Windows 7 and What I'm Doing Next

Just installed Windows 7 over the weekend and so far it's been great! No issues at all running the x64 version.

I haven't had much time to blog lately because I've been busy but on my side project StickTo. The good thing is I've been doing a lot of ASP.NET MVC development and learning IoC / Dependency Injection. I'm using Ninject for DI and Moq for mocking my objects. I'm amazed at how fast I can get things done now. I don't know what it is about MVC but I can crank code out lightning fast, it seems much faster than when I write WebForms. I guess it partially comes down to a lot of the JavaScript integration I write, it's just easier to write in an MVC environment. Also using libraries like JSON.Net is extremely helpful in crossing the language boundaries. I'll be posting some technical tips as I get to them in my project.

StickTo

I've been working on some Twitter integration for my StickTo project, with the help of TweetSharp, and it's nearly complete. I've been using Twitter quite a bit lately to begin promoting my StickTo project and I've seen what a great tool Twitter can be so I'd like to take advantage of that. I'm going to be doing some podcasts about the StickTo business from the point of view of being in the startup / business / developer role and the battle of trying to kick off a hopefully profitable online website business. It should be an interesting ride and I welcome you to follow along either on Twitter or through the website www.stickto.us.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Posted by Denny on Saturday, August 08, 2009 5:50 PM
Permalink | Comments (0) | Post RSSRSS comment feed

ASP.NET MVC and SafeGet (my version of null dereferencing)

When working in ASP.NET MVC you sometimes pass a model to your view. In some cases your model is a few levels deep. For example:

Model.User.Address.ZipCode

(Yes this violates LoD but I don't like LoD anyways...)

Well I use models like this all the time and I constantly had to deal with properties being null when I was expecting a value. Since everything in a view gets rendered as string I decided to make a helper method that will allow me to pass anything in and return an empty string if the value was null (null dereferencing) instead of a NullReference Exception. Out came SafeGet. SafeGet is an extension method that applies to any object. It allows you to pass in the property, or value, you want to check as well as any constraints on the value. It's probably easier to see what I mean with code... check out the example:

 

SafeGet signature:


public static string SafeGet<T>( this T instance, Func<T, object> nonNullFunction, params Func<object>[] nullConstraint ) where T : class

 

Here is how it works:

In my view I wrap SafeGet around the properties I am not sure will have a value and include any constraints:


<%= Html.TextBox( "BirthDate", Model.User.SafeGet( o => o.BirthDate, () => DateTime.MinValue ) )%>

 

Yes, it uses Lambda expressions :)

 

The first param is "nonNullFunction" - this is where you pass in the value you want to check.

 

The second param is "nullConstraint" - Since I am working with a "DateTime" object (not "Nullable DateTime") I know DateTime must have a value but I also want it to consider the value as null IF the value of "o.DateTime" is "DateTime.MinValue" (basically saying: "if (o.DateTime == DateTime.MinValue) return null;"). You can have many nullConstraints if you need to check multiple values.

 

SafeGet then returns the value or "string.Empty" if the expression is null or it matches any constraints.

You could probably include another param as a default value to pass if it is null rather than always passing "string.Empty"

If you're using custom ViewModels you could certainly apply this at that level instead of in the view directly. I'm not sure if this breaks Seperation of Concerns by using it in a View.

 

Here's the SafeGet method:


        public static string SafeGet<T>(this T instance, Func<T, object> nonNullFunction, params Func<object>[] nullConstraint) where T : class
        {
            if(instance != null && nonNullFunction != null)
            {
                try
                {
                    var o = nonNullFunction(instance);

                    if(o == null) return string.Empty;

                    if(nullConstraint != null)
                    {
                        // Check each constraint to make sure it doesn't match
                        foreach(var constraint in nullConstraint)
                        {
                            if(constraint().Equals(o)) return string.Empty;
                        }
                    }

                    return o.ToString();
                }
                catch(NullReferenceException)
                {
                    return string.Empty;
                }
            }

            // in all other cases, return the default
            return string.Empty;
        }
    }

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:
Posted by Denny on Thursday, July 16, 2009 7:00 AM
Permalink | Comments (1) | Post RSSRSS comment feed