Jquery Event Calendar and Microsoft Azure problems - javascript

I recently asked a question pertaining to my calendar project on here and got good results so I figure ill ask another question about it.
this is the tutorial I am following
http://www.dotnetawesome.com/2017/07/curd-operation-on-fullcalendar-in-aspnet-mvc.html
Unfortunately I lost my code I was working on recently when it comes to this project. But I just wanted to know before I restart coding again: Why do events not load on a calendar(jquery and javascript) when I use an Azure database? Specifically after a posting the events don't load. They will load when I use a regular sql database, but they will not load when using an Azure sql database. I can't find any information on a similar issue and am curious if this is a known issue to do with Json possibly?
Here is a snippet of code that fetches events from the backend:
FetchEventAndRenderCalendar();
function FetchEventAndRenderCalendar() {
events = [];
$.ajax({
type: "GET",
url: "/home/GetEvents",
success: function (data) {
$.each(data, function (i, v) {
events.push({
eventID: v.EventID,
title: v.Subject,
description: v.Description,
start: moment(v.Start),
end: v.End != null ? moment(v.End) : null,
color: v.ThemeColor,
allDay: v.IsFullDay
});
})
I can't debug right now but maybe I will try to enter just part of the code so I can test why exactly using an azure database makes it so events don't load on the calendar.

Why do events not load on a calendar(jquery and javascript) when I use an Azure database?
I download the demo code from you mentioned tutorial. Then I change it to use Azure SQL, and it works correctly.
If we run the application locally, we need to add client IP to Azure SQL firewall to let client to access to the Azure SQL. WE could get more info about Azure SQL firewall from this tutorial.
The following is my details steps:
1.Replace the connectionstring to Azure SQL connectionstring
<connectionStrings>
<add name="MyDatabaseEntities" connectionString="Server=tcp:sqlservername.database.windows.net,1433;Initial Catalog=databasename;Persist Security Info=False;User ID={user};Password={password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" providerName="System.Data.Sqlclient" />
</connectionStrings>
2.Create a table with same schema with given Event table in the Azure sql database.
3.Remove the localdb and MyModel.xx related files
4.Add Event.cs and MyDatabaseEntities.cs file
public class Event
{
public int EventID { get; set; }
public string Subject { get; set; }
public string Description { get; set; }
public System.DateTime Start { get; set; }
public Nullable<System.DateTime> End { get; set; }
public string ThemeColor { get; set; }
public bool IsFullDay { get; set; }
}
public partial class MyDatabaseEntities : DbContext
{
public MyDatabaseEntities()
: base("name=MyDatabaseEntities")
{
}
public virtual DbSet<Event> Events { get; set; }
}
project file struct:
5.Test it locally,it works correctly.

Related

Pass collection of objects inside an object from js to C#

This question can be very easy for you but I cannot find the solution anywhere, I've searched on SO as well. How can I send a collection of objects inside an object to a C# API method, here is my code that I try to send
{
"Question":"sdvsdv",
"PollQuestions":
[
{
"QuestionText":"Question Text"
}
]
}
I've tried with Advanced REST client as well (not only from JS), I can see value of parent object's parameters but PollQuestions objects parameters are all empty.
Please suggest a work around. Its been couple of days and I cannot get through it. Thanks in advance.
EDIT:
Here is how API method looks like:
Advanced Rest client request:
JS request:
Poll is a simple class like this:
[Serializable]
[DataContract(Namespace = "")]
public class Poll
{
[DataMember]
public string Question
{
get;
set;
}
[DataMember]
public Collection<PollQuestion> PollQuestions { get; set; }
}
PollQuestion object:
[Serializable]
public class PollQuestion : AnotherClass
{
public string QuestionText
{
get;
set;
}
}
In your case if the problem is to Map the request JSON in C# then try below code:
Class structure:
public class PollQuestion
{
public string QuestionText { get; set; }
}
public class RootObject
{
public string Question { get; set; }
public List<PollQuestion> PollQuestions { get; set; }
}
In Post use [FromBody] attribute to map JSON to C# class:
public void YourMethod([FromBody] RootObject data)
{
// your code to use request data
}
If you are using WebAPI version="5.2.3" (Or might be supported in the lower version also) no need to serialize requested JSON to C# class. Use this to generate C# classes for JSON.
For JSON structure C# treats,
this:
{
}
as Object and
this:
[]
to List<> OR Array.
I set up a simple sample project in .NET Core and it seems to be working fine for me with your JSON data.
These are the classes I used:
public class PollQuestion
{
public string QuestionText { get; set; }
}
public class Poll
{
public string Question { get; set; }
public List<PollQuestion> PollQuestions { get; set; }
}
And here is the API call function:
[HttpPost]
public void Post([FromBody]Poll value)
{
}
When I make a postman request the Poll class is filled as expected.
Here is also a link to my sample project: https://bitbucket.org/alleskapaul/ld42/downloads/JsonExample.zip
Could you change your models in your project to match mine and see if that works? My guess would be that your model is incorrect as the JSON request works for me as well. If it is not working could you upload a sample project so I can see if I can modify it to work?
I was inheriting a class that was using [DataContract] and [DataMember] attributes, so I had to use DataMember for all parameters of the child class as well.
Thanks everyone for your answers but [FromBody] is not required in an API method when parameter is of complex type.
It works without DataContract and DataMember as well if you have not used DataMember anywhere in the class and also not inheriting any class that uses it.
You can get more info here: When to use DataContract and DataMember attributes?

Manage List of Image in Asp.Net MVC Page

I need to create an Asp.Net MVC 5 (Razor) view and controller capable to handle a list of Images.
Suppose a model like this one (the data are stored in a database and loaded with EF)
public class Game
{
public Guid Id {get; set; }
public string Title { get; set; }
public string ImageUrl {get; set; }
public ICollection<Screenshot> Screenshots { get; set; }
}
public class Screenshot
{
public Guid Id {get; set; }
public Game Game {get; set; }
public string Title {get; set; }
public string ImageUrl { get; set; }
}
I would like to:
1) create a page where the user can Create a Game and add one or more screenshots.
2) create a page where the user can Edit a Game info and add/remove any of screenshots.
Do you have any suggestion or example ?
Thanks
-To Add 1 or more screenshots, you might require using Ajax.BeginForm(...){}
-You might need an ability to add multiple images,[use ICollection to get save multiple images, after save, return the saved image data using the onSucccess event.
-For Editing, use the same logic, have a remove button on each image using ajax, then on success, remove image from screen.
Use same logic for adding new screenshots.
Using Ajax will also allow you to easier create effect for adding/ deleting images.
You can save images as I explained above to the db or even to a local temp folder that will be removed when the user clicks a save button, ect

Javascript array sending to asp.net MVC controller

I'm currently trying to develop a web app in which a user defines a set of points with coordinates on google maps, these points are stored on an array like this one:
mvcPolygon: new google.maps.MVCArray(),
Now I need username, password, etc. and submits it to the server. I'm pretty new with javascript and frontend development so I'm quite clueless here as to what is the way to go.
So currently I have the javascript code which is storing the coordinates and what I need is that when the user is finnished defining his polygon, and filling a form with username, password, email, etc. all this info gets sent to the controller as soon as the user hits the submit button.
The webapplication is currently being developed on ASP.NET MVC 5 and c# , any help would be really appreciated!
There's essentially 2 ways you can get that data back to the server:
You can put the data into a form element and post that form to an action that's set up to receive it. This will require you to put your username, password, etc into a series of html elements with name attributes set up to follow MVC's conventions (This page has some information on the conventions to use).
You can use jQuery's ajax features to send a raw javascript object containing your data to an MVC action (See this answer and it's linked post for details on how to accomplish this).
In either case, you probably shouldn't be sending a username & password to the server with every request, as you can use an authentication cookie to verify a user's identity once they're logged in to your application (there's plenty of resources online explaining how this works).
For option 2:
Javascript:
var myobject = {
username: "Joe",
password: "password",
points: [{ x: 111.1112, y: 22.2222 },{ x: 11.12, y: 21.11 }]
}
jQuery.ajax({
url: "/MyController/MyAction",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(myobject)
})
C#:
public class PointModel
{
public double x { get; set; }
public double y { get; set; }
}
public class MyModel
{
public string username { get; set; }
public string password { get; set; }
public IList<PointModel> points { get; set; }
}
public class MyController : Controller
{
[HttpPost]
public JsonResult MyAction(MyModel model) {
...
}
}
you can use below java script method to define JavaScript array
<script type="text/javascript">
var array = [];
array.push(10);
array.push(20);
</script>
you use this array to insert points in array and send this array using following Ajax call
var _data = {
'array ': array
};
$.Post(url ,_data, function(data){
})

Uncaught Error: Unable to recognize DataType for: Edm.Self.Address with breezejs

I get the error when trying to use breezejs, the type is a complex type from entity framework (code first).
Uncaught Error: Unable to recognize DataType for: Edm.Self.Address
Are there any workarounds for using complex types with breezejs?.
from my entity framework model:
public class Address
{
public string Id { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string ZipCode { get; set; }
public string Contry { get; set; }
}
Breeze does not yet support Entity Framework Complex types. It is on our roadmap but we are not there yet. Please vote for this feature on the Breeze website (www.breezejs.com).
Give a try to JayData, it supports complex types for query or for crud. Once you have a working OData endpoint at address http://{yourdomain}/{yourapi}, you can just use it without any further ado:
<script src="http://include.jaydata.org/datajs-1.0.3.js"></script>
<script src="http://include.jaydata.org/jaydata.js"></script>
<script src="http://include.jaydata.org/jaydataproviders/oDataProvider.js"></script>
<script>
$data.service("http://{yourdomain}/{yourapi}", function(contextFactory) {
var context = contextFactory();
context
.myEntitySet
.filter(function(item) { return item.ComplexProp.Field == 42 || item.Title =="Tea"})
.forEach(function(item) {
console.log(item.Title);
});
});
</script>
Note that with JayData you can use TypeScript for any OData endpoint. Using TypeScript gives you
strongly typed client experience
fantastic hints on features
lambda predicates: filter(item => item.ComplexType.Field == 42)
read more here
As of v 0.80.1, breeze now supports complex types. Hope this helps.

How to preserve a C# list in my view page, to manipulate that in client side

I m using ASP.Net MVC 3.0. My model has a list of telephone. I want to preserve that in some way, so that I can manipulate & display later using Jquery in my script.
I tried saving the list in a hidden field, but I am not able to retrieve that in my JavaScript.
Please help me finding a way out. Thx in advance.
You could create a property on your viewmodel which holds a json serialized version of the phonenumbers like this:
public class Person
{
public string Firstname { get; set; }
public string Lastname { get; set; }
public IList<string> PhoneNumbers { get; set; }
public IHtmlString SerializedPhoneNumbers
{
get { return MvcHtmlString.Create(new JavaScriptSerializer().Serialize(PhoneNumbers)); }
}
}
You can use that in the view like:
<script type="text/javascript">
var phoneNumbers = #Model.SerializedPhoneNumbers
</script>
You now can manipulate the collection in your clientside script.

Categories

Resources