C# string equals wont work properly [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I get response string "true" from php file...
but ,my function always return false ... here is piece of code
public Boolean authorization(String korisnik, String zaporka) {
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["korisnik"] = korisnik;
values["zaporka"] = zaporka;
var response = client.UploadValues("http://localhost/projectX/autorizacija.php", values);
String responseString = Encoding.Default.GetString(response);
System.Diagnostics.Debug.WriteLine(responseString);
if (responseString.Equals("true"))
{
return true;
}
else
{
return false;
}
}
}

Try:
if (responseString.Trim().Equals("true", StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
else
{
System.Diagnostics.Debug.WriteLine(responseString);
return false;
}
InvariantCultureIgnoreCase = compares strings in a linguistically relevant manner that ignores case
Trim = remove whitespaces
And if false, check output value

Related

Check if cyclic string or not

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 hours ago.
Improve this question
Enter a string of characters S. Indicates whether the string S is cyclic or not.
For example S='abcdabcdabcdabcd' is cyclic.
My teacher want me to do this but i think it's too hard. I'm thinking using SplitString but it's just an idea and i dont know how to do. I'm very thankful if someone gives me help
using System;
using System.Collections;
public class MYCLASSNAME {
public static void Main(string[] args){
var str = "abcdabcdabcdabcd";
Console.Write(checkCyclicString(str));
}
static bool checkCyclicString (string str){
var checkString ="";
for(var i=0;i<str.Length-1;i++){
checkString= checkString+ str[i];
var countOfCycles =0;
var haveCycles = false;
for(var j=i+1;j<str.Length-checkString.Length+1;j= j+checkString.Length){
if(checkString==str.Substring(j,checkString.Length)){
haveCycles = true;
countOfCycles++;
}else{
haveCycles =false;
}
}
if(haveCycles && countOfCycles == Math.Ceiling((double)(str.Length/checkString.Length))-1){
return true;
}
}
return false;
}
}
check the cyclic behavior by creating substrigs and comparing them with all the parts of the given string

Unable to convert nested dictionaries from json back to c# using Json.Net [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am able to convert my nested dictionary to json but in attempting to use Json.Net.JsonNet.Deserialize<SortedDictionary<string, dynamic>>(js) it causes a null reference exception where js is loaded from a file containing: "{"Table":{"RowEntries":{}}}". Not sure what to do from here.
here is code to those it may concern:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (openFileDialog1.FileName != "" && openFileDialog1.FileName.EndsWith(".fdb"))
{
defaultPath = openFileDialog1.FileName;
js = #File.ReadAllText(openFileDialog1.FileName);
Console.WriteLine(js);
SortedDictionary<string, dynamic> cd;
try
{
cd = Json.Net.JsonNet.Deserialize<SortedDictionary<string, dynamic>>(js);
DatabaseFunct.currentData.Concat(cd);
//load tables
string[] mainTableKeys = DatabaseFunct.GetMainTableKeys();
foreach (string mainTableKey in mainTableKeys)
{
Program.mainForm.tabControl1.TabPages.Add(mainTableKey, mainTableKey);
}
//fileName = openFileDialog1.FileName.Remove(openFileDialog1.FileName.Length-4, openFileDialog1.FileName.Length);
Program.mainForm.label1.Visible = false;
//triggers event
Program.mainForm.tabControl1.SelectedIndex = 0;
}
catch(Exception e)
{
System.Windows.Forms.MessageBox.Show(e.Message);
}
}
else
{
System.Windows.Forms.MessageBox.Show("no valid file selected!");
}
}
Edit:
Was using the wrong Json.net package instead of the newtonsoft one.
Not sure what you are trying to achieve exactly, but based on provided json this should work:
class MyClass
{
public dynamic RowEntries { get; set; }
}
JsonNet.Deserialize<Dictionary<string, MyClass>>("{\"Table\":{\"RowEntries\":{}}}")

Console application that validates address [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
So I'm trying to figure out how to build a Console Application in C# that essentially mimics google maps. I need to be able to enter an address (even if I abbreviate a word. EX: Silverbell Dr) and output the correct spelling (Silverbell Drive).
The goal here is to be able to enter an address in the search, even if the address spelling is incorrect, and output a value that is close enough to the user input that it won't send back a null value.
If anyone has anything that is similar to this, I would greatly appreciate the help!
Boss gave me this assignment knowing that I hardly have a base knowledge on the subject
One way to do it would be to use Googles geocode API. You can pass it a partial address and it will do it's best to return the normalized address for you. If the address isn't very specific, you will get back more than one.
Here's a code example for calling the API and parsing the results:
private static List<string> GetNormalizedAddresses(string address)
{
// Generate request Uri
var baseUrl = "http://maps.googleapis.com/maps/api/geocode/xml";
var requestUri = $"{baseUrl}?address={Uri.EscapeDataString(address)}&sensor=false";
// Get response
var request = WebRequest.Create(requestUri);
var response = request.GetResponse();
var xDoc = XDocument.Load(response.GetResponseStream());
var results = xDoc.Element("GeocodeResponse")?.Elements("result").ToList();
var normalizedAddresses = new List<string>();
// Populate results
if (results != null)
{
normalizedAddresses.AddRange(results
.Select(result => result.Element("formatted_address")?.Value)
.Where(formattedAddress => !string.IsNullOrWhiteSpace(formattedAddress)));
}
return normalizedAddresses;
}
Then, you could call it like so:
while(true)
{
Console.Write("Enter a partial address: ");
var partialAddress = Console.ReadLine();
Console.WriteLine(new string ('-', 25 + partialAddress.Length));
var normalizedAddress = GetNormalizedAddresses(partialAddress);
if (!normalizedAddress.Any())
{
Console.WriteLine("Sorry, couldn't find anything.");
}
else
{
Console.WriteLine("That address normalizes to:");
Console.WriteLine($" - {string.Join($"\n - ", normalizedAddress)}");
}
Console.WriteLine("\n");
}
Output

C# Error Index was outside the bounds of the array [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have this code:
//other streamreader code
var splitsByLine = content.Split('\n');
foreach (var s in splitsByLine)
{
var nameAndSize = s.Split(',');
FileNameAndSizes.Add(nameAndSize[0], Convert.ToInt64(nameAndSize[1]));
}
foreach (var item in FileNameAndSizes)
{
if(File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "cleo", item.Key)))
{
FileInfo f = new FileInfo(Path.Combine(Directory.GetCurrentDirectory(), "cleo", item.Key));
var s1 = f.Length;
if (s1 != item.Value)
{
MessageBox.Show(f.Name + " modified file, please change it to default");
}
}
}
When I run code, i have error in this code:
FileNameAndSizes.Add(nameAndSize[0], Convert.ToInt64(nameAndSize[1]));
Index was outside the bounds of the array. and something about 0x0.. I'm C# newbie, how can i fix it?
It's content value:
AnimModByxXx2o1o.cs, 18616
anims.cs, 18780
Dance.cs, 18661
emergencylights.cs, 32213
fps-de-limiter.cs, 17575
neon.cs, 19019
StreamMemFix.cs, 17560
sun.cs, 17662
WEATHERMENUE.cs, 18437
anim.cs, 17637
anim[0].cs, 20684
anim_0_.cs, 19392
anim1.cs, 18744
anim2.cs, 19012
Anim4.cs, 22900
anim228.cs, 19465
P.S I'm tested it with two files:
First file (current) is getting value from mysql, prints it, and then I need to read value with C# app
Second file (working) is create custom file write to it this content, and it's work ok :?
You need to do simple tests to ensure your values before try to work with them:
http://ideone.com/Iyle5C
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class Test
{
public static void Main()
{
//other streamreader code
string[] splitsByLine = new string[] { "AnimModByxXx2o1o.cs, 18616",
"anims.cs, 18780",
"Dance.cs, 18661",
"emergencylights.cs, 32213",
"fps-de-limiter.cs, 17575",
"neon.cs, 19019",
"StreamMemFix.cs, 17560",
"sun.cs, 17662",
"WEATHERMENUE.cs, 18437",
"anim.cs, 17637",
"anim[0].cs, 20684",
"anim_0_.cs, 19392",
"anim1.cs, 18744",
"anim2.cs, 19012",
"Anim4.cs, 22900",
"anim228.cs, 19465",
"" };
if (splitsByLine != null && splitsByLine.Any()) // Test
{
foreach (string s in splitsByLine)
{
var nameAndSize = s.Split(',');
if (nameAndSize != null && nameAndSize.Any() && nameAndSize.Count() > 1) // Test
{
Console.WriteLine(String.Concat(nameAndSize[0], " - ", Convert.ToInt64(nameAndSize[1])));
//FileNameAndSizes.Add(nameAndSize[0], Convert.ToInt64(nameAndSize[1]));
}
}
}
}
}

XML File reading string failed [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm trying to read from XML file.
I success to read an int. but when I want to convert it so string it doesn't works. I would like to get some help.
XML:
<Data>
<ServerClient>1</ServerClient>
<ClientIP>127.0.0.1</ClientIP>
<ClientPort>11000</ClientPort>
</Data>
The function getType reads good the int in the XML file.
private XmlDocument doc;
public int getType()
{
try
{
// Open the file again
doc.Load("ServerClientXML.xml");
// Read port
XmlNode node = doc.SelectSingleNode("/Data/ServerClient");
return int.Parse(node.InnerText); // 0 = Server, 1 = Client
}
catch
{
return -1;
}
}
public string getIP()
{
string ip;
XmlNode node;
try
{
// Open the file again
doc.Load("ServerClientXML.xml");
int Type = getType();
if (Type == 1) // Client type
{
// Read IP
node = doc.SelectSingleNode("/Data/ServerClient/ClientIP");
ip = doc.InnerXml;
}
else // Server Type
{
// Read IP
node = doc.SelectSingleNode("/Data/ServerClient/ServerIP");
ip = doc.InnerXml;
}
return ip;
}
catch
{
return null;
}
}
I have tried to to like getType but without any success :
return node.InnerText.toString(); // 0 = Server, 1 = Client
Your XPath doesn't match provided XML. It should be /Data/ClientIP and /Data/ServerIP

Categories

Resources