Variable in a C# String - c#

I've tried everything but cannot seem to get a Variable into some text. I think the problem is that the test is in JSON format. I'm trying to pass a variable from a textbox in the UI to this variable, but for testing I've just created a local variable, as below. Here is my code:
Variable:
string Repo1 = "jamesbennett12345678990";
String I'm trying to add my variable into:
var UserAgent1 = new ProductInfoHeaderValue("ScraperBot", "1.0");
request.Headers.TryAddWithoutValidation("Authorization", "token testtesttesttest");
request.Headers.UserAgent.Add(UserAgent1);
//String here
request.Content = new StringContent("{\"name\":\"{Repo1}\"}");
I've read that to do this it is simply a case of putting curly braces around the variable but it doesnt work. I know this because the line - string Repo1 = "jamesbennett12345678990"; says that the variable is not in use.
This part is JSON Data that is getting passed using the HTPClient so I'm thinking as there are already Speachmarks escaped with backslashes that there might be a formatting problem here ---- ("{"name":"{Repo1"}")
I don't have any errors as such, only the one in VS saying the
var string Repo1 = "jamesbennett12345678990";
isn't actually in use.
I've also looked into string Interpolation.

try this
var json = System.Text.Json.JsonSerializer.Serialize(new {name=Repo1});
//or
var json = System.Text.Json.JsonSerializer.SerializeToElement(new {name=Repo1}).ToString();
//or
var json="{\"name\":\""+ Repo1+"\"}";
var content = new StringContent(json, Encoding.UTF8, "application/json");

Related

unable to remove the slash "\" in json string in c#

I am unable to remove the slash while requesting to the Post API in c#.By default slash is added in the value, is there is a way to remove the slash in the string.I am sending the string array to api.I have used replace also but it is not working.
"[\"9782163865630.jpg\",\"9946239664158.jpg\",\"9946237403166.jpg\",\"10056487272478.jpg\",\"10056486322206.jpg\",\"10060074352670.jpg\",\"9999843459102.jpg\",\"9716071170078.jpg\",\"9716071497758.jpg\",\"10052987715614.jpg\",\"10052985683998.jpg\",\"10056390115358.jpg\",\"10056391622686.jpg\",\"10056391360542.jpg\",\"9837103120414.jpg\",\"9837102923806.jpg\",\"9837104857118.jpg\"]"
public void PostWebAPI(List<string> FileNameList)
{
string json = JsonConvert.SerializeObject(FileNameList).ToString();
json = json.Replace(#"\","");
var client = new RestClient("eg.api.stackflow.com/post");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AlwaysMultipartFormData = true;
request.AddParameter("filePaths", json);
request.AddParameter("bucketAsDir", "false");
IRestResponse response = client.Execute(request);
}
Visual Studio debugging:
The backslash \ is not a readable character in your string, its an escape character for the double quotes: \"; its telling the compiler that the " following the backslash is not a string delimiter but a regular character part of the string.
Consider you want to have a string that contains the following text: "Hello" (not Hello). You would write the following:
string s = "\"Hello\"";
s is really "Hello" but the debugger will show it as "\"Hello\"" because it has no better way to desambiguate to the user " as string delimiter from " as part of the string itself.
In short, the escape character \ inside a string tells the compiler that the following character is used in a way that is not the default interpretation the compiler would consider. Other expamples:
\": a regular double quote instead of the string delimiter "
\0: null charater instead of a regular 0
\n: new line character instead of a regular n
\t: tab character instead of a regular t
\\: backslash instead of the escape character \
etc.
Check here for the whole list.
So, to make a long story short, dont worry, your string really is: ["9782163865630.jpg","9946239664158.jpg","9946237403166.jpg",.... You can verify this by simply printing out the string to the console: Console.WriteLine(json);
The slash isn't actually in the string. You're trying to remove something that doesn't exist. The debugger is just escaping the double quotes. Click on the magnifier icon will get you some options on how the debugger displays it.
Each quotes " is a special symbol in C#.
Those backslashes \ just escape sequences for the quotes ".
It dont make your result error.
Try to write this in Visual Studio:
string myString = "This is my "string""; // Error
You can use a backslash before each quote (\") to fix it:
string myString = "This is my \"string\""; // This work well
Try this here
I was facing the problem with the above code using RestClient instead of it, I have used HttpClient, Now from API I am not getting the error. Slash is added to request paramater using RestClient but in HttpClient it is not added, due to this UnicodeEncoding.UTF8, "application/json" the actuall value is been passed in the parameter of the API.
public async Task CallAPIAsync(List<string> objFileNameList)
{
var Info = new APIModel
{
filePaths = objFileNameList,
bucketAsDir = "false"
};
string request = JsonConvert.SerializeObject(Info);
using (var client = new HttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
var stringContent = new StringContent(request, UnicodeEncoding.UTF8, "application/json");
client.BaseAddress = new Uri("eg.api.stackflow.com/post");
var response = await client.PostAsync("post", stringContent);
var message = response.Content.ReadAsStringAsync().Result;
}
}

Replace specific string in large string

I'm writing a small WPF Application which helps my company to update costumer projects. I have a list of SQL-Files which I have to execute. Now these scripts are always written with a "USE [Insert_Database]". I read the whole content of a script into a string, but my Replace method doesn't seem to do anything.
string content = File.ReadAllText(file);
content.Replace("Insert_Database", Database.Name);
SqlScriptsList.Add(new SqlScriptModel {Name = Path.GetFileName(file), Path = file, ScriptContent = content});
String.Replace returns the modified string, so it should be:
content = content.Replace(....);
This method does not modify the value of the current instance.
Instead, it returns a new string in which all occurrences of oldValue
are replaced by newValue.
You can use replace function as follow on strings
str = str.Replace("oldstr","newstr");
if oldstr is found in the str then it will be replaced by new str
You aren't using new value when you call replace.
string content = File.ReadAllText(file);
content = content.Replace("Insert_Database", Database.Name);
SqlScriptsList.Add(new SqlScriptModel {Name = Path.GetFileName(file), Path = file, ScriptContent = content});
for reference: the MSDN doc for replace https://msdn.microsoft.com/en-us/library/system.string.replace(v=vs.110).aspx

Getting string after a specific slash

I have a string and I want to get whatever is after the 3rd slash so.
I don't know of any other way I can do this, I don't really want to use regex if I dont need it.
http://www.website.com/hello for example would be hello
I have used str.LastIndexOf('/') before like:
string str3 = str.Substring(str.LastIndexOf('/') + 1);
However I am still trying to figure out how to do this for a slash that is not the first or last
string s = "some/string/you/want/to/split";
string.Join("/", s.Split('/').Skip(3).ToArray());
As suggested by C.Evenhuis, you should rely on the native System.Uri class:
string url = "http://stackoverflow.com/questions/20213490/getting-string-after-a-specific-slash"
Uri asUri = new Uri(url);
string result = asUri.LocalPath;
Console.WriteLine(result);
(live at http://csharpfiddle.com/LlLbriBm)
This will output:
/questions/20213490/getting-string-after-a-specific-slash
If you don't want the first / in the result, simply use:
string url = "http://stackoverflow.com/questions/20213490/getting-string-after-a-specific-slash"
Uri asUri = new Uri(url);
string result = asUri.LocalPath.TrimStart('/');
Console.WriteLine(result);
You should take a look in the System.Uri class documentation. There's plenty of property that can you can play with, depending on what you want to actually keep in the url (url parameters, hashtag, etc.)
If you're manipulating URLs, then use the Uri class instead of rolling your own.
But if you want to do it manually for educational reasons, you could do something like this:
int startPos = 0;
for(int i = 0; i < 3; i++)
{
startPos = s.IndexOf('/', startPos)+1;
}
var stringOfInterest = s.Substring(startPos);
There are lots of ways this might fail if the string isn't in the form you expect, so it's just an example to get you started.
Although this is premature optimisation, this sort of approach is more efficient than smashing the whole string into components and putting them back together again.

How to use google-diff-match-patch C# library?

I am looking at http://code.google.com/p/google-diff-match-patch/ and have downloaded the file. When I look at it is 2 files
DiffMatchPatch.cs
DiffMatchPatchTest.cs
When I try to make a new object of DiffMatchPatch.cs I have to pass in some operation and string text.
http://neil.fraser.name/software/diff_match_patch/svn/trunk/demos/demo_diff.html
In the demo they cross out the words that are different and that is what I am trying to achieve.
I am trying to compare 2 blocks of text on the server side finds the differences and send a email to the user with the file block of text to them like the end result is in the demo that I posted above.
So does anyone have a tutorial on how to use the C# version?
For reference, this is really easy:
var dmp = new diff_match_patch();
var diffs = dmp.diff_main(text1, text2);
var html = dmp.diff_prettyHtml(diffs);
Implementation with current version(2.1.0) would look like this
var dmp = DiffMatchPatchModule.Default;
var diffs = dmp.DiffMain(text1, text2);
var html = dmp.DiffPrettyHtml(diffs);
For anyone who came across this thread because of the title and expected an explanation on how to use the Google Diff-Match-Patch algorithm via the https://github.com/pocketberserker/Diff.Match.Patch library found on NuGet, to create a diff string, so he can send the change somewhere (e.g. via websocket) and restore it at the destination based on the old value and the diff string, that would work like this:
var oldValue = "Test old text.";
var newValue = "Test new text.";
// create diff string
var dmp = DiffMatchPatch.DiffMatchPatchModule.Default;
var diffs = dmp.DiffMain(oldValue, newValue);
var srcDelta = dmp.DiffToDelta(diffs);
// restore from diff
var dmp = DiffMatchPatch.DiffMatchPatchModule.Default;
var dstDelta = dmp.DiffFromDelta(oldValue, srcDelta);
var restoredNewValue = dmp.DiffText2(dstDelta);

extract query string from a URL string

I am reading from history, and I want that when i come across a google query, I can extract the query string. I am not using request or httputility since i am simply parsing a string. however, when i come across URLs like this, my program fails to parse it properly:
http://www.google.com.mt/search?client=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial&channel=s&hl=mt&source=hp&biw=986&bih=663&q=hotmail&meta=&btnG=Fittex+bil-Google
what i was trying to do is get the index of q= and the index of & and take the words in between but in this case the index of & will be smaller than q= and it will give me errors.
any suggestions?
thanks for your answers, all seem good :) p.s. i couldn't use httputility, not I don't want to. when i add a reference to system.web, httputility isn't included! it's only included in an asp.net application. Thanks again
It's not clear why you don't want to use HttpUtility. You could always add a reference to System.Web and use it:
var parsedQuery = HttpUtility.ParseQueryString(input);
Console.WriteLine(parsedQuery["q"]);
If that's not an option then perhaps this approach will help:
var query = input.Split('&')
.Single(s => s.StartsWith("q="))
.Substring(2);
Console.WriteLine(query);
It splits on & and looks for the single split result that begins with "q=" and takes the substring at position 2 to return everything after the = sign. The assumption is that there will be a single match, which seems reasonable for this case, otherwise an exception will be thrown. If that's not the case then replace Single with Where, loop over the results and perform the same substring operation in the loop.
EDIT: to cover the scenario mentioned in the comments this updated version can be used:
int index = input.IndexOf('?');
var query = input.Substring(index + 1)
.Split('&')
.SingleOrDefault(s => s.StartsWith("q="));
if (query != null)
Console.WriteLine(query.Substring(2));
If you don't want to use System.Web.HttpUtility (thus be able to use the client profile), you can still use Mono HttpUtility.cs which is only an independent .cs file that you can embed in your application. Then you can simply use the ParseQueryString method inside the class to parse the query string properly.
here is the solution -
string GetQueryString(string url, string key)
{
string query_string = string.Empty;
var uri = new Uri(url);
var newQueryString = HttpUtility.ParseQueryString(uri.Query);
query_string = newQueryString[key].ToString();
return query_string;
}
Why don't you create a code which returns the string from the q= onwards till the next &?
For example:
string s = historyString.Substring(url.IndexOf("q="));
int newIndex = s.IndexOf("&");
string newString = s.Substring(0, newIndex);
Cheers
Use the tools available:
String UrlStr = "http://www.google.com.mt/search?client=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial&channel=s&hl=mt&source=hp&biw=986&bih=663&q=hotmail&meta=&btnG=Fittex+bil-Google";
NameValueCollection Items = HttpUtility.ParseQueryString(UrlStr);
String QValue = Items["q"];
If you really need to do the parsing yourself, and are only interested in the value for 'q' then the following would work:
string url = #"http://www.google.com.mt/search?" +
"client=firefoxa&rls=org.mozilla%3Aen-" +
"US%3Aofficial&channel=s&hl=mt&source=hp&" +
"biw=986&bih=663&q=hotmail&meta=&btnG=Fittex+bil-Google";
int question = url.IndexOf("?");
if(question>-1)
{
int qindex = url.IndexOf("q=", question);
if (qindex > -1)
{
int ampersand = url.IndexOf('&', qindex);
string token = null;
if (ampersand > -1)
token = url.Substring(qindex+2, ampersand - qindex - 2);
else
token = url.Substring(qindex+2);
Console.WriteLine(token);
}
}
But do try to look at using a proper URL parser, it will save you a lot of hassle in the future.
(amended this question to include a check for the '?' token, and support 'q' values at the end of the query string (without the '&' at the end) )
And that's why you should use Uri and HttpUtility.ParseQueryString.
HttpUtility is fine for the .Net Framework. However that class is not available for WinRT apps. If you want to get the parameters from a url in a Windows Store App you need to use WwwFromUrlDecoder. You create an object from this class with the query string you want to get the parameters from, the object has an enumerator and supports also lambda expressions.
Here's an example
var stringUrl = "http://localhost/?name=Jonathan&lastName=Morales";
var decoder = new WwwFormUrlDecoder(stringUrl);
//Using GetFirstByName method
string nameValue = decoder.GetFirstByName("name");
//nameValue has "Jonathan"
//Using Lambda Expressions
var parameter = decoder.FirstOrDefault(p => p.Name.Contains("last")); //IWwwFormUrlDecoderEntry variable type
string parameterName = parameter.Name; //lastName
string parameterValue = parameter.Value; //Morales
You can also see http://www.dzhang.com/blog/2012/08/21/parsing-uri-query-strings-in-windows-8-metro-style-apps

Categories