how to pass hardcoded guid in postman body section - c#

I'm trying to pass 2 guid values to a .net api like below image
if i pass like above image i'm not getting the values in .net
like below image .. pls let me know the syntax to pass the hardcoded guid in postman

You should use the static method Guid.NewGuid() instead of calling the default constructor. This should work:
var ApplicationId = Guid.NewGuid();
var DistrictId = Guid.NewGuid();

There is no GUID data type in JSON, so you can't use it directly.
Instead, you can use your parameter's datatype as 'string' in your model.
Then:
Solution 1
Optionally, you can define your parameters as string, then convert them into GUID in your method:
public class AuthenticateModel
{
//...
public string ApplicationId { get; set; }
public string DistrictId { get; set; }
//...
}
In your method:
public SecurityToken AuthenticateUser(AuthenticateModel authenticateModel)
{
var applicationId = Guid.Parse(authenticateModel.ApplicationId);
var districtId = Guid.Parse(authenticateModel.DistrictId);
}
Solution 2:
You can create 2 new variables:
public class AuthenticateModel
{
public string ApplicationId { get; set; }
public string DistrictId { get; set; }
[JsonIgnore] //this is for Newtonsoft.Json
[IgnoreDataMember] //this is for default JavaScriptSerializer class
public Guid ApplicationGuid { get => Guid.Parse(ApplicationId); set => ApplicationId = value.ToString(); }
[JsonIgnore] //this is for Newtonsoft.Json
[IgnoreDataMember] //this is for default JavaScriptSerializer class
public Guid DistrictGuid { get => Guid.Parse(DistrictId); set => DistrictId = value.ToString(); }
}
and then use it in your method:
public SecurityToken AuthenticateUser(AuthenticateModel authenticateModel)
{
//...
doSomething(authenticateModel.ApplicationGuid);
doSomething(authenticateModel.DistrictGuid);
//...
}
Hope it works for you.

Related

EF and [JsonIgnore]: Why do I get an empty dictionary when using an existing type, but not when using an anonymous type?

Question
When using an anonymous type it works, but not when using the type ClientGroupView, which is identical to the anonymous type. Why?
I suspect this has to do with the [JsonIgnore] attribute - it somehow persists with the typed object, but not with the anonymous object.
Background
I've got a many-to-many relationship between Clients and ClientGroups and a controller that returns the groups for a given client.
The controller method returns Json with an empty dictionary, when I use a typed object, but not if I use an anonymous object, then it returns the expected Json. I get the same results with both .NET 5 and .Net 6.
When using an anonymous object, the Json returned is:
[{
"group":{ "clientGroupId":1, "groupName":"ClientGroup1" },
"permissions":{ "rClientGroupClientId":1, "clientGroupId":1, "clientId":1 }
}]
When using an object of type ClientGroupView (that does not contain any [JsonIgnore] attrubutes), the Json returned is:
[{}]
I both cases result is the same, before converting to Json, with return Ok(result).
The controller
The controller method that returns the information for a given ClientId:
[HttpGet]
[Route("{id}")]
public async Task<IActionResult> GetClientGroups(int id)
{
var client = await db.Clients.FindAsync(id);
if (client == null)
return NotFound();
// Works when using an anonymous type - the Json dictionary is not empty.
var groups = db.Entry(client)
.Collection(r => r.XClientGroups)
.Query()
.Include(r => r.ClientGroup)
.Select(r => new { r.ClientGroup, r });
// But fails when not using an anonymous type - the json dictionary is empty.
//var groups = db.Entry(client)
// .Collection(r => r.XClientGroups)
// .Query()
// .Include(r => r.ClientGroup)
// .Select(r => new ClientGroupView(r.ClientGroup, r));
var result = await groups.ToListAsync();
if (result == null || result.Count <= 0)
return NotFound();
return Ok(result);
}
The Client
public class Client
{
public int ClientId { get; set; }
public string ClientName { get; set; } = string.Empty;
[JsonIgnore]
public virtual ICollection<X_ClientGroup_Client> XClientGroups { get; set; }
public Client()
{
XClientGroups = new HashSet<X_ClientGroup_Client>();
}
}
The ClientGroup
public class ClientGroup
{
public int ClientGroupId { get; set; }
public string GroupName { get; set; }
[JsonIgnore]
public virtual ICollection<X_ClientGroup_Client> XClients { get; set; }
public ClientGroup()
{
XClients = new HashSet<X_ClientGroup_Client>();
}
}
The X_ClientGroup_Client
The many-to-many relation between Client and ClientGroup:
public class X_ClientGroup_Client
{
public int RClientGroupClientId { get; set; }
public int ClientGroupId { get; set; }
public int ClientId { get; set; }
[JsonIgnore]
public ClientGroup ClientGroup { get; set; }
[JsonIgnore]
public Client Client { get; set; }
}
The ClientGroupView
Here is the ClientGroupView that corresponds to the anonymous object. It doesn't contain any [JsonIgnore] attributes:
public class ClientGroupView
{
public ClientGroup Group;
public X_ClientGroup_Client Permissions;
public ClientGroupView(ClientGroup group, X_ClientGroup_Client permissions)
{
this.Group = group;
this.Permissions = permissions;
}
}
If I remove the constructor and construct the object like I do with the anonymous object, the result is the same.
A solution is to change ClientGroupView to contain the fields instead of the classes, but I prefer that it contained the classes instead of the fields of the classes, because it is easier to maintain:
// I do not want to use this version of ClientGroupView
public class ClientGroupView
{
public int RClientGroupClientId { get; set; }
public int ClientId { get; set; }
public int ClientGroupId { get; set; }
public string GroupName { get; set; }
public ClientGroupView(ClientGroup clientgroup, X_ClientGroup_Client permissions)
{
RClientGroupClientId = permissions.RClientGroupClientId;
ClientId = permissions.ClientId;
ClientGroupId = clientgroup.ClientGroupId;
GroupName = clientgroup.GroupName;
}
}
The reason I don't want to use this version, is because it requires more maintenance and because the controller is used internally, i.e. I do not need to use a DTO.
ClientGroupView.Group and ClientGroupView.Permissions are fields, not properties.
Add { get; set; }.

Defining a route with multiple parameters

I would like to define a route like this
https://www.example.com/api/Company/Example/Sequence/0325671?Next=10&Reference=1&Option=none...
Where ... can be 0 to N parameters that can be null or default if not used.
Can I do this?
public IHttpActionResult GetNextRange([FromUri] ParameterDto parameters)
{
}
public class ParameterDto
{
public long Next { get; set; }
public string Reference { get; set; }
public string Option { get; set; }
}
Current examples are for .NET Core - using [FromQuery] attribute. It case it is Full .NET [FromUri] should be used.
In case the parameters are in query string you should use [FromQuery] attribute (if it is .NET Core):
public IHttpActionResult GetNextRange([FromQuery] ParameterDto parameters)
{
}
If you want to map query string parameters to object then you should add this attribute for every needed property:
public class ParameterDto
{
[FromQuery]
public long Next { get; set; }
[FromQuery]
public string Reference { get; set; }
[FromQuery]
public string Option { get; set; }
}
You can also specify name of parameter:
[FromQuery(Name = "some_query_parameter_name")]
If you don't know the exact parameters (so why do you need this?) you can get all the parameters from Request.Query (.NET Core) or Request.QueryString (Full .NET) property:
var keys = Request.Query.Keys; // or Request.QueryString.AllKeys;
var parameterValue = Request.Query["parameterName"]; // or Request.QueryString["parameterName"];

Only update parameters where the value is specified by client

I have a servicestack service which accepts a DTO that looks like this:
[Route("/appointment/{id}", Verbs = "POST")]
public class UpdateAppointment
{
public Guid Id { get; set; }
public DateTime StartTime { get; set; }
public int Duration { get; set; }
public string Description { get; set; }
public Guid? MemberId { get; set; }
}
How can I check whether the MemberId value was set by the client since "null" is a valid value. Normally if NULL is not a valid value, I could use the PopulateWithNonDefaultValues() method.
So the result should be that if I don't specify MemberId in my HTTP POST payload, I want the server to not update the value.
I hope that makes sense..
This is not normally an issue if you consider that the client always provides all values when calling the UpdateAppointment Service. So I'd highly recommend that you consider every property is a "valid" value provided by the client and update all fields.
Create a separate Service if only want to update a partial property list.
If I really needed to check whether the client provided a value you can specify a different value in the Request DTO constructor, e.g:
public class UpdateAppointment
{
public UpdateAppointment()
{
MemberId = Guid.Empty;
}
//...
}
where a non Guid.Empty value means it was populated by the client.
Or you could also use a calculated Property:
public class UpdateAppointment
{
[IgnoreDataMember]
public bool HasMemberId { get; set; }
Guid? memberId;
public Guid? MemberId
{
get { return memberId; }
set
{
memberId = value;
HasMemberId = true;
}
}
}
A more fragile alternative is to buffer the Request with the global Request Filter:
appHost.PreRequestFilters.Add((httpReq, httpRes) => {
httpReq.UseBufferedStream = true;
});
Which will retain a copy of the Request Stream which you can get a copy of in your Service with:
var jsonBody = base.Request.GetRawBody();
var hasMemberId = jsonBody.ToLower().Contains("memberid");
Although note this is serializer dependent, i.e. wont work with Binary Serializers like ProtoBuf or MsgPack.
Why is MemberId nullable if null value is not allowed?
Just change its definition to:
public Guid MemberId { get; set; }
have you tried load the values first then editing it before update?
I mean this:
[HttpPost]
public ActionResult Update(UpdateAppointment UAForm){
UpdateAppointment ua = new UpdateAppointmentBll().Find(UAForm.Id);
ua.StartTime = UAForm.StartTime;
//so no...
if(UAForm.MemberId != null)
ua.MemberId = UAForm.MemberId;
new UpdateAppointmentBll().Save(ua);
return View();
}

How Can I Deserialize JSON Data Using C#?

I have seen some other questions like this, but those are quite complex JSON data's that have objects within objects. Although the JSON I'm working with is never static, I doubt it's as complex as those. Also, it's my first time using JSON with C# so I'm a little clueless.
What I'm trying to achieve is to separate the data that is received from an API that I prompt using WebRequest in C#.
{
"johhny.debt": {
"id":35187540,
"name":"johnny.debt",
"profileIconId":786,
"Level":30,
"revisionDate":1428019045000
}
}
The returned JSON data is in a fashion like thereof.
I want to be able to access all of the properties of the above string in the following manner:
ID :
Name:
~~
~~
~~
... and so forth.
I'm assuming some type of class has to be made for this?
All help is appreciated, thank you all in advance.
Install Json.Net from Nuget
Install-Package Newtonsoft.Json
https://www.nuget.org/packages/Newtonsoft.Json/
Declare class for inner object ({"id":..., "name": ... }):
public class InnerObject
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("name")]
public string Username { get; set; }
[JsonProperty("profileIconId")]
public int ProfileIconId { get; set; }
[JsonProperty("level")]
public int Level { get; set; }
[JsonProperty("revisionDate")]
public string RevisionDate { get; set; }
}
As you can see you can specify rename mapping from json fields to .Net object properties using JsonPropertyAttribute.
Read your json to Dictionary<string,InnerObject> and get value of "johhny.debt" key:
var dict = JsonConvert.DeserializeObject<Dictionary<string, InnerObject>>(jsonText);
var johhny = dict["johhny.debt"];
Or if your need always to parse exact json property 'johhny.debt', you could create root object class:
public class RootObject
{
[JsonProperty("johhny.debt")]
public InnerObject JohhnyDept { get; set; }
}
And deserialize it:
var root = JsonConvert.DeserializeObject<RootObject>(jsonText);
var johhny = root.JohhnyDebt;
Just Create a class like this
public class RootObject
{
public int Id { get; set; }
public string name { get; set; }
public int profileIconId { get; set; }
public int Level { get; set; }
public string revisionDate { get; set; }
}
then install json.Net and this code to your main method
var jsonObject=JsonConvert.DeserializeObject<RootObject>(jsonText);
That's all
Update
var obj = JObject.Parse(json);
var RootObject = new RootObject()
{
Id = (int)obj["johhny.debt"]["id"],
Level = (int)obj["johhny.debt"]["Level"],
name = (string)obj["johhny.debt"]["name"],
profileIconId = (int)obj["johhny.debt"]["profileIconId"],
revisionDate = (string)obj["johhny.debt"]["revisionDate"]
};

ServiceStack How generate an Json response with only the Primary Key?

When I create a new record in my table I would like generate an json response with only the primary ID of my new record, somethink like : {"PrimaryID":123}
I actually use this handmade function:
// Inserts a new row into the PatientSession table
public string AddPatientSession(PatientSession p)
{
int id = (int)_dbConnection.Insert<PatientSession>(p, selectIdentity: true);
string Idconvert = id.ToString();
string IdInsert = "{\"PatientSessionId\":" + Idconvert + "}";
return IdInsert;
}
But I assume it's not the best way to do it, have you a suggestion please?
Thanks in advance
If you just want to return a small JSON payload with just an Id you can use a type with only the fields you want to return, e.g:
public class AddPatientSession : IReturn<PatientId> { ... }
public class PatientId {
public int PatientSessionId { get; set; }
}
Then use in your service like:
public class MyServices : Service
{
public object Any(AddPatientSession request)
{
var model = request.ConvertTo<PatientSession>();
return new PatientId {
PatientSessionId = Db.Insert(model, selectIdentity: true);
}
}
}
Returning an object takes advantage of ServiceStack's built-in Content Negotiation to return the object serialized in the preferred Content-Type, e.g. JSON for JSON/ajax clients.
You can also return an anonymous type containing just the Id:
public object Any(AddPatientSession request)
{
var model = request.ConvertTo<PatientSession>();
return new {
PatientSessionId = Db.Insert(model, selectIdentity: true);
}
}
Which will also serialize to JSON when requested, but the lack of a type does prevent this from being called with ServiceStack's generic typed Service Clients.
Thanks you so much #mythz it's working well I just use a convert function to int because "Db.Insert" return a long type.
// Add PatientSession via POST
public class PatientSessionADD : IReturn<PatientSessionResponseId>
{
public int PatientSessionId { get; set; }
public int ByPatientId { get; set; }
public DateTime PatientStartSessionTime { get; set; }
public int PatientStartSessionByUserId { get; set; }
public DateTime PatientEndSessionTime { get; set; }
public int PatientEndSessionByUserId { get; set; }
}
public class PatientSessionResponseId
{
public int PatientSessionId { get; set; }
}
public object Post(PatientSessionADD request)
{
var p =new PatientSession()
{
ByPatientId = request.ByPatientId,
PatientStartSessionTime = request.PatientStartSessionTime,
PatientStartSessionByUserId = request.PatientStartSessionByUserId
};
return new PatientSessionResponseId
{
PatientSessionID = Convert.ToInt16( Db.Insert<PatientSession>(p, selectIdentity: true) )
};
}
To resume this function get a HTTP POST message, store it in database and return a JSON response with only the Primary ID generated.
Have fun and thanks again mythz

Categories

Resources