ASP.Net Mapping Values Lookup - asp.net

Currently in my ASP.Net applications web.config I have an application setting that stores a comma delimited list of mapping values, like the one below. In the code behind I need to perform a lookup on this data based on input values 1, 2, 3 etc. I can either string split it and loop until I find a match, or use Regex to pull the value from the config string.
Currently i'm using Regex to get the mapping value. I'm not opposed to changing how the data is stored in the web.config. Is there a more simple and elegant way of handling this?
<add key="Mappings" value="1|APP,2|TRG,3|KPK,4|KWT,5|CUT" />

If you need to use this lookup frequently and the string in web.config doesn't change very often, then it makes sense to parse the string once into a Dictionary object and store that in the Application or Cache.
Lookups from the Dictionary will be lightning fast, especially compared to parsing the string each time.
private static readonly object _MappingsLock = new object();
public static string GetMapping(int id)
{
// lock to avoid race conditions
lock (_MappingsLock)
{
// try to get the dictionary from the application object
Dictionary<int, string> mappingsDictionary =
(Dictionary<int, string>)Application["MappingsDictionary"];
if (mappingsDictionary == null)
{
// the dictionary wasn't found in the application object
// so we'll create it from the string in web.config
mappingsDictionary = new Dictionary<int, string>();
foreach (string s in mappingsStringFromWebConfig.Split(','))
{
string[] a = s.Split('|');
mappingsDictionary.Add(int.Parse(a[0]), a[1]);
}
// store the dictionary in the application object
// next time around we won't need to recreate it
Application["MappingsDictionary"] = mappingsDictionary;
}
// now do the lookup in the dictionary
return mappingsDictionary[id];
}
}
// eg, get the mapping for id 4
string mapping = GetMapping(4); // returns "KWT"

Just curious :) What about LINQ
string inputValue = "2";
string fromConfig = "1|APP,2|TRG,3|KPK,4|KWT,5|CUT";
string result = fromConfig
.Split(',')
.Where(s => s.StartsWith(inputValue))
.Select(s => s.Split('|')[1])
.FirstOrDefault();
Or
Regex parseRegex = new Regex(#"((?<Key>\d)\|(?<Value>\S{3}),?)");
parseRegex.Matches(fromConfig)
.Cast<Match>()
.Where(m => m.Groups["Key"].Value == inputValue)
.Select(m => m.Groups["Value"].Value)
.FirstOrDefault();

Split the string on commas, then each substring on |, store these in a Dictionary and find it by key.
That's just as an alternative to Regex. You know what they say about Regex.

Related

Selecting only one column linq lambda query asp.net

I am quite new to entity framework and linq but basically I am using data first and my database has a table called tblNumbers and it has 2 columns, an id column and a numbers column which is populated with int values, I want to populate only the number values into my list but when I try do this I get an error saying that I cannot implicitly convert system.collections.generic.list< int> to system.collections.generic.list<projectname.Models.tblNumber>. I am not sure where to go from this, any help would be much appreciated.
Here is my code:
private DatabaseEntities db = new DatabaseEntities();
public ActionResult MyAction()
{
db.Configuration.ProxyCreationEnabled = false;
List<tblNumber> numbers = db.tblNumbers.Select(column => column.numbers).ToList();
return View();
}
Your List<tblNumber> numbers is expecting a list of tblNumber type and you are selecting column.numbers only
var numbers = db.tblNumbers.Select(column => column.numbers).ToList();

Comparing Integer Array in Linq Query

One of the requirements of a module I am currently building requires me to select data using Linq but the ids are being passed to me thru an integer array
var CheckedArray = Request["doc_download"];
string[] detailIds = CheckedArray.Split(',');
List<int> dtIds = new List<int>();
foreach (string words in detailIds)
{
dtIds.Add(Int32.Parse(words));
}
using (var ctx = new Connect2020Entities())
{
DetailList = (from userDetail in ctx.DocumentDetail
where userDetail.ID == <!-- items in dtIds --> //<<I do not know what could be used to compare all of the data from the array in a single query>>
select new DetailList()
{
FilePath = userDetail.FilePath
}).ToList<UserDocument>();
}
What could be done so that all of the ids inside the integer array can be compared inside the query in one go. I currently could not think of a viable logic that will allow the values in the array to be used as parameters in the query I am using.
*The DocumentDetail field ID is an integer.
you can try is use Contains()
ctx.DocumentDetail.Where(ele => dtIds.Contains(ele.ID)).ToList();
or in your current syntax
where dtIds.Contains(userDetail.ID)

change query string values without redirect in c#

I have a query string that looks something like this:
"somename1=123&QueryString=PlaceHolder%3dNothing%26anotherid%3dsomevalue&somename=somevalue"
but I want the query string to be something like the query string below and replace the whole query string with the updated one is there any way to do that without redirection?
"somename1=somevalue1&PlaceHolder=Nothing&somename2=somevalue2&somename3=somevalue3"
basically need to remove:
"QueryString=" with empty string
"%3d" with "&"
"%26" with "="
So far I've done is:
string strQueryString = Request.QueryString.ToString();
if (strQueryString.Contains("QueryString="))
{
strQueryString = strQueryString.Replace("QueryString=", "");
if (strQueryString.Contains("%26")) strQueryString = strQueryString.Replace("%26", "&");
if (strQueryString.Contains("%3d")) strQueryString = strQueryString.Replace("%3d", "=");
string x = strQueryString;
}
and:
// reflect to readonly property
PropertyInfo isreadonly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
// make collection editable
isreadonly.SetValue(this.Request.QueryString, false, null);
if (this.Request.QueryString.ToString().Contains("QueryString="))
{
this.Request.QueryString.ToString().Replace("QueryString=", "");
if (this.Request.QueryString.ToString().Contains("%26")) this.Request.QueryString.ToString().Replace("%26", "&");
if (this.Request.QueryString.ToString().Contains("%3d")) this.Request.QueryString.ToString().Replace("%3d", "=");
string x = this.Request.QueryString.ToString();
}
// make collection readonly again
isreadonly.SetValue(this.Request.QueryString, true, null);
The second part of the code is not replacing the characters and I don't know how after removing all character or replacing them change the query string to new query string.
Any help is greatly appreciated.
Changing the query string of the current request is not supported. Using private Reflection to edit some in-memory state will most likely break ASP.NET because it assumes that the query string is immutable. The only way to change the query string is to issue a new request, either by doing a redirect, or by doing a sort of sub-request, such as by making a new HTTP request to the same page but with a different query string.
May I suggest a not very well known built in key/value dictionary, Context.Items.
With this you very like get a better performance than toggle the readonly QueryString object, and it also last throughout a request so you can share it between module, handlers, etc.
Create
string strQueryString = Request.QueryString.ToString();
if (strQueryString.Contains("QueryString="))
{
HttpContext.Current.Items("qs") = strQueryString.Replace("QueryString=", "").Replace("%26", "&").Replace("%3d", "=");
}
Use
string x = HttpContext.Current.Items("qs_d").ToString();
Side note: I shortened you code some, as there is no need to first check if anything contains and if so, replace, just run replace, it will be faster

NameValueCollection for editing query strings

If I call
var nvc = HttpUtility.ParseQueryString("?foo=bar&baz=robots")
I get back a NameValueCollection where if I call ToString on it, I get back a query string.
var str = nvc.ToString(); //foo=bar&baz=robots....
If I create a new NameValueCollection, add stuff to it, and call ToString() on it, I don't get back a query string.
var nvc= new NameValueCollection();
nvc["foo"] = "bar";
var str = nvc.ToString(); //default for Object.ToString()
Also there doesn't seem to be a way to construct a NameValueCollection that acts as a query string editor. Is there one? If not, why? Being able to edit query strings is a pretty useful thing, but this functionality is totally hidden away in an obscure mode of some object most people don't even know exists.
This is done by the internal HttpValueCollection class, which inherits NameValueCollection and overrides ToString().
ParseQueryString() is the only public way to construct this class.
In the end, query strings are meant to be very simple. So, you can just do something like this:
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("somekey", "someval");
var querystring = string.Join("&", dict.Select(kv => HttpUtility.UrlEncode(kv.Key) + "=" + HttpUtility.UrlEncode(kv.Value)));
Completely untested of course. But yeah, a query string is name=value separated by ampersands. Is there something else you need to do?

Change Single URL query string value

I have an ASP.NET page which takes a number of parameters in the query string:
search.aspx?q=123&source=WebSearch
This would display the first page of search results. Now within the rendering of that page, I want to display a set of links that allow the user to jump to different pages within the search results. I can do this simply by append &page=1 or &page=2 etc.
Where it gets complicated is that I want to preserve the input query string from the original page for every parameter except the one that I'm trying to change. There may be other parameters in the url used by other components and the value I'm trying to replace may or may not already be defined:
search.aspx?q=123&source=WebSearch&page=1&Theme=Blue
In this case to generate a link to the next page of results, I want to change page=1 to page=2 while leaving the rest of the query string unchanged.
Is there a builtin way to do this, or do I need to do all of the string parsing/recombining manually?
You can't modify the QueryString directly as it is readonly. You will need to get the values, modify them, then put them back together. Try this:
var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
nameValues.Set("page", "2");
string url = Request.Url.AbsolutePath;
string updatedQueryString = "?" + nameValues.ToString();
Response.Redirect(url + updatedQueryString);
The ParseQueryString method returns a NameValueCollection (actually it really returns a HttpValueCollection which encodes the results, as I mention in an answer to another question). You can then use the Set method to update a value. You can also use the Add method to add a new one, or Remove to remove a value. Finally, calling ToString() on the name NameValueCollection returns the name value pairs in a name1=value1&name2=value2 querystring ready format. Once you have that append it to the URL and redirect.
Alternately, you can add a new key, or modify an existing one, using the indexer:
nameValues["temp"] = "hello!"; // add "temp" if it didn't exist
nameValues["temp"] = "hello, world!"; // overwrite "temp"
nameValues.Remove("temp"); // can't remove via indexer
You may need to add a using System.Collections.Specialized; to make use of the NameValueCollection class.
You can do this without all the overhead of redirection (which is not inconsiderable). My personal preference is to work with a NameValueCollection which a querystring really is, but using reflection:
// reflect to readonly property
PropertyInfo isReadOnly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
// make collection editable
isReadOnly.SetValue(this.Request.QueryString, false, null);
// remove
this.Request.QueryString.Remove("foo");
// modify
this.Request.QueryString.Set("bar", "123");
// make collection readonly again
isReadOnly.SetValue(this.Request.QueryString, true, null);
Using this QueryStringBuilder helper class, you can grab the current QueryString and call the Add method to change an existing key/value pair...
//before: "?id=123&page=1&sessionId=ABC"
string newQueryString = QueryString.Current.Add("page", "2");
//after: "?id=123&page=2&sessionId=ABC"
Use the URIBuilder Specifically the link textQuery property
I believe that does what you need.
This is pretty arbitrary, in .NET Core at least. And it all boils down to asp-all-route-data
Consider the following trivial example (taken from the "paginator" view model I use in virtually every project):
public class SomeViewModel
{
public Dictionary<string, string> NextPageLink(IQueryCollection query)
{
/*
* NOTE: how you derive the "2" is fully up to you
*/
return ParseQueryCollection(query, "page", "2");
}
Dictionary<string, string> ParseQueryCollection(IQueryCollection query, string replacementKey, string replacementValue)
{
var dict = new Dictionary<string, string>()
{
{ replacementKey, replacementValue }
};
foreach (var q in query)
{
if (!string.Equals(q.Key, replacementKey, StringComparison.OrdinalIgnoreCase))
{
dict.Add(q.Key, q.Value);
}
}
return dict;
}
}
Then to use in your view, simply pass the method the current request query collection from Context.Request:
<a asp-all-route-data="#Model.NextPageLink(Context.Request.Query)">Next</a>

Resources