Thursday, April 01, 2010

jQuery Plugin to Trick Bots from Stealing Email Address




Back in December, I posted a simple jQuery script to trick bots from stealing email addresses. Assuming the bots don’t understand JavaScript. Anyhow, you can read more about that post here. I wanted to convert it to a plugin back then, but didn’t really want to take the time to research how to do it since I was really just starting to play with MVC or I’m just lazy, which ever you believe :)

Anyhow, at the SHDNUG last night, Kevin Lee talked about writing a jQuery plugin and went through the steps to do so among other things. It’s crazy easy! Thanks Kevin for pointing it out!

So, I didn’t remember the exact syntax from Kevin’s presentation, so I googled and went to the first post, which turned out to be jMar’s blog. His example is really good, but I think it’s hard to read for people new to jQuery. I like the code to be a little easier to read on my posts.

Okay…let’s get to the meat!

Step 1: Create Plugin Structure

(function($) {
$.fn.decodeEmail =
function() {
return this.each(function() {
});
};
})(jQuery);

This is all you need to create a jQuery plugin. As Kevin mentioned in his presentation, keep with the standards of other jQuery plugins.

  1. Always use the $ as the alias for jQuery, which is what the first and last line allows us to do. If you have conflicts (like with scriptaculous), you could specify a different alias or just use jQuery(whatever).
  2. Use CamelCase in the plugin name, which in this case is decodeEmail.
  3. Always return your wrapped set so other people can append onto your plugin.
  4. Name the jQuery plugin file jquery.pluginname.js, jquery.pluginname.min.js, etc.

Step 2: Add Options with Defaults (if needed)

(function($) {
$.fn.nameOfPlugin =
function(options) {
var defaults = {
at:
'[[at]]',
dot:
'[[dot]]'
};
var options = $.extend(defaults, options);

return this.each(function() {
});
};
})(jQuery);

Now on line 2, you can see I’m now passing in options. Line 3 starts the definition of my defaults. I just created two options, one for the @ sign called “at” and one for the . called “dot” in an email address. The var options line uses the jQuery extend method to merge the contents of the two objects. In this case, my passed in options and my defaults objects.

Step 3: Add  your code

(function($) {
$.fn.decodeEmail =
function(options) {
var defaults = {
at:
'[[at]]',
dot:
'[[dot]]'
};
var options = $.extend(defaults, options);
return this.each(function() {
e = $(
this).text()
.replace(options.at,
'@')
.replace(options.dot,
'.');

this.href = 'mailto:' + e;
$(
this).text(e);
});
}
})(jQuery);
The only thing in this code that changed from my first blog post is that now instead of doing .replace(‘[[at]]’, ‘@’), I do .replace(options.at, ‘@’) and the same for the dot. I won’t go into anymore detail because it’s discussed in that first blog post, but that’s it for creating a jQuery plugin!

Now I can reference it in my DocumentReady.js as mentioned in this post like this:

$('a[href^=mailto:]').decodeEmail();

or if I wanted to change the default [[at]] and [[dot]], I could do this:

$('a[href^=mailto:]').decodeEmail({at: ' at ', dot: ' dot '});

As I mentioned before (here), I like my sites to still work even if JavaScript is disabled, so I would stick to something readable to your end-users.

I could also change the CSS after decoding the email address like this:

$('a[href^=mailto:]').decodeEmail().addClass("orange");

Pretty cool stuff! Download the plugin here if you want.

Thanks for reading!

kick it on DotNetKicks.com

Sunday, March 28, 2010

Different Approach to the Usual CSS Sprite to Reduce HTTP Requests




I just found this little tidbit today. If you ever have a problem with too many HTTP requests, this could be a solution for you over a CSS sprite. I’m using this approach for my CSS backgrounds that are simple small icons. I would not recommend this approach for anything much larger. FYI: IE8 limits URIs to max length of 32KB.

To help with this approach, you’ll need a couple tools. Here are the few I found:

Obviously, you can always write your own :)

So, this is what I wanted:

image

My original CSS looked like this:

a#createarticle {padding-left: 20px; background: url(/i/ico-addarticle.png) no-repeat center left}

This code will make two HTTP requests, one for the stylesheet and another for the icon. (assuming the above code is in a stylesheet, which in my case, it is)

To eliminate the additional HTTP request, I changed my CSS to look like this:

#createarticle {padding-left: 18px; background: url(data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAYEBAQFBAYFBQYJBgUGCQsIBgYICwwKCgsKCgwQDAwMDAwMEAwODxAPDgwTExQUExMcGxsbHCAgICAgICAgICD/2wBDAQcHBw0MDRgQEBgaFREVGiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICD/wAARCAAQAA8DAREAAhEBAxEB/8QAFwAAAwEAAAAAAAAAAAAAAAAAAQIHCP/EACUQAAICAQIEBwAAAAAAAAAAAAECAwQSAAUGERMhFCIjMTJSgf/EABYBAQEBAAAAAAAAAAAAAAAAAAAEBf/EABwRAQABBAMAAAAAAAAAAAAAAAARAQISIRMxQf/aAAwDAQACEQMRAD8A0nUoVpKMEhhjZ2jRmZkUkkqOZJI0DVl8NajEXlimOEkPIBQwQtknL2+HcaA0b1JKVdHsRo6xoGVnUEEL3BGgktniveJ6lafZbtmfjYSP19mJ6kYbEB/QzKqqKz4nH9+2TzXzqcprpHnXzt//2Q%3D%3D) no-repeat center left}

This might look intimidating, but it’s really pretty simple. You simply replace the “/i/ico-addarticle.png” in the first sample with the generated base64 from one of the tools mentioned above.

To get the base64, I used A Blue Star because I wanted to upload an image and get the base64, but you could also use the greywyvern.com and that’s what I’ll walk through now.

So I’ll grab an icon from famfamfam.com (which is where I get almost all my icons) and paste the URL on the greywyvern.com site.

Step 1: Grab URL
Paste it into the URI textbox on greywyvern.com like this:

image

Step 2: Generate Results
Click Submit Query & you’ll get this:

image

Step 3: Copy & Paste Results
Copy ALL the textarea and paste it into either the src of an img object or into the url of a CSS background attribute.

If you like your CSS to be readable and don’t want to deal with looking at base64, then I would stick to the CSS sprite, but I thought this method was cool. Especially for icons next to hrefs that don’t change a lot. However, I think the configuration for this is much simpler than a CSS sprite and having to deal with the different margins, widths, etc that come along with a CSS sprite :)

Thanks for reading!

kick it on DotNetKicks.com

Monday, March 15, 2010

Drag & Drop with MVC & jQuery AJAX




So my wife decided she’d like her clients to be able to order prints off her website via some type of code. Well I thought I’d start with the fun part. The selection of pictures being dragged over to a cart of some sort. I’ve never used anything like this and thought it’d be fun to learn.

So here’s where I’m at…i have a couple graphics that are draggable to a cart. Once the graphic is dropped, it does something like write to a db or something and then returns a success. Let’s look at the code because I stink at explaining stuff I think…

<style type="text/css">
.draggable { width: 100px; height: 100px; border: solid 1px #ccc; margin: .5em}
#imageboundary {width: 500px; height:500px; border: solid 1px #ccc}
#droppable {border: solid 1px #000; width: 150px; height: 150px}
</
style>
<
div class="result"></div>
<
div id="imageboundary">
<
div id="droppable">
<
ul id="cart"></ul>
</
div>
<
img class="draggable" id="1234" src="../../_a/i/bck-logo.gif" />
<
img class="draggable" id="123456789" src="../../_a/i/bck-required.gif" />
</
div>

So above is my sample HTML code, which is pretty simple I think. Here’s what I got…a few styles, a result box, a boundary for the drag, my cart, and two draggable images.

Okay, so I have a couple references to jquery & jquery.ui. Looks like this:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<
script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>

Okay, now I’m going to post the completed section as of right now, but I will be breaking it apart in sections further down.

<script type="text/javascript">
$(
function() {
$(
".draggable").draggable({ containment: '#imageboundary', revert: 'valid' });
$(
"#droppable").droppable({
drop:
function(event, ui) {
$.ajax({
type:
"POST",
url:
'/Home/AddToCart/' + $(ui.draggable).attr("id"),
success:
function(data) {
$(
'.result').html(data);
$(
"<li>" + $(ui.draggable).attr("id") + "</li>").appendTo($('ul#cart'));
}
});
}
});
});
</
script>

So…to make things draggable, we simply add this line:

$(".draggable").draggable({ containment: '#imageboundary', revert: 'valid' });

You can read more about this here.

To make a droppable box, it’s simply this:

        $("#droppable").droppable({
drop:
function(event, ui) {
$(
'.result').html($(ui.draggable).attr("id"));
}
});

Granted this is not exactly like the code above, but I wanted to simplify it so you could see what it would take to make something droppable. You can read more about this here.

Now to make the ajax call to my action on my controller  you do this:

    $("#droppable").droppable({
drop:
function(event, ui) {
$.ajax({
type:
"POST",
url:
'/Home/AddToCart/' + $(ui.draggable).attr("id"),
success:
function(data) {
$(
'.result').html(data);
$(
"<li>" + $(ui.draggable).attr("id") + "</li>").appendTo($('ul#cart'));
}
});
}
});

Okay, so on my HomeController I have an AddToCart action that looks like this right now:

        [AcceptVerbs(HttpVerbs.Post)]
public string AddToCart(string id)
{
if (string.IsNullOrEmpty(id))
return "Invalid id. Please press back or enable JavaScript.";

//Add to cart logic

return string.Format("Successfully added {0}.", id);
}

I’m just getting started with this little project, but I thought I’d share.

Thanks for reading!


Shout it

kick it on DotNetKicks.com

Friday, March 05, 2010

Contact Form with ASP.NET MVC, Castle Validation, & fluentHtml




Here’s another little tutorial for those of you new to MVC &/or fluentHtml. I figure I’ll do these little tutorials until I find a new project to work on. I do have a couple of ideas…so we’ll see how those turn out.

Let’s get started.

We’ll start with the view model class again like last week. By the way, if you’re not familiar with the way I setup my MVC projects, see this post.

public class ContactView
{
[
ValidateNonEmpty("Name")]
public string Name { get; set; }
[
ValidateNonEmpty("Email"), ValidateEmail("Valid Email")]
public string Email { get; set; }
public string Subject { get; set; }
[
ValidateNonEmpty("Message")]
public string Message { get; set; }
}

The ValidateNonEmpty and ValidateEmail are attributes from the Castle project and I’m passing in the error message I want displayed if invalid. Alrighty, let’s setup our controller action and the view (html).

Controller Action:

public class ContactController : Controller
{
public ActionResult Index()
{
return View(new ContactView());
}
}

View/HTML Markup

<%@ Page Title="Contact Us" Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="MvcContrib.FluentHtml.ModelViewPage<ContactView>" %>

<asp:Content ContentPlaceHolderID="MainContent" runat="server">
<
h2>Contact Us</h2>
<% using(Html.BeginForm("Index", "Contact", FormMethod.Post)) {%>
<%
=Html.DivSuccessMessage("Message sent successfully!")%>
<%
=Html.DivValidationSummary("Please see the items below:")%>
<fieldset>
<
legend>Proposal Form</legend>
<%=this.TextBox(f => f.Name).Label("Name:")%>
<%
=this.TextBox(f => f.Email).Label("Email:")%>
<%
=this.TextBox(f => f.Subject).Label("Subject:")%>
<%
=this.TextArea(f => f.Message).Label("Message:")%>
<%
=Html.AntiForgeryToken() %>
<%
=this.SubmitButton("Send").Attr("accesskey", "S").Class("sb") %> All fields are required.
</
fieldset>
<% } %>
</asp:Content>

This is a simple form with fluentHtml. If you need a tutorial on fluentHtml, here’s a post on it. You should notice that this page inherits from the MvcContrib ModelViewPage with our ContactView from above being passed in. I typically create my own base page that inhertis from the MvcContrib one, but to make this post easier, I just inherit straight from their’s.

Okay, let’s get to the meet where we accept the post in the controller.

[AcceptVerbs(HttpVerbs.Post), ValidateModel(typeof(ContactView)), ValidateAntiForgeryToken]
public ActionResult Index(ContactView form)
{
if (!ModelState.IsValid)
return View(form);

try
{
var notificationService = DI.EmailNotificationService(new EmailNotification(form));
notificationService.Notify();

Success();
}
catch (NotificationException)
{
ModelState.AddModelError(
"notifyerror"
, "Unfortunately, something went wrong with the message delivery. Please try again.");
}

return View(form);
}

Okay, so we’re only accepting a post, we’re validating our model with a validation filter, and validating the anti-forgery token. I’m also accepting my ContactView model. If the model state isn’t valid, I return the model back to the view. Otherwise, I try to create a new instance of EmailNotificationService (which returns an INotificationService) then I call the Notify(). If I don’t receive a NotificationException, then I call Success() on my SmartController (which is what this controller inherits from) Success(); simply does this: ViewData["success"] = ""; You can read more about it in this post. If the Notify() bombs, we add a model error and then finally we return the form to the view. If you wanted to clear out the form, you’d put return View(new ContactView()) right after the Success() call.

So what does the INotificationService look like? Well, this:

public interface INotificationService
{
void Notify();
}

The implementation looks like this:

public class EmailNotificationService : INotificationService
{
private readonly IEmailNotification _emailNotification;

public EmailNotificationService(IEmailNotification emailNotification)
{
_emailNotification = emailNotification;
}

public void Notify()
{
using (var mail = new MailMessage())
{
mail.To.Add(_emailNotification.To);
mail.From =
new MailAddress(_emailNotification.From);
mail.Subject = _emailNotification.Subject;
mail.Body = _emailNotification.Body;
mail.IsBodyHtml =
true;

try
{
mail.Send();
}
catch (SmtpException)
{
throw new NotificationException();
}
}
}
}

NOTE: You can also try using AutoMapper to map to the MailMessage, but for whatever reason, it was not working out for me. I send Jimmy and email about it, but he’s busy enough and it’s not that big a deal to do the left=right thing every once in a while :)

My IEmailNotification looks like this:

public interface IEmailNotification
{
string To { get; }
string From { get; }
string Subject { get; }
string Body { get; }
}

I’ll show the implementation in a sec. First I wanted to show what the NotificationException looks like…

public class NotificationException : Exception
{
}

That’s it…I can adjust as needed, but for this…there’s no reason really. I just want to be able to catch the type in my controller. Yes you could do catch(SmtpException) in the controller, but what if your next implementation of INotificationService doesn’t use smtp and you have catch(SmtpException) spread all through your other code? It wouldn’t be a good thing. Let’s keep truckin…

Here’s the implementation of IEmailNotification:

public class EmailNotification : IEmailNotification
{
private readonly ContactView _view;

public EmailNotification(ContactView view)
{
_view = view;
}

public string To
{
get { return "email@email.com"; }
}

public string From
{
get { return _view.Email; }
}

public string Subject
{
get { return _view.Subject; }
}

public string Body
{
get { return _view.Message; }
}
}

You should pull email@email.com from some type of config file since it could potentially change often. What’s cool about this is that now I could have different versions for nighttime daytime or certain months or whatever…I don’t know why you’d ever do that, but it’s getting late and I can’t think of better examples :)

Anyhow…you can also customize the body here and not have to worry about formatting in your controller. You could do something like this for the Body:

public string Body
{
get
{
var body = new StringBuilder();
body.AppendFormat(
"Date Message Sent: {0}", DateTime.Now);
body.AppendFormat(
"Sent from IP: {0}", HttpContext.Current.Request.UserHostAddress);
body.AppendFormat(
"Browser Used: {0} v{1}", HttpContext.Current.Request.Browser.Browser,
HttpContext.Current.Request.Browser.Version);
return _view.Message;
}
}

I hope I didn’t leave anything out…if I did, please let me know!

Thanks for reading!


Shout it

kick it on DotNetKicks.com

Sunday, February 28, 2010

Authentication with Active Directory, ASP.NET MVC, & fluentHtml




I figure since people are starting to really look into MVC and are realizing that it’s going to be around for a while, they’re going to need some decent samples when researching how to do things. I’m hoping this particular post will possibly be one of those examples. I had the same thought when I wrote the Security Questions with ASP.NET MVC & fluentHtml post.

Let’s get started with the view model class for the sign in page. By the way, if you’re not familiar with the way I setup my MVC projects, see this post.

public class SignInView
{
[
ValidateNonEmpty("Username is required.")]
public string Username { get; set; }
[
ValidateNonEmpty("Password is required.")]
public string Password { get; set; }
}

Really simple. The ValidateNonEmpty is an attribute from the Castle project and I’m passing in the error message I want displayed if invalid.

Okay, so let’s go ahead and pass in this view model to our actual view from the AuthenticationController. This will look like this:

public ActionResult Index()
{
return View(new SignInView());
}

Now we’ll create our actual view (html):

<%=Html.DivValidationSummary("All fields are required.") %>
<form action="/authentication/index" method="post">
<
fieldset>
<
legend>Sign In</legend>
<
p><%=this.TextBox(f => f.Username).Label("Username: ")%></p>
<
p><%=this.Password(f => f.Password).Label("Password: ")%></p>
<%=Html.AntiForgeryToken() %>
<%=Html.SubmitButton("Sign In", cssclass=>"sb", accesskey=>"S") %>
</
fieldset>
</
form>

This is our basic html setup with fluentHtml added to it. If you need a tutorial on fluentHtml, here’s a post on it. Basically, I’m using my htmlHelper for a DivValidationSummary, I’m calling the index action on the authentication controller, then I’m setting up my textboxes with fluentHtml, using the antiforgerytoken to prevent csrf, and I’m using my submit button that I blogged about before this post.

Now let’s look at the action that’s being called by the form above.

[AcceptVerbs(HttpVerbs.Post), ValidateModel(typeof(SignInView)), ValidateAntiForgeryToken]
public ViewResult Index(SignInView form)
{
if (!ModelState.IsValid)
return View("index", form);

IUser user = DependencyRegistrar.With<string, IUser>(form.Username);
bool passwordMatches = _authenticationService.PasswordMatches(user, form.Password);

if (passwordMatches)
{
//Sign In – Write Cookie & Redirect most likely through a UserSession
}

ModelState.AddModelError(
"SignIn", "Invalid credentials");
return View("index", form);
}

Okay, so you can see I’m accepting only post, I’m validating the model, and I’m validating the token. I’m also accepting my SignInView model. If the model state is not valid I return the model back to the view. Otherwise, I get an instance of user with my username and then I call my authenticationService. If passwordMatches, sign in and return, otherwise add an error and return.

So let’s look at my IUser real quick. It’s really simple:

public interface IUser
{
string Username { get; set; }
}

Think my AuthenticationService is much more difficult? Of course not!

public interface IAuthenticationService
{
bool PasswordMatches(IUser user, string password);
}

By the way, I’m accepting an instance of IAuthenticationService in the constructor of the controller like so:

public AuthenticationController(IAuthenticationService authenticationService)
{
_authenticationService = authenticationService;
}

I’m using StructureMap to know what to pass in to the constructor. Okay, so my AuthenticationService implementation looks like this:

public class AuthenticationService : IAuthenticationService
{
private readonly IActiveDirectorySettings _adSettings;

public AuthenticationService(IActiveDirectorySettings activeDirectorySettings)
{
_adSettings = activeDirectorySettings;
}

public bool PasswordMatches(IUser user, string password)
{
var authenticated = false;
var domainAndUsername = _adSettings.DomainName + "\\" + user.Username;
var entry = new DirectoryEntry("LDAP://" + _adSettings.LdapPath, domainAndUsername, password);

try
{
var bindToNativeObjectToForceAuthentication = entry.NativeObject;
authenticated =
true;
}
catch (COMException)
{
}

return authenticated;
}
}

Now my IActiveDirectoryCredentials looks like this:

public interface IActiveDirectorySettings
{
string DomainName { get; }
string LdapPath { get; }
}

That’s basically it. There’s not a whole lot to an authentication process, but thought I’d share anyhow.

Thanks for reading!


Shout it

kick it on DotNetKicks.com

Monday, February 22, 2010

Fun with Lambdas & HtmlHelpers




Since I started using fluentHtml, I’ve loved this syntax: this.Textbox(f=>f.Whatever).Styles(display=>”none”)

The fact that it’s SO easy to read is what I love…specifically the Styles() portion. So I downloaded the MvcContrib source to see how they were handling it and it was actually pretty simple. Basically, you setup a param like this:

params Func<string, string>[] values

So let’s do a quick sample for a…submit button. I want to be able to type this below for a basic submit button with the text “Sample Submit”:

<%=Html.SubmitButton("Sample Submit") %>

If I want to add an accesskey attribute, I want to just type this:

<%=Html.SubmitButton("Sample Submit", accesskey=>"S") %>

If I want to add an id to the button, I want to do this:

<%=Html.SubmitButton("Sample Submit", accesskey=>"S", id=>"sampleid") %>

If I want to add a css class, I want to just do this:

<%=Html.SubmitButton("Sample Submit", accesskey=>"S", id=>"sampleid", cssclass=>"sampleclass") %>

Okay, so I think you get the idea. By the way, the reason we can’t put class=>”sampleclass” is because class is a reserved word and throws an error. I’ll show you how I get around the issue.

So what does this extension method look like? Here it is:

public static string SubmitButton(this HtmlHelper htmlHelper, string textValue, params Func<string, string>[] values)
{
var attributes = new StringBuilder();
foreach (var func in values)
attributes.AppendFormat(
"{0}=\"{1}\" "
, func.Method.GetParameters()[0].Name.ToLower().Replace("cssclass", "class"), func(null));

return string.Format("<input type=\"submit\" value=\"{0}\" {1}/>", textValue, attributes);
}

So let’s break this down.


  1. Notice the params keyword in the method signature. What this allows you to do is pass zero or many Func<string,string>s into the method. Note: when using the params keyword, it should be the last argument in the signature and it should be a defined as an array.

  2. If you’re new to StringBuilder, it is generally used when concatenating string together because it performs better than plain ole string.

  3. So I’m appending the format of attributename=”value”, which is represented by the “{0}=\”{1}\” “. (Notice the AppendFormat signature contains a params object[])

  4. The first argument represented by {0} is the name of the parameter of the generic Func<>. So I’m getting the first parameter from the Func<> method and lowering the name and replacing cssclass with class.

  5. The second argument represented by {1} is the value of the lambda, which we get by calling func(null). We don’t have to pass in null, we could pass in anything we want to func because we’re not using it for anything, we’re just returning the value we set after the =>. However, null is the cleanest method :)

  6. Lastly, I return the formatted submit html code, which sets the value and attributes. If there aren’t any, then the {1} is empty and basically ignored.

Well, that’s it. I thought I’d share because I think it’s something that’s pretty useful, cool, and easy to read for the end-user of your code. Thanks for reading!


Shout it

kick it on DotNetKicks.com

Saturday, February 13, 2010

SQL Logging with log4net & ASP.NET MVC








I wanted to get some logging action on my latest project and I’ve heard a lot about log4net so I thought I’d give it a whirl. My goal was to have a simple interface that implements log4net and writes to SQL Server. With that said, my interface ended up looking like this:

public interface ILoggingService    

{
void Log(string message);
}

I told you it was simple :)

Okay, now let’s go ahead and implement the ILoggingService like this:

public class LoggingService : ILoggingService

{
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public void Log(string message)
{
log.Info(message);
}
}

This particular implementation is only going to log informational type things and not errors or warnings. Basically I want it for auditing purposes. Note: LogManager is part of log4net.

So let’s go on and configure log4net. First we’ll create an IStartUpTask, see this post for more info on the IStartUpTask.

    public class log4netConfigurator : IStartUpTask

{
public void Configure()
{
log4net.Config.XmlConfigurator.Configure();
}
}

I’m going to configure log4net in my web.config. I’ve seen a lot of people have a separate log4net.config file, but I want to just put mine in the web.config. So let’s add a log4net section to the <configSections> like this:

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>

Now we can add the section to the web.config like this:

<log4net>

<root>
<level value="ALL"/>
<appender-ref ref="ADONetAppender"/>
</root>
<appender name="ADONetAppender" type="log4net.Appender.ADONetAppender">
<bufferSize value="1"/>
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<connectionString value="server=serverNAME; uid=userNAME; pwd=passWORD; database=databaseNAME"/>
<commandText value="INSERT INTO ChangePasswordLog ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)"/>
<parameter>
<parameterName value="@log_date"/>
<dbType value="DateTime"/>
<layout type="log4net.Layout.RawTimeStampLayout"/>
</parameter>
<parameter>
<parameterName value="@thread"/>
<dbType value="String"/>
<size value="255"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread"/>
</layout>
</parameter>
<parameter>
<parameterName value="@log_level"/>
<dbType value="String"/>
<size value="50"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level"/>
</layout>
</parameter>
<parameter>
<parameterName value="@logger"/>
<dbType value="String"/>
<size value="255"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger"/>
</layout>
</parameter>
<parameter>
<parameterName value="@message"/>
<dbType value="String"/>
<size value="4000"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message"/>
</layout>
</parameter>
<parameter>
<parameterName value="@exception"/>
<dbType value="String"/>
<size value="2000"/>
<layout type="log4net.Layout.ExceptionLayout"/>
</parameter>
</appender>
</log4net>

Okay, so I have an appender setup here to write to my DB.I think it’s pretty self explanatory, if you disagree, post me a comment and I’ll go into more detail. One hiccup I ran into was the bufferSize because I kept trying to test to see if it was writing to my DB and nothing was showing up. The reason being…I didn’t have 100 log entries. I changed the bufferSize to 1 and POOF my record showed up :)

So now in my controller, I accept an ILoggingService in the constructor like this:

        private readonly ILoggingService _loggingService;

public HomeController(ILoggingService loggingService)
{
_loggingService = loggingService;
}

So now I can call my Log method from any of my actions like this:

var changePasswordService = DI.ChangePasswordService(username);

changePasswordService.ChangePassword(form.ValidationToken, form.Password);
_loggingService.Log("Password changed for user " + username);

All done! Now I have logging in my app.

Thanks for reading!


Shout it

kick it on DotNetKicks.com

Friday, February 12, 2010

SQL to XML with SSIS




Have you ever had a vendor ask for XML instead of a quick CSV file? Well, if you’re using MSSQL 2005 or 2008, I’m sure you realized just how awesome they are when this request came through. I’m going to walk through exporting an XML file from SQL Server 2005 using SSIS ans SQL.

First we’ll need to write the SQL script to generate the XML. I’m going to write an XML file that exports a list of users to a vendor so we’ll have root » customer » action » user info

Let’s start basic and just get something like this:

<root>
<
customer>demousername</customer>
</
root>

To get this with SQL, it looks like this:

select 'demousername'
for xml path('customer'), root('root')

Really simple so far right? Okay, so I need to add two attributes to my customer element called username and password, which are provided by my vendor. So I’ll want my end XML to look like this:

<root>
<
customer id="demouserid" password="demopassword" />
</
root>

To get this result, I simply write this SQL:

select 'demouserid' as '@id', 'demopassword' as '@password'
for xml path('customer'), root('root')

Okay, so now I need to add my action element like this:

<root>
<
customer id="demouserid" password="demopassword">
<
action ActionType="User_Add"/>
</
customer>
</
root>

The SQL looks like this:

select 'demouserid' as '@id', 'demopassword' as '@password',
(
select 'User_Add' as "@ActionType"
for xml path('action'), type)
for xml path('customer'), root('root')

The only weird thing about this SQL is the “@ActionType”, which represents the attribute name on the action element. The @ sign basically says hey I’m an attribute and not an element. Also, the “type” after (‘action’), says that I’m an element. Without the “type”, you’ll get this:

<root>
<
customer id="demouserid" password="demopassword">&lt;action ActionType="User_Add"/&gt;</customer>
</
root>

Okay, so now I need to add my user info and I’ll end up with this:

<root>
<
customer id="demouserid" password="demopassword">
<
action ActionType="User_Add">
<
FirstName>Deran</FirstName>
<
LastName>Schilling</LastName>
<
UserName>test@demo.com</UserName>
<
Password>demopassword</Password>
<
Email>test@demo.com</Email>
<
JobTitle>Something Awesome</JobTitle>
</
action>
</
customer>
</
root>

So to get this XML, I just add in the columns and names I want like this:

select 'demouserid' as '@id', 'demopassword' as '@password',
(
select 'User_Add' as "@ActionType"
, firstname as FirstName, lastname as LastName
, emailaddress as UserName, 'demopassword' as [Password]
, emailaddress as Email, jobtitle as JobTitle
from demousertable
for xml path('action'), type)
for xml path('customer'), root('root')

One more thing I want to show you is how to add a reference number to the action element. So I’ll end up with something like this:

<root>
<
customer id="demouserid" password="demopassword">
<
action ActionType="User_Add" ref="1">
<
FirstName>Deran</FirstName>
<
LastName>Schilling</LastName>
<
UserName>test@demo.com</UserName>
<
Password>demopassword</Password>
<
Email>test@demo.com</Email>
<
JobTitle>Something Awesome</JobTitle>
</
action>
<
action ActionType="User_Add" ref="2">
<
FirstName>John</FirstName>
<
LastName>Demoed</LastName>
<
UserName>john@demo.com</UserName>
<
Password>demopassword</Password>
<
Email>john@demo.com</Email>
<
JobTitle>Something Okay</JobTitle>
</
action>
</
customer>
</
root>

Notice the ref=”1” and ref=”2” on the action element? The way you get that result is with this SQL:

select 'demouserid' as '@id', 'demopassword' as '@password',
(
select 'User_Add' as "@ActionType", ROW_NUMBER() OVER (ORDER BY username) as '@ref'
, firstname as FirstName, lastname as LastName
, emailaddress as UserName, 'demopassword' as [Password]
, emailaddress as Email, jobtitle as JobTitle
from demousertable
for xml path('action'), type)
for xml path('customer'), root('root')

So the ROW_NUMBER() OVER (ORDER BY uniqueidentifierofsomesort) gets the row number for each returned record. I love that feature.

Alrighty! So now let’s get to the SSIS, which is much simpler!

Step 1:
Create new SSIS package in Visual Studio 2005.

Step 2:
Drag an “Execute SQL Task” over to the “Control Flow” and name it something like “Generate XML” or whatever you prefer.

Step 3:
Double-click it.

  • General Section
    • Change ResultSet to XML
    • Select/Create your Connection
    • Enter the SQL statement, like the one we created above

image

  • Result Set Section
    • Add a new string variable called something like XmlContent

imageimage

Step 4:
Drag a “Script Task” over to the “Control Flow” and name it something like “Save Generated XML” or whatever you prefer.

Step 5:
Double-click it.

  • Script Section
    • Add XmlContent (or whatever you named your variable) in the ReadOnlyVariables
    • Click “Design Script…”

image

Step 6:
Once in the ScriptMain for VB, which I’m not a fan, but appears to be the only option. So you’ll just add this snippet in the Public Sub Main():

Dim sw As New IO.StreamWriter("C:\demo\AddUsers.xml")
sw.Write(Dts.Variables("User::XmlContent").Value.ToString())
sw.Dispose()
Dts.TaskResult = Dts.Results.Success
The red text above represents what you’ll need to change to match what you desire. First item is the file path to the location of your xml file and the second item is the name of your variable with the namespace.

That’s it! Now you have a generated XML file from a SQL DB. I thought it was pretty cool and a LOT easier than I thought it would be when I first started.

Thanks for reading!


Shout it

kick it on DotNetKicks.com

Related Posts Plugin for WordPress, Blogger...