How to represent List of Strings in Springdoc Swagger v3? - springdoc

Below is a code that is similar to the situation I have
#ApiResponses(value = {
#ApiResponse(responseCode = "200", description = "OK", content = {#Content(schema = #Schema(
implementation = // <-- What to specify here?
))})
})
#GetMapping(value = "/user")
public ResponseEntity<List<User>> getUsers() {
return ResponseEntity.ok().body(Arrays.asList(new User(), new User()));
}
How do I specify the list of Users being returned from the endpoint in ApiResponse()?
Please note that the Open-API-Definition is not part of the project, but is specified in another project.

Solved using the below method
#ApiResponses(value = {
#ApiResponse(responseCode = "200", description = "OK", content = {
#Content(array = #ArraySchema(schema = #Schema(implementation = User.class)))
})
})
#GetMapping(value = "/user")
public ResponseEntity<List<User>> getUsers() {
return ResponseEntity.ok().body(Arrays.asList(new User(), new User()));
}

Related

Schema Extension Value is always NULL when updating through Microsoft Graph SDK

Step 1:
Created GraphServiceClient using Microsoft.Graph 4.9.0 and Microsoft.Graph.Core 2.0.5 SDK
var scopes = new[] { "https://graph.microsoft.com/.default" };
ClientSecretCredential clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, new ClientSecretCredentialOptions()
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
});`
GraphServiceClient graphServiceClient = new GraphServiceClient(clientSecretCredential, scopes);
Step 2:
And created a custom schema extension like below.
SchemaExtension schemaExtension = new SchemaExtension()
{
Id = "data1",
Description = "creating test schema extn",
TargetTypes = new List<string>()
{
"User"
},
Properties = new List<ExtensionSchemaProperty>()
{
new ExtensionSchemaProperty()
{
Name ="prop1",
Type ="String"
}
}
};
Step 3:
Updated the Schema extension status to "Available"
var updatedExtn = await graphServiceClient
.SchemaExtensions[schemaExtension.Id].Request()
.UpdateAsync(new SchemaExtension()
{
Status = "Available"
});
Step 4:
Create Class for extension data
public class data1
{
// You must serialize your property names to camelCase if your SchemaExtension describes as such.
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "prop1", Required = Newtonsoft.Json.Required.Default)]
public string Prop1 { get; set; }
}
Step 5:
Find the User and add the created schema extension to the user
IDictionary<string, object> extensionInstance = new Dictionary<string, object>();
// The below line is not working. but doesn't throw error
extensionInstance.Add(schemaExtension.Id, new data1 { prop1 = "testing" });
var usrCollection = await graphServiceClient.Users
.Request()
.Filter($"userPrincipalNames eq '{adelev_Mail}'")
.GetAsync();
var usr = usrCollection.FirstOrDefault();
if(usr != null)
{
usr.AdditionalData.Add(extensionInstance);
var updatedUser = await graphServiceClient.Users[usr.Id]
.Request()
.UpdateAsync(usr);
}
Step 6:
When you try to retrieve the extension the value is NULL.
User updatedUser = await graphServiceClient.Users[usr.Id].Request()
.Select($"id, {schemaExtension.Id}")
.GetAsync();
But it works with API using Graph Explorer.
PATCH https://graph.microsoft.com/v1.0/users/{userId}
{
"extXXXXXXXX_data1":
{
"prop1" : "testing"
}
}
Please let me know if I'm missing anything here. Any help here is much appreciated.
You should accessing the data on AdditionalData property. Try looking at user.AdditionalData in your result. Here is a screenshot with my example.
Getting User with Schema extension from Graph explorer.
While using the SDK, i access my custom data in user.AdditionalData
Check this thread - Graph SDK and SchemaExtensions for details.

mvc controller json return

i want to return an image in base64 from my controller to view using json.
public JsonResult changeProfile()
{
var userID = ((SessionModel)Session["SessionModel"]).UserID; // get current user id
TBL_User item = _context.TBL_User.Find(userID);
UserModel model = new UserModel();
model.UserID = userID;
model.BinaryPhoto = item.BinaryPhoto;
return Json(new
{
??????????????'
},
JsonRequestBehavior.AllowGet);
}
what can i put there to return my image and display in the view?
thanks
Update controller
public JsonResult changeProfile()
{
var userID = ((SessionModel)Session["SessionModel"]).UserID; // get current user id
TBL_User item = _context.TBL_User.Find(userID);
UserModel model = new UserModel();
model.UserID = userID;
model.BinaryPhoto = item.BinaryPhoto;
var base64 = Convert.ToBase64String(model.BinaryPhoto);
var imgsrc = string.Format("data:image/jpg;base64,{0}", base64);
return Json(new
{
Image = imgsrc
},
JsonRequestBehavior.AllowGet);
}
Update src for image in ajax success
$.ajax({
url: "/changeProfile",
success: function(data) {
$(".img-circle").attr('src', data.Image);
}
});

Clicking Ajax.ActionLink Produces a GET and a POST

Clicking a certain Ajax ActionLink in this app I just inherited produces a POST request AND a GET request (POST and then a GET immediately after). The first request hits the HttpPost method on the server, but the second request (the GET) throws a "404 (Not Found)" error in the browser. How do I stop the unwanted GET request? Where is it coming from?
If I change the method from POST to GET, the reverse occurs with the POST throwing the error instead of the GET.
I searched the application for similar requests to the same HttpPost method that were configured as GETs and there are none.
I searched for custom JavaScript that was attaching an extra click event to all links and there were no instances of that. Could there be other events that would produce the same result in this instance?
Chrome DevTools Screenshot
In DocumentManagementController.cs:
[HttpPost]
public ActionResult OpenPopup(string ntgLoadId) { ... }
In _GridLoadsAddendum.cshtml:
#Html.DevExpress().GridView(
settings =>
{
settings.Name = "DetailedGrid_" + Model.LoadId;
settings.Width = Unit.Percentage(100);
settings.Settings.ShowFilterRow = false;
settings.Settings.ShowGroupPanel = false;
settings.Settings.ShowFooter = false;
settings.Settings.ShowColumnHeaders = false;
settings.KeyFieldName = "NtgLoadId";
settings.Columns.Add(column =>
{
column.FieldName = "Status";
column.Caption = "Status";
column.Width = Unit.Pixel(83);
column.SetDataItemTemplateContent(c =>
{
ViewContext.Writer.Write(
Ajax.ActionLink(
DataBinder.Eval(c.DataItem, "Status").ToString(),
"OpenPopup",
"DocumentManagement",
new
{
ntgLoadId = c.KeyValue.ToString()
},
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "ModalContainer",
AllowCache = false
},
new
{
#class = "status-link",
data_Toggle = "modal",
data_Target = "#ModalContainer",
data_backdrop = "static",
data_Keyboard = "false"
}).ToHtmlString());
});
});
settings.Styles.Table.CssClass = "MVCxGridViewTable";
settings.Styles.Header.CssClass = "MVCxGridViewHeader";
settings.Styles.Cell.CssClass = "MVCxGridViewCell addendum";
settings.Styles.CommandColumnItem.CssClass = "MVCxGridViewCell";
settings.Styles.AlternatingRow.CssClass = "MVCxGridViewAlternatingRow addendum";
settings.Styles.PagerBottomPanel.CssClass = "MVCxGridViewPagerBottomPanel";
settings.Settings.ShowFooter = false;
settings.ClientSideEvents.BeginCallback = "initechPortal.carrierPaymentStatusHelper.gridResultsHelper.beginCallback";
settings.CallbackRouteValues = new
{
Controller = "CarrierPaymentController",
Action = "GridLoadsAddendum",
Id = Model.LoadId
};
settings.DataBound = (sender, e) =>
{
MVCxGridView gv = sender as MVCxGridView;
gv.Visible = gv.VisibleRowCount > 0;
};
}).BindToLINQ(
string.Empty,
string.Empty,
new EventHandler<DevExpress.Data.Linq.LinqServerModeDataSourceSelectEventArgs>(
(s, e) =>
{
e.QueryableSource = Model.CarrierPaymentResultData;
e.KeyExpression = "ntgLoadId";
})).GetHtml();

TableContinuationToken not getting Deserialised from JSON correctly

I am having trouble trying to retrieve large datasets from Azure TableStorage. After several attempts at trying to get it in one go I have given up and am now using the TableContinuation Token, which is now not getting Deserialized correctly.The object is getting created but all the Next... values (i.e. NextRowKey, NextPartitionKey, etc are NULL, when the in stringresponse that gets created you can see the values it should be populating with...
The class I am passing contains a list of objects and the token
public class FlorDataset
{
public List<FlorData> Flors { get; set; }
public TableContinuationToken Token { get; set; }
}
The controller code is not exactly rocket science either....
[HttpGet, Route("api/list/{token}")]
public IHttpActionResult FindAll(string token)
{
try
{
TableContinuationToken actualToken = token == "None"
? null
: new TableContinuationToken()
{
NextPartitionKey = NextPartition,
NextRowKey = token,
NextTableName = NextTableName
};
var x = Run(actualToken);
Flors = x.Flors;
actualToken = x.Token;
NextTableName = actualToken.NextTableName;
NextPartition = actualToken.NextPartitionKey;
return Flors != null
? (IHttpActionResult)new IsoncOkResult<FlorDataset>(x, this)
: NotFound();
}
catch (Exception ex)
{
Trace.TraceError(ex.ToString());
return NotFound();
}
}
private FlorDataset Run(TableContinuationToken token)
{
return _repo.GetAllByYear("2016", token) as FlorDataset;
}
The calling code, which calls my fairly standard Web API 2 Controller is:
do
{
try
{
HttpResponseMessage response = null;
if (string.IsNullOrEmpty(token.NextRowKey))
{
response = await client.GetAsync("api/list/None");
}
else
{
response = await client.GetAsync($"api/list/{token.NextRowKey}");
}
if (response.IsSuccessStatusCode)
{
var stringresponse = await response.Content.ReadAsStringAsync();
var ds = JsonConvert.DeserializeObject<FlorDataset>(stringresponse);
token = ds.Token;
Flors.AddRange(ds.Flors);
}
else
{
token = null;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
token = null;
}
} while (token != null);
Okay, this is not the greatest solution, but it's the only thing that works so far in case anyone else is trying the same and stumbling across my question....
In the calling code bit you do a horrible bit of string replacement before you do the deserialisation.... I actually feel dirty just posting this, so if anyone comes up with a better answer, please feel free to share.....
if (response.IsSuccessStatusCode)
{
var stringresponse = await response.Content.ReadAsStringAsync();
stringresponse = stringresponse.Replace(">k__BackingField", "");
stringresponse = stringresponse.Replace("<", "");
var ds = JsonConvert.DeserializeObject<FlorDataset>(stringresponse);
token = ds.Token;
Flors.AddRange(ds.Flors);
}
Not nice, not pretty, but does work!!!! :-D Going to wash my fingers with bleach now!!!

View gets Json displayed on the page. not the data

I have an action which returns a JsonResult. The only thing gets displayed on the view is my json which is like
ProcessOrder{"IsValid":true,"url":"/Home/ProcessOrder"}
While debugging the code, I noticed that it gets displayed because of this below line.
var ProcessOrderData = new { IsValid = true, url = Url.Action("ProcessOrder") };
return new JsonResult() { Data = ProcessOrderData };
Can any body please tell me why it gets only json to be displayed on the view?
is something null here that is causing this to get this displayed or any other stuff?
Code:
private ActionResult SubmitAccount(UserAccountModels UserAccountModels)
{
SessionInfo userSession = SiteSetting.Visitor;
if (userSession != null)
{
if (userSession.products.Where(rec => rec.IsAddedToCart).Count() > 0)
{
SiteSetting.Visitor.User.FirstName = UserAccountModels.FirstName;
SiteSetting.Visitor.User.LastName = UserAccountModels.LastName;
SiteSetting.Visitor.User.Phone = UserAccountModels.Phone;
SiteSetting.Visitor.User.Email = UserAccountModels.Email;
var ProcessOrderData = new { IsValid = true, url = Url.Action("ProcessOrder") };
return new JsonResult() { Data = ProcessOrderData };
}}}
It will only display Json because you are returing JsonResult not a View