Populating combobox using data from an API - c#

The idea of this program is to retrieve the employee user ID (or signature) from an API URL once the name has been entered.
Right now my program shows no errors, however when I press start, my combo box (labeled "Name") doesn't show any suggestion as it is intended to. I would like it suggest name when the user is typing names (similar to how google works).
I have tried the ComboBox.DisplayMember, ComboBox.ValueMember, and ComboBox.DataSource, However, my data source is taken from an API JSON.
Thank you for your help in advance.
This is my JSON string:
[{
"signature": "JANDOW",
"firstName": "Jane",
"fullName": "Dow, Jane",
"lastName": "Dow"
}
]
My forms code is
namespace TimeSheets_Try_11
{
public partial class Form1 : Form
{
WebAPI WA = new WebAPI();
public Form1()
{
InitializeComponent();
webBrowser1.Url = new Uri(StaticStrings.UrlIora);
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string sgname; string projectstring;
projectstring = comboBox1.Text.ToString();
sgname = WA.Getsignature(projectstring);
textBox2.Text = sgname;
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(AutoCompleteStringCollection combData)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
Code for calling out the JSON is:
namespace TimeSheets_Try_11.Controllers
{
class WebAPI
{
public string Getsignature(string name)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var cookies = FullWebBrowserCookie.GetCookieInternal(new Uri(StaticStrings.UrlIora), false);
WebClient wc = new WebClient();
wc.Encoding = System.Text.Encoding.UTF8;
wc.Headers.Add("Cookie:" + cookies);
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
wc.UseDefaultCredentials = true;
string uri = "";
uri = StaticStrings.UrlIora + name;
var response = wc.DownloadString(uri);
var status = JsonConvert.DeserializeObject<List<Employeename>>(response);
string signame = status.Select(js => js.signature).First();
return signame;
}
}
}
Code for defining variables is:
namespace TimeSheet_Try11_Models
{
public class Employeename
{
public string signature { get; set; }
public string firstName { get; set; }
public string fullName { get; set; }
public string lastName { get; set; }
}
public class Root
{
public List<Employeename> Employeename { get; set; }
}
}

Firstly, the JSON is an array. You need to change your method to accommodate for that:
public List<string> Getsignature(string name)
{
...
var status = JsonConvert.DeserializeObject<List<Employeename>>(response);
return status.Select(emp => emp.signature).ToList();
}
Then you need to bind up your ComboBox correctly:
private void button1_Click(object sender, EventArgs e)
{
comboBox1.DataSource = WA.Getsignature(textBox2.Text);
}

Related

Newtonsoft.Json.JsonReaderException: Unexpected character encountered

I am very new to Visual Studio. I am writing a program that will retrieve the signature of an employee from an API when their name is entered and a "Get user" button is clicked (e.g. if the employee name Jane Doe is entered, the signature "JNDO" will be retrieved from the API string when the name is entered and the button is clicked).
I have been able to read the data successfully with a text box; however, I would like to incorporate a combo-box, which suggests names as the user is typing (similar to Google).
When I try to run my code with a combo-box, the following is the error I get for my JSON:
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered
while parsing value: <. Path '', line 0, position 0.' This exception
was originally thrown at this call stack:
[External Code]
TimeSheets_Try_11.Controllers.WebAPI.Getsignature(string) in WebAPI.cs
TimeSheets_Try_11.Form1.button1_Click(object, System.EventArgs) in Form1.cs
[External Code]
My JSON string:
[{"signature":"JNDO","firstName":"Jane","fullName":"Doe,
Jane","lastName":"Doe"}]
Code for my Windows form:
namespace TimeSheets_Try_11
{
public partial class Form1 : Form
{
WebAPI WA = new WebAPI();
public Form1()
{
InitializeComponent();
webBrowser1.Url = new Uri(StaticStrings.UrlIora);
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
comboBox1.DataSource = WA.Getsignature(textBox2.Text);
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
Form2 p = new Form2();
p.ShowDialog();
}
}
}
Code calling out my JSON:
namespace TimeSheets_Try_11.Controllers
{
class WebAPI
{
public string Getsignature(string name)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var cookies = FullWebBrowserCookie.GetCookieInternal(new Uri(StaticStrings.UrlIora), false);
WebClient wc = new WebClient();
wc.Encoding = System.Text.Encoding.UTF8;
wc.Headers.Add("Cookie:" + cookies);
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
wc.UseDefaultCredentials = true;
string uri = "";
uri = StaticStrings.UrlIora + name;
var response = wc.DownloadString(uri);
var status = JsonConvert.DeserializeObject<List<Employeename>>(response);
string signame = status.Select(js => js.signature).First();
return signame;
}
Code Defining the variables in my JSON:
namespace TimeSheet_Try11_Models
{
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class Employeename
{
public string signature { get; set; }
public string firstName { get; set; }
public string fullName { get; set; }
public string lastName { get; set; }
}
public class Root
{
public List<Employeename> Employeename { get; set; }
}
}

How to code a combobox with suggest ability using data from an API?

I would like to start by saying that I am not a developer and this is my very first time writing a code to this extend of complication (at least to me). Any help/guidance would be much appreciated.
The idea of this program is to retrieve the employee user ID (or signature) from an API URL once the name has been entered.
Right now my program shows no errors, however when I press start, my combo box (labeled "Name") doesn't show any suggestion as it is intended and no information is shown in textBox 2 (labeled "user ID").
I would like to add that initially I had a text box instead of a combo box, and I was able to retrieve data correctly then. The issue occurred when I switched to the combo box. Thank you in advance.
This is my JSON string:
[{"signature":"JANDOW","firstName":"Jane","fullName":"Dow, Jane","lastName":"Dow"}]
My forms code is:
namespace TimeSheets_Try_11
{
public partial class Form1 : Form
{
WebAPI WA = new WebAPI();
public Form1()
{
InitializeComponent();
webBrowser1.Url = new Uri(StaticStrings.UrlIora);
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string sgname; string projectstring;
projectstring = comboBox1.Text.ToString();
sgname = WA.Getsignature(projectstring);
textBox2.Text = sgname;
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
The code for calling out the API is:
namespace TimeSheets_Try_11.Controllers
{
class WebAPI
{
public string Getsignature(string name)
{
var cookies = FullWebBrowserCookie.GetCookieInternal(new Uri(StaticStrings.UrlIora), false);
WebClient wc = new WebClient();
wc.Encoding = System.Text.Encoding.UTF8;
wc.Headers.Add("Cookie:" + cookies);
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
wc.UseDefaultCredentials = true;
string uri = "";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
uri = StaticStrings.UrlIora + name + "&%24format=json&%24top=30&%24filter=status%20eq%20%27Active%27&%24count=true";
var response = wc.DownloadString(uri);
var status = JsonConvert.DeserializeObject<List<Employeename>>(response);
string signame = status.Select(js => js.signature).FirstOrDefault();
return signame;
}
}
}
My code for defining the variables is:
namespace TimeSheet_Try11_Models
{
public class Employeename
{
public string signature { get; set; }
public string firstName { get; set; }
public string fullName { get; set; }
public string lastName { get; set; }
}
public class Root
{
public List<Employeename> Employeename { get; set; }
}
}

How to connect Windows Azure Database to Microsoft Visual Studio 2012 - Windows Phone 8 project

I am a Final Year Computer Science student trying to develop a Windows 8 phone app and I am very new to this type of development.
I am using a Windows Azure account with a mobile service and a database connection to connect to Visual Studio 2012.
I am trying to allow users to create an account to use my app, however when they enter any details they are not being saved to the table in the database. I am getting the following debugging error when I run my code and press the register button:
"Application_UnhandledException"
Below is what my code looks like.
This is from the CreateAccount.xaml.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.WindowsAzure.MobileServices;
using Newtonsoft.Json;
namespace IME.Miscellaneous
{
public class accountDetails
{
// Setting up the items for inclusion in the createAccount table
public string Id { get; set; }
[JsonProperty(PropertyName = "userpassword")]
public string Password { get; set; }
[JsonProperty(PropertyName = "securityQuestion1")]
public string SecurityQuestion1 { get; set; }
[JsonProperty(PropertyName = "securityQuestion2")]
public string SecurityQuestion2 { get; set; }
[JsonProperty(PropertyName = "securityQuestion3")]
public string SecurityQuestion3 { get; set; }
[JsonProperty(PropertyName = "answer1")]
public string SecurityAnswer1 { get; set; }
[JsonProperty(PropertyName = "answer2")]
public string SecurityAnswer2 { get; set; }
[JsonProperty(PropertyName = "answer3")]
public string SecurityAnswer3 { get; set; }
}
public partial class CreateAccount : PhoneApplicationPage
{
private MobileServiceCollection<accountDetails, accountDetails> items;
private IMobileServiceTable<accountDetails> accountTable = App.MobileService.GetTable<accountDetails>();
public CreateAccount()
{
InitializeComponent();
}
private async void InsertAccountInfo(accountDetails accountDetailsItem)
{
// This code inserts a new item into the database. When the operation completes
// and Mobile Services has assigned an Id, the item is added
await accountTable.InsertAsync(accountDetailsItem);
items.Add(accountDetailsItem);
}
private async void RefreshAccountInfo()
{
// This code refreshes the entries in the list view be querying the createAccount table.
try
{
items = await accountTable
.Where(accountDetailsItem => accountDetailsItem.Password == "")
.ToCollectionAsync();
}
catch (MobileServiceInvalidOperationException e)
{
MessageBox.Show(e.Message, "Error loading items", MessageBoxButton.OK);
}
}
private void Register_Button_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
// Brings the user to the Home hub page
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
// When button is clicked the accountDetails table is updated with the password
//var user = new accountDetails { Id = ID_textbox.Text, Password = Password_Text.Password, SecurityQuestion1 = Security_Question_1.Text, SecurityQuestion2 = Security_Question_2.Text,
// SecurityQuestion3 = Security_Question_3.Text, SecurityAnswer1 = Security_Question_1_Answer.Text, SecurityAnswer2 = Security_Question_2_Answer.Text,
// SecurityAnswer3 = Security_Question_3_Answer.Text};
// InsertAccountInfo(user);
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
RefreshAccountInfo();
}
private void Security_Question_1_Answer_GotFocus(object sender, RoutedEventArgs e)
{
// Sets the textbox to empty when the user clicks on it
TextBox securityAnswerOne = (TextBox)sender;
securityAnswerOne.Text = string.Empty;
securityAnswerOne.GotFocus -= Security_Question_1_Answer_GotFocus;
}
private void Security_Question_2_Answer_GotFocus(object sender, RoutedEventArgs e)
{
// Sets the textbox to empty when the user clicks on it
TextBox securityAnswerTwo = (TextBox)sender;
securityAnswerTwo.Text = string.Empty;
securityAnswerTwo.GotFocus -= Security_Question_2_Answer_GotFocus;
}
private void Security_Question_3_Answer_GotFocus(object sender, RoutedEventArgs e)
{
// Sets the textbox to empty when the user clicks on it
TextBox securityAnswerThree = (TextBox)sender;
securityAnswerThree.Text = string.Empty;
securityAnswerThree.GotFocus -= Security_Question_3_Answer_GotFocus;
}
private void Security_Question_3_Answer_LostFocus(object sender, RoutedEventArgs e)
{
TextBox securityAnswerThree = (TextBox)sender;
if (String.IsNullOrEmpty(Security_Question_3_Answer.Text))
{
securityAnswerThree.Text = "Please Enter an answer";
securityAnswerThree.LostFocus -= Security_Question_3_Answer_LostFocus;
}
}
private void Security_Question_2_Answer_LostFocus(object sender, RoutedEventArgs e)
{
TextBox securityAnswerTwo = (TextBox)sender;
if (String.IsNullOrEmpty(Security_Question_2_Answer.Text))
{
securityAnswerTwo.Text = "Please Enter an answer";
securityAnswerTwo.LostFocus -= Security_Question_2_Answer_LostFocus;
}
}
private void Security_Question_1_Answer_LostFocus(object sender, RoutedEventArgs e)
{
TextBox securityAnswerOne = (TextBox)sender;
if (String.IsNullOrEmpty(Security_Question_3_Answer.Text))
{
securityAnswerOne.Text = "Please Enter an answer";
securityAnswerOne.LostFocus -= Security_Question_3_Answer_LostFocus;
}
}
}
}
This is from the App.xaml.cs file:
// Creating account details table
public class accountDetails
{
public int id { get; set; }
public string userpassword { get; set; }
public string securityQuestion1 { get; set; }
public string securityQuestion2 { get; set; }
public string securityQuestion3 { get; set; }
public string answer1 { get; set; }
public string answer2 { get; set; }
public string answer3 { get; set; }
public accountDetails(string p, string sq1, string sq2, string sq3, string a1, string a2, string a3)
{
// Creating the constructor
userpassword = p;
securityQuestion1 = sq1;
securityQuestion2 = sq2;
securityQuestion3 = sq3;
answer1 = a1;
answer2 = a2;
answer3 = a3;
}
}
The table in the database is called "CreateAccount" also.
Any help would be greatly appreciated.

How to get all cell values form a Property Grid c#

I have a property Grid as follows:
I want to copy the complete content of the property grid to a data grid view(dataGeriView1) when submit button is clicked.
How to do this?
Please help.
private void Submit_Click(object sender, EventArgs e)
{
//propertyGrid1.SelectedObject = this;
dataGridView1.Columns.Add("Property", "Property");
dataGridView1.Columns.Add("Value", "Value");
GridItem gi = propertyGrid1.SelectedGridItem;
while (gi.Parent != null)
gi = gi.Parent;
foreach (GridItem item in gi.GridItems)
ParseGridItems(item); //recursive
dataGridView1.Sort(dataGridView1.Columns["Property"], ListSortDirection.Ascending);
}
private void ParseGridItems(GridItem gi)
{
if (gi.GridItemType == GridItemType.Category)
foreach (GridItem item in gi.GridItems)
ParseGridItems(item);
dataGridView1.Rows.Add(gi.Label, gi.Value);
}
Adapted from https://stackoverflow.com/a/12109186/1163434
Below is a sample snippet i have created to solve the above issue. Create a DataGridview by adding Columns Name,Age,Email,Phone.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Student std = new Student {Name = "Vimal" , Phone = "PhoneValue", Email="mymail",Age=24};
propertyGrid1.SelectedObject= std;
}
private void button1_Click(object sender, EventArgs e)
{
int index = dataGridView1.Rows.Count - 1;
Student std = (Student)propertyGrid1.SelectedObject;
dataGridView1.Rows[index].Cells["Name"].Value = std.Name;
dataGridView1.Rows[index].Cells["Age"].Value = std.Age;
dataGridView1.Rows[index].Cells["Email"].Value = std.Email;
dataGridView1.Rows[index].Cells["Phone"].Value = std.Phone;
}
}
public class Student
{
public int Age { get; set; }
public string Email { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
}

Get back panel from clipboard

This is my class, I always get a null insted of my panel...
Can someone give me a hint on how to do this?
[Serializable]
public class DragDropBlock : Panel
{
public DragDropBlock()
{
this.MouseDown += new MouseEventHandler(Mouse_Down);
this.MouseUp += new MouseEventHandler(Mouse_Up);
}
void Mouse_Down(object sender, System.Windows.Forms.MouseEventArgs e)
{
Clipboard.SetData("DragDropBlock", this);
}
void Mouse_Up(object sender, System.Windows.Forms.MouseEventArgs e)
{
IDataObject IBlock = Clipboard.GetDataObject();
DragDropBlock Block = (DragDropBlock)IBlock.GetData(typeof(DragDropBlock));
}
}
Given a class:
[Serializable]
class Test
{
public string Data
{
get;
set;
}
}
This works:
Test t = new Test()
{
Data = "DERP!"
};
Clipboard.SetData("Test", t);
Test newT = (Test)Clipboard.GetData("Test");
Console.WriteLine(newT.Data);
And if you want to use data objects:
Test t = new Test()
{
Data = "DERP!"
};
Clipboard.SetDataObject(new DataObject("Test", t));
Test newT = (Test)Clipboard.GetDataObject().GetData("Test");
Console.WriteLine(newT.Data);
The output to both of those is:
DERP!
This is the correction of my class: Working!!!
[Serializable]
class DragBlock
{
public string Data
{
get;
set;
}
}
public class DragDropBlock : Panel
{
DragBlock Block;
public DragDropBlock()
{
this.MouseDown += new MouseEventHandler(Mouse_Down);
this.MouseUp += new MouseEventHandler(Mouse_Up);
Block = new DragBlock()
{
Data = "TEST!"
};
}
void Mouse_Down(object sender, System.Windows.Forms.MouseEventArgs e)
{
Clipboard.SetDataObject(new DataObject("DragBlock", Block));
}
void Mouse_Up(object sender, System.Windows.Forms.MouseEventArgs e)
{
DragBlock newBlock = (DragBlock)Clipboard.GetDataObject().GetData("DragBlock");
Console.WriteLine(newBlock.Data);
}
}

Categories