Drag and Drop List Items (with multi selection) - mysql

I need populate the ListBox with items from JSON data, dynamic and coming from Asp.Net and MySQL database.
I've come across some snippets of code on the internet but none seem to be working with my needs.
I don't have error but the ListBox is empty.
My code below.
How to do resolve this?
Thanks!
protected string GetJsonData()
{
string query = "SELECT * FROM City ORDER BY NAME DESC LIMIT 5;";
string constr = ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand(query))
{
List<ListItem> customers = new List<ListItem>();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(new ListItem
{
Value = sdr["Name"].ToString(),
Text = sdr["Name"].ToString()
});
}
}
con.Close();
JavaScriptSerializer jsSer = new JavaScriptSerializer();
string str = jsSer.Serialize(customers);
return str;
}
}
<script type="text/javascript">
$(function () {
//Get data and fill first box
var $json = <% =GetJsonData() %>;
pageload($json);
});
</script>
<div id="list1" class="connectedSortable">
<asp:ListBox ID="lstCustomers" runat="server"></asp:ListBox>
</div>
<div id="list2" class="connectedSortable">
</div>

Then you can read the database query into a reader and fill the objects into a list, like this:
public class Movie
{
public string MovieID { get; set; }
public string MovieName { get; set; }
public string MovieLength { get; set; }
public string MovieDesc { get; set; }
}
List<Movie> listOfMovies = new List<Movie>();
using(SqlConnection connection = new SqlConnection("Data Source=balder.ucn.dk;Initial Catalog=dmaa0213_6;********"))
{
using(SqlCommand cmd = new SqlCommand(connection))
{
cmd.CommandString = "SELECT * FROM movies ORDER BY MovieId";
connection.Open();
using(SqlDataReader reader = cmd.ExecuteDataReader())
{
while(reader.Read())
{
Movie item = new Movie();
item.MovieId = reader.GetInt32(0);
item.MovieName = reader.GetString(1);
item.MovieLength = reader.GetString(2);
item.MovieDesc = reader.GetString(3);
listOfMovies.Add(item);
}
}
connection.Close();
}
}

Related

CsvHelper wrap all values with quotes

I am using CsvHelper I need to wrap all values with quotes.
Is that possible?
Data = is a List
using (StreamWriter textWriter = new StreamWriter(path))
{
textWriter.BaseStream.Write(p, 0, p.Length);
// var dt = new DataTable();
var csv = new CsvWriter(textWriter);
csv.WriteRecords(Data);
textWriter.Flush();
textWriter.Close();
}
Thanks
There is a config value called ShouldQuote where you can determine on a field level if it should be quoted.
void Main()
{
var records = new List<Foo>
{
new Foo { Id = 1, Name = "one" },
new Foo { Id = 2, Name = "two" },
};
using (var writer = new StringWriter())
using (var csv = new CsvWriter(writer))
{
csv.Configuration.ShouldQuote = (field, context) => true;
csv.WriteRecords(records);
writer.ToString().Dump();
}
}
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}
Output:
"Id","Name"
"1","one"
"2","two"
From version 25.0.0 up to the date, the way of doing it is:
var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
ShouldQuote = args => true
};
Just need to add a configuration object. like this
CsvHelper.Configuration.CsvConfiguration config = new CsvHelper.Configuration.CsvConfiguration();
config.QuoteAllFields = true;
var csv = new CsvWriter(textWriter, config);

How to get only specified item of list?

I extract the following data from database with the following MySql Query:
SELECT vs.value, vs.is_header, vsa.is_required, vsa.name, vsar.value
FROM vista_struttura AS vs
LEFT JOIN vista_struttura_attributi AS vsa
ON vs.id_vista_struttura = vsa.id_vista_struttura
LEFT JOIN vista_struttura_attributi_raccordi AS vsar
ON vsa.input_type = vsar.input_type
ORDER BY vs.sort;
Data extracted are
I have to save this data in a model built from myself with the following code:
var model = new List<Header>();
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
var sql = "SELECT vs.value, vs.is_header, vsa.is_required, vsa.name, vsar.value " +
"FROM vista_struttura AS vs " +
"LEFT JOIN vista_struttura_attributi AS vsa " +
"ON vs.id_vista_struttura = vsa.id_vista_struttura " +
"LEFT JOIN vista_struttura_attributi_raccordi AS vsar " +
"ON vsa.input_type = vsar.input_type " +
"ORDER BY vs.sort";
var cmd = new MySqlCommand(sql, connection);
var rdr = cmd.ExecuteReader();
var rows = new List<ViewProperties>();
while (rdr.Read())
{
var value = rdr[0].ToString();
var isHeader = Convert.ToBoolean(rdr[1]);
var isRequired = (rdr[2] == DBNull.Value) ? (bool?) null : Convert.ToBoolean(rdr[2]);
var name = rdr[3].ToString();
var inputType = rdr[4].ToString();
var properties = new ViewProperties()
{
Value = value,
IsHeader = isHeader,
IsRequired = isRequired,
Name = name,
InputType = inputType
};
rows.Add(properties);
var header = new Header()
{
HeaderValue = (properties.IsHeader == true) ? properties.Value : null,
Rows = rows
};
if (header.HeaderValue != null)
{
model.Add(header);
}
}
}
Models
Header
public class Header
{
public string HeaderValue { get; set; }
public IList<ViewProperties> Rows { get; set; }
}
ViewProperties
public class ViewProperties
{
public string Value { get; set; }
public bool IsHeader { get; set; }
public bool? IsRequired { get; set; }
public string Name { get; set; }
public string InputType { get; set; }
}
Debugging the app I get a wrong model, not such as I want...
I want to get first 4 rows for first header and the other last 3 rows for the second header.
How can i do?
What's better to do: before get this model and then handle it with linq, or get already correct model?
Thanks
You need the following code for the desired result, make the necessary modifications:
var rows = new List<ViewProperties>(); // ViewProperties List
// Segregate null value, GroupBy to aggregate using Value
var viewPropertiesGrouping = rows.Where(x => x.IsHeader)
.GroupBy(x => x.Value);
// Traverse through IEnumerable<IGrouping<string,ViewProperties>>, created above and fill the Header object and add to the Model
foreach (var prop in viewPropertiesGrouping)
{
Header header = new Header();
header.HeaderValue = prop.Key;
header.Rows = prop.Select(y => y).ToList();
model.Add(header);
}

Remove an item from listbox in WP8

I'm new to windows phone development. I'm trying to delete selected item from the list box. I've got dataclass
public class MyDataClass
{
public string MSG { get; set; }
public int Id { get; set; }
}
Then I try to delete the selected item (Button1_Click event)
MyDataClass item = MyDict.SelectedItem as MyDataClass;
ObservableCollection dataList = new ObservableCollection();
dataList.Remove(item);
The problem in creating the datalist in task, so it's no availble for the rest of the program, how to change this?
public async Task GETFROMDB()
{
int a = 1;
Database database = new Database(ApplicationData.Current.LocalFolder, "DictData.db");
await database.OpenAsync();
string query = "SELECT * FROM MyDICT";
Statement statement = await database.PrepareStatementAsync(query);
statement.EnableColumnsProperty();
ObservableCollection<MyDataClass> dataList = new ObservableCollection<MyDataClass>();
while (await statement.StepAsync())
{
rawData = string.Format(statement.Columns["value"]);
string[] sep = new string[] { "\r\n" }; //Splittng it with new line
string[] arrData = rawData.Split(sep, StringSplitOptions.RemoveEmptyEntries);
foreach (var d in arrData)
{
dataList.Add(new MyDataClass() { MSG = d, Id= a });
a++;
}
}
MyDict.ItemsSource = dataList;
}
Can you make binding to a dataList outside the Task and make dataList static or reference to it in a Task?
When creating a list:
static ObservableCollection<MyDataClass> dataList = new ObservableCollection<MyDataClass>();
MyDict.ItemsSource = dataList;
Then in Task:
public async Task GETFROMDB()
{
int a = 1;
Database database = new Database(ApplicationData.Current.LocalFolder, "DictData.db");
await database.OpenAsync();
string query = "SELECT * FROM MyDICT";
Statement statement = await database.PrepareStatementAsync(query);
statement.EnableColumnsProperty();
while (await statement.StepAsync())
{
rawData = string.Format(statement.Columns["value"]);
string[] sep = new string[] { "\r\n" }; //Splittng it with new line
string[] arrData = rawData.Split(sep, StringSplitOptions.RemoveEmptyEntries);
foreach (var d in arrData)
{
dataList.Add(new MyDataClass() { MSG = d, Id= a });
a++;
}
}
}
Then in Click:
MyDataClass item = MyDict.SelectedItem as MyDataClass;
dataList.Remove(item);
Or make it:
When creating a list:
ObservableCollection<MyDataClass> dataList = new ObservableCollection<MyDataClass>();
MyDict.ItemsSource = dataList;
Then in Task:
public async Task GETFROMDB(ObservableCollection<MyDataClass> dataList)
{
int a = 1;
Database database = new Database(ApplicationData.Current.LocalFolder, "DictData.db");
await database.OpenAsync();
string query = "SELECT * FROM MyDICT";
Statement statement = await database.PrepareStatementAsync(query);
statement.EnableColumnsProperty();
while (await statement.StepAsync())
{
rawData = string.Format(statement.Columns["value"]);
string[] sep = new string[] { "\r\n" }; //Splittng it with new line
string[] arrData = rawData.Split(sep, StringSplitOptions.RemoveEmptyEntries);
foreach (var d in arrData)
{
dataList.Add(new MyDataClass() { MSG = d, Id= a });
a++;
}
}
}
Then in Click:
MyDataClass item = MyDict.SelectedItem as MyDataClass;
dataList.Remove(item);
Of course you need to wait until the Task is finished.
you appear to be trying to remove the item from a brand new collection - try instead to remove it from the one that your listbox is data bound to.
Try using the button data context
like this
in your click handler
private void ButtonClick(object sender, RoutedEventArgs e)
{
Button btn = sender as Button;
if (btn != null)
{
MyDataClass item = btn.DataContext as MyDataClass;
dataList.Remove(item);
}
}

How can I read this json on windows phone 8?

I'm trying to read the following json in a windows phone app using newtonsoft.json
I can't read anything. the also looks pretty strange to me.
{"type": "Menu","menu":
[{"0":"antipasto","tipo_piatto":"antipasto","1":"porchetta","nome_piatto":"porchetta","2":"1","prezzo":"1"},
{"0":"primo","tipo_piatto":"primo","1":"matriciana","nome_piatto":"matriciana","2":"5","prezzo":"5"},
{"0":"secondo","tipo_piatto":"secondo","1":"salsicce","nome_piatto":"salsicce","2":"4","prezzo":"4"},
{"0":"contorno","tipo_piatto":"contorno","1":"patate","nome_piatto":"patate","2":"2","prezzo":"2"},
{"0":"dolce","tipo_piatto":"dolce","1":"gelato","nome_piatto":"gelato","2":"6","prezzo":"6"}]}
this is my c# code for now
public class piatto_menu_giorno
{
public string tipo_piatto { get; set; }
public string nome_piatto { get; set; }
public string prezzo { get; set; }
}
public menu()
{
InitializeComponent();
WebClient webClient = new WebClient();
Uri uri = new Uri("http://www.stepapp.it/areacli/extDevice/getMenuOdierno_101.php");
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(fine_lettura_web);
webClient.OpenReadAsync(uri);
}
private void fine_lettura_web(object sender, OpenReadCompletedEventArgs e)
{
DataContractJsonSerializer json = null;
json = new DataContractJsonSerializer(typeof(ObservableCollection<piatto_menu_giorno>));
ObservableCollection<piatto_menu_giorno> menu = json.ReadObject(e.Result) as ObservableCollection<piatto_menu_giorno>;
if(menu==null)
menu_giorno.Text = "null";
else
foreach (piatto_menu_giorno piatto in menu)
{
menu_giorno.Text += piatto.nome_piatto + "\n";
}
}
sorry for all the variables name that are in italian
I am writing a code for you it will help you to deserialize the object from json to yourClassCustomObject.
private async Task<List<piatto_menu_giorno>> MyDeserializerFunAsync()
{
List<piatto_menu_giorno> book = new List<piatto_menu_giorno>();
try
{
//I am taking my url from appsettings. myKey is my appsetting key. You can write direct your url.
string url = (string)appSettings["mykey"];
var request = HttpWebRequest.Create(url) as HttpWebRequest;
request.Accept = "application/json;odata=verbose";
var factory = new TaskFactory();
var task = factory.FromAsync<WebResponse>(request.BeginGetResponse,request.EndGetResponse, null);
var response = await task;
Stream responseStream = response.GetResponseStream();
string data;
using (var reader = new System.IO.StreamReader(responseStream))
{
data = reader.ReadToEnd();
}
responseStream.Close();
DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(List<piatto_menu_giorno>));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(data));
book = (List<piatto_menu_giorno>)json.ReadObject(ms);
return book;
}
}
Above code is working in my wp8 application it is faster you can try, it will help you. I am performing asynchronous operation but you can create your simple method with piatto_menu_giorno return type.

'Cannot bind to the new value member. Parameter name: newDisplayMember'.

I'm using C# in Visual Studio 2010. I have 2 comboboxes that pull data from the database. The code looks something like this:
cbo1.DisplayMember = "Name";
cbo1.ValueMember = "HROfficeLocationID";
cbo1.DataSource = offices;
cbo2.DisplayMember = "Name";
cbo2.ValueMember = "HROfficeLocationID";
cbo2.DataSource = offices;
I kept getting this exception: 'Cannot bind to the new value member. Parameter name: newDisplayMember'. I searched around and then reorganized the lines of code so that cbo.DataSource came before .DisplayMember and .ValueMember .It ended up looking something like this:
cbo1.DataSource = offices;
cbo1.DisplayMember = "Name";
cbo1.ValueMember = "HROfficeLocationID";
cbo2.DataSource = offices;
cbo2.DisplayMember = "Name";
cbo2.ValueMember = "HROfficeLocationID";
The exception went away. Just thought I'd share.
I had this occur when the internal class I was using had the varialbles as "internal". Changed them to "public" and it worked fine.
Specify as a Property, not as a variable in a class for example,
public class projectData
{
public string ProjName { get; set; }
public string ProjId { get; set; }
}
List<projectData> projects = getProjects();
lBoxFDTProjects.DataSource = projects;
lBoxFDTProjects.ValueMember = "ProjId";
lBoxFDTProjects.DisplayMember = "ProjName";
Some property attributes also cause this error like the [Browsable(false)]
public class CmbStringItem
{
public CmbStringItem(string text, string val)
{
Text = text;
Value = val;
}
private string text;
public string Text
{
get {return text;}
set {text = value;}
}
private string val;
[System.ComponentModel.BrowsableAttribute(true)] // must use
public string Value
{
get {return val;}
set {val = value;}
}
public override string ToString()
{
return Text;
}
}
List<CmbStringItem> items = new List<CmbStringItem>();
items.Add(new CmbStringItem("Onula", "0"));
items.Add(new CmbStringItem("Jedna", "1"));
items.Add(new CmbStringItem("Dva", "2"));
items.Add(new CmbStringItem("Tri", "3"));
this.cmbSklad.DataSource = items;
this.cmbSklad.ValueMember = "Value";
this.cmbSklad.DisplayMember = "Text";
this.cmbSklad.SelectedIndex = 0;
// set Chombobox - Display vlaue
cmbSklad.SelectedValue = "1";