Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace {x} tokens in strings

Tags:

c#

asp.net

token

We have a template URL like:

http://api.example.com/sale?auth_user=xxxxx&auth_pass=xxxxx&networkid={networkid}&category=b2c&country=IT&pageid={pageid}&programid=133&saleid=1&m={master}&optinfo={optinfo}&publisher={publisher}&msisdn={userId}

and I have values for these constant tokens. How can replace all these tokens in C#?

like image 828
eLs Avatar asked Nov 29 '13 04:11

eLs


4 Answers

There is no standard way to "replace with dictionary values" in .NET. While there are a number of template engines, it's not very hard to write a small solution for such an operation. Here is an example which runs in LINQPad and utilizes a Regular Expression with a Match Evaluator.

As the result is a URL, it is the callers responsibility to make sure all the supplied values are correctly encoded. I recommend using Uri.EscapeDataString as appropriate .. but make sure to not double-encode, if it is processed elsewhere.

Additionally, the rules of what to do when no replacement is found should be tailored to need. If not-found replacements should be eliminated entirely along with the query string key, the following can expand the regular expression to @"\w+=({\w+})" to also capture the parameter key in this specific template situation.

string ReplaceUsingDictionary (string src, IDictionary<string, object> replacements) {
    return Regex.Replace(src, @"{(\w+)}", (m) => {
        object replacement;
        var key = m.Groups[1].Value;
        if (replacements.TryGetValue(key, out replacement)) {
            return Convert.ToString(replacement);
        } else {
            return m.Groups[0].Value;
        }
    });
}

void Main()
{
    var replacements = new Dictionary<string, object> {
        { "networkid", "WHEEE!!" }
        // etc.
    };
    var src = "http://api.example.com/sale?auth_user=xxxxx&auth_pass=xxxxx&networkid={networkid}&category=b2c&country=IT&pageid={pageid}&programid=133&saleid=1&m={master}&optinfo={optinfo}&publisher={publisher}&msisdn={userId}";
    var res = ReplaceUsingDictionary(src, replacements);

    // -> "http://api.example.com/sale?..&networkid=WHEEE!!&..&pageid={pageid}&..
    res.Dump();
}

More advanced techniques, like reflection and transforms, are possible - but those should be left for the real template engines.

like image 181
user2864740 Avatar answered Oct 18 '22 19:10

user2864740


A simple approach is to use a foreach and a Dictionary with a String.Replace:

var values = new Dictionary<string, string> {
    { "{networkid}", "WHEEE!!" }
    // etc.
};
var url = "http://api.example.com/sale?auth_user=xxxxx&auth_pass=xxxxx&networkid={networkid}&category=b2c&country=IT&pageid={pageid}&programid=133&saleid=1&m={master}&optinfo={optinfo}&publisher={publisher}&msisdn={userId}";

foreach(var key in values.Keys){
    url = url.Replace(key,values[key]);
}
like image 34
Grundy Avatar answered Oct 18 '22 20:10

Grundy


I am guessing you are trying to replace parameters in url with your values. This can be done using C# HttpUtility.ParseQueryString

Get the CurrentURL from

   var _myUrl = System.Web.HttpUtility.ParseQueryString(Request.RawUrl);

Read Parameter from your Query string

   string value1 = _myUrl ["networkid"];

Write a value into the QueryString object.

  _myUrl ["networkid"] = "Your Value";

and then finally turn it back into URL

  var _yourURIBuilder= new UriBuilder(_myUrl );
 _myUrl = _yourURIBuilder.ToString();
like image 5
Rohit Avatar answered Oct 18 '22 20:10

Rohit


You can use this alos using LinQ

Dictionary<string, string> myVal = new Dictionary<string, string>();

myVal.Add("networkid", "1");
myVal.Add("pageid", "2");
myVal.Add("master", "3");
myVal.Add("optinfo", "4");
myVal.Add("publisher", "5");
myVal.Add("userId", "6");

string url = @"http://api.example.com/sale?auth_user=xxxxx&auth_pass=xxxxx&networkid={networkid}&category=b2c&country=IT&pageid={pageid}&programid=133&saleid=1&m={master}&optinfo={optinfo}&publisher={publisher}&msisdn={userId}";
myVal.Select(a => url = url.Replace(string.Concat("{", a.Key, "}"), a.Value)).ToList();

this line can do your required functionlity

myVal.Select(a => url = url.Replace(string.Concat("{", a.Key, "}"), a.Value)).ToList();

like image 3
Neeraj Kumar Gupta Avatar answered Oct 18 '22 19:10

Neeraj Kumar Gupta