I have the following script in an page called ajax.aspx page:
<script type="text/javascript">
$(document).ready(function () {
var nameFoundMessage = $('#nameFoundMessage');
var nameInput = $('#name');
nameFoundMessage.hide();
nameInput.blur(function () {
if ($(this).val()) {
$.getJSON('Services/ArtistFound.aspx?' + escape($(this).val()), function (results) {
if (results.available) {
if (nameFoundMessage.is(':visible')) {
nameFoundMessage.html('The name was found');
}
}
else {
nameFoundMessage.show();
nameFoundMessage.html('The name was not found');
}
});
}
});
});
</script>
The page has an input field with an id of "name" and when I blur off of that it goes into a service folder which has another aspx page ArtistFound.aspx and in that Page load, I have the following:
Response.ContentType = "application/json";
string name = Request.QueryString.ToString();
string output = string.Empty;
name = db.Names.Single(x => x.Name== name).Name;
if(name == null)
{
output = "{available:false}";
}
else
{
output = "{available:true}";
}
Response.Write(output);
}
When I run the page and blur off the input, it says the following:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
I have tried ../Services/ArtistFound.aspx... and /Services/ArtistFound.aspx..., but it still gives me the same error.
You want:
name = db.Names.FirstOrDefault(x => x.Name== name);
if(name != null && name.Name != null)
{
output = "{available:true}";
}
else
{
output = "{available:false}";
}
This will return null if it is not found rather than throwing an exception like Single() does.
I would also recommend you use an ASHX handler rather than an ASPX page to do this call.
To do this you just add a 'Generic Handler' file in visual studio then you can put replace the ProcessRequest method with this:
public void ProcessRequest(HttpContext context)
{
string name = context.Request.QueryString.ToString();
string output = string.Empty;
name = db.Names.FirstOrDefault(x => x.Name == name);
if (name != null && name.Name != null)
{
output = "{available:true}";
}
else
{
output = "{available:false}";
}
context.Response.ContentType = "application/json";
context.Response.Write(output);
}
Related
Trying to jQuerify CEF browser in winform solution but the script is not executing, tried many methods but still it didn't work.
I am executing the script in the LoadingStateChanged .. already installed cefsharp from Nuget packages solution !
if there is another option better than CEFsharp please recommend !
string script = #"(function () {
// more or less stolen form jquery core and adapted by paul irish
function getScript(url, success) {
var script = document.createElement('script');
script.src = url;
var head = document.getElementsByTagName('head')[0],
done = false;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function () {
if (!done && (!this.readyState
|| this.readyState == 'loaded'
|| this.readyState == 'complete')) {
done = true;
success();
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
};
head.appendChild(script);
}
getScript('http://code.jquery.com/jquery-latest.min.js', function () {
if (typeof jQuery == 'undefined') {
console.log('Sorry, but jQuery wasn\'t able to load');
} else {
console.log('This page is now jQuerified with v' + $.fn.jquery);
$(document).ready(function () {
alert(1);
//here you can write your jquery code
});
}
});
})();";
if (this.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate {
LoginchromeBrowser.ExecuteScriptAsync(script);
LoginchromeBrowser.EvaluateScriptAsync(script).ContinueWith(x =>
{
var response = x.Result;
if (response.Success && response.Result != null)
{
var startDate = response.Result;
MessageBox.Show(response.Result.ToString());
//startDate is the value of a HTML element.
}
});
});
}
else
{
LoginchromeBrowser.EvaluateScriptAsync(script).ContinueWith(x =>
{
var response = x.Result;
if (response.Success && response.Result != null)
{
var startDate = response.Result;
MessageBox.Show(response.Result.ToString());
//startDate is the value of a HTML element.
}
});
}
I'm using javascript to set the value of a cookie when I open the debugger panel so that if the user has already opened it, it will automatically open when they reload the page.
Here is the javascript:
jQuery(document).ready(function () {
DebuggingPanel.init(jQuery);
DebuggingPanel.GetPanelState();
});
DebuggingPanel.GetPanelState = function () {
jQuery.ajax({
url: "/sitecore modules/DebuggingPanel/DebuggingPanel.asmx/GetPanelState",
type: 'POST',
success: function(data) {
if (data.open === true) {
DebuggingPanel.TogglePanel();
}
}
});
}
DebuggingPanel.TogglePanel = function (changeState) {
var tinyDiv = $('.debuggingPanel.tinyDiv');
if (tinyDiv.text() == '+') {
tinyDiv.text('-');
DebuggingPanel.GetInformation();
DebuggingPanel.panel.slideDown();
interval = setInterval(DebuggingPanel.GetInformation, 5000);
if (changeState) {
DebuggingPanel.SetPanelState("open");
}
} else {
tinyDiv.text('+');
DebuggingPanel.panel.slideUp();
clearInterval(interval);
if (changeState) {
DebuggingPanel.SetPanelState("closed");
}
}
};
tinyDiv.click(function () {
DebuggingPanel.TogglePanel(true);
});
And here are the methods related to the cookie:
public void SetPanelState(string state)
{
var panelCookie = HttpContext.Current.Response.Cookies["PanelState"];
if (panelCookie == null)
{
panelCookie = new HttpCookie("PanelState") {Value = state};
HttpContext.Current.Response.Cookies.Add(panelCookie);
}
else
{
HttpContext.Current.Response.Cookies["PanelState"].Value = state;
}
}
[ScriptMethod(ResponseFormat = ResponseFormat.Json), WebMethod(EnableSession = true)]
public void GetPanelState()
{
var panelCookie = HttpContext.Current.Response.Cookies["PanelState"];
var data = new PanelState(){open = false};
if (panelCookie == null || panelCookie.Value == null)
{
data.open = false;
}
else if (panelCookie.Value == "open")
{
data.open = true;
}
WriteOut(data);
}
In debugging the cookie looks as though it is getting the value correctly, but the next time I go into GetPanelState(), panelCookie.Value is always "" (not "open" as it should be, or "closed", which would indicate it was set by the toggle).
This happens when I reload the page, and it also happens when I call GetPanelState() at the end of SetPanelState(); panelCookie.Value = "open" in SetPanelState() but then equals "" in GetPanelState()
When you are reading from the Cookie, you need to use the Request instead of the response. So your code will be as follows:
public void SetPanelState(string state)
{
var panelCookie = HttpContext.Current.Response.Cookies["PanelState"];
if (panelCookie == null)
{
panelCookie = new HttpCookie("PanelState") {Value = state};
HttpContext.Current.Response.Cookies.Add(panelCookie);
}
else
{
HttpContext.Current.Response.Cookies["PanelState"].Value = state;
}
}
[ScriptMethod(ResponseFormat = ResponseFormat.Json), WebMethod(EnableSession = true)]
public void GetPanelState()
{
//It is here that you are reading the cookie.
var panelCookie = HttpContext.Current.Request.Cookies["PanelState"];
var data = new PanelState(){open = false};
if (panelCookie == null || panelCookie.Value == null)
{
data.open = false;
}
else if (panelCookie.Value == "open")
{
data.open = true;
}
WriteOut(data);
}
Thanks
I am totally new in using FB API and i am trying to post to facebook wall from my Asp.net application.
I have got the Appkey and secret key from FB and just trying to follow
the code to post in FB wall.
LINK : http://kennetham.com/2010/07/21/facebook-api-asp-net/
The problem i am facing now is, in my ConnectAuthentication Class, HttpContext.Current.Request.Cookies[fullCookie] is always NULL. Due to that, when i check for the FB connectivity by "if (ConnectAuthentication.isConnected())" in my pageload, it always returns false and it does not run the code inside condition.
Why is that? Am i missing something ?
ConnectAuthentication Class
public class ConnectAuthentication
{
public ConnectAuthentication()
{
}
public static bool isConnected()
{
return (SessionKey != null && UserID != -1);
}
public static string ApiKey
{
get
{
return ConfigurationManager.AppSettings["APIKey"];
}
}
public static string SecretKey
{
get
{
return ConfigurationManager.AppSettings["Secret"];
}
}
public static string SessionKey
{
get
{
return GetFacebookCookie("session_key");
}
}
public static long UserID
{
get
{
long userID = -1;
long.TryParse(GetFacebookCookie("user"), out userID);
return userID;
}
}
private static string GetFacebookCookie(string cookieName)
{
string retString = null;
string fullCookie = ApiKey + "_" + cookieName;
if (HttpContext.Current.Request.Cookies[fullCookie] != null)
retString = HttpContext.Current.Request.Cookies[fullCookie].Value;
return retString;
}
}
Here is how the ConnectAuthentication Class is used in my page load :
if (ConnectAuthentication.isConnected())
{
Facebook.Session.ConnectSession session = new Facebook.Session.ConnectSession(ConnectAuthentication.ApiKey, ConnectAuthentication.SecretKey);
_connectSession = new ConnectSession(ConnectAuthentication.ApiKey, ConnectAuthentication.SecretKey);
Api _facebookAPI = new Api(_connectSession);
_connectSession.UserId = ConnectAuthentication.UserID;
Facebook.Rest.Api api = new Facebook.Rest.Api(_connectSession);
//Display user data captured from the Facebook API.
Facebook.Schema.user user = api.Users.GetInfo();
string fullName = user.first_name + " " + user.last_name;
Panel1.Visible = true;
Label1.Text = fullName;
}
else
{
//Facebook Connect not authenticated, proceed as usual.
}
}
This code worked perfectly...
<input type="button" id="fblogin" value="Login to Facebook" disabled="disabled" style="display:none"/>
<fb:login-button v="2" length="long" onlogin="window.location = 'Default.aspx'">Login to Facebook</fb:login-button>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function () {
FB.init({
appId: '<%: Facebook.FacebookApplication.Current.AppId %>',
cookie: true,
xfbml: true,
oauth: true
});
function facebooklogin() {
FB.login(function (response) {
if (response.authResponse) {
// user authorized
// make sure to set the top.location instead of using window.location.reload()
top.location = '<%= this.ResolveCanvasPageUrl("~/") %>';
} else {
// user cancelled
}
}, { scope: '<%: string.Join(",", ExtendedPermissions) %>' });
};
$(function () {
// make the button is only enabled after the facebook js sdk has been loaded.
$('#fblogin').attr('disabled', false).click(facebooklogin);
});
};
(function () {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
} ());
</script>
I have configuration problems with uploadify (v.2.1.4) and my MVC 3 project. Here's the code which returns the HTTP 302 code.
#{string auth = #Request.Cookies[FormsAuthentication.FormsCookieName] == null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value;}
$("#fileuploader").uploadify({
uploader: '#Url.Content("~/Scripts/uploadify.swf")',
script: '#Url.Action("Upload", "Control")',
scriptData: { token: "#auth" },
fileDataName: 'file',
buttonText: 'Upload file',
multi: false,
sizeLimit: 22222222222,
simUploadLimit: 1,
cancelImg: '#Url.Content("~/Images/uploadify-cancel.png")',
auto: true,
onError: function(event, queueID, fileObj, errorObj) {
alert("Error!!! Type: [" + errorObj.type + "] Info [" + errorObj.info + "]");
},
onComplete: function (event, queueId, fileObj, response, data) {
alert(response);
}
});
public class ControlController : Controller
{
[HttpPost]
public ActionResult Upload(string token, HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var appData = Server.MapPath("~/app_data");
var filename = Path.Combine(appData, Path.GetFileName(file.FileName));
file.SaveAs(filename);
}
return Json(true);
}
}
1) The controller's action is not being fired
2) I've found that topic Getting Uploadify to work with asp.net-mvc, but if I use that attribute to my controller, I see that "AuthenticationToken" is null (I'm logged in)
3) If I set the uploadify option 'method' to 'post' I get the #2032 error
EDIT
The controller is the Admininistration controller, so I use that Attribute to it:
protected override bool AuthorizeCore(HttpContextBase httpContext) {
if (!HttpContext.Current.User.Identity.IsAuthenticated)
return false;
if (admin && !um.IsAdmin(HttpContext.Current.User.Identity.Name))
return false;
return true;
}
which returns true. I've noticed, if I remove this attribute, the uploads started working. But I need that Attribute
it's help you.
var auth = "#(Request.Cookies[FormsAuthentication.FormsCookieName]==null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value)";
var ASPSESSID = "#(Session.SessionID)";
$("#uploadifyLogo").uploadify({
...
'scriptData': { 'ASPSESSID': ASPSESSID, 'AUTHID': auth }
});
In Global.asax :
protected void Application_BeginRequest(object sender, EventArgs e)
{
/* we guess at this point session is not already retrieved by application so we recreate cookie with the session id... */
try
{
string session_param_name = "ASPSESSID";
string session_cookie_name = "ASP.NET_SessionId";
if (HttpContext.Current.Request.Form[session_param_name] != null)
{
UpdateCookie(session_cookie_name, HttpContext.Current.Request.Form[session_param_name]);
}
else if (HttpContext.Current.Request.QueryString[session_param_name] != null)
{
UpdateCookie(session_cookie_name, HttpContext.Current.Request.QueryString[session_param_name]);
}
}
catch
{
}
try
{
string auth_param_name = "AUTHID";
string auth_cookie_name = FormsAuthentication.FormsCookieName;
if (HttpContext.Current.Request.Form[auth_param_name] != null)
{
UpdateCookie(auth_cookie_name, HttpContext.Current.Request.Form[auth_param_name]);
}
else if (HttpContext.Current.Request.QueryString[auth_param_name] != null)
{
UpdateCookie(auth_cookie_name, HttpContext.Current.Request.QueryString[auth_param_name]);
}
}
catch
{
}
}
private void UpdateCookie(string cookie_name, string cookie_value)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookie_name);
if (null == cookie)
{
cookie = new HttpCookie(cookie_name);
}
cookie.Value = cookie_value;
HttpContext.Current.Request.Cookies.Set(cookie);
}
Currently I am working on a web page which will tell user about certain configurations on client machine. Out of this there is also requirement of detecting if Adobe Reader is installed on client machine or not. I am using ASP.NET/C#.
I have looked the following url for the answer
"Check Adobe Reader is installed (C#)?" but the code look into the server registry entires where IIS is installed and not the client machine where browser is running.
Is it possible to detect if Adobe reader is installed on client machine and not the server which is hosting the website?
pls, check the script below, it worked fine for me in IE, FireFox and Chrome
<html>
<body>
<script type="text/javascript">
var found = false;
var info = '';
try
{
acrobat4 = new ActiveXObject('PDF.PdfCtrl.1');
if (acrobat4)
{
found = true;
info = 'v. 4.0';
}
}
catch (e)
{
//???
}
if (!found)
{
try
{
acrobat7 = new ActiveXObject('AcroPDF.PDF.1');
if (acrobat7)
{
found = true;
info = 'v. 7+';
}
}
catch (e)
{
//???
}
if (!found && navigator.plugins && navigator.plugins.length>0)
{
for (var i = 0; i<navigator.plugins.length; i++)
{
if (navigator.plugins[i].name.indexOf('Adobe Acrobat') > -1)
{
found = true;
info = navigator.plugins[i].description + ' (' + navigator.plugins[i].filename + ')';
break;
}
}
}
}
document.write("Acrobat Reader Installed : " + found);
document.write("<br />");
if (found) document.write("Info : " + info);
</script>
</body>
</html>
hope this helps, regards
I used this script and called it on ready function :
Note: i used the alerts here just to know how to use it.
<script type="text/javascript">
$(document).ready(function () {
alert(getAcrobatInfo().browser);
alert(getAcrobatInfo().acrobat === "installed");
alert(getAcrobatInfo().acrobatVersion);
});
var getAcrobatInfo = function () {
var getBrowserName = function () {
return '<%=Session["browser"].ToString()%>';
};
var getActiveXObject = function (name) {
try { return new ActiveXObject(name); } catch (e) { }
};
var getNavigatorPlugin = function (name) {
for (key in navigator.plugins) {
var plugin = navigator.plugins[key];
if (plugin.name == name) return plugin;
}
};
var getPDFPlugin = function () {
return this.plugin = this.plugin || function () {
if (getBrowserName() == 'ie' || getBrowserName().toLocaleLowerCase() == 'internetexplorer') {
//
// load the activeX control
// AcroPDF.PDF is used by version 7 and later
// PDF.PdfCtrl is used by version 6 and earlier
return getActiveXObject('AcroPDF.PDF') || getActiveXObject('PDF.PdfCtrl');
}
else {
return getNavigatorPlugin('Adobe Acrobat') || getNavigatorPlugin('Chrome PDF Viewer') || getNavigatorPlugin('WebKit built-in PDF') || getWebKitPlugin();
}
}();
};
var getWebKitPlugin = function () {
for (var key in navigator.plugins) {
var plugin = navigator.plugins[key];
if (plugin.name && plugin.name.substring(0, 6) == "WebKit" && (plugin.name.indexOf("pdf") != -1 || plugin.name.indexOf("PDF") != -1)) return plugin;
}
};
var isAcrobatInstalled = function () {
return !!getPDFPlugin();
};
var getAcrobatVersion = function () {
try {
var plugin = getPDFPlugin();
if (getBrowserName() == 'ie' || getBrowserName().toLocaleLowerCase() == 'internetexplorer') {
var versions = plugin.GetVersions().split(',');
var latest = versions[0].split('=');
return parseFloat(latest[1]);
}
if (plugin.version) return parseInt(plugin.version);
return plugin.name
}
catch (e) {
return null;
}
}
// The returned object
return {
browser: getBrowserName(),
acrobat: isAcrobatInstalled() ? 'installed' : false,
acrobatVersion: getAcrobatVersion()
};
};
</script>
Also add this code behind:
public void detectBrowser()
{ //Set the Browser session variable
System.Web.HttpBrowserCapabilities browser = Request.Browser;
Session["Browser"] = browser.Browser;
}
Hope it helps.