Request.ServerVariables("..") returns undefined when assigned to a variable yet its value can be displayed via Response.Write("..") - asp-classic

I am trying to retrieve the user's IP address and assign it to a variable:
var ipAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR") ||
Request.ServerVariables("REMOTE_ADDR") ||
Request.ServerVariables("HTTP_HOST");
Response.Write(Request.ServerVariables("HTTP_HOST") + "<br />\n\n"); // produces "localhost"
Response.Write(Request.ServerVariables("REMOTE_ADDR") + "<br />\n\n"); // produces "::1"
Response.Write(Request.ServerVariables("HTTP_X_FORWARDED_FOR") + "<br />\n\n"); // produces "undefined"
Response.Write("ipAddress = " + typeof ipAddress + " " + ipAddress + "<br />\n\n"); // produces "ipAddress = object undefined"
I am using JScript for Classic ASP. I am unsure as to what to do at this point. Can anyone help?
Thanks

Things work in ASP with JScript a little bit different than ASP with VBScript.
Since everything is an object in JavaScript, with var ipAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR") you get an object reference instead of a string value because like most of other Request collections, the ServerVariables is a collection of IStringList objects
So, to make that short-circuit evaluation work as you expect, you need to play with the values, not the object references.
You can use the Item method that returns the string value of IStringList object if there's a value (the key exists), otherwise it returns an Empty value that evaluated as undefined in JScript.
var ipAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR").Item ||
Request.ServerVariables("REMOTE_ADDR").Item ||
Request.ServerVariables("HTTP_HOST").Item;

I solved the problem with obtaining the IP address, and the truthyness/falsyness of JScript is a complete and utter nightmare.
if (!String.prototype.isNullOrEmpty) {
String.isNullOrEmpty = function(value) {
return (typeof value === 'undefined' || value == null || value.length == undefined || value.length == 0);
};
}
var ipAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR") ||
Request.ServerVariables("REMOTE_ADDR") ||
Request.ServerVariables("HTTP_HOST");
function getIPAddress() {
try {
if (String.isNullOrEmpty(ipAddress)) {
ipAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR");
}
if (String.isNullOrEmpty(ipAddress)) {
ipAddress = Request.ServerVariables("REMOTE_ADDR");
}
if (String.isNullOrEmpty(ipAddress)) {
ipAddress = Request.ServerVariables("HTTP_HOST");
}
} catch (e) {
Response.Write("From getIPAddress(): " + e.message);
hasErrors = true;
} finally {
return ipAddress;
}
}
ipAddress = getIPAddress();
Response.Write("ipAddress = " + typeof ipAddress + " " + ipAddress + "<br />\n\n"); // produces "object localhost"

Related

DBnull issue when converting empty string to number

Hello I am trying to connect with Oracle and sending parameters as part of store procedure. Two of my parameters are coming as empty string so I need to pass null values but the datatype is set as number in the db end. When ever I run the script it gives me error that "Object cannot be cast from DBNull to other types".
Here is my code snippet remember string Case, string SRE_Pricing are coming in as "" .So I need to convert to number if there is anyting in text like "52" and if "" then assign DB null.
OracleParameter CaseParam = new OracleParameter("arg_CASE_NUMBER", OracleType.Number);
CaseParam.Direction = ParameterDirection.Input;
if (Case != null || Case!="")
{
CaseParam.Value = Convert.ToInt32((Case.Equals(string.Empty)) ? (object)DBNull.Value : Case);
}
else
{
CaseParam.Value = DBNull.Value;
}
//CaseParam.Value =Convert.ToInt32(Case);
cmd.Parameters.Add(CaseParam);
OracleParameter SRE_pricingParam = new OracleParameter("arg_SRE_PRICING_ELEMENT", OracleType.Number);
SRE_pricingParam.Direction = ParameterDirection.Input;
if (SRE_Pricing != null || SRE_Pricing != "")
{
SRE_pricingParam.Value = Convert.ToInt32((SRE_Pricing.Equals(string.Empty)) ? (object)DBNull.Value : SRE_Pricing);
}
else
{
SRE_pricingParam.Value = DBNull.Value;
}
//SRE_pricingParam.Value = Convert.ToInt32(SRE_Pricing);
cmd.Parameters.Add(SRE_pricingParam);
enter image description here
You need to use && operator instead of || in the if condition
if (SRE_Pricing != null && SRE_Pricing != "")
{
SRE_pricingParam.Value = Convert.ToInt32(SRE_Pricing);
}
else
{
SRE_pricingParam.Value = DBNull.Value;
}
Better to use Int32.TryParse()
int price;
if (Int32.TryParse(SRE_Pricing, out price))
{
SRE_pricingParam.Value = price;
}
else
{
SRE_pricingParam.Value = DBNull.Value;
}

Modifying Netsuite Object on loading

I am very new to Netsuite. I am trying to do encryption in Netsuite. It works when I add UserEvent Scripts beforeSubmit. But I wanted to decrypt the encrypted text in beforeLoad function. I am able to read the encrypted text and decrypt it successfully as well. But setting it back in the object fails and I see decrypted text in Netsuite UI. Any directions or help is appreciated.
thanks
// this function works
function beforeSubmit(type) {
var email = nlapiGetFieldValue('email');
var newEmail = 'LifeSpan.' + email;
nlapiSetFieldValue('email', newEmail );
nlapiLogExecution('DEBUG', 'Modified before Submit ' + email + ' to ' + newEmail);
}
// this printed "Modified before Submit customercare#abc.com to LifeSpan.customercare#abc.com"
// this function doesn't work; even though the correct value is printed correctly in the log
function beforeLoad(type, form, request) {
var email = nlapiGetFieldValue('email');
if(email.indexOf('SaaSSpan.') != -1) {
var newEmail = email.substring(9);
nlapiSetFieldValue('email', newEmail );
nlapiLogExecution('DEBUG', 'Modified before load ' + email + ' to ' + newEmail);
}
}
// this printed "Modified before load LifeSpan.customercare#abc.com to customercare#abc.com"...but I am still seeing LifeSpan.customercare#abc.com in the user interface
I will suggest you to try this code in a client script(PageInit and SaveRecord Events).
Works fine for me.
My Code :
function PageInit(type) {
try {
if (type == 'edit') {
var email = nlapiGetFieldValue('email');
if (email != null && email.indexOf('LifeSpan.') != -1) {
var newEmail = email.substring(9);
nlapiSetFieldValue('email', newEmail);
nlapiLogExecution('DEBUG', 'Modified before load ' + email + ' to ' + newEmail);
}
}
}
catch (err) {
nlapiLogExecution('ERROR', 'PageInit', err);
}}
function SaveRecord() {
try {
var email = nlapiGetFieldValue('email');
var newEmail = 'LifeSpan.' + email;
nlapiSetFieldValue('email', newEmail);
nlapiLogExecution('DEBUG', 'Modified before Submit ' + email + ' to ' + newEmail);
}
catch (err) {
nlapiLogExecution('ERROR', 'SaveRecord', err);
}
return true;}
nlapiSetFieldValue can be used in user event beforeLoad scripts to initialize field on new records or non-stored fields.

Regarding message send in singnal R

Hello friends I have developed many to many chat application using signal R it is working perfectly fine.But i am getting one problem in developing one thing..that is typing message to the reciever for example:- there are two user online user x and user y.now when user x is typing message..on user y window it should come.."user x is typing message.." but when i send this message to group it is getting displayed on both screen..I want to display it on reciever screen only
This is the code
public void Send(string message, string groupName, string Istypingmessage)
{
if (Clients != null)
{
string[] words = message.Split(':');
string trim = words[0].Trim();
string imagetag = "<img width=\"32px\" height=\"32px\" src=\"userimages/" + trim + ".jpg" + "\"" + "></img> ";
Clients.Group(groupName).addMessage(message, groupName, words[0], imagetag, Istypingmessage);
}
}
where here typing message=0 means normal message and 1 means "user x is typing that message"
This is the key press event
//keypress event of textbbox here..
$(".ChatText").live('keyup', function () {
if($(".ChatText").val().length > 0)
{
var messsage_typing=$("#hdnUserName").val() + " is typing...";
var strGroupName = $(this).parent().attr('groupname');
if (typeof strGroupName !== 'undefined' && strGroupName !== false)
chat.server.send($("#hdnUserName").val() + ' : ' + messsage_typing, $(this).parent().attr('groupname'),"1");
}
});
//end of keypress
and this is add message code
chat.client.addMessage = function (message, groupName,recievername,imagetag,Istypingmessage) {
if ($('div[groupname=' + groupName + ']').length == 0) {
var chatWindow = $("#divChatWindow").clone(true);
$(chatWindow).css('display', 'block');
$(chatWindow).attr('groupname', groupName);
$("#chatContainer").append(chatWindow);
//buggy code do not delete..
//remove all previous li
$('div[groupname=' + groupName + ']').find('ul li').remove();
//replace header tag with new name
$('div[groupname=' + groupName + ']').find('a').html(recievername);
$("#chatContainer").draggable();
$("#chatContainer").css('cursor','move');
}
if(Istypingmessage=="0")
{
var stringParts = message.split(":");
var username = stringParts[0];
var message = stringParts[1];
//this code is for continous message sent
var lastliusername=$('div[groupname=' + groupName + '] ul li').eq(-2).find('div.designnone').html();
if(lastliusername!=null && $.trim(username)==$.trim(lastliusername))
{
$('div[groupname=' + groupName + '] ul li').eq(-2).find('div.designmessage').append("<span class='spansameuser'>" + message + "</span>");
//end of this code is for continous message sent
}
else
{
$('div[groupname=' + groupName + ']').find('ul').append("<li><div class='design'>" + imagetag + "</div><div class='designnone'> " + username + "</div><div class='designmessage'> " + message + " </div></li><li class='cleardivbetweenmsg'></li>");
}
}
else
{
$('div[groupname=' + groupName + ']').find('ul').append("<li><span>Hellos</span></li>");
}
$("#messages").scrollTop($("#messages")[0].scrollHeight);
};
How can i display typing message to my reciever instead of on both screens..please help me out..In short i want to send my message only to reciever of group not to sender of the group
Thanks
If you want to send a message to all clients in a group except for the sender, you can use Clients.OthersInGroup:
Clients.OthersInGroup(groupName).addMessage(/*...*/);
This is the equivalent to passing the sender's connection ID as a second parameter to Clients.Group making it an excluded connection ID.
Clients.Group(groupName, Context.ConnectionId).addMessage(/*...*/);
The method signature for Clients.Group is: public dynamic Group(string groupName, params string[] excludeConnectionIds).

How can we return amount in same website by using Paypal Payflow pro account

How can we return deduct amount in same website by using Paypal Payflow pro account?
I am using Paypal Payflow pro account for one of my application. It does transaction but doesn't return deduct amount detail. I am using first time Paypal Payflow account. So if anybody have done such kind of work before kindly share with me.
Hi i have done this, Anybody who needs solution see below:
protected NameValueCollection httpRequestVariables()
{
var post = Request.Form; // $_POST
var get = Request.QueryString; // $_GET
return Merge(post, get);
}
if (!IsPostBack)
{
string output = "";
if (httpRequestVariables()["RESULT"] != null)
{
HttpContext.Current.Session["payflowresponse"] = httpRequestVariables();
output += "<script type=\"text/javascript\">window.top.location.href = \"" + url + "\";</script>";
BodyContentDiv.InnerHtml = output;
return;
}
var payflowresponse = HttpContext.Current.Session["payflowresponse"] as NameValueCollection;
if (payflowresponse != null)
{
HttpContext.Current.Session["payflowresponse"] = null;
bool success = payflowresponse["RESULT"] == "0";
if (success)
{
output += "<span style='font-family:sans-serif;font-weight:bold;'>Transaction approved! Thank you for your order.</span>";
}
else
{
output += "<span style='font-family:sans-serif;'>Transaction failed! Please try again with another payment method.</span>";
}
output += "<p>(server response follows)</p>\n";
output += print_r(payflowresponse);
AdvancedDemoContent.InnerHtml = output;
public string print_r(Object obj)
{
string output = "<pre>\n";
if (obj is NameValueCollection)
{
NameValueCollection nvc = obj as NameValueCollection;
output += "RESULT" + "=" + nvc["RESULT"] + "\n";
output += "PNREF" + "=" + nvc["PNREF"] + "\n";
output += "RESPMSG" + "=" + nvc["RESPMSG"] + "\n";
output += "AUTHCODE" + "=" + nvc["AUTHCODE"] + "\n";
output += "CVV2MATCH" + "=" + nvc["CVV2MATCH"] + "\n";
output += "AMT" + "=" + nvc["AMT"] + "\n";
}
else
{
output += "UNKNOWN TYPE";
}
output += "</pre>";
return output;
}
go to your PayPal merchant account-->profile-->Selling Preferences-->Website Payment Preferences-->Auto Return for Website Payments turn radio button to on,default it should off.after transaction make sure the value are stored in your database.i hope this help you

Auto save of form

I have form in ASP.NET 3.5. Where lot of data elements and where i have Save and Submit buttions. I need to auto save my form every 2 min. What is the best way to implement this kind of functionility in ASP.NET.
I struggled for awhile with the same problem. The trouble was that I didn't want to save into the usual database tables because that would've required validation (validating integers, currencies, dates, etc). And I didn't want to nag the user about that when they may be trying to leave.
What I finally came up with was a table called AjaxSavedData and making Ajax calls to populate it. AjaxSavedData is a permanent table in the database, but the data it contains tends to be temporary. In other words, it'll store the user's data temporarily until they actually complete the page and move onto the next one.
The table is composed of just a few columns:
AjaxSavedDataID - int:
Primary key.
UserID - int:
Identify the user (easy enough).
PageName - varchar(100):
Necessary if you're working with multiple pages.
ControlID - varchar(100):
I call this a ControlID, but it's really just the ClientID property that .NET exposes for all of the WebControls. So if for example txtEmail was inside a user control named Contact then the ClientID would be Contact_txtEmail.
Value - varchar(MAX):
The value the user entered for a given field or control.
DateChanged - datetime:
The date the value was added or modified.
Along with some custom controls, this system makes it easy for all of this to "just work." On our site, the ClientID of each textbox, dropdownlist, radiobuttonlist, etc is guaranteed to be unique and consistent for a given page. So I was able to write all of this so that the retrieval of the saved data works automatically. In other words, I don't have to wire-up this functionality every time I add some fields to a form.
This auto-saving functionality will be making its way into a very dynamic online business insurance application at techinsurance.com to make it a little more user friendly.
In case you're interested, here's the Javascript that allows auto-saving:
function getNewHTTPObject() {
var xmlhttp;
/** Special IE only code */
/*#cc_on
#if (#_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E) {
xmlhttp = false;
}
}
#else
xmlhttp = false;
#end
#*/
/** Every other browser on the planet */
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
}
catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
function AjaxSend(url, myfunction) {
var xmlHttp = getNewHTTPObject();
url = url + "&_did=" + Date();
xmlHttp.open("GET", url, true);
var requestTimer = setTimeout(function() { xmlHttp.abort(); }, 2000);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2005 00:00:00 GMT");
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState != 4)
return;
var result = xmlHttp.responseText;
myfunction(result);
};
xmlHttp.send(null);
}
// Autosave functions
var SaveQueue = []; // contains id's to the DOM object where the value can be found
var SaveQueueID = []; // contains id's for binding references (not always the same)
function ArrayContains(arr, value) {
for (i = 0; i < arr.length; i++) {
if (arr[i] == value)
return true;
}
return false;
}
function GetShortTime() {
var a_p = "";
var d = new Date();
var curr_hour = d.getHours();
if (curr_hour < 12)
a_p = "AM";
else
a_p = "PM";
if (curr_hour == 0)
curr_hour = 12;
else if (curr_hour > 12)
curr_hour = curr_hour - 12;
var curr_min = d.getMinutes();
curr_min = curr_min + "";
if (curr_min.length == 1)
curr_min = "0" + curr_min;
return curr_hour + ":" + curr_min + " " + a_p;
}
function Saved(result) {
if (result == "OK") {
document.getElementById("divAutoSaved").innerHTML = "Application auto-saved at " + GetShortTime();
document.getElementById("divAutoSaved").style.display = "";
}
else {
document.getElementById("divAutoSaved").innerHTML = result;
document.getElementById("divAutoSaved").style.display = "";
}
}
function getQueryString(name, defaultValue) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == name) {
return pair[1];
}
}
return defaultValue;
}
function urlencode(str) {
return escape(str).replace(/\+/g, '%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/#/g, '%40');
}
function AutoSave() {
if (SaveQueue.length > 0) {
var url = "/AjaxAutoSave.aspx?step=" + getQueryString("step", "ContactInformation");
for (i = 0; i < SaveQueue.length; i++) {
switch (document.getElementById(SaveQueue[i]).type) {
case "radio":
if (document.getElementById(SaveQueue[i]).checked)
url += "&" + SaveQueueID[i] + "=" + urlencode(document.getElementById(SaveQueue[i]).value);
break;
case "checkbox":
if (document.getElementById(SaveQueue[i]).checked)
url += "&" + SaveQueueID[i] + "=" + urlencode(document.getElementById(SaveQueue[i]).value);
default:
url += "&" + SaveQueueID[i] + "=" + urlencode(document.getElementById(SaveQueue[i]).value);
}
}
SaveQueue = [];
SaveQueueID = [];
AjaxSend(url, Saved);
}
}
function AddToQueue(elem, id) {
if (id == null || id.length == 0)
id = elem.id;
if (!ArrayContains(SaveQueueID, id)) {
SaveQueue[SaveQueue.length] = elem.id;
SaveQueueID[SaveQueueID.length] = id;
}
}
Add this to your page to make this work:
window.setInterval("AutoSave()", 5000);
And to apply this to a Textbox, DropdownList, Listbox, or Checkbox you just need to add this attribute:
onchange="AddToQueue(this)"
...or this for a RadioButtonList or CheckBoxList:
onchange="AddToQueue(this, '" + this.ClientID + "')"
I'm sure this Javascript could be simplified quite a bit if you used JQuery so you might want to consider that. But in any case, AJAX is the thing to use. It's what Google uses to auto-save your email message in gmail, and the same thing is in blogger when you're writing a new post. So I took that concept and applied it to a huge ASP.NET application with hundreds of form elements and it all works beautifully.
Use the Timer class and the Tick method.

Resources