Procedure or function "registerStudent" expects parameter "#EmailUsername", which was not supplied.' - javascript

Other people have ran into this similar issue, however I am pretty positive that I'm passing in parameters as necessary, and that I have command type set to stored procedure. I also do a console log in JavaScript file to output whatever is in the textboxes, and yet there is still some error with the API it seems. I need another set of eyes to hopefully find something that I'm missing. Thanks for any help in advance.
JavaScript Code
function registerStudent()
{
var studentID = document.getElementById('id').value;
var studentEmail = document.getElementById('email').value;
var studentEmailPassword = document.getElementById('password').value;
var studentFirstName = document.getElementById('firstname').value;
var studentLastName = document.getElementById('lastname').value;
console.log(studentID + "," + studentEmail + "," + studentEmailPassword + "," + studentFirstName + "," + studentLastName);
if ((studentID=='') || (studentEmail=='') || (studentEmailPassword=='') || (studentFirstName=='') || (studentLastName==''))
{
alert("Please fill in all fields to register");
return false;
}
var postObj = {
ID: studentID,
EmailUsername: studentEmail,
EmailPassword: studentEmailPassword,
FirstName: studentFirstName,
LastName: studentLastName
};
var apiRequest = new XMLHttpRequest();
apiRequest.open('POST', 'https://localhost:44379/api/JSON/registerStudent', true);
apiRequest.setRequestHeader('Content-Type', 'application/json');
apiRequest.onreadystatechange = function()
{
if (this.readyState === XMLHttpRequest.DONE && this.status === 200)
{
if (apiRequest.response=="-1")
{
alert("User already exists");
return false;
}
if (apiRequest.response=="1")
{
alert("User registered");
return false;
}
}
}
apiRequest.send(JSON.stringify(postObj));
return false;
}
C# ASP.NET RESTFUL WEB API CODE
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.IO;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Http.Cors;
namespace AiAngelsAPI.Controllers
{
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class JSONController : ApiController
{
/********************
* Register Student
********************/
[System.Web.Http.HttpPost]
public object registerStudent(Models.RegisterStudent student)
{
var response = Request.CreateResponse(HttpStatusCode.OK);
string sqlStoredProcedureName = "registerStudent";
var json = ExecuteRegisterStudent(sqlStoredProcedureName, student.id, student.email, student.password, student.firstname, student.lastname);
response.Content = new StringContent(json);
return response;
}
private static string ExecuteRegisterStudent(string storedProcedureNameSqlQuery, string studentID, string emailUsername, string emailPassword, string firstname, string lastname)
{
string json = "";
string connectionString = ConfigurationManager.AppSettings["databaseConnection"].ToString();
using (SqlConnection databaseConnection = new SqlConnection(connectionString))
{
databaseConnection.Open();
// 1. create a command object identifying the stored procedure
SqlCommand command = new SqlCommand(storedProcedureNameSqlQuery, databaseConnection);
// 2. set the command object so it knows to execute a stored procedure
command.CommandType = CommandType.StoredProcedure;
// 3. add parameter to command, which will be passed to the stored procedure
command.Parameters.Add(new SqlParameter("#ID", studentID));
command.Parameters.Add(new SqlParameter("#EmailUsername", emailUsername));
command.Parameters.Add(new SqlParameter("#EmailPassword", emailPassword));
command.Parameters.Add(new SqlParameter("#FirstName", firstname));
command.Parameters.Add(new SqlParameter("#Lastname", lastname));
// execute the command
using (SqlDataReader returnData = command.ExecuteReader())
{
// iterate through results, printing each to console
while (returnData.Read())
{
json = (string)returnData[0].ToString();
}
}
}
return json;
}
}
}
SQL Stored Procedure Code
ALTER PROCEDURE [dbo].[registerStudent]
-- variables that will be passed into stored procedure (input)
#ID varchar(16),
#EmailUsername varchar(100),
#EmailPassword varchar(50),
#FirstName varchar(100),
#LastName varchar(100)
AS
BEGIN
-- if structure to check if student already exists/has registered
if 1 = (select count(*)
from [dbo].[Student]
where [studentEmailUsername] = #EmailUsername)
begin
select -1; -- student already exists, returns -1 as indicator
return;
end
-- inserts input into table/registers student by adding to database
insert into [dbo].[Student] (studentID,studentEmailUsername,studentEmailPassword,studentFirstName,studentLastName)
values (#ID,#EmailUsername,#EmailPassword,#FirstName,#LastName)
select 1; -- student is added to database, returns 1 as indicator
return;
END
Error in API
Click here to see error that comes up in API

Related

Plugin/Javascript - Update custom fields agr1 and agr2 on all Contacts with same email addres

I need to make plugin or javascript what work like that:
1.When agr1(bool) change(true<->false) on contact like "John Smith" with emailaddress1 = "john1#example.com" then plugin/js change agr1 field on all contacts with emailaddress1 = "john1#example.com"(duplicates mails).
I got 2 agreement (bool(yes/no)) on form: agr1 and agr2 for example, I create plugin what change agr2=false when I change agr1 from true to false and change agr1 to true when I channge agr2 from false to true - I want to do this on form when I create new Contact - how can I do this?
My code for example2(its work on exist contact not when I create):
namespace IfZgodaChangeMassmailingChange
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Crm.Sdk;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using System.Linq.Expressions;
using System.Activities;
using System.Runtime.Serialization;
using System.Collections.ObjectModel;
using System.Collections;
using System.Reflection;
using Microsoft.Xrm.Sdk.Workflow;
using Microsoft.Xrm.Sdk.Messages;
public class IfZgodaChangeMassmailingChange : IfZgodaChangeSetZgoda2.Plugin
{
public IfZgodaChangeMassmailingChange()
: base(typeof(IfZgodaChangeMassmailingChange))
{
base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>(40, "Update", "contact", new Action<LocalPluginContext>(ExecutePostKontaktUpdate)));
}
protected void ExecutePostKontaktUpdate(LocalPluginContext localContext)
{
if (localContext == null)
{
throw new ArgumentNullException("localContext");
}
IPluginExecutionContext context = localContext.PluginExecutionContext;
IOrganizationService service = localContext.OrganizationService;
ITracingService tracingService = localContext.TracingService;
OrganizationServiceContext _crmOrgContext = new OrganizationServiceContext(service);
tracingService.Trace("ExecutePostFakturaUpdate Plugin: Verifying the client is not offline.");
if (context.IsExecutingOffline || context.IsOfflinePlayback)
return;
if (context.Depth > 1)
return;
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
Entity entity = (Entity)context.InputParameters["Target"];
Entity _postEntity = (context.PostEntityImages.Contains("PostImage") && context.PostEntityImages["PostImage"] is Entity) ? context.PostEntityImages["PostImage"] : null;
Entity _preEntity = (context.PreEntityImages.Contains("PreImage") && context.PreEntityImages["PreImage"] is Entity) ? context.PreEntityImages["PreImage"] : null;
if (entity.LogicalName != "contact")
return;
try
{
if (context.MessageName == "Update")
{
bool agr1pre= _preEntity.GetAttributeValue<bool>("agr1");
bool agr1post= _postEntity.GetAttributeValue<bool>("agr1");
bool agr2pre= _preEntity.GetAttributeValue<bool>("agr2");
bool agr2post= _postEntity.GetAttributeValue<bool>("agr2");
if (agr1pre == true && agr1post == false)
{
entity.Attributes["agr2"] = false;
service.Update(entity);
}
else if (agr2pre== false && agr2post== true)
{
entity.Attributes["agr1"] = true;
service.Update(entity);
}
}
}
catch (FaultException<OrganizationServiceFault> e)
{
tracingService.Trace("Exception: {0}", e.ToString());
throw;
}
catch (Exception e)
{
tracingService.Trace("Exception: {0}", e.ToString());
throw;
}
}
}
[RequiredArgument]
[Input("contact")]
[ReferenceTarget("contact")]
public InArgument<EntityReference> contact { get; set; }
}
}
Thanks
I resolve my problem by code below.
What this code do? -> update custom fields on all contacts with same mail address
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Workflow;
using System;
using System.Activities;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
namespace IfZgodaChangeSetZgoda2
{
public class SpojnoscZgod : Plugin
{
public SpojnoscZgod()
: base(typeof(SpojnoscZgod))
{
base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>(40, "Update", "contact", new Action<LocalPluginContext>(ExecutePostKontaktUpdate)));
}
protected void ExecutePostKontaktUpdate(LocalPluginContext localContext)
{
if (localContext == null)
{
throw new ArgumentNullException("localContext");
}
IPluginExecutionContext context = localContext.PluginExecutionContext;
IOrganizationService service = localContext.OrganizationService;
ITracingService tracingService = localContext.TracingService;
OrganizationServiceContext _crmOrgContext = new OrganizationServiceContext(service);
tracingService.Trace("ExecutePostFakturaUpdate Plugin: Verifying the client is not offline.");
if (context.IsExecutingOffline || context.IsOfflinePlayback)
return;
if (context.Depth > 1)
return;
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
Entity contact = (Entity)context.InputParameters["Target"];
Entity _postEntity = (context.PostEntityImages.Contains("PostImage") && context.PostEntityImages["PostImage"] is Entity) ? context.PostEntityImages["PostImage"] : null;
Entity _preEntity = (context.PreEntityImages.Contains("PreImage") && context.PreEntityImages["PreImage"] is Entity) ? context.PreEntityImages["PreImage"] : null;
string email = _postEntity.GetAttributeValue<string>("emailaddress1"); // get email address from contact
bool zgodaNaMarketing = _postEntity.GetAttributeValue<bool>("alt_zgodanamarketing"); //get marketing agreement before edition
bool zgodaNaMarketingPre = _preEntity.GetAttributeValue<bool>("alt_zgodanamarketing"); //get marketing agreement after edition
bool alt_ZgodanamarketingnewPre = _preEntity.GetAttributeValue<bool>("alt_zgodanamassmailing"); //get marketing agreement for massmailing before edition
bool alt_Zgodanamarketingnew_post = _postEntity.GetAttributeValue<bool>("alt_zgodanamassmailing"); //get marketing agreement for massmailing after edition
string alt_uzasadnieniePre = _preEntity.GetAttributeValue<string>("alt_uzasadnienie"); //get justification of consent before edition
string alt_uzasadnienie = _postEntity.GetAttributeValue<string>("alt_uzasadnienie"); //get justification of consent after edition
if (contact.LogicalName != "contact")
return;
if (_postEntity.GetAttributeValue<string>("emailaddress1") == null) { return; } //if you delete mailaddress from contact add this line for doing nothing
try
{
QueryExpression contactQuery = new QueryExpression("contact"); // new query expression
contactQuery.ColumnSet = new ColumnSet(true); // new column set
contactQuery.Criteria = new FilterExpression(); // new filter for request
contactQuery.Criteria.AddCondition("emailaddress1".ToString(), ConditionOperator.Equal, email.ToString()); // get all contacts with same emailaddress1
EntityCollection retrievedContacts = service.RetrieveMultiple(contactQuery); // retrieve with above criteria
foreach (Entity contacts in retrievedContacts.Entities) // loop for change in all contacts 1 by 1
{
if (zgodaNaMarketingPre == true && zgodaNaMarketing == false)
{
contacts.Attributes["alt_zgodanamarketing"] = false;
contacts.Attributes["alt_zgodanamassmailing"] = false;
contacts.Attributes["alt_uzasadnienie"] = alt_uzasadnienie;
service.Update(contacts);
}
else if (alt_ZgodanamarketingnewPre == false && alt_Zgodanamarketingnew_post == true)
{
contacts.Attributes["alt_zgodanamarketing"] = true;
contacts.Attributes["alt_zgodanamassmailing"] = true;
contacts.Attributes["alt_uzasadnienie"] = alt_uzasadnienie;
service.Update(contacts);
}
else
{
contacts.Attributes["alt_zgodanamarketing"] = zgodaNaMarketing;
contacts.Attributes["alt_zgodanamassmailing"] = alt_Zgodanamarketingnew_post;
contacts.Attributes["alt_uzasadnienie"] = alt_uzasadnienie;
service.Update(contacts);
}
}
}
catch (FaultException<OrganizationServiceFault> e)
{
tracingService.Trace("Exception: {0}", e.ToString());
throw;
}
catch (Exception e)
{
tracingService.Trace("Exception: {0}", e.ToString());
throw;
}
}
}
[RequiredArgument]
[Input("contact")]
[ReferenceTarget("contact")]
public InArgument<EntityReference> contact { get; set; }
}
}

ASP.NET web app with Javascript - properly populate database columns

Creating a CRUD app in ASP.NET with C#, Javascript and SQL Server 2017.
The database table has three columns, Country, CountryCode and CountryCodeId that I'm attempting to populate with a create function (yes I'm aware of the relational design flaw here - that's outside of the scope of the question)...
I have an enum class that looks like this:
public enum Country
{
[Description("Afghanistan")] AFG = 1,
[Description("Ă…land Islands")] ALA = 2,
[Description("Albania")] ALB = 3,
}
I have a dropdown menu in the UI which displays the names of the country as shown in the Description piece above. Let's say the chosen value of the dropdown is Afghanistan. What I need to do upon execution of the create function is populate the Country column of the database with Afghanistan, the CountryCodecolumn with AFG and the CountryCodeId column with 1.
My Javascript skills are what are the most lacking, and I can only get the CountryCodeId to work, out of the three. This is my JS code - the question marks are where I'm lost:
async function newRecord(form) {
var record = {};
record.countryCodeId = $('#country').val();
record.countryCode = $("???").val();
record.country = $("???").val();
var response = await fetch(`${endpoint}api/record`, {
method: 'POST',
crossDomain: true,
cache: 'no-cache',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(record)
});
EDIT 1: as requested, here is the C# Insertfunction:
public bool Insert(Record record)
{
SqlConnection connection = new SqlConnection(_configuration.GetConnectionString("Production"));
connection.Open();
using (connection)
{
string query = "INSERT INTO [dbo].[Table]" +
"([Country]" +
",[CountryCode]" +
",[CountryCodeId]")
"VALUES " +
"(#Country" +
",#CountryCode" +
",#CountryCodeId")";
return connection.Execute(query, record) > 0;
}
}
EDIT 2:
Controller action method for Insert:
[HttpPost]
public JsonResult Insert(Record record)
{
try
{
bool result = _repository.Insert(record);
return new JsonResult(new OperationResult { Success = true });
}
catch (Exception ex)
{
return new JsonResult(new OperationResult { Success = false, Error = ex.Message });
}
}
Try this: -
using System.ComponentModel;
.
.
void ProcessCountry(string countryCode)
{
Country country;
// i.e. countryCode = "AFG"
if (Enum.TryParse(countryCode, out country))
{
string description = null;
try
{
FieldInfo fieldInfo = country.GetType().GetField(country.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])
fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
description = ((attributes.Length != 0) ?
attributes[0].Description :
country.ToString());
}
catch (System.NullReferenceException)
{
}
finally
{
if (string.IsNullOrEmpty(description))
{
description = "Unknown";
}
}
int value = Convert.ToInt32(country);
Console.Write($"countryCode: {countryCode}, description: {description}, value: {value}");
}
}
The FieldInfo/DescriptionAttribute stuff pulls the description out of the System.ComponentModel.Description attribute, and as you've given your enum values INT values then you can parse them as Int.

Spring RESTful GET method with same parameters and different return type

I work with Java/ Sprig MVC RESTful app and the client consumes it. I have 2 RESTful methods in the same input parameters and different return types. The methods are provided below,
// this method should return the `String`
#RequestMapping(value = "wallets/{currencyName}/{walletName}", method = RequestMethod.GET
, produces = "text/html")
public ResponseEntity<String> getAddressWithCurrencyAndWalletName(#PathVariable("currencyName") String currencyName,
#PathVariable("walletName") String walletName) {
logger.info("The currency name is {} and wallet name is {}", currencyName, walletName);
WalletInfo walletInfo = walletService.getWalletInfoWithCurrencyAndWalletName(currencyName, walletName);
if (Objects.isNull(walletInfo)) {
return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
}
String address = walletInfo.getAddress();
return new ResponseEntity<String>(address, HttpStatus.OK);
}
// this method should return the `Long`
#RequestMapping(value = "wallets/{currencyName}/{walletName}", method = RequestMethod.GET,
produces = "text/html")
public ResponseEntity<Long> getWalletIdWithCurrencyAndWalletName(#PathVariable("currencyName") String currencyName,
#PathVariable("walletName") String walletName) {
logger.info("The currency name is {} and wallet name is {}", currencyName, walletName);
WalletInfo walletInfo = walletService.getWalletInfoWithCurrencyAndWalletName(currencyName, walletName);
if (Objects.isNull(walletInfo)) {
return new ResponseEntity<Long>(HttpStatus.NOT_FOUND);
}
Long walletId = walletInfo.getId();
return new ResponseEntity<Long>(walletId, HttpStatus.OK);
}
In the client-side, I have UI like this,
If the Balance button is clicked, I would like to open a new page with URL of http://localhost:63342/WalletClient/balance.html?walletId=someValue and I would like to use the 2nd RESTful method for the very purpose. I imagine the client code to be like;
$(document).ready(function () {
var walletName, selectedCurrency;
// generic request function with the URL, method name and
// the request (GET, POST, PUT, DELETE etc) data
function request(url, method, data) {
$.ajax({
url: baseUrl + url,
// url: url,
method: method,
data: data
})
}
// some code
// we have the walletName and selectedCurrency values extracted
$("#balance").click(function () {
console.log("Open the balance page");
var url = "/rest/wallets/?" + "currencyName=" + selectedCurrency + "&" + "walletName=" + walletName;
// get the wallet Id from the cureny name and the wallet name
request(url, "GET").done(function (data) {
window.open("/WalletClient/balance.html?walletId=" + data);
});
});
}
The URL comes from the RESTful method and I expect it to return the Long. I have few questions in this scenarios,
a. Will it work as the same GET request could potentially return the String and Long?
b. is the data is already the String or the Long or I need to do something on over it?
Obvously, I can write it like window.open("/WalletClient/balance.html?" + "currencyName=" + selectedCurrency + "&" + "walletName=" + walletName);.
However, in this case the currencyName and the walletName will be exposed to the user and I would much prefer to hide it in the URL.
UPDATE
I changed the code to accomodatean optional parameter to distinct between the Long and the String,
/**
* get the wallet address with the currency name and the wallet name
*
* returns the Long value for the walletInfo
* curl -i -H "Accept: text/html" http://localhost:8080/rest/wallets/bitcoin/puut | json
*
*
* returns the String value for the walletInfo address
* curl -i -H "Accept: text/html" http://localhost:8080/rest/wallets/bitcoin/puut/true | json
*
* #param currencyName
* #param walletName
* #return
*/
#RequestMapping(value = "wallets/{currencyName}/{walletName}", method = RequestMethod.GET
, produces = "text/html")
public ResponseEntity<?> getAddressWithCurrencyAndWalletName(#PathVariable("currencyName") String currencyName,
#PathVariable("walletName") String walletName
, #RequestParam(value = "address", required = false) boolean address) {
logger.info("The currency name is {} and wallet name is {}", currencyName, walletName);
WalletInfo walletInfo = walletService.getWalletInfoWithCurrencyAndWalletName(currencyName, walletName);
if (Objects.isNull(walletInfo)) {
return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
}
// address values is expected
if(address){
String addressValue = walletInfo.getAddress();
return new ResponseEntity<String>(addressValue, HttpStatus.OK);
}
else {
Long walletId = walletInfo.getId();
return new ResponseEntity<Long>(walletId, HttpStatus.OK);
}
}
The client side URL will be like this,
var url = "/rest/wallets/?" + "currencyName=" + selectedCurrency + "&" + "walletName=" + walletName;
Is this correct now?
You can change your method and return ResponseEntity<?> type.
It would be:
#RequestMapping(...)
public ResponseEntity<?> yourMethod(...) {
// business-logic
if (some condition) {
return new ResponseEntity<String>(address, HttpStatus.OK);
} else if (...) {
return new ResponseEntity<Long>(walletId, HttpStatus.OK);
}
}

View data using C# and JavaScript

I am using following JavaScript:
jQuery(document).ready(function ($) {
$(function () {
$.ajax({
type: "POST",
url: "candidate-job-alert.aspx/GetJobalerts",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess
});
});
});
function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
console.log(xml);
var customers = xml.find("Table");
console.log(customers);
var row = $("[id*=CandidateAlerts] tr:last-child").clone(true);
$("[id*=CandidateAlerts] tr").not($("[id*=CandidateAlerts] tr:first-child")).remove();
$.each(customers, function () {
var customer = $(this);
AppendRow(row, $(this).find("alert_name").text(), $(this).find("keywords").text(), $(this).find("job_location").text(), $(this).find("job_category").text(), $(this).find("job_type").text(), $(this).find("email_frequency").text())
row = $("[id*=CandidateAlerts] tr:last-child").clone(true);
});
}
function AppendRow(row, alertname, keyword, joblocation, jobcategory, jobtype, emailfrequency) {
//Bind alert_name.
$(".alert_name", row).find("span").html(alertname);
$(".alert_name", row).find("input").val(alertname);
//Bind keywords.
$(".keywords", row).find("span").html(keyword);
$(".keywords", row).find("input").val(keyword);
//Bind job_location.
$(".job_location", row).find("span").html(joblocation);
$(".job_location", row).find("input").val(joblocation);
//Bind job_category.
$(".job_category", row).find("span").html(jobcategory);
$(".job_category", row).find("input").val(jobcategory);
//Bind job_type.
$(".job_type", row).find("span").html(jobtype);
$(".job_type", row).find("input").val(jobtype);
//Bind email_frequency.
$(".email_frequency", row).find("span").html(emailfrequency);
$(".email_frequency", row).find("input").val(joblocation);
$("[id*=CandidateAlerts]").append(row);
}
This is my C# code:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class candidate_job_alert : System.Web.UI.Page
{
string connectionString = ConfigurationManager.ConnectionStrings["JobMonsterConnectionString1"].ConnectionString;
string strg;
SqlCommand cms;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Email"] != null)
{
try
{
this.BindDummyRow();
//memberimg();
//lblRows.Text = getjobalerts();
}
catch (Exception ex)
{
string script = "<script>alert('" + ex.Message + "');</script>";
}
}
}
private void BindDummyRow()
{
DataTable dummy = new DataTable();
dummy.Columns.Add("alert_name");
dummy.Columns.Add("keywords");
dummy.Columns.Add("job_location");
dummy.Columns.Add("job_category");
dummy.Columns.Add("job_type");
dummy.Columns.Add("email_frequency");
dummy.Rows.Add();
CandidateAlerts.DataSource = dummy;
CandidateAlerts.DataBind();
}
[WebMethod]
public static string GetJobalerts()
{
string query = "SELECT alert_name, keywords, job_location, job_category, job_type, email_frequency FROM candidate_job_alerts where candidate_id = #CandidateId";
SqlCommand cmd = new SqlCommand(query);
cmd.Parameters.AddWithValue("#CandidateId", Session["candidate_id"]);
string constr = ConfigurationManager.ConnectionStrings["JobMonsterConnectionString1"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds.GetXml();
}
}
}
}
}
I am getting the following error:
Compiler Error Message: CS0120: An object reference is required for the non-static field, method, or property 'System.Web.UI.Page.Session.get'
Line 55: string query = "SELECT alert_name, keywords, job_location, job_category, job_type, email_frequency FROM candidate_job_alerts where candidate_id='" + Session["candidate_id"] + "'";
As mentioned in my comment, you need to use query parameterisation rather than concatenation otherwise you are open to a plethora of SQL Injection attacks.
The issue with your reference to Session is that your method is static, so you cannot access instance members (such as Session and anything else) of the System.Web.UI.Page. Make it an instance member instead of static should make your code work fine, I can't see any reason for it to be static, nor a POST request.
[WebMethod]
public string GetJobalerts()
{
string query = "SELECT alert_name, keywords, job_location, job_category, job_type, email_frequency FROM candidate_job_alerts where candidate_id = #CandidateId";
SqlCommand cmd = new SqlCommand(query);
cmd.Parameters.AddWithValue("#CandidateId", Session["candidate_id"]);
// ..
}

Using Cordova-sqlite-storage plugin

I am using Cordova-sqlite plugin in order to select and insert data to database embedded in an Android device. In my case I create the database from the native code and then I am trying to read some data from JavaScript source. But, I think that JavaScript is not reading from the same location as Android do.
This is my JS file :
var db = window.sqlitePlugin.openDatabase({name: 'db',iosDatabaseLocation: 'Library'});
var session = this._sessionInfoService.getSessionInfo();
db.transaction(function (tx)
{
var firstName = session.firstName;
var lastName = session.lastName;
var userId = session.id;
tx.executeSql("CREATE TABLE IF NOT EXISTS user (user_id INTEGER, firstname VARCHAR, lastname VARCHAR)");
tx.executeSql('SELECT * FROM user', [], function (tx, results) {
var len = results.rows.length, i;
console.log(len);
for (i = 0; i < len; i++){
var id =results.rows.item(i).user_id;
console.log(results.rows.item(i).user_id );
if(id!=userId){
var dialogTitle = "Another user is already registred for this device";
var dialogText = "Do you want to override it ";
WL.SimpleDialog.show(dialogTitle, dialogText, [ {
text : 'Override',
handler : function(){
db = window.sqlitePlugin.openDatabase({name: 'db',iosDatabaseLocation: 'Library'});
db.transaction(function (tx)
{
tx.executeSql("UPDATE user SET user_id =?, firstname=?, lastname=?", [userId,firstName,lastName]);
}
}
}, {
text : 'No',
handler : function(){
db = window.sqlitePlugin.openDatabase({name: 'db',iosDatabaseLocation: 'Library'});
db.transaction(function (tx)
{
tx.executeSql("INSERT INTO user (user_id,firstname, lastname) VALUES(?,?,?)", [userId,firstName,lastName]);
}
}
}
]);
}
else{
}
}
}, null);
}
});
}
and this is my java file in native source
#Override
public void onStart(Intent intent, int startId) {
final SQLiteDatabase db = openOrCreateDatabase("db",
Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS user (user_id INT, firstname VARCHAR, lastname VARCHAR);");
Log.i("e2", "yes");
db.execSQL("INSERT INTO user (user_id,firstname,lastname) VALUES(91,'ess','ess');");
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
String query = "SELECT * FROM user";
Cursor c = db.rawQuery(query, null);
if (c != null && c.moveToFirst()) {
int userId=c.getInt(1);
System.out.println("userId"+userId);
Log.i("userId",String.valueOf(userId));
}
}
catch(e){}
}
});
thread.start();
}
When try to create my database and my user table from JavaScript and then do the select from java file I am facing an exception : the table user is unknown and when I select users from the JS I always get an empty list . That's why I think that my code creates two databases with the same name but in two different locations.

Categories

Resources