How to set user status "0" when automatically logout inactive user? - c#

I'm using javascript in aspx page to log-out inactive user. But also i need to change user status "0" when logged-out automatically. How can i send the value user status "0" when inactive user will logged-out automatically?
public void ValidateUser_LOGSTS_Update(object sender, EventArgs e)
{
int userId = 0;
string Cur_user = Session["Userid"].ToString();
String constr = ConfigurationManager.ConnectionStrings["abcd"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("sp_tbl_LogCheck_update"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#userID", Cur_user);
cmd.Parameters.Add("#msg", SqlDbType.Int, 20).Direction = ParameterDirection.Output;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
// read output value from #NewId
string msg_sts = Convert.ToString(cmd.Parameters["#msg"].Value);
con.Close();
if (msg_sts == "0")
{
Session.Clear();
Session.Abandon();
//Response.Redirect(FormsAuthentication.LoginUrl);
FormsAuthentication.RedirectToLoginPage();
}
}
}
}
<script type="text/javascript">
var t;
window.onload=resetTimer;
document.onkeypress=resetTimer;
function logout()
{
alert("You are now logged out.")
location.href = 'Login.aspx'
}
function resetTimer()
{
clearTimeout(t);
t=setTimeout(logout,60000) //logs out in 10 min
}
</script>

Well you can send an ajax request to your server while logging out the user. For this you have to send the id parameter regard to current user u want to logout , On success response you can perform any task .
var t;
window.onload=resetTimer;
document.onkeypress=resetTimer;
function logout()
{
alert("You are now logged out.");
location.href = 'Login.aspx';
$.ajax({
url:"",
type:"post",
data:`id=${id}`,
success:function(response){
}
})
}
function resetTimer()
{
clearTimeout(t);
t=setTimeout(logout,60000) //logs out in 10 min
}

#Faisal please add code to original question for easier reading. Please use this syntax for posting. also make sure to use url correctly. Also check your console for error messages and post it here to make progress in case of errors.
$.ajax({
type: "post",
url: "url",
data: {},
dataType: "json",
success: function (response) {
console.log('yey');
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
}
});

Related

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:

response.data/ response.d displayed "undefined"

I am trying to retrieve a list from C# code to an aspx page using ajax.
this is the ajax function:
$.ajax({
type: 'POST',
url: 'admin.aspx/getGenderCount',
contentType: 'application/json',
dataType: 'json',
data: '{}',
success: successRetireveGenders,
failure: function (response) {
alert("Error");
}
});
function successRetireveGenders(dataValues) {
alert(dataValues); // displayed [object object]
// but i actually have 2 rows result
alert(dataValues.data); //alert with "undefined"
alert(dataValues.d); //alert with "undefined"
// i try to put loop from 0 to response.d.length
for (var i = 0; i < dataValues.length; i++) {
alert(dataValues.length); //alert with "undefined"
alert(dataValues.d.length); //alert with "undefined"
}
I am always seeing an alert with message:
undefined
c# code:
[System.Web.Services.WebMethod]
public static List<ParticipantGender> getGenderCount()
{
List<ParticipantGender> ListOfParticipantGender = new List<ParticipantGender>();
var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd = new SqlCommand("getGenderCount", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
while (rdr.Read())
{
ListOfParticipantGender.Add(
new ParticipantGender
{
cnt = rdr.GetValue(0).ToString(),
gender = rdr.GetValue(1).ToString(),
});
}
return ListOfParticipantGender;
}
ParticipantGender class:
public class ParticipantGender
{
public string gender;
public string cnt;
public ParticipantGender()
{
//
// TODO: Add constructor logic here
//
}
public ParticipantGender(string gender, string cnt)
{
this.gender = gender;
this.cnt = cnt;
}
}
EDIT:
$.ajax({
type: 'POST',
url: 'admin.aspx/getGenderCount',
contentType: 'application/json',
dataType: 'json',
data: '{}',
success: callback,
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
var callback = function (data, textStatus, xhr) {
alert("hi"); // not alerted
alert(data + "\t" + textStatus); // not alerted
};
EDIT:
i got in the console:
jsapi:23 A parser-blocking, cross site (i.e. different eTLD+1) script,
https://www.google.com/uds/?file=visualization&v=1&packages=corechart,
is invoked via document.write. The network request for this script MAY
be blocked by the browser in this or a future page load due to poor
network connectivity. If blocked in this page load, it will be
confirmed in a subsequent console message. See
https://www.chromestatus.com/feature/5718547946799104 for more
details. google.loader.f # jsapi:23 jsapi:23 A parser-blocking, cross
site (i.e. different eTLD+1) script,
https://www.google.com/uds/api/visualization/1.0/40ff64b1d9d6b3213524485974f36cc0/format+en,default+en,ui+en,corechart+en.I.js,
is invoked via document.write. The network request for this script MAY
be blocked by the browser in this or a future page load due to poor
network connectivity. If blocked in this page load, it will be
confirmed in a subsequent console message. See
https://www.chromestatus.com/feature/5718547946799104 for more
details. google.loader.f # jsapi:23 fontawesome-webfont.woff2:1 Failed
to load resource: the server responded with a status of 404 (Not
Found)
You should serialize the List<ParticipantGender> to JSON. You can install package Newtonsoft.Json which provides a lot of features.
For your case
using System.Configuration;
using Newtonsoft.Json;
[System.Web.Services.WebMethod]
public static string getGenderCount()
{
var connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
var ListOfParticipantGender = new List<ParticipantGender>();
using(var conn = new SqlConnection(connStr))
{
conn.Open();
using(var cmd = new SqlCommand("getGenderCount", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
using(var rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
while (rdr.Read()) {
ListOfParticipantGender.Add(
new ParticipantGender
{
cnt = rdr.GetValue(0).ToString(),
gender = rdr.GetValue(1).ToString(),
}
);
}
}
}
}
}
var json = JsonConvert.SerializeObject(ListOfParticipantGender);
return json;
}
Define the Callback function with necessary parameters and assign it to the $.ajax success event.
Also, there is no such event failure for $.ajax instead use error
var callback = function(data, textStatus, xhr)
{
alert(data + "\t" + textStatus);
};
Assign this callback to the success event
$.ajax({
type: 'POST',
url: 'admin.aspx/getGenderCount',
contentType: 'application/json',
dataType: 'json',
data: {},
success: callback,
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});

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.

Javascript Database Validation with Ajax

Thanks to my previously asked question, I have successfully shown a new Textbox after a users enters text in a previous TextBox.
Now, I would like to only show the new TextBox after the text in the original TextBox has been validated.
The validation will make sure the data in the original TextBox is not in the database.
The text boxes are in an Ajax Update Panel. Unfortunatly, I can not use AutoPostBack events, because it effectively resets the JavaScript, even when using function pageLoad()
.
I would like to use the JavaScript to validate against the database, and so far used this code:
JavaScript on Text.aspx
<script type="text/javascript">
function pageLoad() {
$('#<%: txtRegisterEmail.ClientID %>').on('blur', function () {
$.ajax({
type: "POST",
url: "Test.aspx/CheckEmail",
data: "{Email: '" + ('#<%: txtRegisterEmail.ClientID %>').value + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response);
}
});
});
}
function OnSuccess(response) {
$('#<%: txtRegisterEmailConfirm.ClientID %>').slideDown();
}
//'input[name$="txtRegisterEmailConfirm"]'
</script>
Test.aspx.cs
[System.Web.Services.WebMethod]
public static bool CheckEmail(string Email)
{
int counter = 0;
const string strSql = "SELECT memberEmail FROM vwGetMemberDetails";
using (SqlCommand sqlComm = new SqlCommand(strSql, DataConn.Connect()) { CommandType = CommandType.Text })
{
using (SqlDataReader rdr = sqlComm.ExecuteReader())
{
while (rdr.Read())
{
counter = counter + 1;
}
}
}
return counter > 0;
}
The only thing this code does is show the text box (seemingly without validation).
How can I make this work?

Categories