Session Some Time reurn Null And some time reurn value - javascript

I create session when user Login and use session to check access page, when i check session some time rerun null if i refresh page or navigate to other page the session is not null , it's not about specific page ,it's about method some time return null some time get session value , my method in web service and i call it use javascript
[WebMethod(EnableSession = true)]
public object CheckIfLoggedin()
{
try
{
return new { Result = resultEnum.ok, Records = GetUserID() };
}
catch
{
return new { Result = resultEnum.error };
}
}
private Guid? GetUserID()
{
if (Context.Session["User"] != null)
{
string userid = Context.Session["User"].ToString();
if (userid != "")
return new Guid(userid);
else
return null;
}
else
return null;
}
function CheckIfLoggedin() {
var status = 0;
var ItemCount;
$.ajax({
type: "POST",
url: "../../../../_layouts/15/TripPlannerFrontend/TripPlannerSrv.asmx/CheckIfLoggedin",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (res) {
if (res.d.Result === 2) {
var userid = res.d.Records;
if (userid == null) {
//
}
else {
//window.location = "TripPlanner.aspx";
var returnurl = GetQueryString("returnurl");
if (returnurl != null && returnurl !== "")
window.location = returnurl;
else
window.location = "TripPlanner.aspx";
}
}
else
console.log("try again");
},
error: function (response) {
console.log("try again");
}
});
};

The problem is session affinity. If you have multiple Web front-ends and a load-balancer dispatching requests to one of these SP servers: a first request may be routed to server A, then the session is created, and when a second request is issued by the client, it may be redirected to server B, where the session does not exist.
In such situations, the best approach is to configure your load-balancer for "session affinity": this means that once a given client is assigned one of the Web front-ends, all subsequent requests will be redirected to the same server. Please Ask the Administrator of the load-balancer if there is Session affinity configuration if not ask him if this can be configured at his level (it depends on the technology used for load-balancing).

Related

redirect in c# method is not working

enter image description hereI am trying to implement Google sign in into my web forms page because we use G suite for business. basically I am using javascript to get the token then using ajax to post to the google api then I am looking at the HD claim to make sure they are apart of our domain and thne posting to the code behind the email and doing a lookup to get a user ID then setting the form cookie and trying to redirect to our defalut page. So we have a mvc app that I done this exact thing with and it works perfectly I just routed them to the controller. For some reason it just seems like I am not getting anything from my code behind code.
here is my javascript.
<script>
function onSignIn(googleUser) {
debugger;
const profile = googleUser.getBasicProfile();
let boolRedirectUrl = false;
const id_token = googleUser.getAuthResponse().id_token;
const pathname = window.location.pathname;
const url = window.location.href;
let redirectPath = "";
if (window.location.href.indexOf("ReturnUrl") > -1) {
boolRedirectUrl = true;
redirectPath = readQueryString("ReturnUrl");
}
const googleUrl = "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=" + id_token;
$.ajax({
url: googleUrl,
dataType: 'json',
data: '{}',
contentType: 'application/json',
success: (data, status, xhr) => {
const domain = data.hd;
const email = data.email;
if (domain === "kimbelmechanical.com") {
$.ajax({
url: "Login.aspx/GoogleLogin",
type: "POST",
data: { 'email': email },
success: (data, status, xhr) => {
//window.location.href = "Default.aspx"
},
error: (xhr, status, error) => {
console.log("I stopeed on the call to controller " + status);
}
});
}
},
error: (xhr, status, error) => {
console.log(status);
}
});
};
function readQueryString(key) {
key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&");
var match = location.search.match(new RegExp("[?&]" + key + "=([^&]+)(&|$)"));
return match && decodeURIComponent(match[1].replace(/\+/g, " "));
}
</script>
this is my c# code behind.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void GoogleLogin(string email)
{
string userID = "";
using (var context = new KPDataContext(KP.Common.KPConnectionString))
{
var user = context.Employees.Where(p => p.Email == email);
foreach (var e in user)
{
userID = e.Username;
}
}
if (userID != "")
{
FormsAuthentication.SetAuthCookie(userID, false);
Response.Redirect("~/Default.aspx", true);
}
}
if I redirect from the success to my default page it loads it default.aspx found but for some reason it does login.aspx?ReturnUrl=?default.aspx but stays on the login page so I am in a endless loop of loading the login page over and over.
Is it MVC? If so you can use RouteData along with creating a new instance of a controller. That controller can then execute a new web request with the new path like so:
var routeData = new RouteData();
routeData.Values.Add("message", errorModel.message);
routeData.Values.Add("action", "Index");
routeData.Values.Add("controller", "ErrorPage");
IController ctrl = new ErrorController();
ctrl.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
Response.End();

Ajax call on $.ajax().complete

I have a problem with jQuery ajax function. I working with API that provides users and RBAC managment. By design this is separated functions, so when i create a user and assign a role for it i should call two requests - first i send 'create user' and it's return a {"success":"true", "id":"[id nuber]"} then i send 'assign role' with params like "{"item":"RoleName", "user_id":"[id from previous request]"}".
There is object "api" which have some methods for work with API. It is a simple wrapper which knocking on www.myurl.api/ and returns json. Because of it may take a long time api object methods takes a handlers that will be run on success and fail. If api now running a request then api.ready == false, otherwise api.aready == true. Result of last request stored in api.data as object.
Problem is that result not saved in api.data in case when two API request cascaded, like:
api.send(params, //params is json for user creation
function(){ //handler on this request result
... //creating another parms for assignment from api.data
api.send(params2, function(){//handler that works if api coorectly creates a new user
... //here i try send a request with params and it fails
})
}
);
code of api.send method:
send: function (entity, request, params, method, handler){
if (!method)
method='POST';
if (request.toLowerCase()=='get')
request = '';
if (request)
request += '-';
api.data = null;
params.apiKey = api.key;
api.ready = false;
api.handler = handler;
$.ajax({
url: this.url+request+ entity,
method: 'GET',
data: params
}).complete(function(msg) {
api.data = JSON.parse(msg.responseText);
if (api.data[0] && api.data[0].meta)
api.data.forEach(function (element, index, array){
element.meta = JSON.parse(element.meta)
});
api.ready = true;
api.handler.call();
});
}
and this is function that calls to create new user
function createUser(){
validateCreateForm();
if (!createValidated )
return;
var values = {
"username": $('#inputUsername').val(),
"password": $('#inputPassword').val(),
"comment": "Added by "+adderUsername
};
api.send('users','add', values, 'POST', function () {
if (api.data.success="true"){
//===========all in this if works ONLY if api works succesfully
//===========and api.data.id is exist and correct
message("success", "Was created username " + values.username);
$('#inputUsername').val('');
$('#inputPassword').val('');
//==========Problem is here
id = api.data.id; //in this var stores id
console.log('api.data.id is ' + id);//undefined, should be some int.
//if write something like id=42 rights will be correcttly assigned for user with id 42
//================================================================
if (!$('#inputRole').val())
return;
api.send('assignments',
'add',
{
"user_id": id,
"item_name": $('#inputRole').val()
},
'POST',
function () {
if (api.data.success="true"){
message("success", "Account was created and permissions granted");
}
else {
message("success", "Inner error. Please, try again later.");
}
}
);
}
else {
message("danger", "Inner error. Please, try again later.");
}
);
}

Reading claims from another application using jquery

I have a static method in static class in MVC application that returns User Claims, when I access directly the url of this application,I am getting those values but when I access application url from another application using Javascript,it is not returning anything.I am not getting any error.It is returning empty result.I am also not getting CORS issue.i suspect it is something related to authentication & passing user credentials,both site is under same ADFS configuration
public static UserDetails GetUserDetails()
{
var userdetails = new UserDetails();
var objClaims = ((ClaimsIdentity)Thread.CurrentPrincipal.Identity).Claims;
foreach(var c in objClaims)
{
else if (c.Type == ConstantsHelper.emailAddress)
{
userdetails.Email = c.Value;
}
else if (c.Type == ConstantsHelper.userName)
{
userdetails.UserName = c.Value;
}
else if (c.Type == ConstantsHelper.shortName)
{
userdetails.ShortName = c.Value;
}
}
return userdetails;
}
Code to access it from another application.
function GetLoggedInUsermethod() {
var url = GetLoggedInUser;
$.ajax({
type: "GET",
url: url,
crossDomain: true,
success: function (json) {
},
error: function (e) {
}
});
}
If the calling application is hosted in different domain (different ports will qualify for different domains), then you may need to add the Access-Control-Allow-Origin header to the response with the value set to the calling application's domain for the call to succeed.
More details here.

Ajax Error 504 - SQL Stored Procedure saving and returning record

I'm trying to run a SQL Stored Procedure called UpdateKey that saves a record called Key into the Kiosks table of my database (called MyDB) based on record ID, and then returns it, as below:
USE [MyDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[UpdateKey]
#id uniqueidentifier,
#key nvarchar(8)
AS
BEGIN
SET NOCOUNT ON;
UPDATE [dbo].[Kiosks]
SET session = NEWID(), [key] = #key
WHERE id = #id;
SELECT #key AS kioskKey
END
I'm trying to call it using Ajax and a service file as below:
Javascript:
function updateKeyOnly(index) {
$.ajax({
type: "POST",
url: "../Services/Common.svc/UpdateKey/" + kioskList[index].id,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.success == true) {
txtNewKeyDisplay.val(response.keyItem.key); //display new key to user
$('#tblKiosks').dataTable().fnClearTable();
$('#tblKiosks').dataTable().fnDestroy();
loadData();
$(this).dialog("close");
}
else {
alert("updateKeyOnly error" + JSON.stringify(response));
}
}
});
}
Service (in C#):
OperationResponse ICommon.updateKey(string id)
{
string newKey = generateKey();
string result;
Guid newID;
if (Guid.TryParse(id, out newID))
{
try
{
result = myDB.UpdateKey(newID, newKey).FirstOrDefault();
//return new OperationResponse(request.key);
}
catch (Exception ex)
{
if (isDebug() == true)
{
return new OperationResponse(ex.Message);
}
else
{
return new OperationResponse("Error: Database inaccessible.");
}
}
if (result != null)
{
//return new OperationResponse();
resetKeyResponse response = new resetKeyResponse();
response.keyItem = new resetKeyItem();
response.keyItem.key = result.ToString();
return response;
}
else
{
return new OperationResponse("Error: Key cannot be updated or retrieved.");
}
}
else
{
return new OperationResponse("Error: Invalid ID.");
}
}
From the ICommon.cs:
//To Update Kiosk Key
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/UpdateKey/{id}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
OperationResponse updateKey(string id);
Currently my problem is that when I running the Ajax, it gives an Error 504 - Receive Failure according to Fiddler, and on my page itself clicking the button that activates the Ajax causes nothing to apparently happen. Despite that however checking the Kiosks table after that shows that the new key is saved into it after all, it's just that the stored proc can't return it to my webpage. Any help is appreciated.
I'm an idiot - I changed all instances of OperationResponse in updateKey to resetKeyResponse after noticing how inconsistent it was, and then it ran.

How can I show a message from server side?

I am not a java developer, but my company purchase a product to handle their accounting stuff based on java. Now I am facing a problem because they want to prevent repeated invoices on the system and the software allows the user to do it. I called support and they suggested me to create a suppressed field on the client side, copy on that field the message I want to show and read that field when the user tab to the next field. those are a lot of steps and totally inefficient. Below is my code based on what they suggested. It currently showed me the invoice exist message twice.
server side
CSServer.log (Step)
if ((CSEvent.getTarget().getName() == "InvoiceNumber") && (CSEvent.getAction() == "Tabout" ) && (Step == 0))
{
if (!cnn)
{
CSServer.log ("GPCONNECT Lookup::CSForm_OnValidateLookup Connection to the database failed");
}
else
{
Sql = "SELECT COUNT (*) as Result FROM [DYNAMICS].[dbo].[AP_Invoice_Table] WHERE [VendorID] = '" + CSForm.getField("VendorID").getValue() + "' and [DocumentNumber] = '" + CSForm.getField("InvoiceNumber").getValue()+"'";
resultInvSet = cnn.executeSQL(Sql);
var x =null;
x = resultInvSet.getValue("Result");
}
if (x > 0)
{
CSForm.getField("msg").setValue("Invoice number already exist, please check your entry!");
return false;
}
else
{
CSForm.getField("msg").setValue("");
}
}
client side
function InvoiceAmount_OnFocus()
{
var m =CSForm.getField('msg').getValue();
if (m != "")
{
$("#InvoiceNumber").focus();
CSClient.alert(m);
CSForm.getField("InvoiceNumber").setFillColor("FF0000");
}
else
{
CSForm.getField("InvoiceNumber").setFillColor("FFFFFF");
}
return true;
}
Could someone please showed me the right way to handle this?
Update:
Client and server use SOAP and HTTP call to communicate.
Create a webmethod that you call via AJAX and pop the javascript alert based on the result of that function.
example (in your .aspx page):
function doSomething(id) {
$.ajax({
type: "POST",
url: "Do_Something.aspx/DoSomething?id=" + id,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response);
}
});
In Do_Something.aspx.cs:
[WebMethod]
public static string DoSomething(string id)
{
var docs = SqlHelper.SelectAllByInvoiceId(id);
if (docs.Count > 0)
{
return "exists";
}
return "does not exist";
}
Step 1: Create AJAX function to talk to server side function.
Step 2: Return message from server side function and handle that in AJAX function (success or done).
Step 3: Alert message if ajax function catches any result.
For ajax implementation you can refer: http://www.w3schools.com/jquery/ajax_ajax.asp
Or
http://api.jquery.com/jquery.ajax/

Categories