Validate Smart Format object against the token available in the string - asp.net

I am trying to validate the smart format object against the token present in the string.
Sample:-
object obj = {"Id": "1", "RegNo": "REG123"}
Smart.Format("Your Id - {Id} for registration - {RegNo}", obj);
If I do not pass RegNo property/value in the object then smart format throws an error. Instead do we have any proper validation method to validate the tokens required against the object provided.
Any help would be appreciated.

SmartFormat provides various extensions which allow to format a string depending on the provided arguments. Here is the example code for a missing "RegNo". Still, this is not "validation", but rather "conditional formatting".
// Create a formatter with necessary extensions, including NewtonsoftJsonSource
var smart = new SmartFormatter(settings ?? new SmartSettings())
.AddExtensions(new NewtonsoftJsonSource(), new DefaultSource())
.AddExtensions(new NullFormatter(), new DefaultFormatter());
// Parse the JSON input
var jObject = JObject.Parse(#"{""Id"": ""1"", ""RegNo"": null}");
var result = smart.Format("Id: {Id:isnull:Value is Null|{}} - RegNo: {RegNo:isnull:Value is Null|{}}", jObject);
// Result: "Id: 1 - RegNo: Value is Null"

Related

Spring-test cannot set #RequestPart. It always send it as null

I cannot test Controller by using mockMvc in spring-test. I want to know right way to test API with #RequestPart.
The method to test is this.
#RequestMapping(value = "/", method = RequestMethod.POST)
public ResponseEntity<Object> replaceFile(
#RequestPart("files") Map<String, Object> files,
#RequestPart("fileKey") String fileKey)
And to test I build a mock request like below.
MockMultipartFile blob = new MockMultipartFile("files", files.getBytes());
MockMultipartFile key = new MockMultipartFile("fileKey", fileKey.getBytes());
mockMvc.perform(fileUpload("/")
.file(blob)
.file(key))
.andDo(print())
.andExpect(status().isOk());
As you can see, I used fileUpload. But in past time, I tried to use post with content or requestAttr because all of them didn't work.
I think current code is the closest to answer among I tried, but can't get closer anymore.
The weird thing is, the real in-use API is almost same with them.
In client side, user sent a new FormData() object to request and server can get data properly.
The server side code is below.
#RequestMapping(value = "/api/{variable}", method = RequestMethod.POST)
public ResponseEntity<Object> apiMethod(
#PathVariable int variable,
#RequestPart("dto1") DTO1 dto1,
#RequestPart("dto2") DTO2 dto2,
#RequestPart("file") Map<String, Object> file)
"file" part consists of "file name" key and its blob value encoded base64.
For example, {"hello.txt": "SGVsbG8gd29ybGQh"}
What I want to know - Right way to test API with #RequestPart
What I tried
method - fileUpload / data - file, content, requestAttr but they send null.
method - post / data - file, content, requestAttr but they throw MultipartException.
Restriction - Cannot use multipart because the system is using a low version of Spring.
Thanks!
Thanks to #borino who commented to my question, I got the clue of problem.
It is certain to use fileUpload for testing API with #RequestPart arguments.
In that case, it caused from content type.
I declared MockMultipartFile without contentType.
MockMultipartFile blob = new MockMultipartFile("files", files.getBytes());
MockMultipartFile key = new MockMultipartFile("fileKey", fileKey.getBytes());
But the arguments of API have a type, Map<String,Object> and String each.
As #borino said to me, I changed constructor of MockMultipartFile to make sure contentType, and it works!
MockMultipartFile blob = new MockMultipartFile("files", "", "application/json", files.getBytes());
MockMultipartFile key = new MockMultipartFile("fileKey", "", "application/json", fileKey.getBytes());
Just add contentType when you have a problem like me. Thanks!

Creating a GET method with request body in kotlin using ARest Framework

I am setting up a new service consisting of GET, DELETE and POST method APIs using ARest framework in kotlin.
I am wrapping up the inputs in a data class and passing it out to the methods. In this case DELETE and POST method works fine but I face some problem with the GET method.
Data class for wrapping the input :
class GetRequest(#QueryParam("aaa") var aaa: String? = null,
#QueryParam("bbb") var bbb: String? = null,
#QueryParam("ccc") var ccc: UserDefinedType? = null)
Model definition :
#GET
#Path("getStatus/")
#Produces(MediaType.APPLICATION_JSON)
fun getStatus(#NotNull #BeanParam getRequest: GetRequest) : GetResponse
I use swagger to call the methods,
Body of the request :
{
"aaa": "string",
"bbb": "string",
"ccc": "HEAD"
}
My understanding is that, #BeanParam will inject the corresponding parameters from the query into the data class. But from swagger I find the request URL as,
https://:8090/api/getStatus and couldn't find any query params. Because of which the value of "aaa" remains null instead of getting changed to "string". Could someone help me in pointing out the mistake I made here?
The resource and data class expects parameters as query parameters, but you send them in the body. You should send them as query parameters instead (getStatus?aaa=string&bbb=string&ccc=HEAD), or if you want to send it in the body (which is not recommended for a GET request), you have to modify your code, for example:
#GET
#Path("getStatus/")
#Produces(MediaType.APPLICATION_JSON)
fun getStatus(getRequest: GetRequest) : GetResponse
class GetRequest(var aaa: String? = null,
var bbb: String? = null,
var ccc: UserDefinedType? = null)

Get c# object list from response.Content.ReadAsStringAsync()

I am wroking on asp.net core web api and I am new in asp.net core. I make a web api and want to call it from web application controller and its works good. My problem is I want to convert json in c# object list. I already get a json format from web api, but enable to convert it into c# object list. I google a lot and find one solution in everywhere and that is
JsonConvert.DeserializeObject<BusinessUnit>(result);
Which is not working for me. My Code :
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetAsync(baseAddress + "/api/BusinessUnit");
var result = response.Content.ReadAsStringAsync();
List<BusinessUnit> businessunits = JsonConvert.DeserializeObject<BusinessUnit>(result); //result shows error because it needs string as parameter.
I am still trying but enable to solve this problem.
How can I convert "result(json format)" in c# object list "businessunits" ?
Thanks in advance.
You need to await the task like so:
var result = await response.Content.ReadAsStringAsync();
Danger of using var, as now it inferred the type as Task<string>. If you had tried:
string result = response.Content.ReadAsStringAsync();
It would have immediately given you an error that it can't cast Task<string> to string.
EDIT: The other error you have is that you are trying to deserialize the JSON into an object when it is actually an array.
List<BusinessUnit> businessunits = JsonConvert.DeserializeObject<List<BusinessUnit>>(result);
In .NET Core this is done as:
var units = await result.Content.ReadFromJsonAsync<List<BusinessUnit>>();
You can use .Result to convert in string :
string XYZ = response.Content.ReadAsStringAsync().Result;
You could try this:
IEnumerable<BusinessUnit> result = await response.Content.ReadAsAsync<IEnumerable<BusinessUnit>>();
Saludos.

Json format of data which is having HTML tags in Web API in C#

I have an object Example
Class Event
{
string country{get;set}
}
Events test = new Evnts();
test.country="<P>India<P>"
How i need to Json format for the above.
I used the method
System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new
System.Web.Script.Serialization.JavaScriptSerializer();
StringContent sc = new StringContent(oSerializer.Serialize(list));
sc.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return sc;
But this is giving output result as "City": "\u003cp\u003eIndia\u003cp\u003e",
Please comment on this .
Thank you
That's encoded <> tag representation. You shouldn't return specific html element in JSON response. Also, no need to use JavaScriptSerializer class. You can simply return your "Event" class as a result of your svc web api service.
Actually I am fetching Rich text from Sitecore Item,
I used Regex to remove the HTML tags and Replace Method to replace the "’" and Replace(" ",""). I am directly sending the List of events not using JavaScriptSerializer class.
((Regex.Replace(eve["text"].ToString(), "<[^>]*>", "").Replace("’", "'")).Replace(" ","")).Replace("\n","");
Thank you Pravin and Ivan Sivak

CreateEnvelopeFromTemplates - Guid should contain 32 digits with 4 dashes

I am attempting to create a DocuSign envelope from a template document using the CreateEnvelopeFromTemplates method, available within their v3 SOAP API web service. This is being instantiated from a asp.NET v4.0 web site.
Upon calling the method armed with the required parameter objects being passed in. I am recieving an exception from the web service, basically telling me that the Template ID is not a valid GUID.
669393: Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).
Line 14889:
Line 14890: public DocuSignDSAPI.EnvelopeStatus CreateEnvelopeFromTemplates(DocuSignDSAPI.TemplateReference[] TemplateReferences, DocuSignDSAPI.Recipient[] Recipients, DocuSignDSAPI.EnvelopeInformation EnvelopeInformation, bool ActivateEnvelope) {
Line 14891: return base.Channel.CreateEnvelopeFromTemplates(TemplateReferences, Recipients, EnvelopeInformation, ActivateEnvelope);
Line 14892: }
Line 14893:
The template reference, a guid. Must be specified as the "Template" string property against TemplateReference object. This is then added to a dynamic array of TemplateReferences, which is one of the input parameters of the CreateEnvelopeFromTemplates method.
Actual template GUID: f37b4d64-54e3-4723-a6f1-a4120f0e9695
I am building up my template reference object using the following function that i wrote to try and make the functionality reusable:
Private Function GetTemplateReference(ByVal TemplateID As String) As TemplateReference
Dim templateReference As New TemplateReference
Dim guidTemplateID As Guid
With TemplateReference
.TemplateLocation = TemplateLocationCode.Server
If Guid.TryParse(TemplateID, guidTemplateID) Then
.Template = guidTemplateID.ToString
End If
End With
Return TemplateReference
End Function
The TemplateID is being passed in from a appSetting configuration value at the time of the TemplateReferences array instantiation like so...
templateReferences = New TemplateReference() {GetTemplateReference(ConfigurationManager.AppSettings("DocuSignTemplate_Reference"))}
recipients = New Recipient() {AddRecipient("myself#work.email", "My Name")}
envelopeInformation = CreateEnvelopeInformation()
envelopeStatus = client.CreateEnvelopeFromTemplates(templateReferences, recipients, envelopeInformation, True)
As you can see from my GetTemplateReference function I am also parsing the GUID before setting it back as a string so i know its valid. The template is managed and stored at the DocuSign end, hence specifying the document location.
I am referring to their own documentation:
CreateEnvelopeFromTemplates
Why oh why is the method not liking my Template ID? I can successfully use their REST API to call the same method, using their own code samples. Worst case I can make use of this but would rather interact with the web service as I would need to construct all the relevent requests in either XML or JSON.
I would really appreciate if someone could perhaps shed some light on this problem.
Thanks for taking the time to read my question!
Andrew might be spot on with the AccountId mention - are you setting the AccountId in the envelope information object? Also, have you seen the DocuSign SOAP SDK up on Github? That has 5 sample SOAP projects including one MS.NET project. The .NET project is in C# not Visual Basic, but still I think it will be helpful to you. Check out the SOAP SDK here:
https://github.com/docusign/DocuSign-eSignature-SDK
For instance, here is the test function for the CreateEnvelopeFromTemplates() function:
public void CreateEnvelopeFromTemplatesTest()
{
// Construct all the recipient information
DocuSignWeb.Recipient[] recipients = HeartbeatTests.CreateOneSigner();
DocuSignWeb.TemplateReferenceRoleAssignment[] finalRoleAssignments = new DocuSignWeb.TemplateReferenceRoleAssignment[1];
finalRoleAssignments[0] = new DocuSignWeb.TemplateReferenceRoleAssignment();
finalRoleAssignments[0].RoleName = recipients[0].RoleName;
finalRoleAssignments[0].RecipientID = recipients[0].ID;
// Use a server-side template -- you could make more than one of these
DocuSignWeb.TemplateReference templateReference = new DocuSignWeb.TemplateReference();
templateReference.TemplateLocation = DocuSignWeb.TemplateLocationCode.Server;
// TODO: replace with template ID from your account
templateReference.Template = "server template ID";
templateReference.RoleAssignments = finalRoleAssignments;
// Construct the envelope information
DocuSignWeb.EnvelopeInformation envelopeInfo = new DocuSignWeb.EnvelopeInformation();
envelopeInfo.AccountId = _accountId;
envelopeInfo.Subject = "create envelope from templates test";
envelopeInfo.EmailBlurb = "testing docusign creation services";
// Create draft with all the template information
DocuSignWeb.EnvelopeStatus status = _apiClient.CreateEnvelopeFromTemplates(new DocuSignWeb.TemplateReference[] { templateReference },
recipients, envelopeInfo, false);
// Confirm that the envelope has been assigned an ID
Assert.IsNotNullOrEmpty(status.EnvelopeID);
Console.WriteLine("Status for envelope {0} is {1}", status.EnvelopeID, status.Status);
}
This code calls other sample functions in the SDK which I have not included, but hopefully this helps shed some light on what you're doing wrong...
This problem arises when you don't set up the field AccountId. This field can be retrieved from your account. In Docusign's console go to Preferences / API and look here
Where to find AccountID Guid in Docusign's Console
Use API Account ID (which is in GUID format) and you should be OK.

Resources