Skip to content

WCF: Pick your flavor (SOAP, xml, json)

Let your consumers choose how to consume your service (in my case a WCF service). Encourage integration with your service by making life easy for your partners(or at least easier). A lack of SOAP support on non-Microsoft/.NET languages can be a barrier to entry for some programs/programmers. It’s not exactly easy or convenient to build a SOAP message with headers and all. Below is an example of the absolute minimum, which is 169 characters with no header or body.

<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
  <soap:Header>
  </soap:Header>
  <soap:Body>
  </soap:Body>
</soap:Envelope>

Then I considered the possibility of using other such standards that are more terse and appeal to a wider audience (e.g. Plain Old Xml(POX) and JavaScript Object Notation(JSON)). I looked around at various projects online to find a suffix anti-pattern in service contracts. Below I have provided the example for a fictitious method called GetData, and the anti-pattern looks like this.

    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        string GetData(int value);

        [WebInvoke(Method = "GET")]
        string GetDataXml(int value);

        [WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        string GetDataJSON(int value);
    }

Following this anti-pattern, I should create three methods in my interface for a single operation, because I want to support three output formats. Fortunately, there is a much better way. However it isn’t really well documented in its entirety(at least that I could find, which is as good as it not existing).

Our trusty and yet increasingly complicated web.config file is part of the solution. There will need to be three separate endpoints each with their own endpoint behavior.

  <system.serviceModel>
    <bindings>
      <webHttpBinding>
        <binding name="jsonBinding"></binding>
        <binding name="xmlBinding"></binding>
      </webHttpBinding>
    </bindings>
    <services>
      <service name="JSONPOXSOAP.Service1">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8732/Design_Time_Addresses/JSONPOXSOAP/Service1/"/>
          </baseAddresses>
        </host>
        <endpoint address="json" bindingConfiguration="jsonBinding" binding="webHttpBinding" behaviorConfiguration="jsonBehavior" contract="JSONPOXSOAP.IService1"></endpoint>
        <endpoint address="xml" bindingConfiguration="xmlBinding" binding="webHttpBinding" behaviorConfiguration="xmlBehavior" contract="JSONPOXSOAP.IService1"></endpoint>
        <endpoint address="" binding="wsHttpBinding" contract="JSONPOXSOAP.IService1">
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="jsonBehavior">
          <webHttp defaultOutgoingResponseFormat="Json"/>
        </behavior>
        <behavior name="xmlBehavior">
          <webHttp defaultOutgoingResponseFormat="Xml"/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
  </system.serviceModel>

This allows for a much simpler and straight forward interface and service that implements it. This means one method for one operation, which is much nicer than three.

[ServiceContract]
public interface IService
{
    [OperationContract]
    [WebInvoke(Method = "GET")]
    string GetData(int value);
}

I hope this helps create cleaner interfaces and makes your services more accessible.

Async Your SMTP

While working on an ASP.NET MVC site, I had a scenario where I needed to send an e-mail using smtp. In my case, it was to confirm an e-mail address in the usual registration fashion. It was at this time that I noticed the SendAsync method of the SmtpClient, which sounded like a great fit. I added the code only to get the below nastiness for my troubles.

System.InvalidOperationException: Asynchronous operations are not allowed in this context. Page starting an asynchronous operation has to have the Async attribute set to true and an asynchronous operation can only be started on a page prior to PreRenderComplete event.

at System.Web.LegacyAspNetSynchronizationContext.OperationStarted()
at System.ComponentModel.AsyncOperation.CreateOperation(Object userSuppliedState, SynchronizationContext syncContext)
at System.Net.Mail.SmtpClient.SendAsync(MailMessage message, Object userToken)

The issue here has to do with the methodology of ASP.NET. Each request returns a response, period. To do anything asynchronously, you will need to use a different thread or process from the one currently servicing the request (or you could do it synchronously, but who wants that?). I developed the below code which draws heavily from information in this Stack Overflow question.

Note the below example uses log4net for logging.

        public static void Send(string recipients, string subject, string body)
        {
            Task.Factory.StartNew(() =>
                {
                    var from = ConfigurationManager.AppSettings["noreplyemail"].ToString();
                    Log.DebugFormat("Sending an e-mail to [{0}] from [{1}] with the subject [{2}] and body [{3}].", recipients, from, subject, body);
                    Send(new MailMessage(from, recipients, subject, body));
                });
        }

        public static void Send(MailMessage message)
        {
            var port = int.Parse(ConfigurationManager.AppSettings["SMTPPort"].ToString());
            var host = ConfigurationManager.AppSettings["SMTPserver"].ToString();
            var username = ConfigurationManager.AppSettings["SMTPusername"].ToString();
            var password = ConfigurationManager.AppSettings["SMTPpassword"].ToString();
            var smtpClient = new SmtpClient(host, port);
            smtpClient.UseDefaultCredentials = string.IsNullOrWhiteSpace(username) && string.IsNullOrWhiteSpace(password);
            smtpClient.Credentials = new NetworkCredential(username, password);

            smtpClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
            smtpClient.SendCompleted += (s, e) =>
            {
                smtpClient.Dispose();
                message.Dispose();
            };

            smtpClient.SendAsync(message, null);
        }

        private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                Log.Error(e.Error);
            }
            else
            {
                Log.InfoFormat("The email message was successfully sent.");
            }
        }

There are some gotcha’s to keep in mind with disposing. Don’t dispose too early or else your message won’t be sent. I learned this the hard way after wrapping the SmtpClient and the MailMessage in using statements which did what they were supposed to (i.e. cleaning up any resources), just before I wanted them to.

You will notice that I chose to use a Task here. I chose to do this mainly for the sake of simplicity. One option to consider is using the WebBackgrounder for these kinds of tasks. In my case, this was overkill since I was only sending e-mail and occasionally at that. In other cases, it may very well be a good fit.

I hope this provides a more complete example to this problem than I could find myself.


 

Warning: Unsolicited Advice

If you are about to embark upon sending e-mail with smtp, I highly recommend that you take the time to learn how to debug it at a low level. You should be able to telnet into your smtp server and send e-mails that way. You should be able to sniff your network traffic with Wireshark, which allows you to even filter your traffic for the smtp protocol. Without this knowledge, you are guaranteed to have a difficult time troubleshooting any issues you encounter.

South Florida Code Camp 2014

Thank you to NSU, all presenters, volunteers, participants and sponsors for making this year’s code camp a great experience. A special thank you to Dave Noderer who helped organize the event and allowed me to use the community table to speak with people about getting involved in Code for Fort Lauderdale. The speakers did a great job focusing on application rather than theory and helped me to walk away with useful information.

I had the opportunity to attend the below sessions. I have included the notes for each of them.

I hope everyone that attended enjoyed themselves, and I am looking forward to seeing everyone again next year.


Intro to SQL Server CE – Benefits & how to use

by Walter V. Williams, Jr.
CHB Consulting

msde?

Notable highlights regarding SQL Server CE 4.0

  • Small footprint, less than 2 MB
  • Easy to install(copy dll’s, no registering)
  • Database management done within program (no need to hire DBA)
  • Similar CRUD calls as in SQL Server express or full
  • Full aggregate support ( I think joins too)
  • Simple setup for development with Nuget repository

Limitations to keep in mind

  • No stored procedures or triggers
  • No role based security
  • No direct upgrade path to sql server or full (i.e. you need to recreate structure and move the data yourself)
  • Limited to 256 simultaneous connections
  • Maximum size of 4 GB
  • No support for datetime stamp(workaround using bigint to store ticks)

We don’t need roads: A developer’s look into sql server indexes

by Richie Rump
Jorriss LLC

Stack Overflow is kind enough to do a data dump. Besides being an incredibly open treasure trove of information, it is a free large database to use for testing, indexes in this case. Richie was kind enough to provide a basic overview for those of us who aren’t DBA’s, experts or just a little rusty.

Starting with the baseics, we took a look at some execution plans and turned on IO statistics. You can use the free online statistics io parser to make the output more readable. The performance implications of scans and seeks became pretty clear, but it is important to understand the difference.

  • Scans -> read the entire table
  • Seeks -> use indexes to take shortcuts

These shortcuts are similar to the way we use alphabetical ordering in a phone book rather than flipping through each page while searching for an entry.

It turns out there are many different types of indexes.

  • clustered -> tell how to physically store the data, only 1 (highlander) uniqueifier?
  • nonclustered -> do not have to unique, maximum of 999 per table
  • heaps -> stored by the order it comes in (default without clustered index)
  • column store -> sort by column value rather than row
  • xml -> make xml faster, but shouldn’t be there
  • spatial -> for mapping stuff
  • full-text -> text field, search inside of text

Tables are a metadata construct, the clustered index is the table. Included columns -> put columns into the leaf level of the index. This prevents bookmark lookups in SQL Server.

If a column is in the where clause use it in the index, if it is in the select use it in the included columns index.

The Fill Factor has a significant impact on performance. It determines how full a page in memory can be before a new one is created. It only applies to leaf pages. Each leaf page contains a reference to each of it’s entries. Pages are typically organized sequentially, which doesn’t work so hot for guids. The result is fragmentation, which creates empty space all over the place. Using sequential guids can help this issue, but it doesn’t solve the issue completely.

Indexes presents some disadvantages and limitations.

  • Creates copies of the data(storage)
  • Insert, Updates and deletes are slower
  • Additional maintenance to keep indexes fast
  • Cannot create index on nvarchar(max)

Big takeaway: Be a part of the community!


A DiBA guide to SQL Server Database Standards

by Diana Betancourt
South Florida SQL Server User Group (SFSSUG)

One of the initial questions asked was,

What are database standards?

Unfortunately the only standards that exist are for coding and not configuration. The solution is a marriage of Microsoft’s best practices and your own.

Best practice analyzers and risk assessments . Have fun with it, because it can take a lot out of you. Create a set of rules that don’t overburden development or deployment. Developers and DBA’s have to play nice. No issue should ever happen twice.

Question everything! Don’t assume that someone else’s advice will work for your situation or system. Prove that it will, and understand why. This course introduced me to The Enterprise Policy Management Framework. This seems like an invaluable tool for anyone that is trying to run a sizeable production environment, which is no small task.

The Enterprise Policy Management Framework is a reporting solution on the state of the enterprise against a desired state defined in a policy. Extend Policy-Based Management to all SQL Server instances in the enterprise. Centralize and report on the policy evaluation results.


Clean JavaScript

by Patrick Delancy

What is “clean” in this context? Clean is easier to read, maintain and test. SOLID design principles can assist in producing cleaner JavaScript.

There are some constructs of JavaScript to keep in mind.
clean = easier to read and maintain

  • ECMA says that javascript is single threaded
  • nodejs is multi-threaded
  • Each page load is an application

Some of the barriers to clean JavaScript are:

  • Not knowing JavaScript
  • Inline code
  • The DOM (Mixture of concerns and a tight coupling)

Solutions! (aside: You will notice that the last one is not at all JavaScript specific)

  • Learn Javascript
    1. Read The ECMA standards
    2. Check out JavaScript: The Good Parts by Douglas Crockford
    3. Contribute to a JavaScript project on github
  • Externalize All JavaScript (data attributes and meta tags rather than using server variables inline)
  • Separate Your Concerns

Takeaways

  1. JavaScript is a real programming language
  2. Every page load is an application
  3. Make it testable, and you will make it clean

Recommended Unit Test Frameworks

Recommended Test Runners

Salesforce SOAP API Login – Minimum Pieces of Flair

I have been working with the Salesforce API lately, and have found the learning curve to be a little bit steep. I can’t say it’s been insurmountable, but often times the first day working with any API is the most frustrating.

So without further ado, I present the Minimum Pieces of Flair required to successfully login to the SOAP API.

Steps to add a Web Reference to your project in Visual Studio.

  1. Right Click Project
  2. Add
  3. Service Reference
  4. Advanced…
  5. Add Web Reference…
  6. Open your salesforce wsdl xml file
  7. Click Add Reference

C# code

var service = new SforceService.SforceService();
var result = service.login("user", "password");
service.Url = result.serverUrl;
service.SessionHeaderValue = 
    new SforceService.SessionHeader() 
    { 
        sessionId = result.sessionId 
    };

This will get you everything that you need to login and start making calls. Salesforce’s introductory example is lengthy with all kinds of exception handling and timeout setting. In my case, this was overkill, but your mileage may vary.

NSIS Select Install Directory and Backup

After quite a few times of having to update my software manually(and really one time is too many), I decided to embark on the difficult road of creating an updater where one had not existed. I turned to my trusted NSIS, which had worked well for me in the past(your mileage may vary).

My only complaint would be that not that many people use it(I know not a lot of people make windows installers anymore, but I needed to for this project.), which leads to confusing documentation, Q&A and resources kind of scattered around online. I had some difficulty finding out elementary basic examples of how to do the following with NSIS.

  • Prompt the user to choose the installation directory
  • Backup the existing directory with a datetime stamp
  • Mark the backup as readonly

These are pretty standard, and I assume pretty common requirements for an install or update. Below is my solution which is performs these simple tasks.

!include FileFunc.nsh
!insertmacro GetTime

SetCompressor /SOLID /FINAL lzma

# name the installer
OutFile "Installer.exe"

InstallDir $%HOMEDRIVE%

Page directory
Page instfiles

Section Backup
    Var /GLOBAL backupFolder
    Var /GLOBAL command

    # define the output path for this file
    setOutPath $INSTDIR

    DetailPrint "The user has chose the directory: $INSTDIR for the install."

    ${GetTime} "" "L" $0 $1 $2 $3 $4 $5 $6

    StrCpy $backupFolder "$INSTDIR.backup.$1-$0-$2.$4_$5_$6"

    StrCpy $command 'xcopy "$INSTDIR" "$backupFolder" /S /E /V /Y /I'
    DetailPrint $command
    ExecWait $command
SectionEnd 

Update!
The following code should be used with caution. I had to remove it, due to the permission implications of setting file/folder attributes. Many configurations will not allow user’s to set these attributes, especially on network drives. So you have been warned.

    ExecWait 'attrib +r "$backupFolder\*.*" /S /D'

Resize and Upload

I recently came across an interesting set of requirements. I had a collection of images that needed to be re-sized and uploaded to an ftp site. I groaned on the inside remembering implementations featuring tedious height, width, resolution and other calculations. Fortunately, a cool head and swift fingertips for searching prevailed. I learned about a wonderful library called ImageResizer.Net. Did you know it abstracts the much of the ugliness away from the consumer?

I never wanted to know about any of that graphics jargon and lingo, and not because it’s not important. It’s not important to me for what I am doing. Below you can see how trivial the image re-sizing code becomes. FTP Upload in .NET – You ain’t need no libraries proved that I could get along without a library just using the .net framework for this task.

            var versions = new Dictionary();
            versions.Add("_small", "width=100&amp;height=100");
            versions.Add("_medium", "width=300&amp;height=300");
            versions.Add("_large", "width=700&amp;height=700");

            foreach (var version in versions)
            {
                var request = (FtpWebRequest)WebRequest.Create("ftp://{domain}/{path}/OS_" + version.Key + ".png");
                request.Credentials = new NetworkCredential(username, password);
                request.KeepAlive = false;
                request.UseBinary = true;
                request.Method = WebRequestMethods.Ftp.UploadFile;

                var memoryStream = new MemoryStream();
                ImageBuilder.Current.Build("OS.png", memoryStream, new ResizeSettings(version.Value), false, true);
                using (var writer = new BinaryWriter(request.GetRequestStream()))
                {
                    writer.Write(memoryStream.ToArray());
                }
            }

I can’t recommend simple research like this enough. It will save you time, energy, frustration and prevent resolved bugs from appearing.

Samba Printer Sharing with Windows XP Gotcha

Make sure the there is not already a local printer with the same name as the printer that you are trying to add, because apparently Windows XP cannot tell the difference. This happened to me and I was greeted with the below dialog.

windowsprinterdialog

There should be the shared printer name under the computer name. So naturally I started to check all kinds of settings on the server, printer and windows client. Luckily I escaped from the wild goose chase. Hopefully this helps someone else do the same.

I was able to set this up in under 2 hours using the Network Printing with Ubuntu and Sharing a printer to Windows XP clients with Samba and Cups guides. The Ubuntu/Linux community has created amazing software and documentation even with something as ugly as printing. If you do not have to play with Windows clients, I highly recommend the CUPS interface.

Follow

Get every new post delivered to your Inbox.

Join 33 other followers

%d bloggers like this: