Fullcalendar in ASP.NET and JSON response - json

I am fetching my events with webservice:
Public Function webGetCalendarEvents(ByVal startDate As String, ByVal endDate As String) As String
Dim sDate As DateTime = ToUnixTimeSpan(startDate)
Dim eDate As DateTime = ToUnixTimeSpan(endDate)
Dim DS As DataSet = DBStoredProcedures.GetEventsCalendarJSON(95, sDate, eDate)
DS.Tables(0).TableName = "events"
Dim dataTable As DataTable = DS.Tables(0)
Dim jsonEvents As String = Newtonsoft.Json.JsonConvert.SerializeObject(dataTable)
Return jsonEvents
The json response is like:
[
{
"id":589311,
"title":"My Title",
"priority":"",
"start":"2011-09-19T08:00",
"end":"2011-09-26T16:00",
"allDay":"false",
"editable":"true",
"EOSid":0
}
]
The problem is, that all my events are shown as allDay events. It seems like "false" value of "allDay" is not recognized.
I am evaluating the response inside fullcalendar.js file (version 1.5.2., line around 981):
success: function (events) {
events = (typeof events.d) == 'string' ? eval('(' + events.d + ')') : events.d || [];
How can I render events to accept "allDay" parameter?

SOLVED:
I changed my SQL procedure where I was generating "allDay" parameter. I changed from:
CASE WHEN EventTypeID=3 THEN 'false' ELSE 'true' END as allDay
to:
CASE WHEN EventTypeID=3 THEN CAST(0 as BIT) ELSE CAST(1 as BIT) END as allDay
This gave me JSON response:
{"allDay": false}
instead of:
{"allDay": "false"}

Related

How to properly query Postgres JSONB field in Vapor/Fluent

I have a table with some jsonb columns created by a migration like this:
public func prepare(on database: Database) -> EventLoopFuture<Void> {
return database.schema(MyTable.schema)
.id()
.field(.metadata, .custom("JSONB"), .required)
.create()
}
I am trying to filter query on jsonb field. The following is a simple string interpolation that works.
//jsonFilters is a dictionary of key value pair for which we want to filter in jsonb field
var query = MyTable.query(on: db)
var filterString = ""
var cycleCount = 0;
jsonFilters.forEach({
(key, value) in
filterString +=
"metadata->>'\(key)' = '\(value)' "
cycleCount+=1
if(cycleCount < filter.metadata!.count) {
filterString += " AND "
}
})
query = query.filter(.custom(metadataString))
// Also filter on something else.
query = query.filter(....)
However this is not secure and is sql injection vulnerable. Is there a way to bind the filter arguments in for example using SQLQueryString? It should work in conjunction with the rest of the regular filter. ( Last line in the code)
Just in case someone runs into the same here is what works with SQLQueryString so you can pass the parameters instead of string interpolation:
var queryString = SQLQueryString("")
var cycleCount = 0;
filter.metadata!.forEach({
(key, value) in
queryString.appendLiteral("metadata->>")
queryString.appendInterpolation(bind: key)
queryString.appendLiteral(" = ")
queryString.appendInterpolation(bind: value)
cycleCount+=1
if(cycleCount < filter.metadata!.count) {
queryString.appendLiteral(" AND ")
}
})

UPDATE: Azure DevOps API: Sending commands to the REST API that are JSON instead of a URI

I am a little new to using the REST API for Azure DevOps and have it working fine where I can send my requests that are basically the URIs I see on the website for the API. Then I get that JSON response and de-serialize it into a class from the JSON response and am off running.
Below is an example of a function I use to get a Work Item by it's ID. It uses the URI from the website.
I can also test things by pasting the URI into my browser and then see the response.
My question is, How do I use the command for Updating the Workitem (Add Link for example) which is not a URI that I can test by pasting it into my browser. Instead it is a JSON message.
here is API Website which shows the JSON message needed to add a link to a work item.
https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/work%20items/update?view=azure-devops-rest-5.1#add-a-link
this is the JSON message they have there for updating a WorkItem Link:
[
{
"op": "test",
"path": "/rev",
"value": 3
},
{
"op": "add",
"path": "/relations/-",
"value": {
"rel": "System.LinkTypes.Dependency-forward",
"url": "https://dev.azure.com/fabrikam/_apis/wit/workItems/300",
"attributes": {
"comment": "Making a new link for the dependency"
}
}
}
]
Do I need a different function to send it the JSON message and then the function could return me the JSON Response? I can not find an example of what that function might look like.
Any Advice on how to send the JSON message instead of the URI to get a response would be greatly appreciated.
===================== UPDATE =====================
The one answer definitely helped me get this finally working.
I pasted in the updated function in case it helps anyone else.
I know it is tricky to find VB.NET samples for this. :)
THANKS!
UPDATED CODE==========================================================
Public Async Function GetRequestAsync(ByVal uri As String, Optional ByVal jsonMessageBody As String = "") As Task(Of String())
Dim client As HttpClient = New HttpClient()
SetUpHttpClient(client)
Dim statusCode As String = "NOTHING"
Dim responseBody As String = "NOTHING"
Try
If jsonMessageBody.Length > 0 Then
'#####################################################################
'### For all PATCH operations that have a URI and a JSON message ###
'#####################################################################
Dim patchValue = New StringContent(jsonMessageBody, Encoding.UTF8, "application/json-patch+json")
Dim method = New HttpMethod("PATCH")
Dim request = New HttpRequestMessage(method, uri) With {.Content = patchValue}
Dim response = client.SendAsync(request).Result
responseBody = response.Content.ReadAsStringAsync.Result()
Else
'#######################################################
'### For all other operations that have just a URI ###
'#######################################################
Using response As HttpResponseMessage = client.GetAsync(uri).Result
statusCode = response.StatusCode.ToString()
response.EnsureSuccessStatusCode()
responseBody = response.Content.ReadAsStringAsync().Result
End Using
End If
Catch
End Try
Dim answer As String() = {statusCode, responseBody}
Return answer
End Function
Public Function GetTestCase(organization As String, project As String, TestCaseID As String) As WorkItemApi
Dim dc As New DevCon.DevOpsConnector
Dim response As String() = dc.GetRequest($"https://dev.azure.com/{organization}/{project}/_apis/wit/workitems/{TestCaseID}?api-version=5.1&$expand=all")
If response(0) <> "OK" Then
Return Nothing
End If
Dim result As WorkItemApi = JsonConvert.DeserializeObject(Of WorkItemApi)(response(1))
Return result
End Function
Public Async Function GetRequestAsync(ByVal getRequest As String) As Task(Of String())
Dim client As HttpClient = New HttpClient()
SetUpHttpClient(client)
Dim statusCode As String = "NOTHING"
Dim responseBody As String = "NOTHING"
Try
Using response As HttpResponseMessage = client.GetAsync(getRequest).Result
statusCode = response.StatusCode.ToString()
' Console.WriteLine("Response: " & statusCode)
response.EnsureSuccessStatusCode()
responseBody = response.Content.ReadAsStringAsync().Result
End Using
Catch
End Try
Dim answer As String() = {statusCode, responseBody}
Return answer
End Function
You need to serialize the fields array into a json string. Check the following sample in C# using the HttpClient class:
public WorkItem CreateBugUsingHTTP()
{
string uri = _uri;
string personalAccessToken = _personalAccessToken;
string project = _project;
string credentials = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", personalAccessToken)));
Object[] patchDocument = new Object[4];
patchDocument[0] = new { op = "add", path = "/fields/System.Title", value = "Authorization Errors" };
patchDocument[1] = new { op = "add", path = "/fields/Microsoft.VSTS.TCM.ReproSteps", value = "Our authorization logic needs to allow for users with Microsoft accounts (formerly Live Ids) - http://msdn.microsoft.com/en-us/library/live/hh826547.aspx" };
patchDocument[2] = new { op = "add", path = "/fields/Microsoft.VSTS.Common.Priority", value = "1" };
patchDocument[3] = new { op = "add", path = "/fields/Microsoft.VSTS.Common.Severity", value = "2 - High" };
using (var client = new HttpClient())
{
//set our headers
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
//serialize the fields array into a json string
var patchValue = new StringContent(JsonConvert.SerializeObject(patchDocument), Encoding.UTF8, "application/json-patch+json");
var method = new HttpMethod("POST");
var request = new HttpRequestMessage(method, uri + "/" + project + "/_apis/wit/workitems/$Bug?api-version=5.1") { Content = patchValue };
var response = client.SendAsync(request).Result;
//if the response is successfull, set the result to the workitem object
if (response.IsSuccessStatusCode)
{
var workItem = response.Content.ReadAsAsync<WorkItem>().Result;
Console.WriteLine("Bug Successfully Created: Bug #{0}", workItem.Id);
return workItem;
}
else
{
Console.WriteLine("Error creating bug: {0}", response.Content);
return null;
}
}
}
You could get started from the documentation below:
https://learn.microsoft.com/en-us/rest/api/azure/devops/?view=azure-devops-rest-5.1
Public Async Function GetRequestAsync(ByVal uri As String, Optional ByVal jsonMessageBody As String = "") As Task(Of String())
Dim client As HttpClient = New HttpClient()
client.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))
client.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("Basic", _accessTokenHttpClient)
Dim statusCode As String = "NOTHING"
Dim responseBody As String = "NOTHING"
Try
If jsonMessageBody.Length > 0 Then
'#####################################################################
'### For all PATCH operations that have a URI and a JSON message ###
'#####################################################################
Dim patchValue = New StringContent(jsonMessageBody, Encoding.UTF8, "application/json-patch+json")
Dim method = New HttpMethod("PATCH")
Dim request = New HttpRequestMessage(method, uri) With {.Content = patchValue}
Dim response = client.SendAsync(request).Result
responseBody = response.Content.ReadAsStringAsync.Result()
Else
'#######################################################
'### For all other operations that have just a URI ###
'#######################################################
Using response As HttpResponseMessage = client.GetAsync(uri).Result
statusCode = response.StatusCode.ToString()
response.EnsureSuccessStatusCode()
responseBody = response.Content.ReadAsStringAsync().Result
End Using
End If
Catch
End Try
Dim answer As String() = {statusCode, responseBody}
Return answer
End Function

Why sub json contains backslashes

I need To Build json of the following structure:
[{
Id: M1
Name: Menu1
Checked: True
Children:[
{Id: I1 , Name: Item1 , Checked: true, view:true , write:true},
{Id: I2 , Name: Item2 , Checked: true, view:true , write:true},
.. etc
]
},
{
Id: M2
Name: Menu2
Checked: True
Children:[
{Id: I1 , Name: Item1 , Checked: true, view:true , write:true},
{Id: I2 , Name: Item2 , Checked: true, view:true , write:true},
.. etc
]
} , etc..
]
I'm Using Vb.Net , SQl Server To get the menus and Items (objects) from the database and convert the data to json string using this code:
'Get Menus
Dim menus = DataFactory.Instance.GetMenusAndObjects(connectionString)
'Create JSON String
Dim jsonSerializer As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer()
Dim json As String = "["
For Each m In menus
Dim children As String = "["
Dim menu_checked As Boolean = True
For Each obj In m.Objects
Dim checked As Boolean = True
Dim view As Boolean = True
Dim write As Boolean = True
Dim link = DataFactory.Instance.GetProfileObjectLink(connectionString, profile_code, obj.ObjectCode)
If IsNothing(link) Then
view = False
write = False
checked = False
menu_checked = False
Else
If link.AllowToView.Equals("N") Then
view = False
menu_checked = False
End If
If link.AllowToModify.Equals("N") Then
write = False
menu_checked = False
End If
End If
children &= jsonSerializer.Serialize(New With {Key .Id = obj.ObjectCode,
.Name = obj.ObjectDesc,
.Checked = checked,
.View = view,
.Write = write}) & ","
Next
children &= "]"
json &= jsonSerializer.Serialize(New With {Key .Id = m.MenuCode,
.Name = m.MenuName,
.Checked = menu_checked,
.Children = children}) & ","
Next
If json.Length > 1 Then
json = json.Substring(0, json.Length - 1)
End If
json &= "]"
A Sample of the Resulted Json string in vb.Net:
[{"Id":"APPLN","Name":"Application","Checked":false,"Children":"
[{\"Id\":\"CUSTOMER_SCR\",\"Name\":\"62- Clients/
Customers\",\"Checked\":true,\"View\":false,\"Write\":false},
{\"Id\":\"EMP_SCR\",\"Name\":\"10- Employee
Manager\",\"Checked\":true,\"View\":true,\"Write\":true},]"}
,]"}
Why Backslashes are added only to the json on 'Children' Property? Do you think that the double Serialization for the children parameter is causing the problem? and if that's is the real reason how can I concatenate children jsons to the main json strings?
I pushed Each Children into a List Of Object then I converted the list to Array after that I serialized the main json, The Code:
Imports System.Web
Imports System.Web.Services
Imports System.Web.Script.Serialization
Public Class GetMenusAndObjects
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "text/plain"
'Get parameters
Dim profile_code = context.Request("profile_code")
Dim connectionString As String = UserIdentity.ClientConfig.ConnectionString
'Get Profiles
Dim menus = DataFactory.Instance.GetMenusAndObjects(connectionString)
'Create JSON String
Dim jsonSerializer As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer()
Dim json As String = "["
For Each m In menus
' Dim children As String = "["
Dim children = New List(Of Object)
Dim menu_checked As Boolean = True
For Each obj In m.Objects
Dim checked As Boolean = True
Dim view As Boolean = True
Dim write As Boolean = True
Dim link = DataFactory.Instance.GetProfileObjectLink(connectionString, profile_code, obj.ObjectCode)
If IsNothing(link) Then
view = False
write = False
checked = False
menu_checked = False
Else
If link.AllowToView.Equals("N") Then
view = False
menu_checked = False
End If
If link.AllowToModify.Equals("N") Then
write = False
menu_checked = False
End If
End If
children.Add(New With {.Id = obj.ObjectCode,
.Name = obj.ObjectDesc,
.Checked = checked,
.View = view,
.Write = write
})
'children &= jsonSerializer.Serialize(New With {Key .Id = obj.ObjectCode,
' .Name = obj.ObjectDesc,
' .Checked = checked,
' .View = view,
' .Write = write}) & ","
Next
'children &= "]"
json &= jsonSerializer.Serialize(New With {Key .Id = m.MenuCode,
.Name = m.MenuName,
.Checked = menu_checked,
.Children = children.ToArray()}) & ","
Next
If json.Length > 1 Then
json = json.Substring(0, json.Length - 1)
End If
json &= "]"
'Return JSON in response
context.Response.Write(json)
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class

Parsing Json using Vb.net Json.NET

Hey all I am getting the following error at random spots in my code:
Object reference not set to an instance of an object.
I know why I am getting it. It does not find the correct property that I have it looking for and therefore it gives the error. Some may have that property and some, as this error shows, may not.
What can I do in order to check first to make sure it has that property? Currently I just have a Try/catch method in place so it can keep going if it does find something that's not there.
For Each Row In json("data")
Try
thePostID = DirectCast(Row("id").ToString(), String)
thePostType = DirectCast(Row("type").ToString(), String)
thePosterID = DirectCast(Row("from")("id").ToString(), String)
thePosterName = DirectCast(Row("from")("name").ToString(), String)
Catch ex As NullReferenceException
msgbox("Did not find that particular property!")
End Try
Next
update
{
"data": [
{
"id": "102zzz533zz_10z52zz9zzzz94z3",
"from": {
"id": "102zzzzz95zzz7",
"name": "Jim zzzzz"
},
"likes": {
"data": [
{
"id": "85zzzzz35zzzz0",
"name": "Anna zzzzz"
},
{
"id": "10zzzz93z31zzzzz",
"name": "Vanessa zzzz zzzz"
},
{
"id": "1zzz44zzz48731z6",
"name": "Leta zzzzzz"
}
],
"paging": {
"cursors": {
"after": "MTAyMdfasdfwrtMTkyNg=",
"before": "ODUasdfasrU5Mwerw"
}
}
}
etc...
This JSON above follows in the same data path as all the others.
Using #Andrews code below:
thePostLikes = NullSafeSelect(Row, "likes.data.id")
If thePostLikes <> "NA" Then
For Each Row2 In json("likes")("data")
thePostLikesID += NullSafeSelect(Row2, "id") & ","
thePostLikesName += NullSafeSelect(Row2, "name") & ","
Next
End If
The value of thePostLikes is always Nothing
There may be a more graceful way to do this that's built in to JSON.NET, but here's a helper function that will just return Nothing if the path you supply doesn't exist:
Function NullSafeSelect(ByVal obj As JToken, ByVal path As String) As String
Dim result As String = Nothing
Dim value As JToken = obj.SelectToken(path, False)
if (value IsNot Nothing)
result = value.ToString()
End If
Return value
End Function
You would call it from your loop like this:
For Each row in json("data")
Dim thePostID As String = NullSafeSelect(row, "id")
Dim thePostType As String = NullSafeSelect(row, "type")
Dim thePosterId As String = NullSafeSelect(row, "from.id")
' ... etc
Next
Note that you do not need the DirectCast because the return type of the function is already String.

Combine date and time values and insert it into database in asp.net

This is my query,
string sdatevalue = mysdate.ToString("yyyy-MM-dd"); // "2014-02-12"
string stime = txttime.Text; // 9.00 A.M
replace 9.00 to 9:00 = correcttime;
finaldate=sdatevalue + correcttime;
How to achieve this.
Thanks i want this to be done in asp.net C#
you might be inserting this into a DataBase which is not a correct approach, its better you do it in your DB itself.
Create a method or extension
string ReplaceFirstOccurenceofCharacter(string text, string search, string replace)
{
int pos = text.IndexOf(search);
if (pos < 0)
{
return text;
}
return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}
and call the method
string sdatevalue = "2014-02-12";
string stime = "9.00 A.M";
string concatinatedstring = string.Format("{0} {1}", sdatevalue, stime);
var result = ReplaceFirstOccurenceofCharacter(concatinatedstring, ".", ":");
Actual code is pulled from This link Hope it helps you.