I see that there are elements. But its not adding to this object, I see null for Name and bytes...
var req = new Details()
{
Saver= new List<SaverDetails>()
{
new SaverDetails()
}
};
foreach (var t in files.ToList())
{
req.Saver.Add(
new SaverDetails()
{
Name= Path.GetFileName(t),
bytes = File.ReadAllBytes(t)
});
}
Related
I got a json as input. I don't know exact structure of that file. I need only add object to "KnownCollection" which may be in file or not. So if there is a collection add item into it, if there is not create a collection with an item. Question is how to do that with System.Text.Json, we used it and I don't want to add dependency on Newtonsoft
{
"UnknownProperty": 1,
"KnownCollection": [{
"ItemProperty1": "1",
"ItemProperty2": 2
}],
// More unknown properties
}
var item = new {ItemProperty1 = "2", ItemProperty2 = 2};
var fileContent = File.ReadAllBytes(filePath);
using var jsonDocument = JsonDocument.Parse(fileContent);
var knownCollection = jsonDocument.RootElement.GetProperty("KnownCollection");
//How to add item to knownCollection?
You could add the item to array like below:
[HttpGet]
public string Index()
{
var fileContent = System.IO.File.ReadAllBytes("filePath");
using (MemoryStream memoryStream1 = new MemoryStream())
{
using (Utf8JsonWriter utf8JsonWriter1 = new Utf8JsonWriter(memoryStream1))
{
using (JsonDocument jsonDocument = JsonDocument.Parse(fileContent))
{
utf8JsonWriter1.WriteStartObject();
foreach (var element in jsonDocument.RootElement.EnumerateObject())
{
if (element.Name == "KnownCollection")
{
utf8JsonWriter1.WritePropertyName(element.Name);
utf8JsonWriter1.WriteStartArray();
// Staring new object
utf8JsonWriter1.WriteStartObject();
utf8JsonWriter1.WriteString("ItemProperty1", "2");
utf8JsonWriter1.WriteNumber("ItemProperty2", 2);
utf8JsonWriter1.WriteEndObject();
// Copying existing values from "KnownCollection" array
foreach (var testDataElement in element.Value.EnumerateArray())
{
testDataElement.WriteTo(utf8JsonWriter1);
}
utf8JsonWriter1.WriteEndArray();
}
else
{
element.WriteTo(utf8JsonWriter1);
}
}
utf8JsonWriter1.WriteEndObject();
}
}
var resultJson = Encoding.UTF8.GetString(memoryStream1.ToArray());
return resultJson;
}
}
Result:
HI i am writing a c# program where i need to populate a array based on a look up table and set of string arrays with metadata. My lookup table looks like this (Table with key: transmitter, value: Array of receiver)
{
LED1: ["px1","px2","px3"],
LED2: ["px4","px5","px6"]
}
and my meta arrays looks like this (It is dynamic. Just an example. This comes as a response from DB query.)
var transmitters = new string[] { "LED1", "LED2" };
var receivers = new string[] { "px1", "px2", "px3", "px4", "px5", "px6" };
My requirement is
If the transmitter LED1 or LED2 (or any other transmitter) is present in the lookup table, the value of the transmitter (ie ["px1","px2","px3"]) has to be compared with the receiver which are present in the lookup and led has to be marked yellow.
Orphan tranmitter or/ receiver has to be marked red.
Example
LookUp
{
LED1: ["px1", "px2", "px3"],
LED2: ["px5", "px8"]
}
Tranmitters and receivers
var transmitters = new string[] { "led1", "led2" };
var receivers = new string[] { "px1", "px2", "px3", "px4", "px5", "px6" };
the result should be a list as
led1-yellow
px1-yellow
px2-yellow
px3-yellow
led2-yellow
px5-yellow
px4-red
px6-red.
I have written code that works
public class Program
{
public static void Main()
{
var transmitters = new string[] { "led1", "led2" };
var receivers = new string[] { "px1", "px2", "px3", "px4", "px5", "px6" };
var lookup = new Dictionary<string, string[]>() { { "led1", new string[] { "px1", "px2", "px3" } }, { "led2", new string[] { "px5", "px8" } } };
var blocks = new List<Block>();
var blocksTracker = new List<string>();
foreach (var transmitter in transmitters)
{
if (lookup.ContainsKey(transmitter))
{
var receiverLookup = lookup[transmitter];
var intersection = receivers.Intersect(receiverLookup).ToArray();
if (intersection.Length > 0)
{
blocks.Add(new Block() { Id = transmitter, status = "yellow" });
blocksTracker.Add(transmitter);
foreach (var receiver in intersection)
{
blocks.Add(new Block() { Id = receiver, status = "yellow" });
blocksTracker.Add(receiver);
}
}
else
{
blocks.Add(new Block() { Id = transmitter, status = "red" });
blocksTracker.Add(transmitter);
}
}
}
}
}
I am new to c# and i wanted to know if there is a better way of doing this. Please help. You can see the working fiddle Here
I am trying to download a file content from the S3 bucket using the SelectObjectContentAsync method from AWSSDK for C#.
But there are some unwanted line break(\n) in mid of the raw data.
Data Example :
{"Id":1,"Name":"aaa"}, {"Id":2,"N
\name":"bbb"}
My Code :
var amazonS3Client = new AmazonS3Client(awsAccessKeyId, awsSecretAccessKey, region);
SelectObjectContentRequest selectObjectContentRequest = new SelectObjectContentRequest()
{
Bucket = bucketName,
Key = key,
ExpressionType = ExpressionType.SQL,
Expression = query,
InputSerialization = new InputSerialization()
{
JSON = new JSONInput()
{
JsonType = JsonType.Lines
},
CompressionType = CompressionType.Gzip
},
OutputSerialization = new OutputSerialization()
{
JSON = new JSONOutput()
{
RecordDelimiter = ","
}
}
};
using (var content = amazonS3Client.SelectObjectContentAsync(selectObjectContentRequest).Result.Payload)
{
foreach (var item in content)
{
if (item is RecordsEvent recordsEvent)
{
using (var reader = new StreamReader(recordsEvent.Payload, Encoding.UTF8))
{
using (var file = new StreamWriter(path, true))
{
file.WriteLine(reader.ReadToEnd());
}
}
}
}
}
I am using a DictionaryList to keep some values coming from an xml file
this is the my xml file
<DnsServers>
<Dns>
<Name>Google</Name>
<Value>8.8.8.8,8.8.4.4</Value>
</Dns>
<Dns>
<Name>Telekom</Name>
<Value>195.175.39.39,195.175.39.40</Value>
</Dns>
</DnsServers>
and then populating a combobax just key values like this way .
void ReadFromDnsServerList()
{
_nameValueDictionary = new Dictionary<string, string>();
//var list = new List<string>();
XDocument doc = XDocument.Load("DnsServerList.xml");
if (doc.Root != null)
{
var keyValueXml = from c in doc.Root.Descendants("Dns")
select new
{
name = c.Element("Name").Value,
value = c.Element("Value").Value
};
foreach (var info in keyValueXml)
{
_nameValueDictionary.Add(info.name,info.value);
}
foreach (KeyValuePair<string, string> item in _nameValueDictionary)
{
cmbDns.Items.Add(item.Key);
}
}
}
I am wondering that How can I get corresponding dns value inside cmbDns_SelectedIndexChanged
change event somethinglike this
name=Google value =8.8.8.8,8.8.4.4
Try this:
void ReadFromDnsServerList()
{
_nameValueDictionary = new Dictionary<string, string>();
XDocument doc = XDocument.Load("DnsServerList.xml");
if (doc.Root != null)
{
var keyValueXml = from c in doc.Root.Descendants("Dns")
select new
{
name = c.Element("Name").Value,
value = c.Element("Value").Value
};
foreach (var info in keyValueXml)
{
_nameValueDictionary.Add(info.name, info.value);
}
cmbDns.DisplayMember = "Key";
cmbDns.ValueMember = "Value";
cmbDns.DataSource = _nameValueDictionary.ToArray();
}
}
I hope it helps.
Is it possible to implicitly declare next Dictionary<HyperLink, Anonymous>:
{ urlA, new { Text = "TextA", Url = "UrlA" } },
{ urlB, new { Text = "TextB", Url = "UrlB" } }
so I could use it this way:
foreach (var k in dic)
{
k.Key.Text = k.Value.Text;
k.Key.NavigateUrl = k.Value.Url;
}
?
How about:
var dict = new[] {
new { Text = "TextA", Url = "UrlA" },
new { Text = "TextB", Url = "UrlB" }
}.ToDictionary(x => x.Url);
// or to add separately:
dict.Add("UrlC", new { Text = "TextC", Url = "UrlC" });
However, you could just foreach on a list/array...
var arr = new[] {
new { Text = "TextA", Url = "UrlA" },
new { Text = "TextB", Url = "UrlB" }
};
foreach (var item in arr) {
Console.WriteLine("{0}: {1}", item.Text, item.Url);
}
You only need a dictionary if you need O(1) lookup via the (unique) key.
Yes, but only with great workaround, and only within a method.
This is how you can do it:
static Dictionary<TKey, TValue> NewDictionary<TKey, TValue>(TKey key, TValue value)
{
return new Dictionary<TKey, TValue>();
}
public void DictRun()
{
var myDict = NewDictionary(new { url="a"},
new { Text = "dollar", Url ="urlA"});
myDict.Add(new { url = "b" }, new { Text = "pound", Url = "urlB" });
myDict.Add(new { url = "c" }, new { Text = "rm", Url = "urlc" });
foreach (var k in myDict)
{
var url= k.Key.url;
var txt= k.Value.Text;
Console.WriteLine(url);
Console.WriteLine(txt);
}
}
You can refer to this SO question for more info.