Split and Append string at specific point - c#

i have use an web API
https://api.nasa.gov/planetary/earth/imagery?lon=100.75&lat=1.5&date=2014-02-01&cloud_score=True&api_key=DEMO_KEY
And display the parameters above
Method input:
imagery?lon=100.75&lat=1.5&date=2014-02-01&cloud_score=True&api_key=DEMO_KEY
Expected Output:
Method name: imagery
Parameters: lon, lat, date, cloud_score, api_key
Values: 100.75, 1.5, 2014-02-01, True, api_key
Method input:
browse?lon=100.75&lat=1.5&date=2014-02-01
Expected Output:
Method name: browse
Parameters: lon, lat, date
Values: 100.75, 1.5, 2014-02-01
Method input:
?lon=100.75&lat=1.5&date=2014-02-01
Expected Output:
Error: malformed URL
Method input:
browse?lon=100.75&lat=1.5&date
Expected Output:
Error: malformed URL
Method input:
browse?
Expected Output:
Error: malformed URL
Method input:
browse
Expected Output:
Method name: browse
i need to split the API from any word before the Question Mark
Here is my code so far
if (S == null || S=="")
{
lbOutput.Text = "Please dont leave Fields Empty";
}
else
{
if (S.Contains("?") || S.Contains("&"))
{
lbOutput.Text = "Output";
string url = txtInput.Text;
string querystring = url.Substring(url.IndexOf("?"));
System.Collections.Specialized.NameValueCollection parameters =
System.Web.HttpUtility.ParseQueryString(querystring);
//lbOutput.Text = querystring;
lbLonRes.Text = System.Web.HttpUtility.ParseQueryString(querystring).Get("lon");
lbLatRes.Text = System.Web.HttpUtility.ParseQueryString(querystring).Get("lat");
lbDateRes.Text = System.Web.HttpUtility.ParseQueryString(querystring).Get("date");
lbCloudRes.Text = System.Web.HttpUtility.ParseQueryString(querystring).Get("cloud_score");
lbAPIRes.Text = System.Web.HttpUtility.ParseQueryString(querystring).Get("api_key");
}
if(S.Contains(" "))
{
lbOutput.Text = "Error: malformed URL";
lbLonRes.Text = "";
lbLatRes.Text = "";
lbDateRes.Text = "";
lbCloudRes.Text = "";
lbAPIRes.Text = "";
}
}

You can use the Segments property of the Uri class to get the method since it will be the last segment.
You need a reference to System.Net.HttpFormatting to use this code, it will remove your dependence on System.Web
using System;
using System.Net.Http;
namespace ConsoleApplication8
{
class Program
{
static void Main(string[] args)
{
string url = "https://api.nasa.gov/planetary/earth/imagery?lon=100.75&lat=1.5&date=2014-02-01&cloud_score=True&api_key=DEMO_KEY";
Uri theUri = new Uri(url);
string method = theUri.Segments[theUri.Segments.Length - 1];
Console.WriteLine("Method: {method}");
var qa = theUri.ParseQueryString();
foreach (string item in qa.AllKeys)
{
Console.WriteLine($"key: {item}, value: {qa[item]}");
}
Console.ReadKey();
}
}
}

Related

How to Get index of a Character in an Unknown Line of a Multiline string in c#

I'm trying to get covid-19 results (only information about Iran) from an Api and show it on a textbox.
and the full result (all countries) that i get from the Api is a json format.
so to get only Iran section i made a Function that loops through lines of the string one by one and check if in that line there is a "{" and if yes get index of that and continue checking if in another line there is a "}" and get index of that too then check if between these, there is "Iran" then add this text (from "{" to "}") in a string:
private string getBetween(string strSourceText, string strStartingPosition, string strEndingPosition)
{
int Starting_CurlyBracket_Index = 0;
int Ending_CurlyBracket_Index = 0;
string FinalText = null;
bool isTurnTo_firstIf = true;
foreach (var line in strSourceText.Split('\r', '\n'))
{
if (isTurnTo_firstIf == true)
{
if (line.Contains(strStartingPosition))
{
Starting_CurlyBracket_Index = line.IndexOf(strStartingPosition); //i think problem is here
isTurnTo_firstIf = false;
}
}
else if (isTurnTo_firstIf == false)
{
if (line.Contains(strEndingPosition))
{
Ending_CurlyBracket_Index = line.IndexOf(strEndingPosition); //i think problem is here
if (strSourceText.Substring(Starting_CurlyBracket_Index, Ending_CurlyBracket_Index - Starting_CurlyBracket_Index).Contains("Iran")) //error here
{
FinalText = strSourceText.Substring(Starting_CurlyBracket_Index, Ending_CurlyBracket_Index - Starting_CurlyBracket_Index);
break;
}
else
{
isTurnTo_firstIf = true;
}
}
}
}
return FinalText;
}
and i call the function like this:
string OnlyIranSection = getBetween(Sorted_Covid19_Result, "{", "}"); //Sorted_Covid19_Result is the full result in json format that converted to string
textBox1.Text = OnlyIranSection;
but i get this Error:
and i know.. its because it gets indexes in the current line but what i need is getting that index in the strSourceText so i can show only this section of the whole result:
USING JSON
As per the comments I read it was really needed to use JSON utility to achieve your needs easier.
You can start with this basic example:
static void Main(string[] args)
{
string jsonString = #"{
""results"": [
{""continent"":""Asia"",""country"":""Indonesia""},
{""continent"":""Asia"",""country"":""Iran""},
{""continent"":""Asia"",""country"":""Philippines""}
]
}";
var result = JsonConvert.DeserializeObject<JsonResult>(jsonString);
var iranInfo = result.InfoList.Where(i => i.Country.ToString() == "Iran").FirstOrDefault();
}
public class JsonResult
{
[JsonProperty("results")]
public List<Info> InfoList { get; set; }
}
public class Info
{
public object Continent { get; set; }
public object Country { get; set; }
}
UPDATE: USING INDEX
As long as the structure of the JSON is consistent always then this kind of sample solution can give you hint.
Console.WriteLine("Original JSON:");
Console.WriteLine(jsonString);
Console.WriteLine();
Console.WriteLine("Step1: Make the json as single line,");
jsonString = jsonString.Replace(" ", "").Replace(Environment.NewLine, " ");
Console.WriteLine(jsonString);
Console.WriteLine();
Console.WriteLine("Step2: Get index of country Iran. And use that index to get the below output using substring.");
var iranIndex = jsonString.ToLower().IndexOf(#"""country"":""iran""");
var iranInitialInfo = jsonString.Substring(iranIndex);
Console.WriteLine(iranInitialInfo);
Console.WriteLine();
Console.WriteLine("Step3: Get inedx of continent. And use that index to get below output using substring.");
var continentIndex = iranInitialInfo.IndexOf(#"""continent"":");
iranInitialInfo = iranInitialInfo.Substring(0, continentIndex-3);
Console.WriteLine(iranInitialInfo);
Console.WriteLine();
Console.WriteLine("Step4: Get the first part of the info by using. And combine it with the initialInfo to bring the output below.");
var beginningIranInfo = jsonString.Substring(0, iranIndex);
var lastOpenCurlyBraceIndex = beginningIranInfo.LastIndexOf("{");
beginningIranInfo = beginningIranInfo.Substring(lastOpenCurlyBraceIndex);
var iranInfo = beginningIranInfo + iranInitialInfo;
Console.WriteLine(iranInfo);
OUTPUT USING INDEX:

Azure Functions Script Compilation Failed

I'm trying to create an Azure Function with Docker. When I create a Function with func new, it works fine and when I go to http://localhost:8182/api/HttpTriggerCSharp?name=John I get the message
Hello, John
Now I'm trying to run the same project but I changed the code. The previous code was this:
#r "Newtonsoft.Json"
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
public static IActionResult Run(HttpRequest req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
string name = req.Query["name"];
string requestBody = new StreamReader(req.Body).ReadToEnd();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
return name != null
? (ActionResult)new OkObjectResult($"Hello, {name}")
: new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}
Now this is my new code:
#r "Newtonsoft.Json"
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
public static IActionResult Run(HttpRequest req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
// Parsing query parameters
string name = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
.Value;
log.Info("name = " + name);
string numberOfTerms = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "numberOfTerms", true) == 0)
.Value;
log.Info("name = " + numberOfTerms);
// Validating the parameters received
if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(numberOfTerms))
{
var errorResponse = req.CreateResponse(HttpStatusCode.BadRequest,
"Please pass a name and the number of digits on the query string.");
return errorResponse;
}
int termsToShow;
try
{
termsToShow = Int32.Parse(numberOfTerms);
}
catch (FormatException e)
{
var errorResponse = req.CreateResponse(HttpStatusCode.BadRequest,
"The numberOfTerms parameter must be an integer!");
return errorResponse;
}
if (termsToShow < 0 || termsToShow > 100) {
var errorResponse = req.CreateResponse(HttpStatusCode.BadRequest,
"Please pass a numberOfTerms parameter between 0 and 100.");
return errorResponse;
}
// Building the response
string incompleteResponse = "Hello, " + name + ", you requested the first " + numberOfTerms + " terms of the Fibonacci series. Here they are: ";
string completeResponse = GenerateFibonacciTerms(incompleteResponse, termsToShow);
var response = req.CreateResponse(HttpStatusCode.OK, completeResponse);
// Returning the HTTP response with the string we created
log.Info("response = " + response);
return response;
}
public static string GenerateFibonacciTerms(string incompleteResponse, int termsToShow)
{
int a = 0;
int b = 1;
string temporalString = "";
for (int i = 0; i < termsToShow; i++)
{
int temp = a;
a = b;
b = temp + b;
temporalString = temporalString + temp.ToString() + " ";
}
string result = incompleteResponse + temporalString + "- That's it, have an awesome day!";
return result;
}
I build the container then I run it and I get this message:
I've already checked my code with VS Code (I did it in Sublime Text so I didn't have code checking) and all the problems it finds are the same error:
And my code has "errors" everywhere:
How can I solve this?
You are using v2 function core tools(based on .net core), while the code you changed is targeted at v1(.net framework).
So you have two choices:
Uninstall v2 and use function core tool v1.
Modify your code to make it work in v2 runtime.
Here the code for you to refer. GenerateFibonacciTerms method needs no change.
log.Info("C# HTTP trigger function processed a request.");
// Parsing query parameters
string name = req.Query["name"];
log.Info("name = " + name);
string numberOfTerms = req.Query["numberOfTerms"];
log.Info("numberOfTerms = " + numberOfTerms);
// Validating the parameters received
if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(numberOfTerms))
{
return new BadRequestObjectResult("Please pass a name and the number of digits on the query string.");
}
int termsToShow;
try
{
termsToShow = Int32.Parse(numberOfTerms);
}
catch (FormatException e)
{
return new BadRequestObjectResult("The numberOfTerms parameter must be an integer!");
}
if (termsToShow < 0 || termsToShow > 100) {
return new BadRequestObjectResult("Please pass a numberOfTerms parameter between 0 and 100.");
}
// Building the response
string incompleteResponse = "Hello, " + name + ", you requested the first " + numberOfTerms + " terms of the Fibonacci series. Here they are: ";
string completeResponse = GenerateFibonacciTerms(incompleteResponse, termsToShow);
var response = new OkObjectResult(completeResponse);
// Returning the HTTP response with the string we created
log.Info("response = " + response);
return response;

C#: How to write special characters to ADLDS?

I'm trying to write contacts into an ADLDS ldap for using them as a phone book for a Yealink T48G. Sometimes the name of the contact includes some special characters like "ö", "ß" and "é". If these characters are contained in the fields "givenName" or "displayName" neither the phone nor the ldap client can show them correctly and instead show some other chars (for example "ö" -> "ö"), however the "name" and "dn" fields show these characters correctly.
If I insert the contactvalues via ADSI-Edit or any other tool, the phone shows the name correctly, but my application is no longer able to read the inserted special chars from givenName and shows some questionmark-boxes, however the dn and name fields are read correctly.
I've already tried using utf-8, utf-16, utf-32, iso-8859-1 and windows-1252 as encoding for my application.
So the question is how can I store these special characters using C# in the givenName property for an inetOrgPerson in an ADLDS instance?
shown correctly:
shown incorrectly:
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.DirectoryServices.Protocols;
using System.Net;
namespace LdapContacts
{
public class LdapClient
{
private LdapConnection connection;
public LdapClient(string host, int port, string distinguishedUsername, string password)
{
connection = new LdapConnection(new LdapDirectoryIdentifier(host, port));
connection.AuthType = AuthType.Basic;
connection.Credential = new NetworkCredential(distinguishedUsername, password);
connection.Bind();
}
public AddResponse SendAddRequest(string distinguishedName, List<DirectoryAttribute> attributes)
{
AddRequest request = new AddRequest(distinguishedName, attributes.ToArray());
return connection.SendRequest(request) as AddResponse;
}
public SearchResponse SendSearchRequest(string distinguishedName, string filter)
{
SearchRequest request = new SearchRequest();
request.DistinguishedName = distinguishedName;
request.Filter = filter;
request.Scope = SearchScope.Subtree;
return connection.SendRequest(request) as SearchResponse;
}
}
public class ContactsToLdap
{
private static void Main(string[] args)
{
LdapClient client = new LdapClient(Settings.LdapHost, Settings.LdapPort, Settings.LdapUsername, Settings.LdapPassword);
client.SendAddRequest("CN=Testöäüß,CN=Users,CN=testpart,DC=csdomain,DC=local", new List<DirectoryAttribute>()
{
new DirectoryAttribute("telephoneNumber", "0123456"),
new DirectoryAttribute("objectClass", "inetOrgPerson"),
new DirectoryAttribute("uid", "io3e"),
new DirectoryAttribute("givenName", "â é testnameöüÄß")
});
//distinguished name of contactsfolder
SearchResponse result = client.SendSearchRequest(Settings.LdapContactsFolder, "(objectClass=inetOrgPerson)");
foreach (SearchResultEntry sResult in result.Entries)
{
//display the index of the current entry
Console.Write((result.Entries.IndexOf(sResult) + 1) + ":\n");
foreach (DirectoryAttribute attribute in sResult.Attributes.Values)
{
//output the name of the attribute
Console.Write("\t" + attribute.Name + " = ");
for (int i = 0; i < attribute.Count; i++)
{
// convert the attribute to a string if it is an byte[]
// output if inserted with ADSI-Edit: ? ? testname????
// output if inserted with this code: â é testnameöüÄß
if (attribute[i].GetType().Equals(typeof(byte[])))
{
Console.Write(Encoding.UTF8.GetString((byte[])attribute[i]) + "; ");
}
else
{
Console.Write(attribute[i] + "; ");
}
}
Console.WriteLine();
}
Console.WriteLine();
}
}
}
}
The issue was resolved by setting the protocolversion that should be used to version 3.
connection = new LdapConnection(new LdapDirectoryIdentifier(host, port));
connection.SessionOptions.ProtocolVersion = 3;

Get host domain from URL?

how to get host domain from a string URL?
GetDomain has 1 input "URL", 1 Output "Domain"
Example1
INPUT: http://support.domain.com/default.aspx?id=12345
OUTPUT: support.domain.com
Example2
INPUT: http://www.domain.com/default.aspx?id=12345
OUTPUT: www.domain.com
Example3
INPUT: http://localhost/default.aspx?id=12345
OUTPUT: localhost
You can use Request object or Uri object to get host of url.
Using Request.Url
string host = Request.Url.Host;
Using Uri
Uri myUri = new Uri("http://www.contoso.com:8080/");
string host = myUri.Host; // host is "www.contoso.com"
Try like this;
Uri.GetLeftPart( UriPartial.Authority )
Defines the parts of a URI for the Uri.GetLeftPart method.
http://www.contoso.com/index.htm?date=today --> http://www.contoso.com
http://www.contoso.com/index.htm#main --> http://www.contoso.com
nntp://news.contoso.com/123456#contoso.com --> nntp://news.contoso.com
file://server/filename.ext --> file://server
Uri uriAddress = new Uri("http://www.contoso.com/index.htm#search");
Console.WriteLine("The path of this Uri is {0}", uriAddress.GetLeftPart(UriPartial.Authority));
Demo
Use Uri class and use Host property
Uri url = new Uri(#"http://support.domain.com/default.aspx?id=12345");
Console.WriteLine(url.Host);
try following statement
Uri myuri = new Uri(System.Web.HttpContext.Current.Request.Url.AbsoluteUri);
string pathQuery = myuri.PathAndQuery;
string hostName = myuri.ToString().Replace(pathQuery , "");
Example1
Input : http://localhost:4366/Default.aspx?id=notlogin
Ouput : http://localhost:4366
Example2
Input : http://support.domain.com/default.aspx?id=12345
Output: support.domain.com
The best way, and the right way to do it is using Uri.Authority field
Load and use Uri like so :
Uri NewUri;
if (Uri.TryCreate([string with your Url], UriKind.Absolute, out NewUri))
{
Console.Writeline(NewUri.Authority);
}
Input : http://support.domain.com/default.aspx?id=12345
Output : support.domain.com
Input : http://www.domain.com/default.aspx?id=12345
output : www.domain.com
Input : http://localhost/default.aspx?id=12345
Output : localhost
If you want to manipulate Url, using Uri object is the good way to do it.
https://msdn.microsoft.com/en-us/library/system.uri(v=vs.110).aspx
var url = Regex.Match(url, #"(http:|https:)\/\/(.*?)\/");
INPUT = "https://stackoverflow.com/questions/";
OUTPUT = "https://stackoverflow.com/";
Try this
Console.WriteLine(GetDomain.GetDomainFromUrl("http://support.domain.com/default.aspx?id=12345"));
It will output support.domain.com
Or try
Uri.GetLeftPart( UriPartial.Authority )
You should construct your string as URI object and Authority property returns what you need.
public static string DownloadImage(string URL, string MetaIcon,string folder,string name)
{
try
{
WebClient oClient = new WebClient();
string LocalState = Windows.Storage.ApplicationData.Current.LocalFolder.Path;
string storesIcons = Directory.CreateDirectory(LocalState + folder).ToString();
string path = Path.Combine(storesIcons, name + ".png");
//si la imagen no es valida ej "/icon.png"
if (!TextBoxEvent.IsValidURL(MetaIcon))
{
Uri uri = new Uri(URL);
string DownloadImage = "https://" + uri.Host + MetaIcon;
oClient.DownloadFile(new Uri(DownloadImage), path);
}
//si la imagen tiene todo ej https://www.mercadolibre.com/icon.png
else
{
oClient.DownloadFile(new Uri(MetaIcon), path);
}
return path;
}
catch (Exception ex)
{
return ex.ToString();
}
}
Here's a solution that will work for all kinds of URLs.
public string GetDomainFromUrl(string url)
{
url = url.Replace("https://", "").Replace("http://", "").Replace("www.", ""); //Remove the prefix
string[] fragments = url.Split('/');
return fragments[0];
}
it will take only domain name (www.bla.com -> bla)
no Uri required
static string GetDomainNameOnly(string s)
{
string domainOnly = "";
if (!string.IsNullOrEmpty(s))
{
if (s.Contains("."))
{
string domain = s.Substring(s.LastIndexOf('.', s.LastIndexOf('.') - 1) + 1);
string countryDomain = s.Substring(s.LastIndexOf('.'));
domainOnly = domain.Replace(countryDomain, "");
}
else
domainOnly = s;
}
return domainOnly;
}
WWW is an alias, so you don't need it if you want a domain.
Here is my litllte function to get the real domain from a string
private string GetDomain(string url)
{
string[] split = url.Split('.');
if (split.Length > 2)
return split[split.Length - 2] + "." + split[split.Length - 1];
else
return url;
}

Error while getting public data from twitter

String status;
IEnumerable<TwitterStatus> twitterStatus = twitterService.ListTweetsOnPublicTimeline();
foreach(String status in twitterStatus)
{
Console.WriteLine(twitterStatus);
}
Why it give can not convert string type error in foreach loop ?
this is my whole code
namespace TweetingTest
{
class Program
{
static void Main(string[] args)
{
TwitterClientInfo twitterClientInfo = new TwitterClientInfo();
twitterClientInfo.ConsumerKey = ConsumerKey; //Read ConsumerKey out of the app.config
twitterClientInfo.ConsumerSecret = ConsumerSecret; //Read the ConsumerSecret out the app.config
TwitterService twitterService = new TwitterService(twitterClientInfo);
if (string.IsNullOrEmpty(AccessToken) || string.IsNullOrEmpty(AccessTokenSecret))
{
//Now we need the Token and TokenSecret
//Firstly we need the RequestToken and the AuthorisationUrl
OAuthRequestToken requestToken = twitterService.GetRequestToken();
string authUrl = twitterService.GetAuthorizationUri(requestToken).ToString();
//authUrl is just a URL we can open IE and paste it in if we want
Console.WriteLine("Please Allow This App to send Tweets on your behalf");
//Process.Start(authUrl); //Launches a browser that'll go to the AuthUrl.
//Allow the App
Console.WriteLine("Enter the PIN from the Browser:");
string pin = Console.ReadLine();
OAuthAccessToken accessToken = twitterService.GetAccessToken(requestToken, pin);
string token = accessToken.Token; //Attach the Debugger and put a break point here
string tokenSecret = accessToken.TokenSecret; //And another Breakpoint here
Console.WriteLine("Write Down The AccessToken: " + token);
Console.WriteLine("Write Down the AccessTokenSecret: " + tokenSecret);
}
twitterService.AuthenticateWith(AccessToken, AccessTokenSecret);
//Console.WriteLine("Enter a Tweet");
//string tweetMessage;
//string data;
//string ListTweetsOnPublicTimeline;
//string TwitterUserStreamStatus = ListTweetsOnPublicTimeline();
//TwitterStatus=ListTweetsOnPublicTimeline();
//tweetMessage = Console.ReadLine();
//ListTweetsOnPublicTimeline = Console.ReadLine();
//TwitterStatus twitterStatus = twitterService.SendTweet(tweetMessage);
//TwitterStatus twitterStatus = twitterService.ListTweetsOnPublicTimeline();
//String status;
IEnumerable<TwitterStatus> tweets = twitterService.ListTweetsOnPublicTimeline();
foreach(var tweet in tweets)
{
Console.WriteLine(tweet);
//Console.WriteLine("{0} says '{1}'", tweet.User.ScreenName, tweet.Text);
}
//twitterStatus=Console.ReadLine();
}
This is my whole code on which I am working and facing just one error on foreach loop which is my lack of knowledge in C#
You will need something like this..
using TweetSharp;
TwitterService service = new TwitterService();
IEnumerable<TwitterStatus> tweets = service.ListTweetsOnPublicTimeline();
foreach (var tweet in tweets)
{
Console.WriteLine("{0} says '{1}'", tweet.User.ScreenName, tweet.Text);
}
Also try this code to see why it is failing.. try to debug response.StatusCode
using TweetSharp;
TwitterService service = new TwitterService();
IAsyncResult result = service.ListTweetsOnPublicTimeline(
(tweets, response) =>
{
if(response.StatusCode == HttpStatusCode.OK)
{
foreach (var tweet in tweets)
{
Console.WriteLine("{0} said '{1}'", tweet.User.ScreenName, tweet.Text);
}
}
});
More here : https://github.com/danielcrenna/tweetsharp
The object you are itterating through is of type "TwitterStatus", not string... so you are confusing it when you try to automatically cast a TwitterStatus object as a string.
Your question is very vague, so I'm going to assume your TitterStatus object has a "Text" property for the purposes of this answer.
foreach(TwitterStatus status in twitterStatus)
{
Console.WriteLine(status.Text);
}
(just replace the ".Text" with whatever property of TwitterStatus
holds the status text)

Categories

Resources