reference model variable to global variable value in .net mvc3 - asp.net-mvc-3

with curiosity...
i am seeking for a temporary solution that will lead to an expansions of a system side controller.
i a mvc3.net razor based project with 100+ of class file
all of the class file (model) has a system field
specific
public string u_by { get; set; }
public System.DateTime u_date { get; set; }
public System.DateTime c_date { get; set; }
public string c_by { get; set; }
public int version { get; set;
public int groupid { get; set; }
public int status { get; set; }
at the moment the useraccess control has not been build yet which in the end the useraccess controller will and suppose to fill in this variable.
i need to fixed the value for all the variable above during a form insert, update, delete
is there any where i can
create a class and put a default value to it ?
i have created a
namespace webapp.Models
{
public class sysfield
{
public string _updatedBy;
public string _createdBy;
public DateTime _updatedDate;
public DateTime _createdDate;
public int _version;
public int _groupid;
public int _status;
//Constructor
public sysfield()
{
_updatedBy = HttpContext.Current.Server.MachineName.ToString();
_createdBy = HttpContext.Current.Server.MachineName.ToString();
_updatedDate = System.DateTime.Now;
_createdDate = System.DateTime.Now;
_version = updateVersion;
_groupid = 100;
_status = 1;
}
//Property
public int updateVersion
{
get
{
return _version;
}
set
{
_version = _version + 1;
}
}
//Set Values
public string createdBy(string initialCreator)
{
if (updateVersion == 1)
{
return _createdBy = initialCreator;
}
else
{
return _createdBy = HttpContext.Current.Server.MachineName.ToString();
}
}
public DateTime createdDate(DateTime initialDate)
{
if (updateVersion == 1)
{
return _createdDate = initialDate;
}
else
{
return _createdDate = System.DateTime.Now;
}
}
}
}
now the question is how do i default it in code below, where when i insert the model
of
namespace webapp.Models
{
public partial class usr_myapp
{
public int VEHID { get; set; }
public string CARNAME { get; set; }
public string CATEGORY { get; set; }
public string TYPE { get; set; }
public string u_by { get; set; }
public System.DateTime u_date { get; set; }
public System.DateTime c_date { get; set; }
public string c_by { get; set; }
public int version { get; set; }
public int groupid { get; set; }
public int status { get; set; }
}
}
with the Controller:
Where user will fill in everything else except for the system field c_by,u_by, and etc...
// POST: /myapp/Create
[HttpPost]
public ActionResult Create(usr_myapp usr_myapp)
{
if (ModelState.IsValid)
{
db.usr_myapp.Add(usr_myapp);
db.SaveChanges();
}
return View(usr_myapp);
}
how do i default the
`
public ActionResult Create(usr_myapp usr_myapp)
{
if (ModelState.IsValid)
{
db.usr_myapp.Add(usr_myapp);
db.SaveChanges();
}
return View(usr_myapp);
}
`
where usr_myapp consist of
public int VEHID { get; set; }
public string CARNAME { get; set; }
public string CATEGORY { get; set; }
public string TYPE { get; set; }
public string u_by { get; set; }
public System.DateTime u_date { get; set; }
public System.DateTime c_date { get; set; }
public string c_by { get; set; }
public int version { get; set; }
public int groupid { get; set; }
public int status { get; set; }
the partial class, i got it from the edmx generation should i be changing all of it?
a lost man in the amazing world

You set the defaults in the constructor. Do you have a specific need for it to be a partial class?

Related

Receiving Multi-part form data in dotnet core web API

I'm working on an web API, where it needs to receive the multi-part form data with in a model. As of now it's not receiving the request and showing the Bad request When I tried from the Postman.
My model :
public class InvoiceDetails
{
public int? po_id { get; set; }
public DateTime created_date { get; set; }
public string grn_status { get; set; }
public int utilization_amount { get; set; }
public int currency_id { get; set; }
public string currency_code { get; set; }
public string currency_symbol { get; set; }
[FromForm(Name = "invoice_file")]
public List<IFormCollection> invoice_file { get;set;}
[FromForm(Name = "other_files")]
public List<IFormCollection> other_files { get; set; }
}
In the above class/model "invoice_file" and "other_files" can have multiple file uploads so I made it List.
My Action Method :
[HttpPost]
[Route("CreateInvoice")]
public IActionResult CreateInvoice([FromForm]InvoiceDetails idobj )
{
//var modelData = Request.Form["invoice_file"];
Response resobj = new Response();
try
{
if (idobj.invoice_file.Count > 0)
{
resobj = _dataContext.AddInvoice(idobj);
if (resobj.flag == true)
{
Upload(idobj);
}
}
else
{
resobj.flag = false;
resobj.message = "please upload atleast one invioce file";
}
}
catch (Exception ex)
{
}
return Ok(resobj);
}
How can I make the action method or model, in such a way that user can upload the model with multiple files to the properties other_files & invoice_file.
Reference of postman Image
As CodeCaster says,add Content-Type:multipart/form-data; and change List<IFormCollection> to List<IFormFile>.It is not changing the whole model to List.So you can also retrieve other information which exists in your model with idobj.xxx.Change
public class InvoiceDetails
{
public int? po_id { get; set; }
public DateTime created_date { get; set; }
public string grn_status { get; set; }
public int utilization_amount { get; set; }
public int currency_id { get; set; }
public string currency_code { get; set; }
public string currency_symbol { get; set; }
[FromForm(Name = "invoice_file")]
public List<IFormCollection> invoice_file { get;set;}
[FromForm(Name = "other_files")]
public List<IFormCollection> other_files { get; set; }
}
to
public class InvoiceDetails
{
public int? po_id { get; set; }
public DateTime created_date { get; set; }
public string grn_status { get; set; }
public int utilization_amount { get; set; }
public int currency_id { get; set; }
public string currency_code { get; set; }
public string currency_symbol { get; set; }
[FromForm(Name = "invoice_file")]
public List<IFormFile> invoice_file { get; set; }
[FromForm(Name = "other_files")]
public List<IFormFile> other_files { get; set; }
}
result:
IFormCollection is used to retrieve all the values from posted form data.refer to the official document.
If you want to use c,you can try to use it,you can do like this
public IActionResult CreateInvoice([FromForm]IFormCollection idobj)
and you need to get the data you want to foreach keys of IFormCollection,so public List<IFormCollection> invoice_file { get;set;} is better than use IFormCollection.

Web API JSON deserialization converting value issue

I am trying to insert JSON data into my models via EF 6. I am getting this error;
Inner Exception is {0}System.ArgumentException: Could not cast or convert from System.String to EPINMiddleWareAPI.Models.Serial.
konum: Newtonsoft.Json.Utilities.ConvertUtils.EnsureTypeAssignable(Object value, Type initialType, Type targetType)
konum: Newtonsoft.Json.Utilities.ConvertUtils.ConvertOrCast(Object initialValue, CultureInfo culture, Type targetType)
konum: Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfo culture, JsonContract contract, Type targetType)
Message ---
{0}Error converting value "c57a55b5-b2d4-46e7-86e0-cc13726ca8a7" to type 'EPINMiddleWareAPI.Models.Serial'. Path 'coupons[0].serials[0]', line 1, position 310.
Here is my model structure:
public class ConfirmResponse
{
public int Id { get; set; }
public string referenceId { get; set; }
public string version { get; set; }
public string signature { get; set; }
public string paymentID { get; set; }
public string productCode { get; set; }
public string currency { get; set; }
public string ApplicationCode { get; set; }
public double unitPrice { get; set; }
public double totalPrice { get; set; }
public string purchaseStatusCode { get; set; }
public DateTime? purchaseStatusDate { get; set; }
public DateTime? requestDateTime { get; set; } = DateTime.Now;
public string merchantProductCode { get; set; }
public List<Coupon> coupons { get; set; }
}
public class Coupon
{
public int Id { get; set; }
public int ConfirmResponseID { get; set; }
public List<Serial> serials { get; set; }
public List<Pin> pins { get; set; }
public virtual ConfirmResponse confirmResponse { get; set; }
}
public class Serial
{
public int Id { get; set; }
public string serials { get; set; }
public int CouponID { get; set; }
public virtual Coupon coupons { get; set; }
}
My sample JSON:
"{\"referenceId\":\"0000000046\",\"paymentId\":\"MDO1037624\",\"productCode\":\"001002461285\",\"quantity\":\"1\",\"currency\":\"TL\",\"unitPrice\":\"46,47\",\"totalPrice\":\"46,47\",\"merchantProductCode\":\"\",\"purchaseStatusCode\":\"00\",\"purchaseStatusDate\":\"2019-03-17T20:58:48Z\",\"coupons\":[{\"serials\":[\"c57a55b5-b2d4-46e7-86e0-cc13726ca8a7\"],\"pins\":[\"T6VC-XC6X-3H6JS-NVWL-93PCa\"]}],\"version\":\"V1\",\"signature\":\"2f961c7dbc32c3bc128b6e69d19e8e1a\",\"applicationCode\":\"52e7cf966b724749a7c4efadc3727ed7\"}"
How can I fix this problem? I would like to insert this JSON into my database tables. I am using EF 6.
edit:
This model structure solved my problem. Now I can insert serials and pins into database.
public class ConfirmResponse
{
public int Id { get; set; }
public string referenceId { get; set; }
public string version { get; set; }
public string signature { get; set; }
public string paymentID { get; set; }
public string productCode { get; set; }
public string currency { get; set; }
public string ApplicationCode { get; set; }
public double unitPrice { get; set; }
public double totalPrice { get; set; }
public string purchaseStatusCode { get; set; }
public DateTime? purchaseStatusDate { get; set; }
public DateTime? requestDateTime { get; set; } = DateTime.Now;
public string merchantProductCode { get; set; }
public List<Coupon> coupons { get; set; }
}
public class Coupon
{
public int Id { get; set; }
public int ConfirmResponseID { get; set; }
public List<string> serials { get; set; }
public List<string> pins { get; set; }
public virtual ConfirmResponse confirmResponse { get; set; }
public List<string> StringsSerial
{
get { return serials; }
set { serials = value; }
}
public List<string> StringsPin
{
get { return pins; }
set { pins = value; }
}
[Required]
public string Serial
{
get { return String.Join(",", serials); }
set { serials = value.Split(',').ToList(); }
}
[Required]
public string Pin
{
get { return String.Join(",", pins); }
set { pins = value.Split(',').ToList(); }
}
}
Thanks in advance.
you're json is wrong
take a look into the coupons array, you initialize the serials array with an string/guid and not with a model of serial
it should be
"coupons": [{
{
"serials": [{
"serials": "c57a55b5-b2d4-46e7-86e0-cc13726ca8a7"
}
],
}
}
]...
I guess for Pins the same

Why Entity Framework replaces provided value with a new incremental value

I'm trying to work my way through a Dot Net Core MVC project, but I am facing a problem I couldn't solve.
And honestly, I didn't know what to search for.
The project is a simple vehicle registry,
Each vehicle has a Make, a Model, a some Features.
Here are the domain models:
public class Make
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Model> Models { get; set; }
public Make()
{
Models=new Collection<Model>();
}
}
public class Model
{
public int Id { get; set; }
public string Name { get; set; }
public Make Make { get; set; }
public int MakeId { get; set; }
public Model()
{
Make=new Make();
}
}
public class Feature
{
public int Id { get; set; }
public string Name { get; set; }
}
[Table(name:"VehicleFeatures")]
public class VehicleFeature
{
public int VehicleId { get; set; }
public int FeatureId { get; set; }
public Feature Feature { get; set; }
public Vehicle Vehicle { get; set; }
public VehicleFeature()
{
Feature=new Feature();
Vehicle=new Vehicle();
}
}
public class Vehicle
{
public int Id { get; set; }
public Model Model { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ModelId { get; set; }
public ICollection<VehicleFeature> VehicleFeatures { get; set; }
public string ContactName { get; set; }
public string ContactPhone { get; set; }
public string ContactEmail { get; set; }
public DateTime LastUpdate { get; set; }
public bool IsRegistered { get; set; }
public Vehicle()
{
Model=new Model();
VehicleFeatures=new Collection<VehicleFeature>();
}
}
The problem is that when I send the following request to the corresponding controller, EF is replacing the provided value with a new incremental value.
The request I send:
{
"ModelId":10,
"VehicleFeatures":[
{"featureId":45},
{"featureId":46}
],
"ContactName":"Alice",
"ContactPhone":"1234",
"ContactEmail":"Alice#local",
"LastUpdate":"1980-01-01",
"IsRegistered":true
}
And this is what happens:
The controller receives correct values,
Correct values are added to the context,
And then suddenly all hell breaks loose.
This is the controller code:
[HttpPost]
public async Task<IActionResult> CreateVehicle([FromBody] Vehicle v)
{
context.Vehicles.Add(v);
await context.SaveChangesAsync();
return Ok(v.ModelId);
}
What am I missing here?

Xamarin - reading JSON file and reading the values

everyone ! I'm new in Xamarin. I've this json file...
{
"debug":true,
"sequence":[
"p1"
],
"pages":[
{
"pageId":"p1",
"type":"seq",
"elements":[
{
"type":"smallVideo",
"width":300,
"height":300,
"top":0,
"left":0,
"file":"xxx.mp4"
}
]
}
],
"index":[
{
"width":300,
"height":300,
"top":0,
"left":0,
"goTo":"p1"
}
]
}
And this is my simple code...
using Newtonsoft.Json;
JObject elements = JObject.Parse(File.ReadAllText("elements.json"));
Console.WriteLine(elements);
Ok, I can see on my output screen the whole JSON file. Fine...
But I'd like to read any value just like javascript, examples...
elements.debug (true)
elements.pages[0].pageId
So, I need to retrieve values based on the key/path like it's usual in Javascript. Any clue ?
ty !
C# is a little bit different from js, here you need to declare objects.
In your case you need to create new class called ElementsObj and your object would be this class instance:
public class ElementsObj
{
public bool debug { get; set; }
public List<string> sequence { get; set; }
public List<Page> pages { get; set; }
public List<Index> index { get; set; }
}
public class Element
{
public string type { get; set; }
public int width { get; set; }
public int height { get; set; }
public int top { get; set; }
public int left { get; set; }
public string file { get; set; }
}
public class Page
{
public string pageId { get; set; }
public string type { get; set; }
public List<Element> elements { get; set; }
}
public class Index
{
public int width { get; set; }
public int height { get; set; }
public int top { get; set; }
public int left { get; set; }
public string goTo { get; set; }
}
In future use http://json2csharp.com/ to generate classes from JSON file.
Later you can deserialize your JSON to this object.
I'd suggest Newtonsoft lib to do this:
ElementsObj tmp = JsonConvert.DeserializeObject<ElementsObj>(jsonString);
1) Option create an object that reflects your JSON structure:
public class Element
{
public string type { get; set; }
public int width { get; set; }
public int height { get; set; }
public int top { get; set; }
public int left { get; set; }
public string file { get; set; }
}
public class Page
{
public string pageId { get; set; }
public string type { get; set; }
public List<Element> elements { get; set; }
}
public class Index
{
public int width { get; set; }
public int height { get; set; }
public int top { get; set; }
public int left { get; set; }
public string goTo { get; set; }
}
public class MyObject
{
public bool debug { get; set; }
public List<string> sequence { get; set; }
public List<Page> pages { get; set; }
public List<Index> index { get; set; }
}
MyObject parsed = JsonConvert.DeserializeObject<MyObject>(File.ReadAllText("elements.json"));
var debug = parsed.debug;
2) Option using dynamic
dynamic results = JsonConvert.DeserializeObject<dynamic>(File.ReadAllText("elements.json"));
var debug = dynamic.debug;

Microsoft Cognitive Services Web Search API - DeSerialization Issues

I want to learn Cognitive Services Web Search APIs so I started creating a bot application . I already have a account sub- key and other required information also I read many articles and watch build 2016 videos on this as well.I am having trouble while deserializing the result .
I am not able to find the proxy class that I can use to do that .
The url I am using is https://api.cognitive.microsoft.com/bing/v5.0/search/
and I found a proxy class for previous api version . Can anybody tell me how to get proxy class of the api request / response in VS 2015 for these service.
My Code look like this:
string BingSearchUrl = "https://api.cognitive.microsoft.com/bing/v5.0/search/";
const string bingKey = "Key";
public static async Task<string> Search(string query)
{
var client = HttpClientFactory.Create();
var queryString = BingSearchUrl + "?q=" + query + "&count=10";
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", bingKey);
client.DefaultRequestHeaders.Add("Accept", "application/json");
// Request parameters
string r = await client.GetStringAsync(queryString);
var jsonResult = JsonConvert.DeserializeObject<Bing.ExpandableSearchResult>(r);
return jsonResult.Web.First().Title;
Try below code
public string BingSearchUrl = "https://api.cognitive.microsoft.com/bing/v5.0/search/";
const string bingKey =[KEY];
public async void Search()
{
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", bingKey);
// Request parameters
queryString["q"] = "microsoft";
queryString["count"] = "10";
queryString["offset"] = "0";
queryString["mkt"] = "en-us";
queryString["safeSearch"] = "Moderate";
var uri = "https://api.cognitive.microsoft.com/bing/v5.0/news/search?" + queryString;
var response = await client.GetStringAsync(uri);
var jsonResult = JsonConvert.DeserializeObject<BingJson>(response);
string title = jsonResult.value[0].name.ToString();
}
With the jsonResult.value[0] you can loop through the results. First results is at [0] position.
I Created a model class looking at the bing search response json. It looks like,
public class BingJson
{
public string _type { get; set; }
public Instrumentation instrumentation { get; set; }
public string readLink { get; set; }
public int totalEstimatedMatches { get; set; }
public Value[] value { get; set; }
}
public class Instrumentation
{
public string pingUrlBase { get; set; }
public string pageLoadPingUrl { get; set; }
}
public class Value
{
public string name { get; set; }
public string url { get; set; }
public string urlPingSuffix { get; set; }
public Image image { get; set; }
public string description { get; set; }
public About[] about { get; set; }
public Provider[] provider { get; set; }
public DateTime datePublished { get; set; }
public string category { get; set; }
}
public class Image
{
public Thumbnail thumbnail { get; set; }
}
public class Thumbnail
{
public string contentUrl { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class About
{
public string readLink { get; set; }
public string name { get; set; }
}
public class Provider
{
public string _type { get; set; }
public string name { get; set; }
}
With this model, I am able to get the desired result. The Model which is presented in the other answer is not working in my case.
namespace BingSearchBot
{
public class RootObject
{
public string _type { get; set; }
public WebPages webPages { get; set; }
public RelatedSearches relatedSearches { get; set; }
public RankingResponse rankingResponse { get; set; }
}
public class WebPages
{
public string webSearchUrl { get; set; }
public int totalEstimatedMatches { get; set; }
public List<Value> value { get; set; }
}
public class Value
{
public string id { get; set; }
public string name { get; set; }
public string url { get; set; }
public List<About> about { get; set; }
public string displayUrl { get; set; }
public string snippet { get; set; }
public List<DeepLink> deepLinks { get; set; }
public string dateLastCrawled { get; set; }
public List<SearchTag> searchTags { get; set; }
}
public class About
{
public string name { get; set; }
}
public class DeepLink
{
public string name { get; set; }
public string url { get; set; }
public string snippet { get; set; }
}
public class SearchTag
{
public string name { get; set; }
public string content { get; set; }
}
public class Value2
{
public string text { get; set; }
public string displayText { get; set; }
public string webSearchUrl { get; set; }
}
public class RelatedSearches
{
public string id { get; set; }
public List<Value2> value { get; set; }
}
public class Value3
{
public string id { get; set; }
}
public class Item
{
public string answerType { get; set; }
public int resultIndex { get; set; }
public Value3 value { get; set; }
}
public class Mainline
{
public List<Item> items { get; set; }
}
public class RankingResponse
{
public Mainline mainline { get; set; }
}
}

Resources