Google maps autocomplete textbox in c# - c#

I have a restaurant delivery WINFORM c# application where in user needs to enter the address, as to avoid human error we are trying to integrate google map's autocomplete functionality into textbox. I have googled and all I saw was for asp nothing for WINFORM. I tried one code however its namespace is missing and i am not sure which one it is
Namespace used :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Google.Api.Maps ;
using GoogleApi.Helpers;
Heres the code :
private void textBox1_TextChanged(object sender, EventArgs e)
{
var autoCompleteListCollection = new AutoCompleteStringCollection();
autoCompleteListCollection.AddRange(new GoogleApi.Instance.GetAddressPredictionsByInput(textBox1.Text).ToArray());
textBox1.AutoCompleteCustomSource = autoCompleteListCollection;
}
Error :
Error 1 The type or namespace name 'Instance' does not exist in the namespace 'GoogleApi' (are you missing an assembly reference?)
I think this might work. So please let me know right namespace or guide me how to achieve above requirement
Finally I got it to work, but it crashes the app, heres the code :
private void textBox1_TextChanged(object sender, EventArgs e)
{
string url = "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=" + var + "&types=geocode&key=YOURAPIKEY";
string content = fileGetContents(url);
JObject o = JObject.Parse(content);
List<string> add = new List<string>();
try
{
JObject jObj = (JObject)JsonConvert.DeserializeObject(content);
int count = jObj.Count;
for (int i = 0; i < count; i++)
{
add.Add((string)o.SelectToken("predictions["+i+"].description"));
}
var collection = new AutoCompleteStringCollection();
collection.AddRange(add.ToArray());
textBox1.AutoCompleteCustomSource = collection;
textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
}
catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); }
{
}
protected string fileGetContents(string fileName)
{
string sContents = string.Empty;
string me = string.Empty;
try
{
if (fileName.ToLower().IndexOf("https:") > -1)
{
System.Net.WebClient wc = new System.Net.WebClient();
byte[] response = wc.DownloadData(fileName);
sContents = System.Text.Encoding.ASCII.GetString(response);
}
else
{
System.IO.StreamReader sr = new System.IO.StreamReader(fileName);
sContents = sr.ReadToEnd();
sr.Close();
}
}
catch { sContents = "unable to connect to server "; }
return sContents;
}
Everytime I run after few attempts it crashes.
Thanks

Related

why can't I add a new List object in button event

why can't I add a new item/object to my list in button (or combobox etc.) events? I mean, the events don't see my list if it's outside of the brackets...it's underlined in red... can you help me?
long story short: i want to add a new object by clicking the button
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;
using System.IO;
namespace Samochody
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
List<Samochod> ListaSamochodow = new List<Samochod>();
comboBox1.DataSource = ListaSamochodow;
comboBox1.DisplayMember = "Marka";
XmlRootAttribute oRootAttr = new XmlRootAttribute();
XmlSerializer oSerializer = new XmlSerializer(typeof(List<Samochod>), oRootAttr);
StreamWriter oStreamWriter = null;
oStreamWriter = new StreamWriter("samochody.xml");
oSerializer.Serialize(oStreamWriter, ListaSamochodow);
}
private void button1_Click(object sender, EventArgs e)
{
try
{
ListaSamochodow.Add(new Samochod(textBox1.Text, textBox2.Text, Convert.ToInt32(textBox3.Text)));
}
catch (Exception oException)
{
Console.WriteLine("Aplikacja wygenerowała następujący wyjątek: " + oException.Message);
}
}
I think you should instantiate your list globally and not under Form1_Load event.
that way it will be accessible all around your class (the window in this case).
This seems to work fine. You might need to set your textboxes to contain valid values when you start the form. also make sure that you make the list visible throughout your form1 class.
namespace Samochody
{
public partial class Form1 : Form
{
// make sure your list looks like this, created outside your functions.
List<Samochod> ListaSamochodow = new List<Samochod>();
public Form1()
{
InitializeComponent();
label1.Text = "the amount in your list is " + ListaSamochodow.Count.ToString();
textBox1.Text = "string here";
textBox2.Text = "string here";
textBox3.Text = "100";
}
private void Form1_Load(object sender, EventArgs e)
{
XmlRootAttribute oRootAttr = new XmlRootAttribute();
XmlSerializer oSerializer = new XmlSerializer(typeof(List<Samochod>), oRootAttr);
StreamWriter oStreamWriter = null;
oStreamWriter = new StreamWriter("samochody.xml");
oSerializer.Serialize(oStreamWriter, ListaSamochodow);
}
private void button1_Click_1(object sender, EventArgs e)
{
Samochod s = new Samochod(textBox1.Text, textBox2.Text, Convert.ToInt32(textBox3.Text));
ListaSamochodow.Add(s);
label1.Text = "the amount in your list is " + ListaSamochodow.Count.ToString();
}
}
}

C# adapt code to a button click event

I am trying to adapt the following code so that the functionality is on a click event ...
Here is the code as is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string IN_FILENAME = #"c:\temp\testin.csv";
const string OUT_FILENAME = #"c:\temp\testout.csv";
static void Main(string[] args)
{
StreamReader reader = new StreamReader(IN_FILENAME);
StreamWriter writer = new StreamWriter(OUT_FILENAME);
string inputLine = "";
while ((inputLine = reader.ReadLine()) != null)
{
List<string> inputArray = inputLine.Split(new char[] { ',' }).ToList();
inputArray.Add(inputArray[3]);
writer.WriteLine(string.Join(",", inputArray));
}
reader.Close();
writer.Flush();
writer.Close();
}
}
}
Then I need to add the functionality to a click even so this is where I am:
private void button1_Click(object sender, EventArgs e)
{
const string IN_FILENAME = #"c:\temp\testin.csv";
const string OUT_FILENAME = #"c:\temp\testout.csv";
StreamReader reader = new StreamReader(IN_FILENAME);
StreamWriter writer = new StreamWriter(OUT_FILENAME);
}
and I can't do anymore because it's telling me StreamReader cannot be found.
Can anyone help me adapt this code to the click event?
The StreamReader is a class define in the System.IO namespace. Using this namespace at the start of your file, you would resolve it.
using System.IO;

foreach loop syntax error C# Visual Studio 2013 ultimate

Okay so yes I am doing homework and I am SO close on this one I know it, but ive been messing with it for over an hour and now I'm going insane, if i take the loop out my program will read the file and say weather you passed but it wont write the wrong answers in the listbox, if i put in my foreach code it gives me a syntax error.
this is my current code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace DriversLicenseExam
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] answerArray ={"B","D","A","A","C",
"A", "B","A","C","D",
"B", "C","D","A","D",
"C", "C","B","D","A"};
string[] studentansArray = new string[20];
List<string> incorrectList = new List<string>();
int count = 0, index = 0, qnumber = 0;
try
{
string filename = "../../" + filenametxt.Text;
StreamReader inputFile = File.OpenText(filename);
while(!inputFile.EndOfStream)
{
studentansArray[index] = inputFile.ReadLine();
if (studentansArray[index] == answerArray[index])
count++;
else
{
qnumber = index + 1;
incorrectList.Add(qnumber.ToString());
}
index++;
}
inputFile.Close();
if (count >= 15)
{
resultoutput.Text = "You Passed The Test!";
}
else
resultoutput.Text = "You Failed The Test... You're a Failure!";
}
foreach (string str in incorrectList) // <<-- error is here
{
lbox.Items.Add(str);
} // <<-- error is here
catch (Exception)
{
MessageBox.Show("File Not Found");
}
}
private void button2_Click(object sender, EventArgs e)
{
filenametxt.Text = "";
resultoutput.Text = "";
lbox.Items.Clear();
}
private void exitbutton_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
I'm not 100% sure about this, but your foreach is between your try and catch block, maybe try with that:
try
{
string filename = "../../" + filenametxt.Text;
StreamReader inputFile = File.OpenText(filename);
while(!inputFile.EndOfStream)
{
studentansArray[index] = inputFile.ReadLine();
if (studentansArray[index] == answerArray[index])
count++;
else
{
qnumber = index + 1;
incorrectList.Add(qnumber.ToString());
}
index++;
}
inputFile.Close();
if (count >= 15)
{
resultoutput.Text = "You Passed The Test!";
}
else
resultoutput.Text = "You Failed The Test... You're a Failure!";
foreach (string str in incorrectList)
{
lbox.Items.Add(str);
}
}
catch (Exception)
{
MessageBox.Show("File Not Found");
}

How to use C# to convert any file to some other arbitrary format(.rjb) & recover to original format?

This is my first question in Stackoverflow
I am trying to convert some files(.txt,.mp3,.mp4,.pdf,.png,.exe etc.) in a folder to a format .rjb, created by me. And I also want to recover the original files from the .rjb files. But every files other than .txt files get corrupted. Please help me, to accomplish this. The below code is what I am using.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace rjbformat
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
try
{
//string data = Convert.ToString(File.ReadAllBytes(textBox1.Text));
// string datas = File.ReadAllText(textBox1.Text);
//string dat = File.ReadAllText(textBox1.Text, Encoding.ASCII);
//var dataS = Convert.ToString(datas);
using (StreamWriter sw = new StreamWriter(textBox1.Text + ".rjb"))
{
sw.Write(textBox3.Text);
}
}
catch (Exception)
{
MessageBox.Show("Specified Input file DOESNOT EXIST!", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
//throw;
}
}
else
{
MessageBox.Show("Please select Input file");
}
}
private void button2_Click(object sender, EventArgs e)
{
openFileDialog1.Title = "Open Text File (Rajib)";
openFileDialog1.Filter = "Text Files(*.txt;*.cod;*.ubc)|*.txt;*.cod;*.ubc";
openFileDialog1.Filter = "All Files(*.*)|*.*";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
textBox2.Text = openFileDialog1.FileName + ".rjb";
File.Copy(textBox1.Text, textBox2.Text,true);
FileAccess.ReadWrite.ToString(textBox1.Text);
var lines = File.ReadAllLines(textBox1.Text);
/* foreach (string line in lines)
{
textBox3.Text += line+"\r\n";
}*/
File.AppendAllLines(textBox2.Text, lines);
// FileStream fs = new FileStream(textBox1.Text, FileMode.Open);
// int hexIn;
// String hex = "";
// for (int i = 0; i<50/*(hexIn = fs.ReadByte()) != -1*/; i++)
// {
// hex = string.Format("{0:X2}", fs.ReadByte());
// // int bina = fs.ReadByte();
// textBox3.Text += hex;
//}
}
}
}
}
If all you are doing is storing one or more files into your .rjb format and want to get them back intact, this sounds a lot like creating archive files. In that case, you may want to consider just using a standard zip file and customize the extension.
Here's an example using the ZipArchive class:
using System.IO.Compression;
namespace CustomZip
{
class Program
{
static void Main(string[] args)
{
string startPath = #"c:\example\start";
string zipPath = #"c:\example\result.rjb";
string extractPath = #"c:\example\extract";
ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
}
}
}
You will need to add a reference to System.IO.Compression.FileSystem to your project.

C# form instantly closing

All of a sudden my form window has begun to close as soon as the application is launched. There's nothing in the output window that gives a hint as to what could be causing it and there are no errors thrown at me either. Does anybody have any ideas?
I've provided to form's class.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ProjectBoardManagement {
public partial class CreateBoard : Form {
Functions funcs = new Functions();
public CreateBoard() {
InitializeComponent();
}
private void CreateBoardButton_Click(object sender, EventArgs e) {
String BoardName = BoardNameText.Text;
String Pages = "";
String Labels = "";
foreach (ListViewItem i in PageNameList.Items) {
Pages = (Pages + i.Name.ToString() + ",");
}
foreach (ListViewItem i in LabelNameList.Items) {
Labels = (Labels + i.Name.ToString() + ",");
}
String BoardFile = ("board_" + BoardName + ".txt");
funcs.SaveSetting(BoardFile, "name", BoardName);
funcs.SaveSetting(BoardFile, "pages", Pages);
funcs.SaveSetting(BoardFile, "labels", Labels);
FormManagement.CreateBoard.Hide();
FormManagement.BoardList.LoadBoardList();
}
private void PageNameButtonAdd_Click(object sender, EventArgs e) {
String pagename = PageNameText.Text;
if (pagename != "") {
PageNameList.Items.Add(pagename);
}
PageNameText.Text = "";
}
private void LabelNameButtonAdd_Click(object sender, EventArgs e) {
String labelname = LabelNameText.Text;
if (labelname != "") {
LabelNameList.Items.Add(labelname);
}
LabelNameText.Text = "";
}
}
}
Obvious first thing to do - run it in Debug mode and stop execution on all exceptions. This should give you enough information on how to go from there.
Otherwise Functions funcs = new Functions(); looks suspicious.

Categories