Passing parameters though url? - c#

I am trying to test a call to my one of my functions.
This is called from outside of my website an acts like a Webservice.
To test im trying to pass the parameters though my url.
http://localhost:0000/APIService/UploadValuationDetails?ValuationDetails=[{property_details_address_address1{TagValue:'Test'},{ImageBase64:''}}]?Id=4785
My code in my service:
public void UploadValuationDetails(Dictionary<string, ValuationDetails> JsonResult, int Id)
{
DatabaseHelper DBH = new DatabaseHelper();
foreach (var item in JsonResult)
{ //(ValuationId , TagName , TagValue , ImageBase64)
DBH.WSValuationDetailUpdate(Id, item.Key, item.Value.TagValue, item.Value.ImageBase64);
}
}
ValuationDetails class:
public class ValuationDetails
{
public string TagValue { get; set; }
public string ImageBase64 { get; set; }
}
Edit Changed ? for the second parameter to &:
> http://localhost:0000/APIService/UploadValuationDetails?ValuationDetails={'property_details_address_address1':[{TagValue:'Test',ImageBase64:''}]}&Id=4785
After changing my url to the one above a break point was hit but the values were incorrect.
Edit 2 Trying to get the correct values in the json result.
I think i'm closer:
http://localhost:0000/APIService/UploadValuationDetails?JsonResult={TagName:"property_details_address_address1",ValuationDetails:{TagValue:"Test","ImageBase64:""}}]&Id=4785
But now my jsonResult = 0

You should use an ampersand (&) to separate multiple query string parameters. As you have it, you're using ?, so "?Id=4785" is being interpreted as part of the value for the ValuationDetails parameter.
Corrected:
this is correct ┐
↓
http://localhost:0000/APIService/UploadValuationDetails?ValuationDetails=
[{property_details_address_address1{TagValue:'Test'},{ImageBase64:''}}]&Id=4785
↑
but this should be fixed ┘

I think it is better to Encode the JSON too.
Since the moment you will have for instance in side your data an ? or & you will get an exception too.

Your URL string looks improperly formatted.
For the separator of the URL and the parameters you would use ?.
But to separate parameters use &
http://localhost:0000/APIService/UploadValuationDetails?ValuationDetails=[{property_details_address_address1{TagValue:'Test'},{ImageBase64:''}}]&Id=4785
Your JSON is invalid.
I've worked with it a bit, but it still needs input from you.
[
{
"property_details_address_address1": {
"TagValue": "Test"
},
"needs_a_name_here": {
"ImageBase64": ""
}
}
]
Notice that i've put quotes around the names. And your second object also requires a name.
I used JSONLint to validate and create the proper json

Related

How Get everything after index of a specific character to end?

I'm trying to get some part of string by substring and this is my string :{"samanState":"OK","samanResNum":"97d590e2-9ce3-49f9-85cf-2228b33cad57","samanTraceNo":"479936"} I can't do something like this : substring(8,16) because this string is change every time. I want to get 479936 from that. I'm sure TraceNo":" is static and never change so I did this :
<td>#(bankDepositHistoryItem.AdditionalData.Substring
(bankDepositHistoryItem.AdditionalData.IndexOf("TraceNo\":\""),
bankDepositHistoryItem.AdditionalData.Length- bankDepositHistoryItem.AdditionalData.IndexOf("TraceNo\":\"")-2)) </td>
but the out put is : TraceNo":"479936 How should I get this : 479936
I have to say that I Know this is possible with serialize and deserialize but I want to know if this is possible with substring or split or methods like these.
Many thanks
That is a JSON string, so I would first convert the string to a .NET object using the popular Json.NET framework library.
After adding the Newtonsoft.Json NuGet package to your project, your code would look something like this:
#using Newtonsoft.Json.Linq //add this to your Razor page or to _ViewImports.cshtml
<td>#(JObject.Parse(bankDepositHistoryItem)["samanTraceNo"])</td>
If you still want to parse the string, you can use a couple of handy string extension methods (I have variations for integers and Regex as well):
public static string Past(this string s, string starter) {
var starterPos = s.IndexOf(starter);
return starterPos == -1 ? String.Empty : s.Substring(starterPos + starter.Length);
}
public static string UpTo(this string s, string stopper) {
var stopPos = s.IndexOf(stopper);
return (stopPos >= 0) ? s.Substring(0, stopPos) : s;
}
Then extract with:
var ans = bankDepositHistoryItem.Past("\"samanTraceNo\":\"").UpTo("\"");

Smartly replace strings

I am working with JSON API. As c# doesn't accept characters like - (minus) or . (point), I had to replace each character by _ (underscore). The replacement happens when the JSON response is received as a string so that every attribute name containing a - or a . will have it replaced by a _ , then every attribute name will be the same as the attributes names in the class it will be deserialized into.
To make it clearer, here are some examples:
I recieve the following JSON : { "id": 1, "result": [ { "data": [ { "adm-pass": ""}]}
In the class I want to deserialize into I have this attribute : public String adm_pass {get; set;}
So I replace the minus with an underscore so that the NewtonSoft parser can deserialize it accordingly.
My problem is that I sometimes I get some negative integers in my JSON. So if I do the string replacement in: {"beta" : -1}, I get a parsing exception since the -1 (integer here) becomes _1 and cannot be deserialized properly and raises an exception.
Is there a way to replace the string smartly so I can avoid this error?
For example if - is followed by an int it's not replaced.
If this way does not exist, is there a solution for this kind of problems?
Newtonsoft allows you to specify the exact name of the JSON property, which it will use to serialize/deserialize.
So you should be able to do this
[JsonProperty("adm-pass")]
public String adm_pass { get; set; }
This way you are not restricted to name your properties exactly as the JSON property names. And in your case, you won't need to do a string replace.
Hope this helps.
You'll have to check that you are replacing the key and not the value, maybe by using a regex like http://regexr.com/3d471
Regex could work as wlalele suggests.
But I would create a new object like this:
Create a new object:
var sharpObj = {};
loop through the objects as properties as described here:
Iterate through object properties
for (var property in object) {
if (object.hasOwnProperty(property)) {
// do stuff
}
}
In the // do stuff section, create a property on sharpObj with the desired string replacements and set the property to the same value.
var cleanProperty = cleanPropertyName(property);
sharpObj[cleanProperty] = orginalObject[property];
Note: I assume you can figure out the cleanPropertyName() method or similar.
Stringify the object
var string = JSON.stringify(sharpObj);
You can substring to check whether the next character is an integer, this can adapt into your code easily as you already find a character, as such you could do
int a;
if(int.TryParse(adm_pass.Substring(adm_pass.IndexOf("-") + 1,1),out a))
{
//Code if next character is an int
}
else
{
adm_pass = adm_pass.Replace("-","_");
}
This kind of code can be looped until there are no remaining hyphens/minuses

Returning string is not successful

I have a problem which may look easy but I can't solve it.
I have a function which returns a string and has two arguments:
public string MyFunc(string ID, string TargetID) // ID is 9999999995 and TargetID is 9999999998
{
return ID + TargetID; // Gives me ID only(9999999995).
}
When I try to put text instead of the ID, it works, but not with a number. I've tried to use StringBuilder but I get the same result.
I use it like this:
MessageBox.Show(MyFunc(Settings.Default.ID, ComboBox1.Text));
The function is working as intended. Check that the incoming parameters ID and TargetID actually contain values and they are the values you expect.
Check the values are not null to be safe and do a String.Concat(...)
Thank you everybody, but the problem was in receiving the string from netStream, That was my fault. When sending the string I haven't added the "$" char in the end and so the string maybe was so long or something...

Url mapping in web forms - allow question marks and hyphens

I have implemented URL mapping in our ASP.NET 4 application, but I have a problem with some of our content.
Some of our products has a hyphen "-" or a question mark "?" in them. It's not an option to remove that. A productname could be "My Product - Good for you?".
We use two custom made methods, MakeUrlSeoReady and MakeUrlNonSeoReady. We replace space like this: Replace(" ","-"), as this is the most SEO-friendly solution. However, we also need to make this work with both question marks and hyphens.
The reason we use the MakeUrlSeoReady / NonReady methods is to be able to show the "real" name.
Currently the mapping is defined as follows:
routes.MapPageRoute("Produkt visning",
"artikler/{Categoryname}/{SubCategoryname}/{ProductName}",
"~/SingleProduct.aspx");
So what I do is I retrieve the product depending on the ProductName. I use two methods I've created:
public static string MakeUrlNonSeoReady(string text)
{
return text.ToLower().
Replace("oe", "ø").
Replace("aa", "å").
Replace("ae", "æ").
Replace("-", " ");
}
public static string MakeUrlSeoReady(string text)
{
return text.ToLower().
Replace("ø", "oe").
Replace("å", "aa").
Replace("æ", "ae").
Replace(" ", "-");
}
So in the SingleProduct.aspx page I use the following string to get from our database:
string categoryName = HelperFunctions.MakeUrlNonSeoReady(Page.RouteData.Values["ProductName"]);
But this will of course not work. So any help is really appreciated :-)
An arguably cleaner and simpler method is to use a unique product identifier that is numerical or alphanumerical and is natively HTML encoded, and then simply put the product name as an unused parameter for SEO or search purposes.
MSDN RouteCollection.MapPageRoute Method (String, String, String, Boolean, RouteValueDictionary)
routes.MapPageRoute("Produkt visning",
"artikler/{Categoryname}/{SubCategoryname}/{ProductIdentifier}/{ProductName}",
"~/SingleProduct.aspx", false, new RouteValueDictionary
{ { "ProductName ", string.Empty } });

How to get POST data as array with C#

I'm developing an ASP.NET handler with C# that receives an array of data posted from an external Flash program. How can I use the data as array? It seems the HTTP Context used in ASP.NET automatically html-decodes the post data so that it comes out as a simple string. The separator in this case is comma (could be it's always a comma, never worked with this before).
Seems I need either of two things:
1) A way to get to the data in its html-encoded form, where the comma used as a separator for the arrays can ONLY represent real arrays instead of customer form input (the customer input comma would remain encoded at this point).
2) A way to simulate the PHP print_r(), var_dump() function (don't know PHP myself, but I'm told that does the trick there) to dump the variable into an array.
So any help on how to do either would be appreciated. Thanks in advance!
Edit 1: The data being posted can be for example a bunch of addresses, postalcodes and optional extra info. Such as address=testroad%5F5,another%5Ftestroad%5F6&postalcode=12345,56789&extrainfo=,firstwasempty. In that example, there were two addresses (%5F equals whitespace), two postalcodes, but only the second address contained extrainfo as the space before the comma was empty. Now once more, as English isn't my mothertongue, the problem was that possible customer-written comma gets mixed with the actual array-splitting comma after decoding.
I had the same trouble and found this post, but just now I've found a better way to do it.
You should put the same name on all the POST variables, so the data to be posted is:
address=AddressValue1&address=AddressValue2&address=AddressValue3
In the C# code script you can then access the data parameters with:
string[] addresses = this.Request.Form.GetValues("address");
foreach (string address in addresses)
{
// Your code here ...
}
public void ProcessRequest(HttpContext context)
{
using (var reader = new StreamReader(context.Request.InputStream))
{
string postedData = reader.ReadToEnd();
foreach (var item in postedData.Split(new [] { '&' }, StringSplitOptions.RemoveEmptyEntries))
{
var tokens = item.Split(new [] { '=' }, StringSplitOptions.RemoveEmptyEntries);
if (tokens.Length < 2)
{
continue;
}
var paramName = tokens[0];
var paramValue = tokens[1];
var values = paramValue.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var value in values)
{
var decodedValue = context.Server.UrlDecode(value);
// Do something with the decoded value which corresponds to paramName
}
}
}
}
I found
Request.Params[null]
refers to the RAW data posted to the page in C# ASP.NET.
Check HttpRequest.InputStream property: http://msdn.microsoft.com/en-us/library/system.web.httprequest.inputstream.aspx

Categories

Resources