I am getting response like this from the Client :
http://192.168.25.241/CPMO.asmx?wsdl|context=
{transaction_id=9610842, ref_id=14943018526993,
service_id=CPA_MCOM_999, error_list=n/a, sub_eff_date=201705121715460,
notification_ind=2, error_code=1, destination_mobtel=0105660125,
keyword=dummy, CURRENT_STEP=0, sub_exp_date=201705131200000}
Note :
?wsdl|context=
{transaction_id=9610842, ref_id=14943018526993, service_id=CPA_MCOM_999, error_list=n/a, sub_eff_date=201705121715460, notification_ind=2, error_code=1, destination_mobtel=0105660125, keyword=dummy, CURRENT_STEP=0, sub_exp_date=201705131200000}
So How can I read this string within the {}, after reading the parameters, redirect to the particular URL (I mean above URL), Can anyone help me in C#?
You can read the string as explained below.
var text = "{transaction_id=9610842, ref_id=14943018526993, service_id=CPA_MCOM_999, error_list=n/a, sub_eff_date=201705121715460, notification_ind=2, error_code=1, destination_mobtel=0105660125, keyword=dummy, CURRENT_STEP=0, sub_exp_date=201705131200000}";
//replace {} from your string.
var dict = text.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
.Select(part => part.Split('='))
.ToDictionary(split => split[0], split => split[1]);
Related
I am converting a single string into a string[] but I can getting the {"Non-static method requires a target."} error message. I did a search on the web and there is many cases that people have received that error but non seem to be in line with the situation I have.
Here is the code that I receive the error at:
string[] techEmail = { db.Users.Single(u => u.NTUserName.Equals(ticket.Technician.NTUserName)).EmailAddress.ToString() };
I even tried without the .ToString() and also tried to use this method:
string[] result = " [null,null,'3',null,null,null]".Replace("[","").Replace("]","").Split(',');
Here is the second attempt using the code above:
string[] techEmail = " [" + db.Users.Single(u => u.NTUserName.Equals(ticket.Technician.NTUserName)).EmailAddress.ToString() + "]".Replace("[", "").Replace("]", "").Split(',');
but nothing worked. This seems like something that should be so simple.
You can use List and add your string to it later.
Something like that:
string email = db.Users.Single(u => u.NTUserName.Equals(ticket.Technician.NTUserName)).EmailAddress.ToString();
List<string> techEmail = new List<string>();
techEmail.Add(email);
here is a program i made to display all the possible strings containing "who" & "your" within an xml file. The xml file contains few sentences like:
how are you,what is your name,what is your school name. The program which i code is displaying the sentences if both "who" and "you" comes one after one. How can i break a string into chunks and then pass them to check through xml.
The code whice i tried is :
var doc = XDocument.Load("dic.xml");
string findString = "what your";
var results = doc.Descendants("s")
.Where(d => d.Value.Contains(findString.ToLower()))
.Select(d => d.Value);
foreach (string result in results)
{
Console.WriteLine(result);
}
Thanks in advance.
You would need to check if each result contains "who" and "your". Your original code was looking for the string "who your" not the two strings "who" and "your". See this link for information on string.Contains(string)
Code
var doc = XDocument.Load("dic.xml");
var results = doc.Descendants("s").Where(d => d.Value.Contains("your") || d.Value.Contains("who")).Select(d => d.Value);
foreach (string result in results)
{
Console.WriteLine(result);
}
Edit: Misread your original code and put the filtering in the wrong spot
I have a list of strings in a List container class that look like the following:
MainMenuItem|MenuItem|subItemX
..
..
..
..
MainMenuItem|MenuItem|subItem99
What I am trying to do is transform the string, using LINQ, so that the first item for each of the tokenised string is removed.
This is the code I already have:
protected static List<string> _menuItems = GetMenuItemsFromXMLFile();
_menuItems.Where(x => x.Contains(menuItemToSearch)).ToList();
First line of code is returning an entire XML file with all the menu items that exist within an application in a tokenised form;
The second line is saying 'get me all menu items that belong to menuItemToSearch'.
menuItemToSearch is contained in the delimited string that is returned. How do I remove it using linq?
EXAMPLE
Before transform: MainMenuItem|MenuItem|subItem99
After transform : MenuItem|subItem99
Hope the example illustrates my intentions
Thanks
You can take a substring from the first position of the pipe symbol '|' to remove the first item from a string, like this:
var str = "MainMenuItem|MenuItem|subItemX";
var dropFirst = str.Substring(str.IndexOf('|')+1);
Demo.
Apply this to all strings from the list in a LINQ Select to produce the desired result:
var res = _menuItems
.Where(x => x.Contains(menuItemToSearch))
.Select(str => str.Substring(str.IndexOf('|')+1))
.ToList();
Maybe sth like this can help you.
var regex = new Regex("[^\\|]+\\|(.+)");
var list = new List<string>(new string[] { "MainMenuItem|MenuItem|subItem99", "MainMenuItem|MenuItem|subItem99" });
var result = list.Where(p => regex.IsMatch(p)).Select(p => regex.Match(p).Groups[1]).ToList();
This should work correctly.
I am trying to read json into my C# application from a url. When I run the application I keep getting a error:
"Additional Text encountered after finished reading JSON content: {. Path ",line 2, position 667".
This is from this URL
I checked the page and the view source and can't seem to find the problem. How do I fix this?
The JSON is derived from a php array that is json encoded and echoed:
$args = array( 'post_type' => 'product', 'posts_per_page' => 200, 'product_cat' => 'Alcopops' );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
echo json_encode($product);
endwhile;
wp_reset_query();
That page doesn't contain valid json. Take a look at this:
"product_type":"simple"}{"id":246,"post":
there's no comma between } and {
Edit:
The problem is with your php, rather than the c#.
Try this:
$args = array( 'post_type' => 'product', 'posts_per_page' => 200, 'product_cat' => 'Alcopops' );
$loop = new WP_Query( $args );
echo json_encode($loop->get_posts());
wp_reset_query();
use WebClient :
var json = new WebClient().DownloadString("http://cbbnideas.com/brydens-website/products/?category=Alcopops");
With the following code:
string q = "userID=16555&gameID=60&score=4542.122&time=343114";
What would be the easiest way to parse the values, preferably without writing my own parser? I'm looking for something with the same functionality as Request.querystring["gameID"].
Pretty easy... Use the HttpUtility.ParseQueryString method.
Untested, but this should work:
var qs = "userID=16555&gameID=60&score=4542.122&time=343114";
var parsed = HttpUtility.ParseQueryString(qs);
var userId = parsed["userID"];
// ^^^^^^ Should be "16555". Note this will be a string of course.
You can do it with linq like this.
string query = "id=3123123&userId=44423&format=json";
Dictionary<string,string> dicQueryString =
query.Split('&')
.ToDictionary(c => c.Split('=')[0],
c => Uri.UnescapeDataString(c.Split('=')[1]));
string userId = dicQueryString["userID"];
Edit
If you can use HttpUtility.ParseQueryString then it will be a lot more straight forward and it wont be case-sensitive as in case of LinQ.
As has been mentioned in each of the previous answers, if you are in a context where you can add a dependency to the System.Web library, using HttpUtility.ParseQueryString makes sense. (For reference, the relevant source can be found in the Microsoft Reference Source). However, if this is not possible, I would like to propose the following modification to Adil's answer which accounts for many of the concerns addressed in the comments (such as case sensitivity and duplicate keys):
var q = "userID=16555&gameID=60&score=4542.122&time=343114";
var parsed = q.TrimStart('?')
.Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries)
.Select(k => k.Split('='))
.Where(k => k.Length == 2)
.ToLookup(a => a[0], a => Uri.UnescapeDataString(a[1])
, StringComparer.OrdinalIgnoreCase);
var userId = parsed["userID"].FirstOrDefault();
var time = parsed["TIME"].Select(v => (int?)int.Parse(v)).FirstOrDefault();
If you want to avoid the dependency on System.Web that is required to use HttpUtility.ParseQueryString, you could use the Uri extension method ParseQueryString found in System.Net.Http.
Note that you have to convert the response body to a valid Uri so that ParseQueryString works.
Please also note in the MSDN document, this method is an extension method for the Uri class, so you need reference the assembly System.Net.Http.Formatting (in System.Net.Http.Formatting.dll). I tried installed it by the nuget package with the name "System.Net.Http.Formatting", and it works fine.
string body = "value1=randomvalue1&value2=randomValue2";
// "http://localhost/query?" is added to the string "body" in order to create a valid Uri.
string urlBody = "http://localhost/query?" + body;
NameValueCollection coll = new Uri(urlBody).ParseQueryString();
How is this
using System.Text.RegularExpressions;
// query example
// "name1=value1&name2=value2&name3=value3"
// "?name1=value1&name2=value2&name3=value3"
private Dictionary<string, string> ParseQuery(string query)
{
var dic = new Dictionary<string, string>();
var reg = new Regex("(?:[?&]|^)([^&]+)=([^&]*)");
var matches = reg.Matches(query);
foreach (Match match in matches) {
dic[match.Groups[1].Value] = Uri.UnescapeDataString(match.Groups[2].Value);
}
return dic;
}
System.Net.Http ParseQueryString extension method worked for me. I'm using OData query options and trying to parse out some custom parameters.
options.Request.RequestUri.ParseQueryString();
Seems to give me what I need.
HttpUtility.ParseQueryString will work as long as you are in a web app or don't mind including a dependency on System.Web. Another way to do this is:
// NameValueCollection nameValueCollection = HttpUtility.ParseQueryString(queryString);
NameValueCollection nameValueCollection = new NameValueCollection();
string[] querySegments = queryString.Split('&');
foreach(string segment in querySegments)
{
string[] parts = segment.Split('=');
if (parts.Length > 0)
{
string key = parts[0].Trim(new char[] { '?', ' ' });
string val = parts[1].Trim();
nameValueCollection.Add(key, val);
}
}
For .NET Core there is Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery
var queryString = QueryHelpers.ParseQuery("?param1=value");
var queryParamValue = queryString["param1"];
Code snippet modified from trackjs.com: