c# Save JSON response to Database table - c#

Ok I tried this for a couple of days now.
I'm trying to read JSON response and insert/update it to DB table (already exists) based on a condition from the response. I have created a Console app.
What my JSON looks like:
[
{
"logtime", "2022-10-19T08:50:06.515Z");
"lat_value", "Some-Latitude-Value");
"long_value", "Some-Longitude-Value");
"name", "Name"
"population", "Population"
"unemployment_rate", "UnemploymentPercentage"
},
{
"logtime", "2022-10-19T08:50:06.515Z");
"lat_value", "Some-Latitude-Value");
"long_value", "Some-Longitude-Value");
"name", "Name"
"population", "Population"
"unemployment_rate", "UnemploymentPercentage"
},
{
"logtime", "2022-10-19T08:50:06.515Z");
"lat_value", "Some-Latitude-Value");
"long_value", "Some-Longitude-Value");
"name", "Name"
"population", "Population"
"unemployment_rate", "UnemploymentPercentage"
},
...
]
Condition is:
if(UnemploymentPercentage > 70)
{
if(Name matches to NameCol && UnemploymentPercentage != UnemploymentRateCol)
{ //InsertRecord }
else
{ //UpdateUnemploymentPercentageValue }
}
What I have tried:
ModelClass.cs:
public string LogTime { get; set; }
public string Lat { get; set; }
public string Long { get; set; }
public string Name { get; set; }
public string Population { get; set; }
public decimal UnemploymentRate { get; set; }
ControllerClass.cs:
string url = "https://my-url-goes-here.net";
ModelClass dataModel = new();
public void JsonParser()
{
var clients = new RestClient(url);
var request = new RestRequest("api/constructorName", Method.Get)
{
Timeout = -1
};
request.AddHeader("api-key", "myKeyGoesHere");
request.AddParameter("param1", "someParam");
RestResponse response = clients.Execute(request);
if(response.Content != null)
{
string result = response.Content;
_ = JsonConvert.DeserializeObject<List<ModelClass>>(result);
}
}
public void WriteJsonDataToMSSql()
{
//var rates = ((JObject)json["feild6"]).Properties().Select(x => new { Feild6 = x.Name, Rate = Convert.ToDecimal(x.Value.ToString()) });
using (SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["Conn"].ConnectionString))
{
sqlCon.Open();
using (SqlBulkCopy copy = new SqlBulkCopy(sqlCon))
{
copy.DestinationTableName = "tbl_name";
copy.ColumnMappings.Add("LogTime", "logtime");
copy.ColumnMappings.Add("Lat", "Latitude");
copy.ColumnMappings.Add("Long", "Longitude");
copy.ColumnMappings.Add("Name", "Name");
copy.ColumnMappings.Add("Population", "Population");
copy.ColumnMappings.Add("UnemploymentRate", "Unemployment");
copy.WriteToServer(output.AsDataReader());
}
sqlCon.Close();
}
}
I don't know how much I am right and what to do next. Please feel free to correct me. Any help is appreciated.
Thanks in advance.

Related

custom response object for model validation in asp.net core

I want custom object in response of API having [required] data annotation on model properties like this:
{
"resourceType": "OperationOutcome",
"issue": [
{
"severity": "fatal",
"code": "required",
"location": [
"/f:AllergyIntolerance/f:status"
]
}
]
}
Is it possible to do it or I would have to code it.
Because model validation happens before action is called, is there any way I can do it?
To create custom request and respond samples for your api, you can use Swashbuckle.AspNetCore.Swagger and to improve validations on your models you can use FluentValidations Sample. Good Luck!
first for simplify define your models like these :
public class ResponseModel
{
public string resourceType { get; set; }
public List<ResponseIssueModel> issue { get; set; } = new List<ResponseIssueModel>();
}
public class ResponseIssueModel
{
public string severity { get; set; }
public string code { get; set; }
public List<string> locations { get; set; } = new List<string>();
}
Then on your actions you can return this :
var response = new ResponseModel();
response.resourceType = "OperationOutcome";
response.issue.Add(new ResponseIssueModel
{
severity = "fatal",
code = "required",
locations = { "/f:AllergyIntolerance/f:status" }
});
return Ok(response);
you can use Builder Pattern for easy create response object
If you want to validate your model in controller,you could try with TryValidateModel method as mentioned in the document:
I tried as below:
in controller:
var model = new TestModel() { Id=1,nestedModels=new List<NestedModel>() { new NestedModel() { Prop1="P11"} } };
var isvalid=TryValidateModel(model);
var errorfiledlist = new List<string>();
if (!isvalid)
{
foreach (var value in ModelState.Values)
{
foreach (var error in value.Errors)
{
errorfiledlist.Add(MidStrEx(error.ErrorMessage,"The "," field"));
}
}
}
var jsonstring = JsonSerializer.Serialize(model);
foreach (var field in errorfiledlist)
{
var oldstr = String.Format("\"{0}\":null", field);
var newstr = String.Format("\"{0}\":\"required\"", field);
jsonstring = jsonstring.Replace(oldstr, newstr);
};
var obj = JsonSerializer.Deserialize<Object>(jsonstring);
return Ok(obj);
MidStrEx method:
public static string MidStrEx(string sourse, string startstr, string endstr)
{
string result = string.Empty;
int startindex, endindex;
try
{
startindex = sourse.IndexOf(startstr);
if (startindex == -1)
return result;
string tmpstr = sourse.Substring(startindex + startstr.Length);
endindex = tmpstr.IndexOf(endstr);
if (endindex == -1)
return result;
result = tmpstr.Remove(endindex);
}
catch (Exception ex)
{
}
return result;
}
Models:
public class TestModel
{
public int Id { get; set; }
[Required]
public string Prop { get; set; }
public List<NestedModel> nestedModels { get; set; }=new List<NestedModel>();
}
public class NestedModel
{
public string Prop1 { get; set; }
[Required]
public string Prop2 { get; set; }
}
The result:

Looping an Array or List in C# and perform update using MongoDB

i want to loop my request and perform something for my array ( Cart ) but i dont know how to loop the request
here is the request
enter image description here
and here is the object class or the model for the request
public class OrderRRModel
{
public ObjectId id { get; set; }
public string cutomer_name { get; set; }
public string table_number { get; set; }
public List<ListCart> Cart { get; set; }
public OrderRRModel()
{
Cart = new List<ListCart>();
}
}
public class ListCart
{
public string product { get; set; }
public double amount { get; set; }
public double price { get; set; }
}
here is my full code
public ResponseModel<OrderRRModel> InsertOrderTest(string tokenAdmin, OrderRRModel entity)
{
var entityResult = new ResponseModel<OrderRRModel>();
try
{
var auth = _adminCollection.Find(x => x.token == tokenAdmin).FirstOrDefault();
if (auth != null)
{
var dates = DateTime.Now.ToUniversalTime();
// looping here
var check = _menuCollection.Find(x => x.product_name == cart.product_name).FirstOrDefault();
cart.price = check.price;
var result = _menuCollection.UpdateOne(
x => x.product_name == cart.product_name,
Builders<MenuRRModel>.Update.Set(x => x.updated_at, dates)
.Set(x => x.stock, check.stock - cart.amount) // updating stock by reducing stock based on quantity
);
// end of looping
_orderCollection.InsertOne(entity);
entityResult.Status = true;
entityResult.Messages.Add(new ResponseMessageModel()
{
Type = ResponseMessageModel.MessageType.SUCCESS,
Title = "Success",
Message = "Successful"
});
}
else
{
entityResult.Messages.Add(new ResponseMessageModel()
{
Type = ResponseMessageModel.MessageType.WARNING,
Title = "Action Failed",
Message = "Anda Tidak Memiliki Wewenang!"
});
}
}
catch (Exception ex)
{
entityResult.Messages.Add(new ResponseMessageModel()
{
Type = ResponseMessageModel.MessageType.ERROR,
Title = "Error",
Message = ex.Message
});
}
return entityResult;
}
can you guys tell me the code for looping my request ?
please be kind im a newbie
just do this
foreach (var cart in entity.cart)
{
cart.itemcart
}

How to assign value to variable from a google API Json Response c#

I am trying to assign the value of a key from an async JSON response to a variable, the JSON key in question is the "threatType" Key. I am querying google's safebrowsing v4 API and I get a good response, the problem is when I try to assign a key to a variable nothing is assigned. Here's my code:
public static async Task<string> CheckUrl( string Api_Key, string MyUrl)
{
safeBrowsing_panel i = new safeBrowsing_panel();
var service = new SafebrowsingService(new BaseClientService.Initializer
{
ApplicationName = "Link-checker",
ApiKey = Api_Key
});
var request = service.ThreatMatches.Find(new FindThreatMatchesRequest()
{
Client = new ClientInfo
{
ClientId = "Link-checker",
ClientVersion = "1.5.2"
},
ThreatInfo = new ThreatInfo()
{
ThreatTypes = new List<string> { "SOCIAL_ENGINEERING", "MALWARE" },
PlatformTypes = new List<string> { "ANY_PLATFORM" },
ThreatEntryTypes = new List<string> { "URL" },
ThreatEntries = new List<ThreatEntry>
{
new ThreatEntry
{
Url = MyUrl
}
}
}
});
var response = await request.ExecuteAsync();
string json = JsonConvert.SerializeObject(await request.ExecuteAsync());
string jsonFormatted = JToken.Parse(json).ToString(Formatting.Indented);
Console.WriteLine(jsonFormatted);
return jsonFormatted;
}
I created classes to parse the json:
public class ThreatRes
{
public string threatType;
}
public class RootObjSB
{
public List<ThreatRes> matches;
}
And I call it with:
string SB_Result = await CheckUrl("MyAPIKey", "Bad_URL");
RootObjSB obj = JsonConvert.DeserializeObject<RootObjSB>(SB_Result);
The JSON response from google:
{
"matches": [
{
"cacheDuration": "300s",
"platformType": "ANY_PLATFORM",
"threat": {
"digest": null,
"hash": null,
"url": "http://badurl.com/",
"ETag": null
},
"threatEntryMetadata": null,
"threatEntryType": "URL",
"threatType": "SOCIAL_ENGINEERING",
"ETag": null
}
],
"ETag": null
}
I need help please.
So I tried using JavaScriptSerializer and it seemed to work just fine, I also reconstructed my classes to parse all the properties on the JSON response.
Reconstructed Classes:
public class Threat
{
public object digest { get; set; }
public object hash { get; set; }
public string url { get; set; }
public object ETag { get; set; }
}
public class Match
{
public string cacheDuration { get; set; }
public string platformType { get; set; }
public Threat threat { get; set; }
public object threatEntryMetadata { get; set; }
public string threatEntryType { get; set; }
public string threatType { get; set; }
public object ETag { get; set; }
}
public class RootObjSB
{
public List<Match> matches { get; set; }
public object ETag { get; set; }
}
and i deserialize it like this:
string SB_Result = await CheckUrl("MyAPIKey", "Bad_URL");
var obj = new JavaScriptSerializer().Deserialize<RootObjSB>(SB_Result);
string threat = obj.matches[0].threatType;
Console.WriteLine(threat);
I really don't know why the first option I tried didn't parse the data correctly but this was how I overcame that problem. Hope it helps anyone going through the same thing

Custom Jump lists in Windows Phone

I have been looking at this: http://code.msdn.microsoft.com/wpapps/Custom-LongList-Selector-bf8cb9ad and trying to incorporate into my app. However, its a little confusing since my data is loaded differently. Right now, I have two errors The best overloaded method match for CustomKeyGroup<.ViewModels.SoundData>.GetSoundGroups(System.Collections.Generic.List<.ViewModels.SoundData>)' has some invalid arguments
Argument 1: cannot convert from 'string' to 'System.Collections.Generic.List'
The error is at 'CustomKeyGroup.GetSoundGroups(mvm.Items);' from the mainpage.cs. I know the items is an issue. If you look at the link, they load the data differently w/ listmovie.add.
I know something is screwed up big time but since my data is loaded different, im struggling to get it working correctly.
Id like to have custom jumplist w/ headers by Groups (Alpha, Bravo, etc) located in my SoundModel. Here is a portion:
namespace T.ViewModels
{
public class SoundModel: BindableBase
{
public SoundGroup NewAdds { get; set; }
public SoundGroup Software { get; set; }
}
public bool IsDataLoaded { get; set; }
public void LoadData()
{
// Load data into the model
Software = CreateSoftwareGroup();
NewAdds = CreateNewAddsGroup();
IsDataLoaded = true;
}
private SoundGroup CreateNewAddsGroup()
{
SoundGroup data = new SoundGroup();
data.Title = "New";
string basePath = "assets/audio/newadds/";
data.Items.Add(new SoundData
{
Title = "Test1",
FilePath = basePath + "Test.mp3",
Groups = "Alpha"
});
data.Items.Add(new SoundData
{
Title = "Test2",
FilePath = basePath + "Test2.mp3",
Groups="Bravo"
});
data.Items.Add(new SoundData
{
Title = "Test3",
FilePath = basePath + "Test3.mp3",
Groups= "Zulu"
});
private SoundGroup CreateSoftwareGroup()
{
SoundGroup data = new SoundGroup();
data.Title = "Software";
string basePath = "assets/audio/Software/";
data.Items.Add(new SoundData
{
Title = "Test1",
FilePath = basePath + "Test.mp3",
Groups = "Alpha"
});
data.Items.Add(new SoundData
{
Title = "Test2",
FilePath = basePath + "Test2.mp3",
Groups="Bravo"
});
data.Items.Add(new SoundData
{
Title = "Test3",
FilePath = basePath + "Test3.mp3",
Groups= "Zulu"
});
Here is the relevant mainpage.cs:
SoundData mvm = new SoundData();
this.LongList.ItemsSource = CustomKeyGroup<SoundData>.GetSoundGroups(mvm.Items);
SoundGroup:
{
public class SoundGroup
{
public SoundGroup()
{
Items = new List<SoundData>();
}
public List<SoundData> Items { get; set; }
public string Title { get; set; }
public string Groups { get; set; }
}
}
SoundData :
{
public class SoundData : ViewModelBase
{
public string Title { get; set; }
public string FilePath { get; set; }
public string Items { get; set; }
public string Groups { get; set; }
public RelayCommand<string> SaveSoundAsRingtone { get; set; }
private void ExecuteSaveSoundAsRingtone(string soundPath)
{
App.Current.RootVisual.Dispatcher.BeginInvoke(() =>
{
SaveRingtoneTask task = new SaveRingtoneTask();
task.Source = new Uri("appdata:/" + this.FilePath);
task.DisplayName = this.Title;
task.Show();
}
);
}
public SoundData()
{
SaveSoundAsRingtone = new RelayCommand<string>(ExecuteSaveSoundAsRingtone);
}
}
}
So far from I what can see you should be calling the function as below
SoundModel svm = new SoundModel();
svm.LoadData();
this.LongList.ItemsSource = CustomKeyGroup<SoundData>.GetSoundGroups(svm.Software.Items);
or
this.LongList.ItemsSource = CustomKeyGroup<SoundData>.GetSoundGroups(svm.NewAdds.Items);
the reason is that you need to pass a Generic.List<.ViewModels.SoundData> in method GetSoundGroups and the list is contained in SoundGroup class. Since your data loaded is within SoundModel class so I could probably think of the above implementation only.

Create a json formatted object

I have this JSON array created in C#/aspx:
[
{
nome: "test",
apelido: "test"
}
]
And I want to create JSON like this:
{
success: 1,
error: 0,
gestor: "test",
cliente: [
{
nome: "test",
apelido: "test"
}
]
}
this is the code that i have:
var gestor = new JArray();
foreach (System.Data.DataRow item in com.Execute("select * from utilizadores").Rows)
{
gestor.Add(new JObject(new JProperty("nome", item["first_name"].ToString()),
new JProperty("apelido", item["last_name"].ToString())));
}
context.Response.Write(gestor);
I would just create a class for this (actually 2):
public class MyClass
{
public int success { get; set; }
public int error { get; set; }
public string gestor { get; set; }
public List<Cliente> cliente { get; set; }
}
public class Cliente
{
public string nome { get; set; }
public string apelido { get; set; }
}
And now you can loop to populate a list of these objects:
var myObj = new MyClass();
myObj.cliente = new List<Cliente>();
foreach (System.Data.DataRow item in com.Execute("select * from utilizadores").Rows)
{
myObj.cliente.Add(new Cliente()
{
nome = item["first_name"].ToString(),
apelido = item["last_name"].ToString()
};
}
// assuming that is successful
myObj.success = 1;
// not sure how you wanted this to be populated:
myObj.gestor = "test";
And now to serialize it you can just do:
context.Response.Write(JsonConvert.SerializeObject(myObj));
Charles' suggestion of anonymous classes is also perfectly fine if you have no other use for this class and it's not too complicated.
The most succinct way to do this is just with an anonymous class, if you are throwing this to some client side code and not really messing around with this exact object again elsewhere in server side code this is the easiest way to handle it.
var outputString = JsonConvert.SerializeObject(new {
success=1,
error=0,
gestor="test",
cliente = (from System.Data.DataRow i in com.Execute("select * from utilizadores").Rows
select new {
nome=item["first_name"],
apelido= item["last_name"]
}).ToArray()
});

Categories