How to get only specified item of list? - mysql

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);
}

Related

Signing the Header and Payload with json private key in C#

I have to generate a Client assertion string signing with the json private key.
I have the private key in the private.json file. How do I use the private key in the file to sign the Header and payload?
Except the signing part, I have managed to get the other things to work. Following is the code I use for getting the Signed Client assertion string
public string GetSignedClientAssertion()
{
var header = new Dictionary<string, string>()
{
{ "typ" , "JWT"},
{ "alg", "ES512"},
{ "kid", "TST_Staging" }
};
string token = Encode(Encoding.UTF8.GetBytes(JObject.FromObject(header).ToString())) + "." + Encode(Encoding.UTF8.GetBytes(JObject.FromObject(GetClaims()).ToString()));
var rsa = new RSACryptoServiceProvider();
var filename = System.Web.HttpContext.Current.Server.MapPath("Private.json");
string data = File.ReadAllText(filename);
string key = Encode(Encoding.UTF8.GetBytes(data));
byte[] databyte = File.ReadAllBytes(filename);
//-----I am stuck here on how to sign the token with the Private key from the private.key file
//---the method used for SignData does not work
string signature = SignData(token, data);
signature = Encode(Encoding.UTF8.GetBytes(signature));
return signedClientAssertion = string.Concat(token, ".", signature);
}
Private.json has something like the following
{
"kty": "EC",
"d": "AfJ_hlRFCP0g2PghjghjghjtryrtytyFpbALpoG0gqh9tyaSv8JIZuhKYOgvbAzkI6pi2gdCce3fvWb5csiL24PiS9Ke5CKlh3QyW-YOO",
"use": "sig",
"crv": "P-521",
"kid": "TST_Staging",
"x": "ADRSCG8Acsqj6SlShpEJYa9UhA7ojghjgjK4eUVHj9CDqbH4j2_F84j7qtK4fdH94xGzYqQwV0rLfJrAISknoudPQm743H",
"y": "AYnLkWp3Up69WQoc-kZ8ugvSiCNChMiBra3jLHmSotDdzSJ6MgMCokfRdHsfsF-z4VAGq3zam1Z604_rC5N9xrtyrtyufV",
"alg": "ES512"
}
Can someone point out how to sign the token with the Private key will be much helpful. Thanks.
I have managed to find the solution myself. I am using EC Json public and private keys. Previously I was using the Algorithm ES512 which had some issues while decrypting the JWE response from the server, so I had changed my JWT key algorithm to ES256 and with this encryption and decryption works perfectly with Jose.JWT.
I have been struggling for more than a month to find a solution for the EC Json Public and private key Encryption and Decryption. All the solution available out there was for PEM key method only and nothing much for the Json EC keys. It took me a lot of time find the necessary pieces and put them together and make it work. I am providing the entire code for the page where the encryption and decryption happens, so that someone might find it useful.
using System.Net;
using System.Text; // For class Encoding
using System.IO; // For StreamReader
using System;
using System.Collections.Generic;
using System.Configuration;
using Jose;
using System.Security.Cryptography;
using System.Web;
using Jose.keys;
using Stream = System.IO.Stream;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
public partial class holding : System.Web.UI.Page
{
string ClientID = "mlDBKnXXXXXTYRTYRTYyYdmzFGD6HcBPsHZ2W";
string RemoteURL = "https://www.example.org";
string RemoteTokenAppend = "/token";
string RedirectURL = "https://www.exampleabc.com/holding.aspx";
//-----private key for Encrypting the token
string PrivateKey = #"
{
""x"": ""4kELRTR545GDGDGtvilOLrtr5luaQaWgaTlpqUf7o"",
""y"": ""iCyNdwX73FWKJTjn1Q19gdjEILKjEILK3Y_XwgY3Y_XwgY"",
""d"": ""wiYrwNa5SgBNgdqRtSMpaUvRmipaBJ6hfmL1CUMpwlQ"",
""kty"": ""EC"",
""crv"": ""P-256""
}";
Dictionary<string, object> PrivateKeyHeader = new Dictionary<string, object>
{
{ "typ", "JWT" },
{ "kid", "TST_SERVER" },
{ "alg", "ES256" }
};
//----Public Enc key for Decrypting the JWE token from the remote host
string PublicKey_Enc = #"
{
""x"": ""_ylhMfdVwaRrLx8HL8z7X1ixVkk2rbpwD9oU-uAqyhE"",
""y"": ""aCRo4kY2dTl7wZXjsp2NJyF9Tcmzk1XZN5ueJWNq7Lk"",
""d"": ""Jz9aEpbt_4aKL5FVdCLlux7U-Ubt_4aKL5VdCLLTR2Y"",
""kty"": ""EC"",
""crv"": ""P-256""
}";
public void Page_Load(object sender, EventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(RemoteURL + RemoteTokenAppend);
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
request.ProtocolVersion = HttpVersion.Version10;
var postData = "client_assertion_type=" + HttpUtility.UrlEncode("urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
postData += "&client_id=" + HttpUtility.UrlEncode(ClientID);
postData += "&grant_type=" + HttpUtility.UrlEncode("authorization_code");
postData += "&redirect_uri=" + HttpUtility.UrlEncode(RedirectURL);
postData += "&code=" + HttpUtility.UrlEncode(Request.QueryString["code"]);
postData += "&client_assertion=" + EncryptTokenJose();
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("Content-Encoding", "ISO-8859-1");
request.ContentLength = data.Length;
try
{
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var webResponse = (HttpWebResponse)request.GetResponse();
var webStream = webResponse.GetResponseStream();
var responseReader = new StreamReader(webStream);
var response = responseReader.ReadToEnd();
//---Decrypt the Response from Remote
string JoseRes = DecryptTokenJose(response.ToString());
//---close the response reader
responseReader.Close();
Response.Write("<br><br>Payload = " + JoseRes + "<br><br>");
//---Get the json string and values from the decrypted Token
JsonTextReader reader = new JsonTextReader(new StringReader(JoseRes));
var sData = JsonSerializer.CreateDefault().Deserialize<payload>(reader);
//----Sample Payload
//---- Payload = { "sub":"s=S775566X,u=c57acrtereb8-d102-455a-860a-ae7dretef4b8d","aud":"mlDBKnGyYfgdgdmzwx770mqXKb6HcBPsHZ2W","amr":["pwd","swk"],"iss":"https:\/\/www.exampleabc.com","exp":1637810980,"iat":1637810380,"nonce":"TJtv85f586sTgxjUlFm5"}
//----get the sub from Payload
string sub = sData.sub;
Response.Write("<br><br>Sub = " + sub + "<br><br>");
//---Get the list array of sub to extract the IC
string[] subList = sub.Split(',');
//---Get the first item of the array to get the IC
Response.Write("<br><br>NRIC = " + subList[0] + "<br><br>");
//---Retrieved IC value will be s=S775566X, so replace s= to "" to get the exact NRIC value and set the Session value
Session["NRIC"] = subList[0].Replace("s=", "");
//---if Session["RedirctPage"] is set then go to that page
if (Session["RedirctPage"] != null)
Response.Redirect(Session["RedirctPage"].ToString());
else
Response.Redirect("Register_uat.aspx");
}
catch (WebException ex)
{
using (WebResponse response = ex.Response)
{
string ErrorString = "Error from the Server:-----<br><br>";
HttpWebResponse httpResponse = (HttpWebResponse)response;
using (Stream data1 = response.GetResponseStream())
using (var reader = new StreamReader(data1))
{
ErrorString += reader.ReadToEnd();
Response.Write(ErrorString);
}
}
}
}
public string EncryptTokenJose()
{
const uint JwtToAadLifetimeInSeconds = 60 * 2;
DateTime validFrom = DateTime.UtcNow;
long exp = ConvertToTimeT(validFrom + TimeSpan.FromSeconds(JwtToAadLifetimeInSeconds));
long iat = ConvertToTimeT(validFrom);
//---Payload string
string payloadStr = "{\"aud\":\"" + RemoteURL + "\",\"exp\":" + exp.ToString() + ",\"iss\":\"" + ClientID + "\",\"iat\": " + iat.ToString() + ",\"sub\":\"" + ClientID + "\"}";
//---get the Private key to form the public key
JsonTextReader reader = new JsonTextReader(new StringReader(PrivateKey));
var jwk = JsonSerializer.CreateDefault().Deserialize<JWK>(reader);
var publicECCKey = EccKey.New(Base64Url.Decode(jwk.x), Base64Url.Decode(jwk.y), Base64Url.Decode(jwk.d), usage: CngKeyUsages.KeyAgreement);
string token = Jose.JWT.Encode(payloadStr, publicECCKey, JwsAlgorithm.ES256, extraHeaders: PrivateKeyHeader);
return token;
}
public string DecryptTokenJose(string Res)
{
var jss = new JavaScriptSerializer();
string json = Res;
Dictionary<string, string> sData = jss.Deserialize<Dictionary<string, string>>(json);
string AccessToken = sData["access_token"].ToString();
string TokenType = sData["token_type"].ToString();
string IdToken = sData["id_token"].ToString();
Response.Write("<br><br>" + IdToken + "<br><br>");
//---get the Public key Enc to decrypt the JWE token
JsonTextReader reader = new JsonTextReader(new StringReader(PublicKey_Enc));
var jwk = JsonSerializer.CreateDefault().Deserialize<JWK>(reader);
var publicECCKey = EccKey.New(Base64Url.Decode(jwk.x), Base64Url.Decode(jwk.y), Base64Url.Decode(jwk.d), usage: CngKeyUsages.KeyAgreement);
//---get the decrypted token
string token = Jose.JWT.Decode(IdToken, publicECCKey, JweAlgorithm.ECDH_ES_A128KW, JweEncryption.A256CBC_HS512);
//----todo: Verify the signature of the decoded JWS token
//----5 parts token with dot(.) as separator
string[] toklist = token.Split('.');
//----get the 2nd item of the list which will have the Payload with User IC details
string Payload = toklist[1];
//----decode the payload to bytes and from bytes to readable string
var base64EncodedBytes = Base64Url.Decode(Payload);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
public static long ConvertToTimeT(DateTime dt)
{
return (long)(dt - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds;
}
public class payload
{
public string sub { get; set; }
public string aud { get; set; }
public string iss { get; set; }
public string exp { get; set; }
public string iat { get; set; }
}
public class JWK
{
public string x { get; set; }
public string y { get; set; }
public string d { get; set; }
}
}

Drag and Drop List Items (with multi selection)

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();
}
}

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);

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);
}
}

'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";