populating fullcalendar using SQL Server - c#

I have seen several questions around this topic on here, but can't seem to get my fullcalendar to display properly using the provided methods, so I was hoping someone could give me a hand with fixing my issue.
My JSON feed seems to populate correctly, although I see some saying that it only works with single quote, and others only work with double quotes. (possibly an issue with the double quotes surrounding the whole feed?)
"[{"title":"change1","start":"2016-10-17T10:00:00","end":"2016-10-17T12:00:00","allDay":false},{"title":"change2","start":"2016-10-18T10:00:00","end":"2016-10-18T12:00:00","allDay":true},{"title":"change3","start":"2016-10-19T10:00:00","end":"2016-10-19T12:00:00","allDay":false}]"
calendar.aspx.cs:
public class Event
{
public string title;
public string start;
public string end;
public bool allDay;
}
[WebMethod]
public static string GetEvents()
{
var events = new List<Event>();
var sqlQuery = "SELECT title, starttime, endtime, allDay FROM [DeploymentDashboard].[dbo].[ChangeCalendar]";
using (var sqlConnection = new SqlConnection("Data Source=*server*;Initial Catalog=DeploymentDashboard;Integrated Security=True;"))
{
using (var cmd = new SqlCommand(sqlQuery, sqlConnection))
{
sqlConnection.Open();
using (var reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
events.Add(new Event()
{
start = DateTime.Parse(reader["starttime"].ToString()).ToString("s"),
end = DateTime.Parse(reader["endtime"].ToString()).ToString("s"),
title = reader["title"].ToString(),
allDay = (bool)reader["allDay"]
});
}
}
}
sqlConnection.Close();
}
}
var theSerializer = new JavaScriptSerializer();
return theSerializer.Serialize(events);
}
calendar.aspx:
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "calendar.aspx/GetEvents",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (data) {
$('#calendar2').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
events: data.d
});
});
});
</script>

Try this:
var eventsArray = [{"title":"change1","start":"2016-10-17T10:00:00","end":"2016-10-17T12:00:00","allDay":false},{"title":"change2","start":"2016-10-18T10:00:00","end":"2016-10-18T12:00:00","allDay":true},{"title":"change3","start":"2016-10-19T10:00:00","end":"2016-10-19T12:00:00","allDay":false}]
$('#calendar2').fullCalendar({
events: eventsArray
});

This should fix it.
events: JSON.parse(data.d);
This helped: https://www.w3schools.com/js/js_json_parse.asp
Imagine we received this text from a web server:
'{ "name":"John", "age":30, "city":"New York"}'
Use the JavaScript function JSON.parse() to convert text into a
JavaScript object:
var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');

Related

Jquery/Ajax autocomplete textbox not working in ASP.net

I have a text box that I am trying to have autocomplete with values from a database. The code is, however, not doing anything when I begin typing in the text box. Does anyone have any idea how to fix this? The Scripts are in the head of the page.
<asp:TextBox placeholder="Search by job title" runat="server" CssClass="search" ID="searchTitle"></asp:TextBox>
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js"></script>
<script>
$(function () {
$("#searchTitle").autocomplete({
source: function (request,response) {
var param = { posting_jobPosition: $("#searchTitle").val() };
$.ajax({
url: "jobseekerHome.aspx/GetTitles",
data: JSON.stringify(param),
type: "post",
contentType: "application/json; charset=utf-8",
datafilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) { return {value: item }}))
},
});
},
minlength: 1
});
});
</script>
[WebMethod]
public static List<string> GetTitles(string posting_jobPosition)
{
string CS = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
OleDbConnection Connection = new OleDbConnection(CS);
List<string> Titles = new List<string>();
string query = string.Format("SELECT posting_jobPosition FROM BusinessJobPosting WHERE (posting_jobPosition LIKE '%{0}%' AND isActive = true)", posting_jobPosition);
OleDbCommand oleCom1 = new OleDbCommand(query, Connection);
Connection.Open();
OleDbDataReader reader = oleCom1.ExecuteReader();
while (reader.Read())
{
Titles.Add(reader[0].ToString());
}
Connection.Close();
return Titles;
}
Thanks guys :)
One possible reason that I see is the ID. Change the id as:
$("#<%=searchTitle.ClientID%>").autocomplete({
related: Accessing control client name and not ID in ASP.NET

how to get session value in asmx method asp.net

How can i get session value to the web method . I have tried but it giving me the object reference not set to be instance of object . Any body know the issue .i want to get first method session value in my second method .
how can i do it . i am getting value form my ajax function to my asmx page in getid method . but i want that it to be in my second method as parameter so that i can perform search process
The full code is here
**javascript code**
<script type="text/javascript">
$(document).ready(function () {
$('#btn').on('click', function () {
$.ajax({
url: 'EmployeeWebService.asmx/GetEmployees',
data: { id: '2'}, //this is id i want to get
dataType: "json",
method: 'post',
success: function (data) {
},
error: function (err) {
alert(err);
}
});
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$('#btn').on('click', function () {
$('#datatables').DataTable({
columns: [
{ 'data': 'Id' },
{ 'data': 'FirstName' },
{ 'data': 'LastName' },
{ 'data': 'Gender' },
{ 'data': 'JobTitle' },
{
data: "TotalQuestions", render: function
(data, type, row) {
return '<button type="button" data-id=" '
+ row.Gender + ' " class="get_tsk" style="background-
color:steelblue;color:white;border:none;">view</button> '
}
},
],
bServerSide: true,
sAjaxSource: 'EmployeeWebService.asmx/GetEmployees',
sServerMethod:'post'
});
});
});
</script>
**first Method**
First Method
string nameofid;
[WebMethod(EnableSession = true)]
public void GetId(string id)
{
Session["nameofid"] = id;
}
**Second Method**
public void GetEmployees(string id,int iDisplayLength,int
iDisplayStart,int
iSortCol_0,string sSortDir_0,string sSearch)
{
int displayLength = iDisplayLength;
int displayStart = iDisplayStart;
int sortCol = iSortCol_0;
string sortDir = sSortDir_0;
string search = sSearch;
int filteredRows = 0;
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
//
List<Employee> listEmployee = new List<Employee>();
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetEmployees", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Id", SqlDbType.NVarChar, 50).Value =id;
SqlParameter paramDisplayLength = new SqlParameter()
{
ParameterName = "#DisplayLength",
Value = displayLength
};
cmd.Parameters.Add(paramDisplayLength);
SqlParameter paramDisplayStart = new SqlParameter()
{
ParameterName = "#DisplayStart",
Value = displayStart
};
cmd.Parameters.Add(paramDisplayStart);
SqlParameter paramSortCol = new SqlParameter()
{
ParameterName = "#SortCol",
Value = sortCol
};
cmd.Parameters.Add(paramSortCol);
SqlParameter paramSortDir = new SqlParameter()
{
ParameterName = "#SortDir",
Value = sortDir
};
cmd.Parameters.Add(paramSortDir);
SqlParameter paramSearchString = new SqlParameter()
{
ParameterName = "#Search",
Value = string.IsNullOrEmpty(search) ? null : search
};
cmd.Parameters.Add(paramSearchString);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
filteredRows = Convert.ToInt32(rdr["TotalCount"]);
Employee employee = new Employee();
employee.Id = Convert.ToInt32(rdr["Id"]);
employee.FirstName = rdr["FirstName"].ToString();
employee.LastName = rdr["LastName"].ToString();
employee.Gender = rdr["Gender"].ToString();
employee.JobTitle = rdr["JobTitle"].ToString();
listEmployee.Add(employee);
}
}
var result = new
{
iTotalRecords = GetEmployeeTotalCount(),
iTotalDisplayRecords = filteredRows,
aaData = listEmployee
};
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(result));
}
private int GetEmployeeTotalCount()
{
int totalEmployees = 0;
string cs =
ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("Select count(*) from
tblEmployees", con);
con.Open();
totalEmployees = (int)cmd.ExecuteScalar();
}
return totalEmployees;
}
}
Add Route Config File below Line :
routes.IgnoreRoute("{x}", new { x = #"..asmx(/.*)?" });
Add WebService File :
[WebMethod(EnableSession = true)]
[ScriptMethod]
public string HelloWorld()
{
if (HttpContext.Current.Session["SessionDetail"] != null)
{
string _SessionData = Convert.ToString(HttpContext.Current.Session["SessionDetail"]);
}
return "Hello World";
}
Assign Session Value :
public ActionResult Index()
{
Session["SessionDetail"] = "Value for Session";
return View();
}
Well, first, you using this:
Session["nameofid"] = id;
and then this:
HttpContext.Current.Session["nameofid"].ToString();
The next issue is how are you calling these methods? If you using say jQuery.ajax?
Remember they are async calls. If you call to set and then in the same code stub call the 2nd routine, it will often fail since such calls are async.
You "could" consider using async = false in the ajax calls, but browers (and jQuery) is now warning that non async calls will not be allowed or supported.
What this means? Be carefull, and if you do a web method call to SET a value, then you need to split out the code that follows to a seperate routine.
we used to do:
function ShowPdf(pID) {
// set/save the id
$.ajax({
type: "POST",
async: false,
url: 'ProjectUpload.aspx/SetChoice',
data: '{strSess:"ProofID", strValue:' + pID + '}',
contentType: "application/json",
datatype: "json"
});
// MORE code here - and MAYBE some code that calls or MIGHT
// use the value based on the ABOVE web method call
// but we CAN'T use async: false anymore!
// so we CAN NOT write code folling here that needs or
// assumes the above call is finished - this code does not
// wait.
So, above code becomes this:
function ShowPdf(pID) {
// set/save the id
$.ajax({
type: "POST",
success: ShowPdf2, <- AFTER code now is moved to this rouine
url: 'ProjectUpload.aspx/SetChoice',
data: '{strSess:"ProofID", strValue:' + pID + '}',
contentType: "application/json",
datatype: "json"
});
}
function ShowPdf2() {
// split out due to we have to wait async
// for web call to complete. This code ONLY runs WHEN
// the above web call is 100% done. Even if web server is slow today!
// MUST set session() ProofID before calling this routine
// show a dialog in this page pdfdiv
var mydiv = $('#pdfdiv');
mydiv.dialog({
autoOpen: false, modal: true, title: 'Proofing: ', width: '100%',
position: {
my: "center top",
at: "center top+80"
},close: myempty,
dialogClass: 'dialog-no-close'
});
mydiv.load('../PDF1.aspx');
// Open the dialog
mydiv.dialog('open');
// }
}
So, the above code was failing since the following the web call would start running before the session() set ajax call was done.
Setting async: false DID work well, but in the browser debug, we saw warnings that async:false will soon not be supported in jQuery (or web browsers). So, you wire up a routine to run when the async call is done and move out the code that follows to that routine so, the code that follows was moved out and called by the jQuery (success: event).
So, it not clear how/when/where your code calls the first web method, but if any code call FOLLOWS to check/see/grab/get/look at the session() value to be return from the 2nd web method? You have to deal with the async issue.
and depending on your imports (using for c# folks), then if you need to include the namespace before using session() in a web method.
I find I have to use this:
HttpContext.Current.Session(strSess) = strValue
So, I would use the same name space reference in both your web methods - is it NOT AT ALL clear why you left out the name space in one code stub, but put it in the other.
As noted, it also not clear how your js is testing/getting the session() value, but as noted, the first web call to set the session() will NOT wait, and you find sometimes that when you call the 2nd routine to get the session(), the first routine may well not yet have finished (since the calls are async).
Check my below screenshot and follow the steps:

Alert from back-end

This is a WebMethod that takes value from front-end in the lvl string.
Later that string is checked through getDuplicate procedure if there is already that value in the database. If the value exists then the insert procedure InsertObject is not activated and if there is no such value in the database first procedure returns null and the insert procedure will work.
Everything work well in the code all I need is some kind of an alert message from the C# part of the code if the insert is a success, and if it fails.
I tried so many examples and I can't find any solution :/
Can someone please help ?
[WebMethod(EnableSession = true)]
public static void GetCollection(string lvl)
{
string conn = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(conn))
try
{
connection.Open();
SqlCommand cmdCount = new SqlCommand("getDuplicate", connection);
cmdCount.CommandType = CommandType.StoredProcedure;
cmdCount.Parameters.AddWithValue("#ObjekatName", lvl);
var count = (string)cmdCount.ExecuteScalar();
if (count == null)
{
SqlCommand cmdProc = new SqlCommand("InsertObjekat", connection);
cmdProc.CommandType = CommandType.StoredProcedure;
cmdProc.Parameters.AddWithValue("#ObjekatName", lvl);
cmdProc.ExecuteNonQuery();
//successful alert
}
else
{
//fail alert
}
}
catch
{
}
finally
{
connection.Close();
}
return;
}
Update:
Ajax that sends values to the method:
$(function () {
$('#myButton').on('click', function () {
var lvl = $('#MainContent_txtProductConstruction').val()
$.ajax({
type: "POST",
url: "NewProductConstruction.aspx/GetCollection",
data: JSON.stringify({'lvl': lvl }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Saved successfully.");
console.log(response);
location.reload(true);
},
error: function (response) {
alert("Not Saved!");
console.log(response);
location.reload(true);
}
});
});
});
You can return a json object. Change the return type of method as string.Include using Newtonsoft.Json; and then when you want to return, create an object like this:
[WebMethod]
public static string GetCollection(string lvl)
{
bool isInserted = false;
// set the value of isInserted
// you can send code a numeric value or bool value according to your need
var result = new {code = isInserted, message = isInserted ? "Succesfully inserted" : "Already Exists"};
return JsonConvert.SerializeObject(result);
}
At the client side, check the response
success: function (response) {
console.log(response);
if(response != null){
var data = $.parseJSON(response)
alert(data.message)
}
location.reload(true);
}

asp.net webservice jquery textbox autocomplete

I'm trying to implement jquery - textbox autocomplete. for this setup a web service.
[WebMethod]
public List<Condition> GetCondition(string term)
{
List<Condition> listCondition = new List<Condition>();
string cs = ConfigurationManager.ConnectionStrings["db5"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spSelCondition", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "#term",
Value = term
});
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
listCondition.Add(new Condition { ConditionID = rdr["ConditionID"].ToString(), ConditionName = rdr["ConditionName"].ToString() });
}
return listCondition;
}
}
public class Condition
{
public string ConditionName { get; set; }
public string ConditionID { get; set; }
}
WebService works perfectly fine. To populate the textbox with jquery autocomplete this javascript I've written.
<script type="text/javascript">
$(document).ready(function () {
$('#txtCondition').autocomplete({
source: function (request, response) {
$.ajax({
url: 'ibs_ws.asmx/GetCondition',
method: 'post',
contentType: 'application/json;charset=utf-8',
data: JSON.stringify({ term: request.term }),
dataType: 'json',
success: function (data) {
response(data.d);
},
error: function (err) {
alert(err);
}
});
}
});
})</script>
When I access the webservice it takes the #term as parameter and returns the result with ConditionID and ConditionName in xml formate. But on the webform when I give type anything in the textbox it alerts with [object object].
What could be the problem.
--
Thanks & Regards
May be it will help you. try this
I think you need to use $.map(data.d, function (value, key) {}). here is the example need to update your success code like below then you can get value inside object.
success: function (data) {
response($.map(data.d, function (value, key) {
return {
ConID: value.ConditionID,
ConNAme: value.ConditionName,
}
}))
},
AS you said your service returns conditionID and Name so i used these variable you can match what it returns exactly.

how to bind dropdown in sharepoint using angularJS?

Hi I am developing one small application in sharepoint 2013 webparts. I am trying to bind dropdown from database using angular js. My pages are RFRegretLetterWP.ascx and RFRegretLetterWP.ascx. I have tried as below.
<script type="text/javascript">
angular.module('drpdwnApp', []).controller('drpdwnCtrl', function ($scope, $http) {
$scope.ProductList = null;
//Declaring the function to load data from database
$scope.fillProductList = function () {
$http({
method: 'POST',
url: 'RFPRegretLetterWP.ascx/GetDDLNames',
data: {}
}).success(function (result) {
$scope.ProductList = result.d;
});
};
//Calling the function to load the data on pageload
$scope.fillProductList();
});
</script>
This is my html code.
<div ng-app="drpdwnApp" ng-controller="drpdwnCtrl">
<select ng-model="drpdpwnvalue" ng-options="item.OrderID for item in ProductList">
<option value="" label="Select and item"></option>
</select>
</div>
This is my server side code.
public static List<OrderList> GetDDLNames()
{
List<OrderList> list = new List<OrderList>();
using (SqlConnection conn = new SqlConnection("I have connection string here"))
{
conn.Open();
string strquery = ("select * from CategoryMaster order by CategoryName Asc");
using (SqlCommand cmd = new SqlCommand(strquery, conn))
{
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
OrderList objorder = new OrderList(reader["Vendor_ID"].ToString());
list.Add(objorder);
}
}
}
return list;
}
public class OrderList
{
public string Vendor_ID;
public OrderList(string UName)
{
Vendor_ID = UName;
}
}
I have little doubt in making call to server. This is my Url
url: 'RFPRegretLetterWP.ascx/GetDDLNames' but my page name is RFPRegretLetterWP.ascx.cs so i am having confusion. In some articles i noticed [System.Web.Services.WebMethod()] but when i put it it gives me error. May I have some suggestions on this regards. thank you for consideration
I suggest you to insert the server side code into a LayoutsPage like this:
using System.Web.Services;
public partial class RFPRegretLetterWP : LayoutsPageBase
{
[WebMethod]
public static IEnumerable GetDDLNames()
{
List<OrderList> list = new List<OrderList>();
/* your code */
return list;
}
public class OrderList
{
/* your code */
}
}
and call the web method with the url:
_spPageContextInfo.webAbsoluteUrl/_layouts/15/<project name>/<pagename>.aspx/GetDDLNames
like this:
<script type="text/javascript">
angular.module('drpdwnApp', []).controller('drpdwnCtrl', function ($scope, $http) {
$scope.ProductList = null;
//Declaring the function to load data from database
$scope.fillProductList = function () {
$.ajax({
type: "POST",
url: _spPageContextInfo.webAbsoluteUrl + "/_layouts/15/<project name>/RFPRegretLetterWP.aspx/GetDDLNames",
data: null,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: onCompleted,
error: onError
});
function onCompleted(data) {
if (data !== null)
$scope.ProductList = data.d;
}
function onError(error) {
console.log('An error has occurred: ' + error.data);
}
};
//Calling the function to load the data on pageload
$scope.fillProductList();
});
</script>
Replace <project name> with your visual studio project's name.

Categories