CsvHelper wrap all values with quotes - csv

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

Related

.NET 6 - Change Json Property Casing

How can I change the casing of the property names of a json without performing model binding?
JsonElement serialization ignores PropertyNaming JsonSerializer options as is also confirmed here: https://github.com/dotnet/runtime/issues/61843
The suggested use of JsonNode/JsonObject results in the same behavior.
Any hints how I can accomplish this?
As example I want to change this:
{
"MyPoperty" : 5,
"MyComplexProperty" : {
"MyOtherProperty": "value",
"MyThirdProperty": true
}
}
to this:
{
"myPoperty" : 5,
"myComplexProperty" : {
"myOtherProperty": "value",
"myThirdProperty": true
}
}
Cheers.
I think you try to use Newtonsoft json
class Person
{
public string UserName { get; set; }
public int Age { get; set; }
}
coding
static void Main(string[] args)
{
Person person = new Person();
person.UserName = "Bob";
person.Age = 20;
var serializerSettings = new JsonSerializerSettings();
serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
var json = JsonConvert.SerializeObject(person, serializerSettings);
Console.WriteLine(json);
}
output
{"userName":"Bob","age":20}
not depend on Newtonsoft json but in the case of multi-layer objects
var json = #"{""ShouldWindUpAsCamelCase"":""does it?""}";
var obj = JsonSerializer.Deserialize<Dictionary<string,string>>(json);
var dic = new Dictionary<string, string>();
foreach (var item in obj)
{
dic.Add(item.Key.FirstCharToLower(), item.Value);
}
var serialized = System.Text.Json.JsonSerializer.Serialize(dic);
Console.WriteLine(serialized);
FirstCharToLower() function
public static string FirstCharToLower(this string input)
{
if (String.IsNullOrEmpty(input))
return input;
string str = input.First().ToString().ToLower() + input.Substring(1);
return str;
}
#output
{"shouldWindUpAsCamelCase":"does it?"}

Correct JSON structure using RestSharp

What is the Correct format for sending JSON using RestSharp:
Example PUT JSON:
{
"properties": [
{
"name": "description",
"value": "A far better description than before"
}
]
}
In C# how to correctly send, I'm attempting with:
request.AddJsonBody(new
{
properties = new[]
{
new{property="name",value="about_us"},
new{property="value",value="My description"}
}
});
Below is the full code:
private void UpdateCompanyProperty(string companyId)
{
var hapikey = "{YOUR_HAPI_KEY_HERE}";
var client = new RestClient("https://api.hubapi.com/");
var request = new RestRequest("companies/v2/companies/{companyId}", Method.PUT);
request.AddUrlSegment("companyId", companyId);
request.AddQueryParameter("hapikey", hapikey);
request.RequestFormat = DataFormat.Json;
request.AddJsonBody(new
{
properties = new[]
{
new{property="name",value="about_us"},
new{property="value",value="My description"}
}
});
IRestResponse response = client.Execute(request);
JObject jObject = JObject.Parse(response.Content);
JToken jvid = jObject["portalId"];
Debug.WriteLine(jvid);
}
No errors but not updating or returning values.
Try my answer here:
https://stackoverflow.com/a/57281157/5478655
request.RequestFormat = DataFormat.Json; // Important
var input = new Dictionary<string, object>();
// props could be an array or real objects too of course
var props = new[]
{
new{property="name",value="about_us"},
new{property="value",value="My description"}
};
input.Add("properties", props);
request.AddBody(input);
Create a class and give it any name
class MyClass
{
public string property {get;set;}
private string value {get;set;}
}
Define your class as an object
List<MyClass> list = new List<MyClass>
{
new MyClass() { property = "name", value = "about_us"},
new MyClass() { property = "value", value = "My Description"},
};
Now using Newtonsoft.Json serialize your object
string result = JsonConvert.SerializeObject(list);
Now add it to an array
var resArray = new object[] { result };
Find your modified code below
class MyClass
{
public string property {get;set;}
private string value {get;set;}
}
using Newtonsoft.Json;
using RestSharp;
private void UpdateCompanyProperty(string companyId)
{
List<MyClass> list = new List<MyClass>
{
new MyClass() { property = "name", value = "about_us"},
new MyClass() { property = "value", value = "My Description"},
};
string result = JsonConvert.SerializeObject(list);
var hapikey = "{YOUR_HAPI_KEY_HERE}";
var client = new RestClient("https://api.hubapi.com/");
var request = new RestRequest("companies/v2/companies/{companyId}", Method.PUT);
request.AddUrlSegment("companyId", companyId);
request.AddQueryParameter("hapikey", hapikey);
request.RequestFormat = DataFormat.Json;
request.AddJsonBody(new
{
properties =result
});
IRestResponse response = client.Execute(request);
JObject jObject = JObject.Parse(response.Content);
JToken jvid = jObject["portalId"];
Debug.WriteLine(jvid);
}

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

UWP - writing to JSON without owerwrite data

I want to write data to JSON file, without overwriting them. I am using this code
Item test = new Item("test", 23);
try
{
var Folder = Windows.Storage.ApplicationData.Current.LocalFolder;
//var file = await Folder.CreateFileAsync("data.json", Windows.Storage.CreationCollisionOption.ReplaceExisting);
var file = await Folder.GetFileAsync("data.json");
var data = await file.OpenStreamForWriteAsync();
using (StreamWriter r = new StreamWriter(data))
{
var serelizedfile = JsonConvert.SerializeObject(test);
r.Write(serelizedfile);
}
}
catch (Exception a)
{
throw a;
}
Noticed that you're possibly using the Json.NET for serialization and deserialization the Json file. I think it's better to deserialize the list of Json object and you can operate on this list, then serialize the new list to Json and save into the file, not directly serialize one item and write it into the file.
For example, my Json file is like this:
[
{"color":"red","value":"#f00"},
{"color":"green","value":"#0f0"},
{"color":"blue","value":"#00f"},
{"color":"cyan","value":"#0ff"},
{"color":"magenta","value":"#f0f"},
{"color":"yellow","value":"#ff0"},
{"color":"black","value":"#000"}
]
code for adding one item to this file:
if (file != null)
{
using (var streamIn = await file.OpenAsync(FileAccessMode.ReadWrite))
{
DataReader reader = new DataReader(streamIn);
await reader.LoadAsync((uint)streamIn.Size);
var jsonInstring = reader.ReadString((uint)streamIn.Size);
var JobjList = JsonConvert.DeserializeObject<List<JsonColor>>(jsonInstring);
reader.Dispose();
JobjList.Add(new JsonColor() { color = "pink", value = "#c0c" });
JsonOutstring = JsonConvert.SerializeObject(JobjList);
}
using (var streamOut = await file.OpenAsync(FileAccessMode.ReadWrite))
{
DataWriter writer = new DataWriter(streamOut);
writer.WriteString(JsonOutstring);
await writer.StoreAsync();
writer.DetachStream();
writer.Dispose();
}
}
else
{
}
My class object:
public class JsonColor
{
public string color { get; set; }
public string value { get; set; }
}
As you can see, I deserialized the Json file and get the List<JsonColor>, then I added one item new JsonColor() { color = "pink", value = "#c0c" } to this list, and finally serialized this new list and save it. So for your scenario, you can modify the Json file and my JsonColor class to fit your need.
Update:
private string JsonOutstring;
private async void Button_Click(object sender, RoutedEventArgs e)
{
//create a json file, if the file is exit, then open it.
var local = Windows.Storage.ApplicationData.Current.LocalFolder;
var Jsonfile = await local.CreateFileAsync("test.json", Windows.Storage.CreationCollisionOption.OpenIfExists);
if (Jsonfile != null)
{
ReadAndWriteJsonFile(Jsonfile);
}
else
{
}
}
public async void ReadAndWriteJsonFile(StorageFile file)
{
using (var streamIn = await file.OpenAsync(FileAccessMode.ReadWrite))
{
DataReader reader = new DataReader(streamIn);
await reader.LoadAsync((uint)streamIn.Size);
var jsonInstring = reader.ReadString((uint)streamIn.Size);
var JobjList = JsonConvert.DeserializeObject<List<JsonColor>>(jsonInstring);
reader.Dispose();
if (JobjList == null)
{
JobjList = new List<JsonColor>();
}
JobjList.Add(new JsonColor() { color = "pink", value = "#c0c" });
JsonOutstring = JsonConvert.SerializeObject(JobjList);
}
using (var streamOut = await file.OpenAsync(FileAccessMode.ReadWrite))
{
DataWriter writer = new DataWriter(streamOut);
writer.WriteString(JsonOutstring);
await writer.StoreAsync();
writer.DetachStream();
writer.Dispose();
}
}
public class JsonColor
{
public string color { get; set; }
public string value { get; set; }
}

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