Convert FormCollection && HttpRequest to Hashtable

Viewed 791

I have two function that one receives a FormCollection and another receives a HttpRequest like this:

public void SetUrlParameters(FormCollection request, string controllerName = "")
{
    string sessionID = ConvertToString(request["sessionID"]);
    string idSession = ConvertToString(request["idSession"]);
    string sessionid = ConvertToString(request["sessionid"]);

    if (idSession.Length > 0)
        this.sessionID = idSession;
    else if (sessionid.Length > 0)
        this.sessionID = sessionid;
    else
        this.sessionID = sessionID;

}

private void SetUrlParameters(HttpRequest request, string controllerName = "")
{

    string sessionID = ConvertToString(request["sessionID"]);
    string idSession = ConvertToString(request["idSession"]);
    string sessionid = ConvertToString(request["sessionid"]);

    if (idSession.Length > 0)
        this.sessionID = idSession;
    else if (sessionid.Length > 0)
        this.sessionID = sessionid;
    else
        this.sessionID = sessionID;

}

private string ConvertToString(object obj, string defaultValue = "")
{
      if (obj == null) return defaultValue;

      return Convert.ToString(filterSameVariablesValue(obj));
}

As you can see, the both the functions do exact the same. The only difference is the type of the value that each one receives.

Both function are working. What I want is to avoid having repeated code in both function.

There is any way that I can collapse this to function into one ? Like for example convert the FormCollection and HttpRequest to a Hashtable and the use it?

2 Answers

You can simply expect a NameValueCollection parameter that is a (almost) common to both types:

private void SetUrlParameters(NameValueCollection data, string controllerName = "")
{
    string sessionID = ConvertToString(data["sessionID"]);
    string idSession = ConvertToString(data["idSession"]);
    string sessionid = ConvertToString(data["sessionid"]);

    if (idSession.Length > 0)
        this.sessionID = idSession;
    else if (sessionid.Length > 0)
        this.sessionID = sessionid;
    else
        this.sessionID = sessionID;
}

Usage for HttpRequest:

SetUrlParameters(request.Params);

Usage for FormCollection:

SetUrlParameters(formCollection);

See MSDN

FormCollection is inherits from NameValueCollection. HttpRequest has HttpRequest.Form property which is NameValueCollection too. So your can avoid duplication using convertion to NameValueCollection

public void GetParameters(FormCollection form, HttpRequest request)
{
    var parameters = Convert(form);
    parameters = Convert(request.Parameters);
}

public YourParameters Convert(NameValueCollection form)
{
    //your code here
}
Related