Sending Data From javaScript Which Is retrived from LocalStorage(WebSql) and pass to MVC Controller - asp.net-mvc

db.transaction(
function (transaction) {
transaction.executeSql('INSERT INTO EmployeeTable(Firstname,Lastname,BirthDate,EmployeeType,MaritalStatus,Company,IsActive,Dependents) values(?,?,?,?,?,?,?,?)',
[Firstname.toString(), Lastname.toString(), BirthDate, parseInt(empType), parseInt(marital),Company.toString(),active, parseInt(Dependents)]);
transaction.executeSql('SELECT * FROM EmployeeTable', [], function (transaction, results) {
result = results;
alert(result.length);
for (i = 0; i < results.length; i++) {
var EmployeeID = results.rows.item(i).EmployeeID;
var Firstname = results.rows.item(i).Firstname;
var Lastname = results.rows.item(i).Lastname;
alert(results.rows.item(i).EmployeeID + " " + results.rows.item(i).Firstname + " " + results.rows.item(i).Lastname);
//var product = [productid, productname, price, qty];
//insertTableRow(product,i);
}
}, null);
}
);
am Using WEB SQL as Local Database
want to send data retrived from websql using
db.Transaction() method
to server controller.
Please Help On same.....
How should i transfer data to controller of mvc.....
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
if (Save(0, collection))
{
// List<char> bulkdata = collection["bulkdata"].ToList();
return RedirectToAction("Index");
}
else
{
return View("Edit");
}
}
catch
{
return View();
}
}

The following tutorial shows an example how to sync local db with a WCF Data Service endpoint. By combining this with the WebAPI tutorial you will be able to sync to the online DB with these lines:
function synchronizeData() {
offlinedb
.TodoItems
.filter("it.InSync === false")
.toArray(function (todoItems) {
onlinedb.addMany(todoItems);
onlinedb.saveChanges(function () {
todoItems.forEach(function (todoItem) {
offlinedb.attach(todoItem);
todoItem.InSync = true;
});
offlinedb.saveChanges(function () {
listLocalTodoItems();
listRemoteTodoItems();
});
});
})
}

You might try serializing your localstorage string and then send to the server...
ASP.NET MVC How to pass JSON object from View to Controller as Parameter

Related

Can I serialize data to send to a Infragistics isgrid using json instead of sending a IQueryable<T> object?

I'm using an Infragistics isGrid defined below. Is there anyway I can get it to work with a json string instead of an IQueryable object?
function bindSitesGrid() {
try {
$("#TheftGrid").igGrid({
}
]
});
var parameters = $('#VTRModifiedCriteriaForm').serialize();
var url = '/VTR/VehicleTheftRecovery/Search/?ticks=' + new Date() + "&" + parameters;
$('#TheftGrid').igGrid('option', 'dataSource', url);
}
catch (error) {
console.log(error)
}
}
So can I do this
Public Function Search(ssViewModel As VehicleTheftRecoveryVM) As ActionResult
Return View(Json(siteSearchResults))
End Function
Instead of this
Public Function Search(ssViewModel As VehicleTheftRecoveryVM) As ActionResult
Return View(siteSearchResults.AsQueryable())
End Function

MVC SignalR not firing from Controller Post Method

When Saving schedule to calendar it must auto update the activity logs on my notification bar in my Home Controller. It saves the data but only show when notification bar is refreshed. It seems that Hub is not starting when saved.
CalendarController.cs
[HttpPost]
public JsonResult SaveSchedule(Schedule s)
{
var userid = User.Identity.GetUserId();
var profile = _context.Profiles.Single(p => p.Id == userid);
var status = false;
if (s.Schedule_ID > 0)
{
//Update
var v = _context.Schedules.Where(a => a.Schedule_ID == s.Schedule_ID).FirstOrDefault();
if (v != null)
{
v.Shift = s.Shift;
}
}
var activitylog = new ActivityLog
{
UserId = userid,
LogDate = DateTime.Now,
Activity = ActivityHelper.GetActivityLog(4, profile.FirstName)
};
// save to data and must be shown on notification bar
_context.ActivityLogs.Add(activitylog);
_context.SaveChanges();
ActivityHub.StartLogging();
status = true;
return new JsonResult { Data = new { status = status } };
}
HomeController.cs
public JsonResult GetLogs()
{
return Json(ActivityHelper.GetActivityLogs(), JsonRequestBehavior.AllowGet);
}
ActivityHub.cs
public class ActivityHub : Hub
{
public static void StartLogging()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<ActivityHub>();
//calls the signalR client part to execute javascript method
context.Clients.All.displayLog();
}
}
My CSHTML
<script>
$(function () {
var activityFromHub = $.connection.activityHub;
$.connection.hub.start().done(function () {
FetchLogs();
});
activityFromHub.client.displayLog = function () {
console.log('Hub Started');
FetchLogs();
}
function FetchLogs() {
$.ajax({
type: 'GET',
url: '/Home/GetLogs',
datatype: 'json',
success: function (data) {
$("#logs tr").remove();
data = $.parseJSON(data);
if (data.length > 0) {
.... do some append here
}
},
error: function (error) {
alert("error");
}
});
}
});
</script>
ActivityHelper.cs
static readonly string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
public static class ActivityHelper
{
public static string GetActivityLogs()
{
string sqlCommand = #"my select query here";
try
{
var messages = new List<ActivityLog>();
using(var connection = new SqlConnection(connString))
{
connection.Open();
using (SqlConnection con = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sqlCommand, con);
if(con.State != System.Data.ConnectionState.Open)
{
con.Open();
}
cmd.Notification = null;
SqlDependency dependency = new SqlDependency(cmd);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
messages.Add(item: new ActivityLog
{
Activity = reader["Activity"] != DBNull.Value ? (string)reader["Activity"] : "",
LogDate = (DateTime)reader["LogDate"]
});
}
}
}
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(messages);
return json;
}
catch(Exception ex)
{
throw;
}
}
public static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
SqlDependency dependency = sender as SqlDependency;
dependency.OnChange -= dependency_OnChange;
var activityHub = GlobalHost.ConnectionManager.GetHubContext<ActivityHub>();
GetActivityLogs();
}
}
}
FIRST METHOD
First Solution change your javascript code like this. If this not works move to the second method:
$(function () {
var activityFromHub = $.connection.ActivityHub;
$.connection.hub.start().done(function () {
FetchLogs();
});
activityFromHub.client.displayLog = function () {
console.log('Hub Started');
FetchLogs();
}
});
SECOND METHOD:
Each client connecting to a hub passes a unique connection id. You can retrieve this value in the Context.ConnectionId property of the hub context. And i found there is nothing happening like this. You may try this solution.
I think the simplest solution for your question is to use groups.
http://www.asp.net/signalr/overview/guide-to-the-api/working-with-groups
Your hub class would contain methods to join a group:
public Task JoinGroup(string groupName)
{
return Groups.Add(Context.ConnectionId, groupName);
}
public Task LeaveGroup(string groupName)
{
return Groups.Remove(Context.ConnectionId, groupName);
}
and your hub will be look like this:
public static void StartLogging(string groupName)
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<ActivityHub>();
context.Clients.Group(groupName).displayLog();
//calls the signalR client part to execute javascript method
//context.Clients.All.displayLog();
}
And change your javascript as like this:
$(function () {
var activityFromHub = $.connection.ActivityHub;
$.connection.hub.start().done(function () {
activityFromHub.server.joinGroup("Group1");
activityFromHub.server.StartLogging("Group1");
FetchLogs();
});
activityFromHub.client.displayLog = function () {
console.log('Hub Started');
FetchLogs();
}
});
I hope this will resolve your issue. If you are still facing issue. Please leave comments. Thank you.

ASP.NET Core 2 - How to call and manipulate a Database class from a controller

I am using ASP.NET Core 2 and I have a controller that runs Tasks.
For example, the one below does a simple file upload, I have others that run other Tasks or Actions and I want to be able to log the events or tasks into my database.
So I need to create a class to run INSERTs or UPDATEs on a database.
How do I create a class that does my database manipulation either using DbContext or call a stored procedure using a class (and not a controller)?
Here is a sample of one of my controller's code:
public async Task<IActionResult> Uploads(string fullName, IFormFile pic)
{
try {
string user = null;
try
{
user = User.Identity.Name.ToString();
}
catch (Exception err)
{
user = "anonymous";
}
if (user == null)
{
user = "";
}
string path = he.WebRootPath + "/uploads/" + user ;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
DateTime date = DateTime.Now ;
var dates = date.ToLongDateString();
var ext = Path.GetExtension(path).ToLowerInvariant();
var fileName = Path.Combine(he.WebRootPath + "/uploads/" + "/" + user, Path.GetFileName(pic.FileName));
var f = Path.Combine(he.WebRootPath + "/uploads/" + "/" + user, dates+Path.GetFileName(pic.FileName));
int i = 0;
ViewData["fname"] = fullName;
if (pic != null || pic.Length == 0)
{
using (var stream = new FileStream(fileName, FileMode.Create))
{
await pic.CopyToAsync(stream);
}
ViewData["fileLocation"] = "/uploads/" + user + "/" + Path.GetFileName(pic.FileName);
// }
}
You can use dependency injection to inject your DbContext into your controller:
public class MyController : Controller
{
private readonly DbContext _db;
public MyController(DbContext db)
{
_db = db;
}
public async Task<IActionResult> Uploads(string fullName, IFormFile pic)
{
_db.ExecuteSql("INSERT ...");
}
}
Once you have your Db context, you can do what you need with it.

ASP.Net MVC, WebAPI, AngularJS - Check if value exists in database

I am using webapi and angularjs in my ASP.net MVC app. Everything is working good but in my insert (post) method I need to check if a value exists in the db before doing an insert. I am not sure where that should go. I ruled out the webapi because a void does not return a value. The logical place seems to be the controller, but I cannot find the right way to call my angular getEmployee(id) method from within the insert controller method. Any help is appreciated.
Angular controller (post):
$scope.insertEmployee = function (employee) {
employeeFactory.insertEmployee(employee)
.success(function (emp) {
$scope.employee = emp;
})
.error(function (error) {
$scope.status = 'Unable to load employee data: ' + error.message;
});
};
Angular factory (post):
factory.insertEmployee = function (employee) {
url = baseAddress + "employee/insert/";
$http.post(url, employee).success(function (data) {
alert("Saved Successfully!!");
}).error(function (data) {
$scope.error = "An Error has occured while saving employee! " + data;
});
};
webapi controller post method:
[Route("api/employee/insert/")]
public void Post(Employee employee)
{
if (ModelState.IsValid)
{
context.Employee.Add(employee);
context.SaveChanges();
}
}
Angular controller (get):
$scope.getEmployees = function (term) {
employeeFactory.getEmployees(term)
.success(function (data) {
$scope.employees = data;
})
.error(function (error) {
$scope.status = 'Unable to load employee data: ' + error.message;
});
};
I would suggest doing this in your web-api server side. You can construct an exception and throw it. Some pseudo-code:
[Route("api/employee/insert/")]
public void Post(Employee employee)
{
if (ModelState.IsValid)
{
// verify doesn't already exist
if(...item-already-exists...) {
var resp = new HttpResponseMessage(HttpStatusCode.Conflict)
{
Content = new StringContent("Employee already exists!")),
ReasonPhrase = "Employee already exists!"
}
throw new HttpResponseException(resp);
}
context.Employee.Add(employee);
context.SaveChanges();
}
}
Your factory doesn't match your controller. If you want to use success and error from employeeFactory.insertEmployee, it needs to return the promise:
factory.insertEmployee = function (employee) {
url = baseAddress + "employee/insert/";
return $http.post(url, employee);
};
So then you can do
employeeFactory.insertEmployee(employee).success( ... )
Now to answer your question you could either do a database read in insertEmployee to check if the value exists before you insert it. Or save a server call and do the check during the insert request: if the employee exists, return an error or a specific message to tell the client.
With the help of floribon and Nicholas Smith I managed to come up with a solution that bubbles the error up to my view, which I display in a div element. This is only bare bones, but is a start.
My angular controller:
$scope.insertEmployee = function (employee) {
employeeFactory.insertEmployee(employee)
.success(function (data) {
$scope.employee = data;
$scope.status = 'The item was saved';
})
.error(function (error) {
$scope.status = 'Unable to save the employee data: ' + error;
});
};
My angular factory:
factory.insertEmployee = function (employee) {
url = baseAddress + "employee/insert/";
return $http.post(url, employee);
};
my webapi controller:
[Route("api/employee/insert/")]
public HttpResponseMessage Post(Employee employee)
{
HttpResponseMessage response;
// check for the employee
var employeeCheck = context.Employee
.Where(b => b.EmployeeNumber == employee.EmployeeNumber)
.FirstOrDefault();
if (employeeCheck == null)
{
// save the item here
response = Request.CreateResponse(HttpStatusCode.OK);
}
else
{
response = Request.CreateResponse(HttpStatusCode.Conflict, "The item already exists");
}
return response;
}
The result is the message is "Unable to save the employee data: The item already exists".

Can't invoke client functions from the Server

I'm working on a small concept trying to get to work with SignalR.
In this scenario all connected clients need to refresh when one of the clients perform an update, this update is performed through an Ajax request.
Because there might be different instances of the page, depending on a parameter, I'm using groups for this.
The client side code looks as followed:
<script>
window.onload = function () {
DoRefresh();
}
$(function () {
var hub = $.connection.commonHub;
hub.client.refresh = function () {
DoRefresh();//This doesn't get called for the other clients
};
$.connection.hub.start();
$.connection.hub.start().done(function () {
hub.server.join("MyPage" + #Model.Id + "");
});
});
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
function DoRefresh() {
$.ajax({
url: '#Url.Action("LoadData")',
cache: false,
data: "&id=" + #Model.Id + "",
success: function (html) {
$("#conversation").empty();
$("#conversation").append(html);
},
error: function (xhr, status, err) {
alert('Response code:' + xhr.status + '\r\n[Error:' + err + '] ' + status);
}
});
return false;
};
function DoUpdate() {
$.ajax({
url: '#Url.Action("DoUpdate")',
cache: false,
data: "&id=" + #Model.Id + "&posterID=" + #userAccount.AccountID + "&message=" + $("#Textbox").val().replaceAll("\n", "[br]"),
success: function () {
$("#Textbox").empty();
DoRefresh();
},
error: function () {
$("#Textbox").empty();
DoRefresh();
}
});
return false;
};
</script>
In my controller, following functions are part of this scenario:
public class MyController : Controller
{
private Hubs.CommonHub hub = new Hubs.CommonHub();
//Some other Controller Methods
public PartialViewResult LoadData(int id)
{
MyModel item = Connection.DB.MyData.FirstOrDefault(x => x.Id == id);
return PartialView(item);
}
public virtual EmptyResult DoUpdate(int id, int posterID, string message)
{
message = message.Replace("[br]", "\r\n");
MyModel item = Connection.DB.MyData.FirstOrDefault(x => x.Id == id);
Account poster = Connection.DB.Accounts.FirstOrDefault(x => x.Id == posterID);;
item.Updates.Add(new Update()
{
PosterId = posterID,
Poster = poster,
Id = id,
Item = item,
PostDate = DateTime.UtcNow,
Message = message.Replace(Environment.NewLine,"\r\n")
});
Connection.DB.SaveChanges();
hub.Refresh("MyPage" + item.Id);
return null;
}
}
And finally, my hub class looks like this:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.SignalR;
using MyProject.Models;
namespace MyProject.Hubs
{
public class CommonHub : Hub
{
private string myInfo;
public override Task OnConnected()
{
myInfo = Context.ConnectionId;
return base.OnConnected();
}
public Task Join(string groupName)
{
return Groups.Add(Context.ConnectionId, groupName);
}
public Task Leave(string groupName)
{
return Groups.Remove(Context.ConnectionId, groupName);
}
public void Refresh(string groupName)
{
var context = GlobalHost.ConnectionManager.GetHubContext<CommonHub>();
context.Clients.Group(groupName).Refresh();
}
}
}
The Join task in the hub is called with every connect of a new browser window. The Refresh method is invoked on the hub, but only the invoking window has its page refreshed. The client side refresh function only gets invoked once when debugging, probably for the invoking client.
I have no idea why the other clients are not doing their updates, please help.

Resources