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);
}
Related
DELETE request give 204 response code from Insomnia/Postman, But from the frontend it gives error for Delete request.
Please find my Service code below :
public bool Dissociate(string envCode, string serialNumber, string gatewayType)
{
envCode.ThrowIfNull();
serialNumber.ThrowIfNull();
gatewayType.ThrowIfNull();
if (!IsAssociated(envCode, serialNumber, gatewayType))
{
_logService.Warn($"DspService - Dissociate - {gatewayType} {serialNumber} not associated to DSP tenant on environment {envCode}");
return false;
}
EnvironmentSettings dspEnvSettings = GetEnvironmentSettings(envCode);
string baseUri = DspHelper.GetBaseUriByAction(dspEnvSettings, DspActionType.Dissociate);
string dspDeviceId = DspHelper.BuildDeviceId(serialNumber, gatewayType, true);
string uri = $"{baseUri}/registry/devices/{dspDeviceId}/claim";
var body = new
{
Claimable = true
};
try
{
var authToken = GetAuthorizationHeader(dspEnvSettings, DspActionType.Dissociate);
RunDspCommand<bool>(dspEnvSettings, uri, authToken, body, HttpMethod.Put, DspActionType.Dissociate);
return true;
}
catch (Exception e)
{
_logService.ErrorException(e, $"DspService - Dissociate - Error dissociating {gatewayType} {serialNumber} on environment {envCode}. {uri}");
throw;
}
}
Please find my insomnia response:
CONTROLLER :
[AcceptVerbs("DELETE")]
[Route("dissociate")]
public bool Dissociate([FromUri] string gatewayType, [FromUri] string gatewaySerial)
{
if (string.IsNullOrEmpty(gatewaySerial) || string.IsNullOrEmpty(gatewayType))
{
this.BadRequestResponse();
}
var connectedUser = this.permissionService.GetConnectedUser();
this.permissionService.CheckRolePermission(connectedUser.Role, PermissionConstant.DissociateComX);
bool hasSucceeded = this.dspService.Dissociate(connectedUser.CurrentEnvironment, gatewaySerial, gatewayType);
if (hasSucceeded)
{
this.applicationDataAccess.LogAction(connectedUser.CurrentEnvironment, connectedUser.Email, LogActionConstants.Action.DissociateComX, string.Format(LogActionConstants.Message.DissociateComX, gatewayType, gatewaySerial));
}
else
{
this.BadRequestResponse("cannot deprovioned comx");
}
return hasSucceeded;
}
It gives the exception in the Service Code
RunDspCommand<bool>(dspEnvSettings, uri, authToken, body, HttpMethod.Put, DspActionType.Dissociate);
Below is my front end code.
controller.ts
dissociateGateway() {
if (!this.isDspGateway || this.isLoadingDspState || this.isDissociating
|| this.gateway.FirmwareUpgradeWorkflow || this.gateway.DeleteGatewayWorkflow
|| !this.isAssociated()) {
return;
}
this.modalService.confirm(
`The ${this.gateway.Type} ${this.gateway.SerialNumber} will be dissociated from its DSP tenant ${this
.dspGatewayState.Tenant}.`,
'Are you sure you want to dissociate the gateway from DSP tenant?')
.then(() => {
this.isDissociating = true;
this.dspService.dissociate(this.gateway.Type, this.getDeviceId())
.then(() => this.getDspGatewayState())
.catch((e) => {
if (e) {
this.modalService.error('Error dissociating the gateway. Please retry later');
}
})
.finally(() => this.isDissociating = false);
});
}
service.ts
dissociate(gatewayType: string, gatewaySerial: string): ng.IPromise<boolean> {
var uri = this.ROUTES.dissociate
.replace('{:gatewayType}', gatewayType.toString())
.replace('{:gatewaySerial}', gatewaySerial);
return this.restService
.delete(uri, null)
.then((response: any) => {
return response;
})
.catch((response: any) => {
return this.$q.reject(response);
});
}
Path :
dissociate: '/dsp/dissociate?gatewaytype={:gatewayType}&gatewaySerial={:gatewaySerial}',
If you need more information please comment below.
Please help me. Thanks in Advance.
I am using Firebase API for Unity and I am pushing some data to the realtime database using the Post request
Right after using that Post request I need the created ID for the new node to do something else but I am not sure how to retrieve that ID.
Firebase.Instance.Post(uri, new Dictionary<string, string>() { { "name", name } },
delegate { Debug.Log("Name has been added successfully!"); //here is where i need the new ID to do something else },
delegate { Debug.Log("Something Wrong! .. Please try again later"); });
The post function:
public void Post<T, K>(URI uri, T body, System.Action<K> onSuccess, System.Action<string> onFail)
{
RequestHelper currentRequest = new RequestHelper
{
Uri = uri.Path,
BodyString = JsonConvert.SerializeObject(body),
IgnoreHttpException = true
};
Debug.Log("BODY_post: " + currentRequest.BodyString);
RestClient.Post(currentRequest, (exception, res) => ResolveResponse(exception, res, onSuccess, onFail));
}
void ResolveResponse<T>(RequestException exception, ResponseHelper res, System.Action<T> onSuccess, System.Action<string> onFail)
{
string returnedText = res.Text;
AuthError authError = null;
try
{
authError = JsonConvert.DeserializeObject<AuthError>(returnedText);
}
catch (System.Exception ex)
{
Debug.Log(ex);
}
finally
{
if (authError != null && authError.error != null && authError.error.message != null)
{
onFail(BeautifyMessage(authError.error.message));
}
else if (exception != null && (exception.IsHttpError || exception.IsNetworkError))
{
onFail(BeautifyMessage(exception.Message));
}
else if (typeof(T) == typeof(string))
{
onSuccess((T)(object)returnedText);
}
else
{
onSuccess(JsonConvert.DeserializeObject<T>(returnedText));
}
}
}
And it calls to the rest api's library post function.
You are wrapping the Firebase REST API, where calling POST returns the key in the response:
A successful request is indicated by a 200 OK HTTP status code. The response contains the child name of the new data specified in the POST request.
{ "name": "-INOQPH-aV_psbk3ZXEX" }
So your response handler will need to parse that result, and return the "-IN...." key back to the caller.
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 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);
}