How to execute arbitrary SQL statement in ASP.NET/Angular application - asp.net

I am trying to make a trivial call to a SQL Server 2000 database using Angular's $http service. Angular factory containing the $http:
var RegistrationFactory = function ($http, $q, SessionService) {
return function (email, password, confirmPassword) {
var result = $q.defer();
$http({
method: 'POST',
url: SessionService.apiUrl + '/api/Account/Register',
data: { Email: email, Password: password, ConfirmPassword: confirmPassword },
headers: { 'Content-Type': 'application/json' }
})
.success(function (response) {
result.resolve(response);
})
.error(function (response) {
result.reject(response);
});
return result.promise;
}
}
RegistrationFactory.$inject = ['$http', '$q', 'SessionService'];
And inside the AccountController:
[HttpPost]
[AllowAnonymous]
public async Task<bool> Register(RegisterViewModel model)
{
string queryString = "INSERT INTO Northwind VALUES('test', 'values')";
SqlConnection cnxn = new SqlConnection(WebConfigurationManager.ConnectionStrings["TheConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand(queryString, cnxn);
cnxn.Open();
command.ExecuteNonQuery();
cnxn.Close();
var user = new ApplicationUser
{
UserName = model.Email,
Email = model.Email
};
var result = await UserManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
return false;
}
await SignInManager.SignInAsync(user, false, false);
return true;
}
This program is merely trying to show that the SQL-related codes are executed upon the RegistrationFactory being utilized.
The Register.cshtml view:
<form ng-submit="register()">
<label for="emailAddress">Email Address:</label>
<input id="emailAddress" type="text" ng-model="registerForm.emailAddress" required />
<label for="password">Password:</label>
<input id="password" type="password" ng-model="registerForm.password" required />
<label for="confirmPassword">Password:</label>
<input id="confirmPassword" type="password" ng-model="registerForm.confirmPassword" required />
<button type="submit">Register</button>
</form>
And the RegisterController.js that handles above view:
var RegisterController = function ($scope) {
$scope.registerForm = {
emailAddress: '',
password: '',
confirmPassword: '',
registrationFailure: false
};
$scope.register = function () {
var result = RegistrationFactory($scope.registerForm.emailAddress, $scope.registerForm.password, $scope.registerForm.confirmPassword);
result.then(function (result) {
if (result.success) {
$location.path('/routeOne');
} else {
$scope.registerForm.registrationFailure = true;
}
});
}
}
RegisterController.$inject = ['$scope', '$location', 'RegistrationFactory'];
I am trying to figure out how to actually execute the statement as the result of my $http. Additionally, being able to pass data through the 'POST' would be awesome. And, yes, it has to be for SQL Server 2000, so Entity Framework is not an option. Thanks, everyone!

Related

XML pasing Error: no root element found in location when i try to pass data to action of controller asp.net mvc application

when i pass data to the first action its working fine and based on the return of that action i call another one with another ajax post request and pass the same data but the error message appears on console and nothing happens, note that if i don't pass data at all(not in the same nor the second query) both actions get called without problem but with no data passed enter image description here
those are the codes for the actions and the script(second)
[HttpPost]
public async Task<bool> Check(string login = "", string password = "")
{
var model = new HomeViewModel()
{
LoginRequest = new LoginRequest()
{
Login = login,
Password = password,
}
};
var test = model;
var authResult = await _accountUseCases.LoginAsync(model).ConfigureAwait(false);
var testAuthResult = authResult;
return authResult.force;
}
[HttpPost]
public async Task<IActionResult> LoginV2(string login = "", string password = "")
{
var model = new HomeViewModel()
{
LoginRequest = new LoginRequest()
{
Login = login,
Password = password,
}
};
var test = model;
var authResult = await _accountUseCases.LoginAsync(model).ConfigureAwait(false);
if (!authResult.result)
{
model.LoginRequest.Password = "";
TempData["Message"] = authResult.message;
return RedirectToAction("Index", "Login", model);
}
if (!string.IsNullOrEmpty(model.ReturnUrl) && Url.IsLocalUrl(model.ReturnUrl))
{
return Redirect(model.ReturnUrl);
}
return RedirectToAction("Index", "Trainings");
}
public IActionResult IndexV2()
{
return View();
}
and this is the script
#using System.Text.Encodings.Web
#using Microsoft.AspNetCore.Mvc.Localization
#using Microsoft.Extensions.Localization
#using UI
#inject IViewLocalizer Localizer
#inject IStringLocalizer<SharedResource> SharedLocalizer
#inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
#functions {
private string GetAntiXsrfRequestToken()
{
return Xsrf.GetAndStoreTokens(Context).RequestToken;
}
}
<script type="text/javascript" nonce="bGFsYWNvY29qYW1ib2xhbGF5ZWFhYWE=">
$(document).on("click", "#LoginFormSubmit",
function (e) {
setLoginCredentials();
})
function GetLoginCredentials() {
var login = document.getElementById("txtUsername2").value;
var pwd = document.getElementById("Password").value;
var data = {
'login': login,
'password': pwd
};
//var jData = JSON.stringify({ login: login, password: pwd });
//return jData
return data ;
}
function setLoginCredentials() {
var data = GetLoginCredentials();
console.log(data);
$.ajax({
type: "POST",
url: "#Url.Action("Check", "Login")",
headers: {
"RequestVerificationToken": "#GetAntiXsrfRequestToken()"
},
//contentType: "application/json; charset=utf-8",
//dataType: "json",
//data: JSON.stringify({login:data.login, password: data.password}),
data: data,
success: function (result, status, xhr) {
if (result == true) {
$('#LoginConfirmationModal').modal('show');
}
else if(result == false) {
//var data2 = GetLoginCredentials();
$.ajax({
type: "POST",
url: "#Url.Action("LoginV2", "Login")",
headers: {
"RequestVerificationToken": "#GetAntiXsrfRequestToken()"
},
data: data,
//contentType: "application/json",
//dataType: "json",
//data: JSON.stringify({ login: data.login, password: data.password }),
//data:JSON.stringify({login:data2.login , password:data2.password}),
//contentType:"application/json;charset=utf-8",
//dataType:"json",
success: function (result, status, xhr) {
},
error: function (xhr, status, error) {
}
});
}
}
,
error: function (xhr, status, error) {
}
});
};
</script>

Validation errors required Angular (frontend) and ASP.NET (backend)

I am trying to create a new instance of a model from Angular with an ASP.NET backend. However I am facing validation errors saying that the fields are required.
This is what I have tried - template :
<h1>Add employee : </h1>
<form [formGroup]="form">
<label for="EmployeeName">Employee Name : </label>
<input type="text" formControlName="EmployeeName">
<label for="Department">Employee Department: </label>
<input type="text" formControlName="Department">
<label for="DateOfJoining">Date of joining : </label>
<input type="date" formControlName="DateOfJoining">
<label for="fileimage">Main image</label>
<input type="file" accept="image/*" fomrControlName="fileimage" (change)="onImageUpload($event)">
<button (click)="onSubmit()">Create Employee</button>
</form>
This is the Angular component:
ngOnInit(): void {
this.form=this.formBuilder.group({
EmployeeName:[''],
Department:[''],
DateOfJoining:[''],
fileimage:['', Validators.required]
})
}
onImageUpload(event) {
const file = event.target.files[0];
if (file) {
this.form.patchValue({fileimage:file});
this.form.get('fileimage').updateValueAndValidity();
const fileReader = new FileReader();
fileReader.onload = ()=> {
this.imageDisplay=fileReader.result;
};
fileReader.readAsDataURL(file);
}
}
onSubmit() {
const Employee : Employee = {
EmployeeName:this.form.get('EmployeeName').value,
Department:this.form.get('Department').value,
};
this.imageService.createEmployee(Employee, this.form.get('fileimage').value).subscribe(
()=>{
console.log("Employee Created")
},
()=>{
console.log("Error in Employee Creation")
}
);
}
This is the service I am working with :
createEmployee(employee:Employee, file:File):Observable<ArrayBuffer>{
let headers = new Headers();
headers.append('Content-Type', 'multipart/form-data;boundary=<calculated when request is sent>');
const options = {
headers: new HttpHeaders({
'Content-Type': 'multipart/form-data;boundary=<calculated when request is sent>'
}),
body: {}
}
return this.http.post<ArrayBuffer>(`${this.apiURLEmployee}`, {employee, file}, options)
}
And finally this is my backend endpoint :
public IActionResult Post([FromForm]Employee emp, IFormFile file)
{
MongoClient dbClient = new MongoClient(_configuration.GetConnectionString("EmployeeAppCon"));
int LastEmployeeId = dbClient.GetDatabase("BDD").GetCollection<Employee>("Employee").AsQueryable().Count();
emp.EmployeeId = LastEmployeeId + 1;
string wwwRootPath = _hostEnvironment.WebRootPath;
if (file != null)
{
string filename = Guid.NewGuid().ToString();
var uploads = Path.Combine(wwwRootPath, #"images\employee");
var extension = Path.GetExtension(file.FileName);
Uri domain = new Uri(Request.GetDisplayUrl());
if (emp.PhotoFileName != null)
{
var oldImagePath = Path.Combine(wwwRootPath, emp.PhotoFileName.TrimStart('/'));
if (System.IO.File.Exists(oldImagePath))
{
System.IO.File.Delete(oldImagePath);
}
}
using (var fileStreams = new FileStream(Path.Combine(uploads, filename + extension), FileMode.Create))
{
file.CopyTo(fileStreams);
}
emp.PhotoFileName = domain.Scheme + "://" + domain.Host + (domain.IsDefaultPort ? "" : ":" + domain.Port) + "/images/employee/" + filename + extension;
}
dbClient.GetDatabase("BDD").GetCollection<Employee>("Employee").InsertOne(emp);
return Json("Employee added successfully");
}
The validation errors are from the backend. Here is the error :
Error Image
Request
Payload

jQuery function not getting called in mvc text-changed event

I am getting this strange behavior in jQuery when working with mvc application.
Below is MVC view in which I have implemented Text change event,
#Html.TextBoxFor(m => m.UserId, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.UserId, "", new { #class = "text-danger" })
$("#UserId").change(function () {
var UserId = $(this).val();
//$("#txtName").val(emailId);
$.ajax({
url: 'GetValidUserName',
type: 'POST',
data: JSON.stringify({ UserId: UserId }),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
if (!$.trim(data)) {
alert("User does not exist in system. Please enter valid User Id.");
$(':input[type="submit"]').prop('disabled', true);
}
else {
$("#UserId").val(data);
$("#UserId").focus();
$(':input[type="submit"]').prop('disabled', false);
}
}
});
});
While debugging application when I load Index view directly first time , jQuery function gets called and invoke the controller action properly.http://localhost:51012/UserApplication/Index
But when I load the view again, jQuery function doesn't get called.
Controller code,
public JsonResult GetValidUserName(string userId)
{
LMTUsage objLMT = new LMTUsage();
LMTDAL objLMTDAL = new LMTDAL();
string UserID = "";
objLMT.UserList = objLMTDAL.GetAll_User("", 0, "6");
var AllUsersInDatabase = from p in objLMT.UserList
where p.UserId == userId
select new
{
Name = p.UserName,
Id = p.UserId,
};
foreach (var user in AllUsersInDatabase)
{
if (user.Name != null)
{
UserID = user.Id;
}
}
return Json(UserID, JsonRequestBehavior.AllowGet);
}
You have several issues with AJAX callback:
1) type: 'POST' option requires [HttpPost] attribute. If the attribute isn't present on the action method, use type: 'GET' instead.
2) You don't need JSON.stringify() to pass single parameter containing simple types (numeric and string values). A simple { userId: UserId } should be fine.
3) The controller action's parameter name must be exactly match with parameter name sent from AJAX callback.
Therefore, your AJAX callback should be follow example below:
$(function () {
$("#UserId").change(function () {
var UserId = $(this).val();
$.ajax({
url: '#Url.Action("GetValidUserName", "ControllerName")',
type: 'GET',
data: { userId: UserId },
dataType: 'json',
success: function (data) {
if (!$.trim(data)) {
alert("User does not exist in system. Please enter valid User Id.");
$(':input[type="submit"]').prop('disabled', true);
}
else {
$("#UserId").val(data);
$("#UserId").focus();
$(':input[type="submit"]').prop('disabled', false);
}
}
});
});
});

ASP.NET Upload file return its content

I'm trying to upload a file then retrieve its content as JSon
My controller :
controller.cs
[HttpPost]
public JsonResult Upload(HttpPostedFileBase file)
{
List<string> list = doStuff(file);
return Json(list);
}
My view :
view.cshtml
#using (Html.BeginForm("Upload", "Files", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" id="file" name="file" />
<input type="submit" name="Upload" value="Upload" />
}
When I upload a file it propose me to download a JSON file, but what I want is to set a javascript variable with this JSON so I can use it directly on my webpage.
I believe that the best solution is to use an ajax form.
See the example below:
Controller:
[HttpPost]
public JsonResult Upload(HttpPostedFileBase file)
{
return Json(new { ReturnMessage = "Success!!!!!" + file.FileName});
}
View:
#using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { #id="formUploadFile", #onsubmit = "return SubmitFormWithFile();" }))
{
#Html.TextBox("file", null, new { #type = "file", #id = "file" })
<button type="submit">Send</button>
}
Javascript:
function SubmitFormWithFile() {
var form = $("#formUploadFile");
$.ajax({
url: form.attr("action"),
type: form.attr("method"),
data: new FormData(form[0]),
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
alert("Before Send");
},
success: function (dataResult) {
//set its variable here...
//the dataResult is returned json...
alert(dataResult.ReturnMessage);
},
error: function () {
alert("Error");
}
});
return false;
}

How can I call a vb.net function from angularJS code?

I'm trying to pass data stored in a dynamically created table to the server, and while I can access the data in my angularJS controller, I am having difficulty learning how to pass this data to the server to process.
Here is my angularjs function that is able to access my table data, its just passing the data and calling my vb.net function that I am having trouble with.
$scope.requestThatCertificatesBeEmailed = function () {
for (index = 0; index < $scope.requests.length; ++index) {
alert('For loop entered')
var submittedEmailAddressString = $scope.requests[index].emailAddress;
var submittedCertificateTypeString = $scope.requests[index].certificateType;
var submittedSearchTypeString = $scope.requests[index].searchType;
var submittedSearchString = $scope.requests[index].submittedNumbers;
alert(submittedSearchTypeString);
$http.post("/Home/NewTextFile", { submittedEmailAddress: submittedEmailAddressString, submittedCertificateType: submittedCertificateTypeString, submittedSearchType: submittedSearchTypeString, submittedSearch: submittedSearchString }).error(function () {
$scope.requests = [];
});
You will need to post/put the data back to the server. If you are working in a ASP.NET WebForms application, you will likely need to pass the value as JSON to the server in a hidden input field. If you are working in an ASP.NET MVC application, you should be able to invoke a controller action sending in the JSON table data from javascript.
Your action method in your MVC Controller should look like this:
<HttpPost> _
Public Function NewTextFile(submittedEmailAddress As String, submittedCertificateType As String, submittedSearchType As String, submittedSearch As String) As ActionResult
'do some work
End Function
Using jQuery, you could invoke the controller action like so:
$.ajax({
url: '/Home/NewTextFile',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
submittedEmailAddress: submittedEmailAddressString,
submittedCertificateType: submittedCertificateTypeString,
submittedSearchType: submittedSearchTypeString,
submittedSearch: submittedSearchString
}),
processData: false,
dataType: 'json'
});
Below is an AngularJS example I whipped together:
On/referenced from the View:
<script type="text/javascript">
angular.module('httpExample', [])
.controller('ContactController', ['$scope', '$http',
function ($scope, $http, $templateCache) {
$scope.contact = { userName: '', firstName: '', lastName: '' };
$scope.get = function () {
$scope.code = null;
$scope.response = null;
$http.get('/Home/Contact').
success(function (data, status) {
$scope.status = status;
$scope.data = data;
$scope.contact = data;
}).
error(function (data, status) {
$scope.data = data || "Request failed";
$scope.contact = { userName: '', firstName: '', lastName: '' }
$scope.status = status;
});
};
$scope.post = function () {
$scope.code = null;
$scope.response = null;
$http.post('/Home/Contact', $scope.contact).
success(function (data, status) {
$scope.status = status;
$scope.data = data;
}).
error(function (data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
}]);
</script>
Somewhere in the body:
<div>
<div ng-app="httpExample">
<div ng-controller="ContactController">
<fieldset>
<legend>Contact</legend>
Username: <input type="text" ng-model="contact.userName"/><br/>
Last Name: <input type="text" ng-model="contact.lastName"/><br/>
First Name: <input type="text" ng-model="contact.firstName"/><br/>
</fieldset>
<br />
<button id="getbtn" ng-click="get()">get</button>
<button id="postbtn" ng-click="post()">post</button><br/><br/>
<pre>http status code: {{status}}</pre>
<pre>http response data: {{data}}</pre>
</div>
</div>
</div>
And your MVC server side Home controller has methods that look like this:
<HttpGet> _
Public Function Contact() As JsonResult
Dim contact = New With { .userName = "smithjk", .firstName = "John", .lastName = "Smith" }
Return Json(contact, JsonRequestBehavior.AllowGet)
End Function
<HttpPost> _
Public Function Contact(userName As String, firstName As String, lastName As String) As ActionResult
'do some work
System.Diagnostics.Debug.Print(userName)
Return New EmptyResult()
End Function

Resources