Tag Archives: code

An IoC Conundrum: Looking for feedback

Today at work, my boss and I were brainstorming on the best way to use IoC across all our code. During this, he proposed an idea for using IoC that at first made me feel uneasy with the way it was being used. But the more I think about it, the more I am amazed by its design. Let me set this up for you and the best way is with pictures.

Note: The code examples given here are not functional and just provided to give a rough idea of what is intended.

Explanation: 

  • The BaseLib is a library that contains all the interfaces we define. It also contains the CDepInjection class.
  • The CDepInjection class contains a static Register method that will find an assembly that corresponds to an interface and using Reflection, load it.
  • The Database library contains a CDatabase class with a static constructor that will be called from the previous step when the Database library is reflected and loaded. See image below.

Benefits:

  • By having all the interfaced in BaseLib, we are programming against an interface.
  • By having the CDepInjection class in BaseLib, there is only 1 place we need to update code and only 1 dll that we will need to deploy in production should changes be needed. (Note: We could have 100 servers running 100 application each and they may be windows services, web services, asp.net mvc apps, windows forms apps, console apps etc.).
  • By making a change in CDepInjection and telling it to map an interface name to the appropriate assembly and class and having the RegisterType be in the CDatabase class, we can create a new database class, CNoSqlDatabase in another assembly, deploy it, make a change to BaseLib by telling it to now map IDatabase to the CNoSqlDatabase and then deploy that to all our servers GAC. Now, everything will use the new CNoSQLDatabase.

Concerns I have:

  • Using a static constructor in CDatabase means that it will be called one per process and only when the assembly is loaded in the Register(..) method of CDepInjection. I’m not convinced that a static constructor would be the best thing to do. In essence, aren’t we just abstracting the mappings that would go in a config file and putting them into BaseLib instead of an app.config of BaseLib?
  • Resolving parent-child would necessitate having to call register in the ‘main’ method of all our applications. For instance, if CDatabase was going to need logging, it would have to call Register(“ILogging”) in the static constructor above the Container.RegisterType<IDatabase, CDatabase>() call.

I would very much appreciate a critique of this design. Thank you.

Advertisement
Tagged , , , , , , , ,

Developer Professionalism

There are numerous articles on the net about “developer professionalism” but I keep coming back to “Software Engineering Code of Ethics and Professional Practice“. You see, just about anyone can call themselves a developer, read a few books, accrue work experience at sub-par companies (those that do not demand professionalism) and end up as part of your organization.

As a professional in charge of hiring, it is your responsibility, to find developers who meet a certain level of professionalism. Junior developers are rarely held up to the same standards and I feel this does them a disservice. There are some things the junior dev will not be able to talk about but asking them questions like, “Give me an example of how you took responsibility for your code/work?” is a good way to get them talking about ethics and to find out just how professional they are. I have rarely come across any question that tried to ascertain your professionalism in interviews and that is both sad and scary.

If I find a problem with your code that would take you 10 min to fix and take me 30, don’t ever pass your faulty code to me to fix because you’re busy. Take responsibility [1.01, 6.08]. Fix it yourself.  And on the other side of the coin, if you find fault with my code, bring it to me to fix. Give me the chance to learn what I did wrong so that I don’t make the same mistake again.

So the next time you run into a problem, be it hiring a new dev, or an issue in code, ask yourself, “What would a professional dev do?”

Tagged , , ,

Excelcification: Brain Teaser Code

Problem: Someone at work recently asked me how you would go about converting excel header rows into integers. In the image below, you see each column and its corresponding integer value.

 image

Thus, A = 0, B = 1, C = 2 and so on. Since I have no better word to describe this process, I’m going to call it Excelcification.

Def: Excelcification. The act of converting a alpha column into its numeric representation.

However, Excel cells go from A to Z and then become AA, AB, AC etc. So if Z = 25, AA = 26, AB = 27 and so on.

Your mission is to create a method that takes a string that corresponds to the excel column (don’t have to worry about spaces etc for now) and change that to its integer value.

 

In case you didn’t know, the largest column in Excel 2010 that I could see was XFD.

image

So what is the Excelcification of “XFD”?

 

[Jeopardy theme music plays…]

 

[Some time later…]

 

[Some more time later…]

 

Are you done? How did you do it?

 

My process was to recognize that this is going to be Base 26 arithmetic, also know as Hexavigesimal. But you didn’t need to know that. If you know how base 2 (binary) works, you can extrapolate it to work for base 26.  So how does base 2 work. If you remember your truth tables from high school/college, you would know that in binary:

01 = 2^0

10 = 2^1

11 = 2^1 + 2^0

 

Now extrapolate this for base 26 and realize that in binary, your digits are only 0 and 1 whereas in hexavigesimal, your digits are 0 through 25. (See the link there to A through Z).

Thus,

A = (26^0) * Numeric_Value(A)

B = (26^0) * Numeric_Value(B)

etc.

 

So if you create a method for this your code should be:

         public static class ExtensionMethods
    {
        /// <summary>
        /// Converts a string into its hexavigesical (base 26) representation.
        /// </summary>
        /// <param name="sxCol">Input string of letters.</param>
        /// <returns>-1 if input is null or empty, base 26 integer representation of input otherwise.</returns>
        public static int Excelcify(this string sxCol)
        {
            int result = -1;
            sxCol = sxCol.ToUpper();

            if (string.IsNullOrEmpty(sxCol))
                return result;


            for (int i = sxCol.Length; i > 0; i--)
            {
                char _c = sxCol[i-1];
                //
                // Function =>  (26 ^ reversed_char_index) * char_value
                //          A = 1 ------ Z = 26 ------ AA = 27 ------ AZ = 54
                // 64 because there 'A' starts at index 65 and we want to give 'A' the value 1.
                result += Math.Pow(26, sxCol.Length - i).ToSafeInt() *  (_c.ToSafeInt() - 64);
            }

            return result;
        }
    } 

And you would call your code as such:

 int iResult = “A”.Excelcify();
Debug.Assert(res == 0);
iResult = "Z".Excelcify();
Debug.Assert(res == 25);
iResult = "AA".Excelcify();
Debug.Assert(res == 26);

 

Thus “AAA” = 702, and “XFD” = 16383.

That is exactly 2^14 cells for those binary folk!

Tagged , , , , ,

Zeep Mobile: SMS with Ads

I recently started working on integrating Zeep Mobile into an app. The documentation provided by Zeep is not the best or accurate but they do provide source code examples in…python, pearl, java. I asked about c# and the response was “i’m sure someone has posted something, search the group”. Well, no-one posted a solution so I went about coding and iteratively developing the code to send an SMS. Running into an issue, I even tried StackOverflow but that wasn’t too helpful either.

Well I finally managed to get my code working. Here is some sample c# code to send messages using the zeep framework.

I hope you all looking for c# code find this helpful.

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Web;
using System.Web.Handlers;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

namespace ConsoleApplication1
{
class Program
{
public static string API_KEY = “YOUR_API_KEY_GOES_HERE! INCLUDE DASHES!”;
public static string SECRET_ACCESS_KEY = “YOUR_SECRET_KEY_GOES_HERE!”;

static void Main(string[] args)
{
Console.WriteLine(“BLAST – \r\n\r\n”);
BlastTcpPost();

Console.WriteLine(“SEND – \r\n\r\n”);
SendTcpPost();
}

///

/// Send a BLAST to all users in your ZEEP account.
///

public static void BlastTcpPost()
{
SendSMS(
https://api.zeepmobile.com/messaging/2008-07-14/blast_message&#8221;, // URL for Send_Message
“You are on blast”, // Message to send
string.Empty // No UserId to send.
);
}

///

/// Send a single message to a user in your ZEEP account.
///

public static void SendTcpPost()
{
// Note:- 22 I use for the UserId is just a user I have signed up. Yours may be different and you
// might want to pass that in as a parameter.

SendSMS(
https://api.zeepmobile.com/messaging/2008-07-14/send_message&#8221;, // URL for Send_Message
“You are a user…good job!”, // Message to send
“22” // User Id in your system.
);

}

///

/// Uses a TCPClient and SSLStream to perform a POST.
///

/// URL that the POST must be directed to. /// Message that is to be sent. /// UserId in your Zeep System. Only required if your sending a Single Message to a User.
/// Otherwise, just send a string.Empty. /// Response from the server. (although it will write the response to console)
public static string SendSMS(string requestUrl, string body, string user)
{
string parameters = “”;
string requestHeaders = “”;
string responseData = “”;

// FORMAT must be Sun, 06 Nov 1994 08:49:37 GMT
string http_date = DateTime.UtcNow.ToString(“r”);

// Clean the text to send
body = HttpUtility.UrlEncode(body, System.Text.Encoding.UTF8);

if (user.Length > 0) parameters += “user_id=” + user + “&”;
if (body.Length > 0) parameters += “body=” + body;

// String that will be converted into a signature.
string canonicalString = API_KEY + http_date + parameters;

//————START HASH COMPUTATION———————
// Compute the Base64 HMACSHA1 value
HMACSHA1 hmacsha1 = new HMACSHA1(SECRET_ACCESS_KEY.ToByteArray());

// Compute the hash of the input file.
byte[] hashValue = hmacsha1.ComputeHash(canonicalString.ToByteArray());

String b64Mac = hashValue.ToBase64String();
String authentication = String.Format(“Zeep {0}:{1}”, API_KEY, b64Mac);
//———–END HASH COMPUTATION————————

string auth = String.Format(“Zeep {0}:{1}”, API_KEY, b64Mac);

System.Uri uri = new Uri(requestUrl);
System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(uri.Host, uri.Port);
string requestMethod = “POST ” + uri.LocalPath + ” HTTP/1.1\r\n”;

// Set Headers for the POST message
requestHeaders += “Host: api.zeepmobile.com\r\n”;
requestHeaders += “Authorization: ” + auth + “\r\n”;
requestHeaders += “Date: ” + http_date + “\r\n”;
requestHeaders += “Content-Type: application/x-www-form-urlencoded\r\n”;
requestHeaders += “Content-Length: ” + parameters.ToByteArray().Length + “\r\n”;
requestHeaders += “\r\n”;

// Get the data to be sent as a byte array.
Byte[] data = System.Text.Encoding.UTF8.GetBytes(requestMethod + requestHeaders + parameters + “\r\n”);
// Send the message to the connected TcpServer.
NetworkStream stream = client.GetStream();

// SSL Authentication is used because the Server requires https.
System.Net.Security.SslStream sslStream = new System.Net.Security.SslStream(
stream,
false,
new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate));
sslStream.AuthenticateAsClient(uri.Host);

// Send the data over the SSL stream.
sslStream.Write(data, 0, data.Length);
sslStream.Flush();

// Receive the TcpServer.response.
for (int i = 0; i < 100; i++) { if (stream.DataAvailable) { break; } System.Threading.Thread.Sleep(100); } Byte[] bytes = new byte[1024]; System.Text.StringBuilder sb = new System.Text.StringBuilder(); while (stream.DataAvailable) { int count = sslStream.Read(bytes, 0, 1024); if (count == 0) { break; } sb.Append(System.Text.Encoding.UTF8.GetString(bytes, 0, count)); } responseData = sb.ToString(); Console.WriteLine(responseData); // Close everything. client.Close(); return responseData; } // The following method is invoked by the RemoteCertificateValidationDelegate. // We want to make sure the SSL has no Policy errors and is safe. public static bool ValidateServerCertificate( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { // Somehow the cert always has PolicyErrors so I am returning true regardless. return true; //if (sslPolicyErrors == SslPolicyErrors.None) // return true; //Console.WriteLine("Certificate error: {0}", sslPolicyErrors); //// Do not allow this client to communicate with unauthenticated servers. //return false; } } public static class Extensions { public static byte[] ToByteArray(this string input) { UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(input); } public static string ToBase64String(this byte[] input) { return Convert.ToBase64String(input); } } } [/sourcecode]

Tagged , , , , , , , , , , , ,