Using mongoose style schemas MSSQL in Node.js - javascript

I am currently writing an API with Express.js and have seen many examples about how to create schemas/models for mongodb, but was wondering if there is any similar solution for MSSQL. For example, I have the following method in a C# controller:
public void SubmitExpenses(List<Expense> expenses)
{
using (cnxn)
{
cnxn.Open();
for (int i = 0; i < expenses.Count; i++)
{
int employeeId = expenses.ElementAt(i).employeeId;
string expenseDate = expenses.ElementAt(i).expenseDate;
int taskId = expenses.ElementAt(i).taskId;
int expenseTypeId = expenses.ElementAt(i).expenseTypeId;
int billingCategory = expenses.ElementAt(i).billingCategory;
string notes = expenses.ElementAt(i).notes;
float amount = expenses.ElementAt(i).amount;
string lastUpdatedDate = expenses.ElementAt(i).LastUpdatedDate;
int lastUpdatedBy = expenses.ElementAt(i).LastUpdatedBy;
string dateSubmitted = expenses.ElementAt(i).dateSubmitted;
//public void SubmitExpenses(int employeeId, string expenseDate, int taskId, int expenseTypeId, int billingCategory,
// string notes, float amount, string lastUpdatedDate, int lastUpdatedBy, string dateSubmitted)
//{
using (SqlCommand sqlQuery = new SqlCommand("INSERT INTO Expenses " +
"(Employee_ID, Task_ID, Expense_Date, Expense_Type_ID, Billing_Category_ID, " +
"Amount, Notes, Last_Updated_By, Last_Update_Datetime, Date_Submitted, Location) " +
"Values (#employeeId, #taskId, #expenseDate, #expenseTypeId, #billingCategory, #amount, #notes, " +
"#lastUpdatedBy, #lastUpdatedDate, #dateSubmitted, #locationId)", cnxn))
{
sqlQuery.Parameters.Add(new SqlParameter("#employeeId", SqlDbType.Int) { Value = employeeId });
sqlQuery.Parameters.Add(new SqlParameter("#expenseDate", SqlDbType.DateTime) { Value = expenseDate });
sqlQuery.Parameters.Add(new SqlParameter("#taskId", SqlDbType.Int) { Value = taskId });
sqlQuery.Parameters.Add(new SqlParameter("#expenseTypeId", SqlDbType.Int) { Value = expenseTypeId });
sqlQuery.Parameters.Add(new SqlParameter("#billingCategory", SqlDbType.Int) { Value = billingCategory });
sqlQuery.Parameters.Add(new SqlParameter("#notes", SqlDbType.Text) { Value = notes });
sqlQuery.Parameters.Add(new SqlParameter("#amount", SqlDbType.Money) { Value = amount });
sqlQuery.Parameters.Add(new SqlParameter("#lastUpdatedDate", SqlDbType.DateTime) { Value = lastUpdatedDate });
sqlQuery.Parameters.Add(new SqlParameter("#lastUpdatedBy", SqlDbType.Int) { Value = lastUpdatedBy });
sqlQuery.Parameters.Add(new SqlParameter("#dateSubmitted", SqlDbType.DateTime) { Value = dateSubmitted });
sqlQuery.Parameters.Add(new SqlParameter("#locationId", SqlDbType.VarChar) { Value = "" });
sqlQuery.ExecuteNonQuery();
}
}
}
}
And the Expense.cs model:
public class Expense
{
public int employeeId { get; set; }
public string expenseDate { get; set; }
public int taskId { get; set; }
public int expenseTypeId { get; set; }
public int billingCategory { get; set; }
public string notes { get; set; }
public float amount { get; set; }
public string LastUpdatedDate { get; set; }
public int LastUpdatedBy { get; set; }
public string dateSubmitted { get; set; }
public string location { get; set; }
}
How would I go about in similar fashion in Express.js so I could take a list of JavaScript objects, break them into elements which could then be parameterized and submitted?
Would it be something like...
app.post('/route/to/api', function (req, res) {
var sql = require('mssql');
sql.connect("mssql://user:password#localhost/Northwind").then(function () {
console.log('connected');
for (var i = 0; i < req.length; i++) {
new sql.Request()
.input('input_param', sql.VARCHAR, req[i]['PropertyName'])
.query('INSERT INTO Table VALUES (#input_param)')
.then(function (recordset) {
console.log(recordset);
})
.catch(function (err) {
console.log(err);
});
}
}).catch(function (err) {
console.log(err);
});
});
Any advice would be much appreciated!

Have a look at sequelize. It should give you the functionality you require.

Related

How to use ActionResult in onkeyup and onkeydown in a input which type is number?

I am trying to use an action result in a input function,here is my code,my goal is that when user Keyup or keydown or type a number in input,Sum of ProductPrice changes.i dont know,which event is proper for my goal,i have used onkeydown & onkeyup events.but nothing changes.
<td><input type="number" onkeyup="#Url.Action("CountUp","ShoppingCart",new { id = #item.ProductId })"
onkeydown="#Url.Action("CountDown","ShoppingCart",new { id = #item.ProductId })"
value="#item.ProductCount" min="0" style="width:70px"></td>
and Here is My controller
// GET: ShoppingCart
public ActionResult Index()
{
List<ShowShoppingCart> shopcart = new List<ShowShoppingCart>();
if (Session["ShoppingCart"] != null)
{
List<ShopCartItem> shop = Session["ShoppingCart"] as List<ShopCartItem>;
foreach (var item in shop)
{
var product = db.Products.Find(item.ProductId);
shopcart.Add(new ShowShoppingCart()
{
ProductCount = item.ProductCount,
ProductId = item.ProductId,
ProductPrice = product.ProductPrice,
ProductTitle = product.ProductTitle,
Sum = item.ProductCount * product.ProductPrice
});
}
}
return View(shopcart);
}
public ActionResult CountUp(int id)
{
List<ShopCartItem> shop = Session["ShoppingCart"] as List<ShopCartItem>;
int index = shop.FindIndex(s => s.ProductId == id);
shop[index].ProductCount += 1;
Session["ShoppingCart"] = shop;
return RedirectToAction("Index");
}
public ActionResult CountDown(int id)
{
List<ShopCartItem> shop = Session["ShoppingCart"] as List<ShopCartItem>;
int index = shop.FindIndex(s => s.ProductId == id);
shop[index].ProductCount -= 1;
if (shop[index].ProductCount == 0)
{
shop.Remove(shop[index]);
}
Session["ShoppingCart"] = shop;
return RedirectToAction("Index");
}
and this is ShopCart
public class ShopCartItem
{
public int ProductId { get; set; }
public int ProductCount { get; set; }
}
and another question?
when user type a number in input which event should i use? onChange()? or another?
Not really sure about your main question, but about the second one, you should really use onChange()

How to pass model object to javascript function in asp.net Core

i have a problem in passing model objects to a javascript function in .cshtml(asp.net Core project).
I have done a lot of search,but can't find a solution to solve this problem.
I build a web application use ChartJs line sample.
web app
js files
There is a js function in .cshtml file,
<script>
document.getElementById('addData').addEventListener('click', function() {
if (config.data.datasets.length > 0) {
var month = MONTHS[config.data.labels.length % MONTHS.length];
config.data.labels.push(month);
config.data.datasets.forEach(function(dataset) {
dataset.data.push(randomScalingFactor());
});
window.myLine.update();
}
});
</script>
I'm new to asp.net core and js.
If there is a way to add data from model to js function?
Thanks!
I have solved this problem!
Solution:
Model:
public class SalesViewModel
{
public string salesdate { get; set; }
public int salesprice { get; set; }
}
Data:
public class SalesContext
{
public string ConnectionString { get; set; }
public SalesContext(string connectionString)
{
this.ConnectionString = connectionString;
}
public SalesContext()
{
}
public List<SalesViewModel> GetAllData()
{
List<SalesViewModel> list = new List<SalesViewModel>();
list.Add(new SalesViewModel() { salesdate = "1", salesprice = 3 });
list.Add(new SalesViewModel() { salesdate = "2", salesprice = 6 });
list.Add(new SalesViewModel() { salesdate = "3", salesprice = 7 });
list.Add(new SalesViewModel() { salesdate = "4", salesprice = 2 });
list.Add(new SalesViewModel() { salesdate = "5", salesprice = 1 });
return list;
}
}
Controller:
using Newtonsoft.Json;
public IActionResult Chart()
{
SalesContext sc = new SalesContext();
string json = JsonConvert.SerializeObject(sc.GetAllData());
//ViewData["chart"] = json;
ViewBag.Sales = json;
return View(sc.GetAllData());
}
View:
document.getElementById('addData').addEventListener('click', function() {
if (config.data.datasets.length > 0) {
var salesdata = #Html.Raw(ViewBag.Sales);
config.data.datasets.forEach(function(dataset) {
for (var i = 0; i < salesdata.length; i++) {
var month = MONTHS[config.data.labels.length % MONTHS.length];
config.data.labels.push(month);
dataset.data.push(salesdata[i].salesprice);
}
});
window.myLine.update();
}
});
use var salesdata = #Html.Raw(ViewBag.Sales) to get data from controller!
use salesdata[i].salesprice to push data to the dataset!
Thanks!

Uploading files in chunks with blueimp in Asp.Net MVC

I try to put the plugin blueimp to my Asp.Net MVC application.
My upload target is about 1GB.
How to handle chunk file upload fle in server side?
I suppose you mean FileUpload jquery module from blueimp. This is how I handle it in my project. I upload large images that don't go over 30MB. So this example is merely about the code, not the fact that you need to handle 1GB files.
This is part of the javascript code. There's nothing special. I just follow the FileUpload documentation and example. I just send couple more properties (inlcuding AntiforgeryToken) - that are not required for the correct behavior.
$("#file-upload").fileupload({
url: 'upload-file',
dataType: 'json',
autoUpload: false,
maxChunkSize: 5000000,
progressInterval: 1000,
bitrateInterval: 1000
}).on('fileuploadadd', function (e, data) {
fileData = data; // save data to be able to submit them later
if (window.File && window.Blob) {
// update form data
data.formData = {
uploadFolder: '/upload-folder/some-guid',
__RequestVerificationToken: $("#upload-form").find('input[name=__RequestVerificationToken]').val()
};
} else {
// chunk upload not supported
}
});
$("#file-submit").on('click', function (e) {
e.preventDefault();
fileData.submit();
});
On the server side I have a model class:
public class UploadViewRequest
{
public Guid UploadFolder { get; set; }
public bool IsChunk { get; set; }
public int ChunkNumber { get; set; }
public bool IsFirst { get; set; }
public bool IsLast { get; set; }
public HttpPostedFileBase OriginalFile { get; set; }
public bool JsonAccepted { get; set; }
}
And I wrote a custom model binder for this class, so that I can see if it's whole file or just a chunk and if yes, that what part of the file I'm going to process:
public class UploadViewRequestBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
UploadViewRequest model = base.BindModel(controllerContext, bindingContext) as UploadViewRequest;
string rangeHeader = controllerContext.HttpContext.Request.Headers["Content-Range"];
if (string.IsNullOrEmpty(rangeHeader))
model.IsChunk = false;
else
{
model.IsChunk = true;
Match match = Regex.Match(rangeHeader, "^bytes ([\\d]+)-([\\d]+)\\/([\\d]+)$", RegexOptions.IgnoreCase);
int bytesFrom = int.Parse(match.Groups[1].Value);
int bytesTo = int.Parse(match.Groups[2].Value);
int bytesFull = int.Parse(match.Groups[3].Value);
if (bytesTo == bytesFull)
model.IsLast = true;
else
model.IsLast = false;
if (bytesFrom == 0)
{
model.ChunkNumber = 1;
model.IsFirst = true;
}
else
{
int bytesSize = bytesTo - bytesFrom + 1;
model.ChunkNumber = (bytesFrom / bytesSize) + 1;
model.IsFirst = false;
}
}
if (controllerContext.HttpContext.Request["HTTP_ACCEPT"] != null && controllerContext.HttpContext.Request["HTTP_ACCEPT"].Contains("application/json"))
model.JsonAccepted = true;
else
model.JsonAccepted = false;
return model;
}
}
and this is the controller action method:
public ActionResult Upload(UploadViewRequest request)
{
var path = ''; // create path
FileStatus status = null;
try
{
if (request.IsChunk)
{
if (request.IsFirst )
{
// do some stuff that has to be done before the file starts uploading
}
var inputStream = request.OriginalFile.InputStream;
using (var fs = new FileStream(path, FileMode.Append, FileAccess.Write))
{
var buffer = new byte[1024];
var l = inputStream.Read(buffer, 0, 1024);
while (l > 0)
{
fs.Write(buffer, 0, l);
l = inputStream.Read(buffer, 0, 1024);
}
fs.Flush();
fs.Close();
}
status = new FileStatus(new FileInfo(path));
if (request.IsLast)
{
// do some stuff that has to be done after the file is uploaded
}
}
else
{
file.SaveAs(path);
status = new FileStatus(new FileInfo(path));
}
} catch {
status = new FileStatus
{
error = "Something went wrong"
};
}
// this is just a browser json support/compatibility workaround
if (request.JsonAccepted)
return Json(status);
else
return Json(status, "text/plain");
}
The FileStatus class I use as a return value and transform it into json (for the UploadFile jquery module):
public class FileStatus
{
public const string HandlerPath = "/";
public string group { get; set; }
public string name { get; set; }
public string type { get; set; }
public int size { get; set; }
public string progress { get; set; }
public string url { get; set; }
public string thumbnail_url { get; set; }
public string delete_url { get; set; }
public string delete_type { get; set; }
public string error { get; set; }
public FileStatus()
{
}
public FileStatus(FileInfo fileInfo)
{
SetValues(fileInfo.Name, (int)fileInfo.Length, fileInfo.FullName);
}
public FileStatus(string fileName, int fileLength, string fullPath)
{
SetValues(fileName, fileLength, fullPath);
}
private void SetValues(string fileName, int fileLength, string fullPath)
{
name = fileName;
type = "image/png";
size = fileLength;
progress = "1.0";
url = HandlerPath + "/file/upload?f=" + fileName;
delete_url = HandlerPath + "/file/delete?f=" + fileName;
delete_type = "DELETE";
thumbnail_url = "/Content/img/generalFile.png";
}
}

How to bind checkbox to model binder that were created dynamically

I added checkbox dynamically in the view with PropertiesList select box. When submiting the form it posted the checkbox data but in controller Properties in null that presented in below image.
Browser header:
Debugging mode:
Model:
public class ModelView
{
[HiddenInput]
public int Id { get; set; }
public string Title { get; set; }
public IEnumerable<SelectListItem> PropertiesList { get; set; }
public List<PropertyModels> Properties { get; set; }
}
public class PropertyModels
{
public int PropertyID { get; set; }
public string PropertyIcon { get; set; }
public int PropertyType { get; set; }
public string PropertyName { get; set; }
public bool IsSelected { get; set; }
}
View:
<div class="form-group">
<label>Properties</label>
<select id="PropertiesList" class="form-control" placeholder="Add ...">
#for (var i = 0; i < Model.Properties.Count(); i++)
{
<option value="#Model.Properties[i].PropertyID" data-value="#Model.Properties[i].IsSelected" data-icon="#Model.Properties[i].PropertyIcon">#Model.Properties[i].PropertyName</option>
}
</select>
</div>
<div>
<dl class="dl-horizontal"></dl>
</div>
JQuery:
$("#PropertiesList").on("change", function (e) {
var id = $(this).val();
var icon = $('#PropertiesList option:selected').attr('data-icon');
var name = $('#PropertiesList option:selected').text();
var dt = "<dt><span class='" + icon + "'></span> <span>" + name + "</span></dt>";
var value = ($('#PropertiesList option:selected').attr('data-value') === "True");
var dd = "<dd><input id='Properties_" + id + "__IsSelected' name='Properties[" + id + "].IsSelected' type='checkbox' class='minimal' value='false'> \
<input name='Properties[" + id + "].IsSelected' type='hidden'></dd>";
}
$('.dl-horizontal').append(dt + dd);
});
Conrtoller:
public virtual ActionResult EditView(int Id)
{
List<PropertyModels> PropertyItems = new List<PropertyModels>();
using (var context = new DB())
{
var properties = context.Property
.Where(prpinfo => prpinfo.Status == true)
.Select(prpinfo => new
{
prp_id = prpinfo.PropertyID,
prp_name = prpinfo.PropertyName
prp_icon = prpinfo.PropertyIcon,
});
foreach (var prp in properties)
{
PropertyModels prop = new PropertyModels();
prop.PropertyID = prp.prp_id;
prop.PropertyName = prp.prp_name.FirstOrDefault().prp_name;
prop.PropertyIcon = prp.prp_icon;
prop.IsSelected = false;
PropertyItems.Add(prop);
}
AddPlanModelView EPW = new AddPlanModelView()
{
Properties = PropertyItems
};
return View(EPW);
}
}
[HttpPost]
public virtual ActionResult EditView(ModelView MW)
{
if (TryUpdateModel(Plan, includeProperties: new[] { "PlanId","Title","Properties" }))
{
if (ModelState.IsValid)
{
using (var context = new DB())
{
var selected_property = context.ModelProperty.Where(d => d.ID == MW.Id)
.Select(prpinfo => new
{
prp_id = prpinfo.PropertyID,
prp_val = prpinfo.PropertyValueID
}).ToList();
IList<ModelProperty> modelprps = new List<ModelProperty>();
foreach (var cc in ModelView .Properties)
{
var match = selected_property.Where(c => c.prp_id == cc.PropertyID).Count();
if (match == 0)
{
modelprps.Add(new ModelProperty() { ModelID = Plan.PlanId, PropertyID = cc.PropertyID, Value = cc.IsSelected.ToString() });
}
}
context.ModelProperty.AddRange(modelprps);
}
}
context.SaveChanges();
return Json(new { success = true });
}
}
else
{
return Json(new { success = false });
}
}
else
{
return Json(new { success = false });
}
}

Get the javascript push object array in a MVC3 controller action

This is my javascript code:
var bankOptions = {};
var playerOptions = [];
bankOptions["BankTotalAmount"] = $("#totalBankAmountID").val();
bankOptions["SinglePlayerAmount"] = $("#singlePlayerAmountID").val();
while (_playerNumber != 0) {
if (_playerNumber == 1) {
var player1Option = {};
player1Option["Name"] = $("#p" + _playerNumber + "Name").val();
player1Option["Color"] = $("#p" + _playerNumber + "Color").val();
playerOptions.push(player1Option);
}
if (_playerNumber == 2) {
var player2Option = {};
player2Option["Name"] = $("#p" + _playerNumber + "Name").val();
player2Option["Color"] = $("#p" + _playerNumber + "Color").val();
playerOptions.push(player2Option);
}
if (_playerNumber == 3) {
var player3Option = {};
player3Option["Name"] = $("#p" + _playerNumber + "Name").val();
player3Option["Color"] = $("#p" + _playerNumber + "Color").val();
playerOptions.push(player3Option);
}
if (_playerNumber == 4) {
var player4Option = {};
player4Option["Name"] = $("#p" + _playerNumber + "Name").val();
player4Option["Color"] = $("#p" + _playerNumber + "Color").val();
playerOptions.push(player4Option);
}
_playerNumber--;
}
alert(playerOptions);
$.ajax({
url: "/StartOption/setOptions/",
contentType: 'application/json',
data: JSON.stringify({ bankOptions: bankOptions, playerOptions: playerOptions }),
type: "POST",
timeout: 10000,
success: function (result) {
}
});
and i have this Controller class
public class StartOptionController : Controller
{
private MonopolyDB db = new MonopolyDB();
//
// GET: /StartOption/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult setOptions(BankOptions bankOptions, Playeroptions[] playerOptions)
{
//int length = (int)playerOptions.GetType().InvokeMember("length", BindingFlags.GetProperty, null, playerOptions, null);
BankAccount bankaccount = new BankAccount();
bankaccount.ID = 1;
bankaccount.TotalAmmount = bankOptions.BankTotalAmount;
db.BankAccount_Table.Add(bankaccount);
db.SaveChanges();
//Here i want to get each (player1Option, player2Option...) object array from that playerOptions object array
//return RedirectToAction("Index");
return View();
}
}
public class BankOptions
{
public int BankTotalAmount { get; set; }
public int SinglePlayerAmount { get; set; }
}
public class Playeroptions
{
public string Name { get; set; }
public string Color { get; set; }
}
My question is how i can get those object array that i push into playerOptions object array in my setOptions action?
as like i want to save each player info in my DB from playerOptions object array where i push each player info in my javascript code.
Well first to make it easy I would like to recommend that changes the sign of your action
from
public ActionResult setOptions(BankOptions bankOptions, Playeroptions[] playerOptions)
To
public ActionResult setOptions(BankOptions bankOptions, List<PlayerOptions> playerOptions)
That's it's going to make it easy the handle of each element of the array, and there's not problem for the framework to serialize this object.
Now to answer your question you could iterate the array like this
[HttpPost]
public ActionResult setOptions(BankOptions bankOptions, Playeroptions[] playerOptions)
{
//int length = (int)playerOptions.GetType().InvokeMember("length", BindingFlags.GetProperty, null, playerOptions, null);
BankAccount bankaccount = new BankAccount();
bankaccount.ID = 1;
bankaccount.TotalAmmount = bankOptions.BankTotalAmount;
db.BankAccount_Table.Add(bankaccount);
db.SaveChanges();
//Here i want to get each (player1Option, player2Option...) object array from that playerOptions object array
for ( int i = 0 ; i< playerOptions.Length, i++)
{
playerOptions[i]; //<-- this give's the specific element
}
//return RedirectToAction("Index");
return View();
}
Nevertheless if you follow my recommendation and changes the sign of your action you could iterate your code like this
[HttpPost]
public ActionResult setOptions(BankOptions bankOptions, List<PlayerOptions> playerOptions)
{
//int length = (int)playerOptions.GetType().InvokeMember("length", BindingFlags.GetProperty, null, playerOptions, null);
BankAccount bankaccount = new BankAccount();
bankaccount.ID = 1;
bankaccount.TotalAmmount = bankOptions.BankTotalAmount;
db.BankAccount_Table.Add(bankaccount);
db.SaveChanges();
//Here i want to get each (player1Option, player2Option...) object array from that playerOptions object array
foreach( var item in playerOptions){
item //<--- in this variable you have the element PlayerOption
}
//return RedirectToAction("Index");
return View();
}

Categories