Get value from dictionary based on key throws error - syncfusion schedule - asp.net

In my ASP.NET (c#) application using syncfusion schedule, I am trying to get a value from a dictionary based on the key.
When I try to do that I get this error message:
System.Collections.Generic.KeyNotFoundException: 'The given key was not present in the dictionary.
This line of code (where I try to get the value of key 'Subject' and assign it to variable sSubject) throws the error:
string sSubject = list["Subject"].ToString();
Code:
public Dictionary<string, object> Arguments { get; set; }
protected void Schedule1_ServerAppointmentEdited(object sender, Syncfusion.JavaScript.Web.ScheduleEventArgs e)
{
Arguments = e.Arguments["appointment"] as Dictionary<string, object>;
dynamic list = Arguments as Dictionary<string, object>;
string sSubject = list["Subject"].ToString();
}
If I debug my code to look what's in my dictionary, I do see that key 'Subject' is present:
What am I doing wrong? How can I get value 'test subject' from key 'subject'?
Project: http://www.syncfusion.com/downloads/support/forum/119417/ze/ScheduleCRUDWithWebServices-728709208
Documentation: https://www.syncfusion.com/kb/5182/how-to-perform-the-crud-operation-in-the-schedule-control-with-webservices-datasource
Thank you

Your dictionary is inside a list, namely the 2nd element. You should access it as follows:
string sSubject = list[1]["Subject"].ToString();

This is how I finally retrieved the value of key 'subject':
Arguments = e.Arguments["appointment"] as Dictionary<string, object>;
//dynamic list = Arguments as Dictionary<string, object>;
System.Collections.ArrayList list2 = (System.Collections.ArrayList)Arguments["changed"];
Dictionary<string, object> dic = (Dictionary<string,object>)list2[0];
string sSubject2 = dic["Subject"].ToString();

Usually the server-side arguments will receive only the appointment details while performing the edit action. Can you share the details on which particular scenario, you are getting the arguments with “added” and “changed” options as depicted in your screenshot.
Regards,
Dharani

Related

What is a BindAsync method with two params in the IBinding interface

In the Azure WebJobs SDK, we have the IBinding interface. This interface has a method BindAsync with two params, but I can't understand what is the first param object value and when this overload method will be called.
The same question related ITriggerBinding interface.
I have tried to find the answer in the SDK code source. I know that BindingSource contains a dictionary of parameters where the key is an argument name and value is an argument value that will be provided to the BindAsync method, but I cannot understand what these arguments are and where they come from?
UPDATE
IBinding.BindAsync Method Returns Task<IValueProvider>.
The usage of IBinding.BindAsync.
Microsoft.Azure.WebJobs.Host.Bindings.IBinding.BindAsync(Microsoft.Azure.WebJobs.Host.Bindings.BindingContext)
Sample Code
public async Task BindAsync_String()
{
ParameterInfo parameterInfo = GetType().GetMethod("TestStringFunction").GetParameters()[0];
HttpTriggerAttributeBindingProvider.HttpTriggerBinding binding = new HttpTriggerAttributeBindingProvider.HttpTriggerBinding(new HttpTriggerAttribute(), parameterInfo, false);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://functions/myfunc?code=abc123");
request.Content = new StringContent("This is a test");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/text");
FunctionBindingContext functionContext = new FunctionBindingContext(Guid.NewGuid(), CancellationToken.None, new TestTraceWriter(TraceLevel.Verbose));
ValueBindingContext context = new ValueBindingContext(functionContext, CancellationToken.None);
ITriggerData triggerData = await binding.BindAsync(request, context);
Assert.Equal(0, triggerData.BindingData.Count);
string result = (string)triggerData.ValueProvider.GetValue();
Assert.Equal("This is a test", result);
}
From sample code(HttpTrigger), you will find request, context. They are two params in BindAsync. You will know the usage of BindAsync.

How to Store A Json Array or Json Object in mysql using Spring And Mybatis

Controller.java
#RequestMapping(value = { ControllerUriConstant.add }, method = RequestMethod.POST)
#ActivityMapping(activity = ActivityEnum.ADD)
public String addActivities(#ModelAttribute("activityForm") ActivityForm activityForm, BindingResult bindingResult, Model model,
HttpServletRequest request) throws Exception {
new ActivityFormValidator().validate(activityForm, bindingResult, request.getLocale(), getMessageSource(), null, activityService);
if (bindingResult.hasErrors()) {
model.addAttribute(Constants.ACTIVITY_FORM,activityForm );
model.addAttribute(Constants.HAS_ERROR, Boolean.TRUE);
model.addAttribute("add", true);
model.addAttribute(Constants.ERROR_MESSAGE, getMessageSource().getMessage("ulearn.messages.add.failed", activityForm.getName()));
return "activityform";
} else {
model.addAttribute(Constants.SUCCESS_MESSAGE, getMessageSource().getMessage("ulearn.messages.add.success", activityForm.getName()));
JSONArray address =new JSONArray();
JSONObject jo = new JSONObject();
jo.put("id", "1");
jo.put("name","Test");
JSONObject jo1= new JSONObject();
jo1.put("id", "1");
jo1.put("name", "Test2");
JSONObject jo2= new JSONObject();
jo2.put("id", "1");
jo2.put("name", "Test3");
address.add(jo);
address.add(jo1);
address.add(jo2);
activityForm.setInsertJsonMysql(address);
activityService.add(activityForm);
}
return getActivities( model, request);
}
Service.java
public void add(ActivityForm activityForm) throws TechnoShineException {
try {
Activity activity = new Activity();
activity.setName(activityForm.getName());
activity.setActive(activityForm.getActive());
activity.setInsertJsonMysql(activityForm.getInsertJsonMysql());
activityDAO.getMapper().insert(activity);
logAudit(getAuditableList(activity, null), getMessageSource().getMessage("ulearn.messages.add.success", activity.getName()), 0, ActivityEnum.ADD);
} catch (Exception e) {
throw new TechnoShineException(e, ActivityService.class);
}
}
Mapper.xml
<insert id="insert" parameterType="com.technoshinelabs.ulearn.persistance.bean.controlpanel.Activity">
INSERT INTO activity (activity_name,is_active,json_array)
VALUES (#{name},#{active},#{insertJsonMysql})
</insert>
// Finally got this error error Caused by: java.lang.IllegalStateException: Type handler was null on parameter mapping for property 'insertJsonMysql'. It was either not specified and/or could not be found for the javaType / jdbcType combination specified.
[1]: https://i.stack.imgur.com/OeZeR.png
I suppose what you want to store is the actual JSON and the MySQL table column json_array is of type VARCHAR or TEXT.
JSONArray is actually but an utility class used to build the JSON.
Then you shall change the type of property insertJsonMysql of class Activity to String and set it to the String representation of the JSONArray.
activity.setInsertJsonMysql(activityForm.getInsertJsonMysql().toString());
EDIT: about inserting into enum column.
According to MySQL 5.7 Reference Manual, I would say you insert into enum typed column the same way you insert any String, the DB will check provided value against list of values declared in CREATE TABLE.
But according to the code sample you provide, the value for insertJsonMysql will be:
[{"id":"1","name":"Test1"},{"id":"1","name":"Test2"},{"id":"1","name":"Test3"}]
that means one of the enum values would have to be this exact string.
However, I feel like that's not what you expect. Maybe using a SET typed column is a closer answer.

Unable to call web api PUT method

[System.Web.Http.Route("{id}")]
[System.Web.Http.HttpPut]
public async Task<ComplaintVM> Put(int id,int? employeeId)
{
var obj = _resolver.GetService<Complaint>();
obj.FranchiseId = 1;
obj.Id = id;
await obj.GetDetailAsyc();
obj.EmployeeId = employeeId;
await obj.AllocateAndManageCallAsyc();
return obj.EntityToVM();
}
This is put method with [System.Web.Http.RoutePrefix("api/app/complaint")]
so when i call my method with a PUT request i get the following error "message: "The requested resource does not support http method 'PUT'.".
but when i make the same call when the method does not have int? employeeId parameter. The call happens fine.
I am passing the employeeId as a json formatted request. I am using fiddler to test the code
The issue with Put(int id,int? employeeId) is the variable int? employeeId, since it was not part of the URL the model binder was not able to bind the attribute and hence was not able call the method with 2 parameters.
Using the [FormBody] did not work, the value returned was null, this is because the input was in form of a json.
The issue was solved by using a parameter of type Employee which had a property of EmployeeId so the value was mapped to the EmployeeId of the employee object, the method signature is Put(int id,Employee employee),
if there is no model class to bind, a parameter of type JObject can used as a input parameter and later the value can be extracted from JObject.

Problem with Object Data Source in ASP.NET (GetData method)

I want to create a report viewer in ASP.NET that presents to the users their data.
the data for all the users is located in the same table.
for now I created DBDataSet and in the TableAdapter there is this method
GetData(#idNumber, #userNumber)
in code behind of the screen that I want to show the report viewer I wrote:
FlightsDBDataSetTableAdapters.ReservationsTableAdapter ReservationsTableAdapter;
ReservationsTableAdapter = new FlightsDBDataSetTableAdapters.ReservationsTableAdapter();
FlightsDBDataSet.ReservationsDataTable newReservationTable;
newReservationTable = ReservationsTableAdapter.GetData(userId, userName);
ObjectDataSource1.SelectParameters.Add("userName", userName);
ObjectDataSource1.SelectParameters.Add("idNumber", userId);
when I run this I get the next error
An error has occurred during report processing. ObjectDataSource
'ObjectDataSource1' could not find a non-generic method
'GetData(idNumber, userName)' that has parameters: userName, idNumber.
SO, my question is where do I need to write the method GetData and how can I generate the report with the right data.
thanks a lot.
Try this out.
1.Create a method which will return db null if parameter is not passed in the stored procedure
public static object GetDataValue(object o)
{
if (o == null || String.Empty.Equals(o))
return DBNull.Value;
else
return o;
}
2.Create a method which will called the stored procedure and fill the dataset.
public DataSet GetspTest(string userName, string userId) {
try
{
DataSet oDS = new DataSet();
SqlParameter[] oParam = new SqlParameter[2];
oParam[0] = new SqlParameter("#userName", GetDataValue(userName));
oParam[1] = new SqlParameter("#idNumber", GetDataValue(userId));
oDS = SqlHelper.ExecuteDataset(DataConnectionString, CommandType.StoredProcedure, "spTest", oParam);
return oDS;
}
catch (Exception e)
{
ErrorMessage = e.Message;
return null;
}
}
Now you add the dataset let us say 'DataSet1.xsd'
Drag and Drop the TableAdapter and it will ask you the following details
3.1 Connection String (Either Select the existing connection string or create new connection string)
3.2 Choose Command Type (Now select the existing stored Procedure, specify the stored procedure with you have create earlier to display details in the report
3.3 Choose Methods to Generate (check both Fill a Datatable and Return a datatable
3.4 Click on Next and Submit ( Now your dataset is really to use in the report)
Create a report and use this DataSet1 as datasource.

Reverse function of HttpUtility.ParseQueryString

.Net's System.Web.HttpUtility class defines the following function to parse a query string into a NameValueCollection:
public static NameValueCollection ParseQueryString(string query);
Is there any function to do the reverse (i.e. to convert a NameValueCollection into a query string)?
System.Collections.Specialized.NameValueCollection does NOT support this, but a derived internal class System.Web.HttpValueCollection DOES (by overriding ToString()).
Unfortunately (being internal) you cannot instantiate this class directly, but one is returned by HttpUtility.ParseQueryString() (and you can call this with String.Empty, but not Null).
Once you have a HttpValueCollection, you can fill it from your original NameValueCollection by calling Add(), before finally calling ToString().
var nameValueCollection = new NameValueCollection {{"a","b"},{"c","d"}};
var httpValueCollection = System.Web.HttpUtility.ParseQueryString(String.Empty);
httpValueCollection.Add(nameValueCollection);
var qs = httpValueCollection.ToString();
nameValueCollection.ToString() = "System.Collections.Specialized.NameValueCollection"
httpValueCollection.ToString() = "a=b&c=d"
A NameValueCollection has an automatic ToString() method that will write all your elements out as a querystring automatically.
you don't need to write your own.
var querystringCollection = HttpUtility.ParseQueryString("test=value1&test=value2");
var output = querystringCollection.ToString();
output = "test=value1&test=value2"
I found that a combination of UriBuilder and HttpUtility classes meets my requirements to manipulate query parameters. The Uri class on its own is not enough, particularly as its Query property is read only.
var uriBuilder = new UriBuilder("http://example.com/something?param1=whatever");
var queryParameters = HttpUtility.ParseQueryString(uriBuilder.Query);
queryParameters.Add("param2", "whatever2");
queryParameters.Add("param3", "whatever2");
uriBuilder.Query = queryParameters.ToString();
var urlString = uriBuilder.Uri.ToString();
The above code results in the URL string: http://example.com/something?param1=whatever&param2=whatever2&param3=whatever2
Note that the ToString() goes via a Uri property, otherwise the output string would have an explicit port 80 in it.
It's nice to be able to do all this using framework classes and not have to write our own code.
I don't think there is a built in one, but here is an example of how to implement http://blog.leekelleher.com/2008/06/06/how-to-convert-namevaluecollection-to-a-query-string/
Here are 2 very useful functions that I use all the time:
private string GetQueryStringParameterValue(Uri url, string key)
{
return HttpUtility.ParseQueryString(url.Query.TrimStart('?'))[key];
}
private Uri SetQueryStringParameterValue(Uri url, string key, string value)
{
var parameters = HttpUtility.ParseQueryString(url.Query.TrimStart('?'));
parameters[key] = value;
var uriBuilder = new UriBuilder(url) { Query = parameters.ToString() };
return uriBuilder.Uri;
}

Resources