How to check if the file exist in xamarin forms - c#

I want to check if the file inside my device exist. When the variable crphoto1 is empty or the file does not exist the "Photo1" json should be {"Photo1", ""}
JObject ph1json = string.IsNullOrEmpty(crphoto1)
? new JObject
{
{"ContactID", crcontactID},
{"Photo1", ""}
}
: new JObject
{
{"ContactID", crcontactID},
{"Photo1", File.ReadAllBytes(crphoto1)}
};

If you are just looking for how to check if file exist you can use
using System.IO;
string fileName = Path.Combine(Environment
.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "yourfile.jpg");
JObject ph1json;
bool doesExist = File.Exists(fileName);
if (!doesExist || string.IsNullOrEmpty(crphoto1))
{
ph1json = new JObject
{
{"ContactID",crcontactID},
{ "Photo1",""}
};
}
else
{
ph1json = new JObject
{
{"ContactID",crcontactID},
{"Photo1",File.ReadAllBytes(crphoto1)}
};
}

Related

Is there a built-in method to convert .NET Configuration to JSON?

It's easy to convert JSON into configuration, e.g. with
using var stream = new MemoryStream(Encoding.UTF8.GetBytes(json));
var configuration = new ConfigurationBuilder().AddJsonStream(stream).Build();
which gives you an IConfigurationRoot.
Is there a method (preferably in one of the Microsoft.Extensions.Configuration packages) that does the reverse?
Context: I'm downloading a bunch of Azure App Configuration settings and want to export them as JSON. Similar functionality is available in the Azure Portal but I want to resolve key vault references as well.
I can probably do something like this:
// Convert to JSON
var jRoot = new JObject();
foreach (var setting in settings) {
Add(jRoot, setting.Key, setting.Value);
}
with the Add method defined as
private void Add(JObject jObject, string key, string value) {
var index = key.IndexOf(':');
if (index == -1) {
jObject[key] = value;
return;
}
var prefix = key[..index];
if (!jObject.ContainsKey(prefix)) {
jObject[prefix] = new JObject();
}
Add((JObject)jObject[prefix], key[(index + 1)..], value);
}
which I'd probably need to extend to support arrays, but I was hoping I'd not have to reinvent the wheel.
For now, I've expanded the Add method to support arrays:
private void Add(JToken jToken, string key, string value) {
var components = key.Split(":", 3);
if (components.Length == 1) {
// Leaf node
if (jToken is JArray jArray_) {
jArray_.Add(value);
} else {
jToken[components[0]] = value;
}
return;
}
// Next level
JToken nextToken;
var nextTokenIsAnArray = int.TryParse(components[1], out _);
if (jToken is JArray jArray) {
var index = int.Parse(components[0]);
if (jArray.Count == index) {
nextToken = nextTokenIsAnArray ? new JArray() : (JToken)new JObject();
jArray.Add(nextToken);
} else {
nextToken = jArray[index];
}
} else {
nextToken = jToken[components[0]];
if (nextToken == null) {
nextToken = jToken[components[0]] = nextTokenIsAnArray ? new JArray() : (JToken)new JObject();
}
}
Add(nextToken, key[(components[0].Length + 1)..], value);
}
which works for me, assuming arrays appear in the right order, e.g.
key "Foo:0", value "Bar"
key "Foo:1", value "Baz"
which gets serialized as
{ "Foo": ["Bar", "Baz"] }

How to create JSON object in C#

I need to create JSON like this:
{
"files": [
{
"file_path": "example.txt",
"content" : "source code \n with multiple lines\n"
}
]
}
But my code (I serialized it to JSON later) doesn't correspond to this example above
var requestBody = new
{
files = new string[] { snippet.FileName, snippet.Content }
};
Can someone help me :)?
EDIT:
my serialization method:
protected string serializeToJson( object obj )
{
return JsonConvert.SerializeObject( obj, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() } );
}
Try That:
using System.Text.Json;
var obj = new
{
files = new[]
{
new
{
file_path = "example.txt",
content ="source code \n with multiple lines\n"
}
}
};
var json = JsonSerializer.Serialize(obj);
Console.WriteLine(json);
Result:
We can make use of the serializeobject to convert into json
string jsonStr = JsonConvert.SerializeObject(obj);
This method will be available in the newtonsoft package

c# .netcore Get ImageURL of all files under amazon s3 folder

Using C# and amazon .Net core, able to list all the files URL path with in a amazon S3 folder as below:
public async Task<string> GetMenuUrl(entities.Restaurant restaurant)
{
AmazonS3Client s3Client = new AmazonS3Client(_appSettings.AWSPublicKey, _appSettings.AWSPrivateKey, Amazon.RegionEndpoint.APSoutheast2);
string imagePath;
int restaurantId = restaurant.RestaurantId;
ListObjectsRequest listRequest = new ListObjectsRequest();
ListObjectsResponse listResponse;
imagePath = $"Business_menu/{restaurantId}/";
listRequest.BucketName = _appSettings.AWSS3BucketName;
listRequest.Prefix = imagePath;
do
{
listResponse = await s3Client.ListObjectsAsync(listRequest);
} while (listResponse.IsTruncated);
var files = listResponse.S3Objects.Select(x => x.Key);
var fileName = files.Select(x => Path.GetFileName(x)).ToList(); //outputs Test.jpg, Test2.jpg on this line
var fileNameJoin = string.Join(", ", fileName);
var result = fileNameJoin.Split(); // contains 2 files Test.jpg, Test2.jpg
//Need AWSS3BucketUrl for all files in imagePath
string imageUrl = $"{_appSettings.AWSS3BucketUrl}{imagePath}{result}";
return imageUrl;
}
public async Task<MenuResponse> GetVenueMenuUrl(int restaurantId)
{
var restaurant = await _context.Restaurant.Where(w => w.RestaurantId == restaurantId).FirstOrDefaultAsync();
var result = await _Service.GetMenuUrl(restaurant);
var response = new MenuResponse()
{
MenuUrl = result
};
return response;
}
I want to return each imageurl as the following:
{
menuUrl : "https://...bucketpath../test.jpg"
},
{
menuUrl: "https://...bucketpath../test2.jpg"
},
What Is currently being outputted:
{
"menuUrl": "https://..bucketpath../System.String[]"
}
It should be outputting two imageUrls not one and also it seems to be outputting the list type not the content.
string imageUrl = $"{_appSettings.AWSS3BucketUrl}{imagePath}{result}";
You're telling C# to concatenate a string with "result", but "result" is not a string, it's an array. To tell the compiler what you really want, you need to get the individual strings out of the array and use those instead.
It also looks like you're converting your result into JSON in code we can't see. If that's the case, you could try returning a list of objects from your function instead of a string, which will then get serialized into something a lot closer to your expected output:
// make a simple class that will be serialized cleanly
public class MenuURL
{
public string menuUrl;
}
// .... back in your function ....
List<MenuURL> URLs = new List<MenuURL>();
// Loop through your "results" variable
foreach (string str in result)
{
MenuURL url = new MenuURL()
{
menuUrl = $"{_appSettings.AWSS3BucketUrl}{imagePath}{str}"
};
URLs.Add(url);
}
return URLs;
When you convert the list you get back into JSON, it should look more like what you want, ie:
[
{
"menuUrl" : "https://...bucketpath../test.jpg"
},
{
"menuUrl": "https://...bucketpath../test2.jpg"
},
]

How do you run through the entire JSON file, while filtering out specific values & strings from code behind?

may i know how do you run through the entire JSON file and during the process, filter out specific values and strings, such as db_table_name? from code - behind
Here is an example of a JSON file
d={"db_table_name":"form_for_hub_trooper_in_store_feedback_form_20160829174321","Date of Audit":"2017-04-27"}
test.json file:
{
"db_table_name": "from_for_bub_trooper_in_store_feedback_from_20160829174321",
"Date of Audit": "2017-04-27"
}
You may simply use Newtonsoft.Json. Working code is below:
string jsonText = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "test.json");
using (StreamReader r = new StreamReader(jsonText))
{
string json = r.ReadToEnd();
JObject token = JObject.Parse(json);
string dbTable = token.SelectToken("db_table_name").ToString();
}
If you want to access json dynamically by condition:
string jsonText = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "test.json");
using (StreamReader r = new StreamReader(jsonText))
{
string json = r.ReadToEnd();
dynamic dynamicJson = JsonConvert.DeserializeObject(json);
foreach (var item in dynamicJson)
{
if (item.Name == "db_table_name")
Console.WriteLine(item.Value);
if (item.Name == "Date of Audit")
Console.WriteLine(item.Value);
}
}
void Main()
{
string d = "{'db_table_name':'form_for_hub_trooper_in_store_feedback_form_20160829174321','Date of Audit':'2017-04-27'}";
var obj = (JObject)JsonConvert.DeserializeObject(d);
Console.WriteLine($"Table Name = {(obj["db_table_name"])}");
}

Customizing the JSON received from Web API

I need to add one more node to Json string.
Following is the code from where I am reading the data.
var url = "https://xyz_12232_abc/0908978978979.json";
var sys = new WebClient();
var content = sys.DownloadString(url);
I received following output from above code:
{
"2312312312313":
{
"emailId":"abc#gmail.com",
"model":"XYZ001",
"phone":"+654784512547",
"userName":"User1"
},
"23456464512313":
{
"emailId":"abcd#gmail.com",
"model":"XYZ002",
"phone":"+98745114474",
"userName":"User2"
},
"45114512312313":
{
"emailId":"abcde#gmail.com",
"model":"XYZ3",
"phone":"+214784558741",
"userName":"User3"
}
}
But, I want this output like below:
{
"Records": [
{
"UID":"2312312312313":,
"emailId":"abc#gmail.com",
"model":"XYZ001",
"phone":"+654784512547",
"userName":"User1"
},
{
"UID":"23456464512313":,
"emailId":"abcd#gmail.com",
"model":"XYZ002",
"phone":"+98745114474",
"userName":"User2"
},
{
"UID":"45114512312313":,
"emailId":"abcde#gmail.com",
"model":"XYZ3",
"phone":"+214784558741",
"userName":"User3"
}
]
}
Now, how can it be achieved ?
You can use Json.NET to massage the data into your desired output:
var jsonStr = #"..."; // your JSON here
var obj = JsonConvert.DeserializeObject<Dictionary<string, JObject>>(jsonStr);
var formattedObj = new
{
Records = obj.Select(x =>
{
x.Value.AddFirst(new JProperty("UID", x.Key));
return x.Value;
})
};
// serialize back to JSON
var formattedJson = JsonConvert.SerializeObject(formattedObj);

Categories