Repeating Facebook post throwing error(Bad request)c# mvc - c#

I am working on c#mvc4 project.I am trying to post messages,link,images and video to facebook via my website.I followed this tutorial http://www.codeproject.com/Articles/569920/Publish-a-post-on-Facebook-wall-using-Graph-API.I am success with first posting,Secondly while posting it throws an error bad request(400) on the code
facebook.GetAccessToken(Session["facebookQueryStringValue"].ToString());
My code snippets are here
Controller
Authentication auth = new Authentication();
public ActionResult Success()
{
if (Request.QueryString["code"] != null)
{
string Code = Request.QueryString["code"];
Session["facebookQueryStringValue"] = Code;
}
if (Session["facebookQueryStringValue"] != null)
{
Facebook facebook = auth.FacebookAuth();
facebook.GetAccessToken(Session["facebookQueryStringValue"].ToString());
FBUser currentUser = facebook.GetLoggedInUserInfo();
IFeedPost FBpost = new FeedPost();
if (Session["postStatus"].ToString() != "")
{
FBpost.Message = Session["postStatus"].ToString();
facebook.PostToWall(currentUser.id.GetValueOrDefault(), FBpost);
//return RedirectToAction("Index");
}
}
return View();
}
public JsonResult PostStatus(string msg)
{
Session["postStatus"] = msg;
Facebook facebook = auth.FacebookAuth();
if (Session["facebookQueryStringValue"] == null)
{
string authLink = facebook.GetAuthorizationLink();
return Json(authLink);
}
if (Session["facebookQueryStringValue"] != null)
{
facebook.GetAccessToken(Session["facebookQueryStringValue"].ToString());
FBUser currentUser = facebook.GetLoggedInUserInfo();
IFeedPost FBpost = new FeedPost();
if (Session["postStatus"].ToString() != "")
{
FBpost.Message = Session["postStatus"].ToString();
facebook.PostToWall(currentUser.id.GetValueOrDefault(), FBpost);
Session["facebookQueryStringValue"] = "";
}
}
return Json("No");
}
Authentication
public class Authentication
{
public Facebook FacebookAuth()
{
//Setting up the facebook object
Facebook facebook = new Facebook();
facebook.AppID = "xxxxxxxxxxxxxxxxxxx";
facebook.CallBackURL = "http://localhost:8088/PostStatus/Success";
facebook.Secret = "xxxxxxxxxxxxxxxxxxx";
//Setting up the permissions
List<FBPermissions> permissions = new List<FBPermissions>() {
FBPermissions.user_about_me, // to read about me
FBPermissions.user_events,
FBPermissions.user_status,
FBPermissions.read_stream,
FBPermissions.friends_events,
FBPermissions.publish_stream
};
//Pass the permissions object to facebook instance
facebook.Permissions = permissions;
return facebook;
}
}
Ajax call
$.ajax({
url: '/PostStatus/PostStatus',
type: 'POST',
data: { msg: msg },
success: function (authLink) {
if (authLink != 'No') {
// window.open(authLink, 'title', 'width=660,height=500,status=no,scrollbars=yes,toolbar=0,menubar=no,resizable=yes,top=60,left=320');
window.location.href = authLink;
}
}
});
Any help on this error is appreciable.I cant see any other tutorial for posting message,link,video,images on facebook in c# mvc4

Related

How to get Facebook profile Picture C# .Net

I need to get the user´s facebook profile picture and input it in a crop structure. I´m using Asp.NET MVC, jcrop and the facebook SDK. Untill now i can input files from my computer. I also have a function that access the facebook of the user and returns a session with the user Id, and a GetPhoto function that should return the profile picture. Can someone help me?
I use this code to input the files from the computer:
[ValidateAntiForgeryToken]
public ActionResult _Upload(IEnumerable<HttpPostedFileBase> files)
{
if (files == null || !files.Any()) return Json(new { success = false, errorMessage = "No file uploaded." });
var file = files.FirstOrDefault(); // get ONE only
if (file == null || !IsImage(file)) return Json(new { success = false, errorMessage = "File is of wrong format." });
if (file.ContentLength <= 0) return Json(new { success = false, errorMessage = "File cannot be zero length." });
var webPath = GetTempSavedFilePath(file);
//mistertommat - 18 Nov '15 - replacing '\' to '//' results in incorrect image url on firefox and IE,
// therefore replacing '\\' to '/' so that a proper web url is returned.
return Json(new { success = true, fileName = webPath.Replace("\\", "/") }); // success
}
i tried doing this but the GetPhoto() is returning a null element.
public ActionResult RetornoFb()
{
var _fb = new FacebookClient();
FacebookOAuthResult oauthResult;
if (!_fb.TryParseOAuthCallbackUrl(Request.Url, out oauthResult))
{
// Error
}
if (oauthResult.IsSuccess)
{
dynamic parameters = new ExpandoObject();
parameters.client_id = id;
parameters.redirect_uri = "http://localhost:4323/Avatar/RetornoFb/";
parameters.client_secret = secretkey;
parameters.code = oauthResult.Code;
dynamic result = _fb.Get("/oauth/access_token", parameters);
var accessToken = result.access_token;
Session.Add("FbUserToken", accessToken);
}
else
{
}
//return RedirectToAction("Upload");
HttpPostedFileBase objFile = (HttpPostedFileBase)new MemoryPostedFile(GetPhoto());
var webPath = GetTempSavedFilePath(objFile);
return Json(new { success = true, fileName = webPath.Replace("\\", "/") }); // success
}
public byte[] GetPhoto()
{
try
{
string url = "https://graph.facebook.com/" + GetProfileId() + "?fields=picture.width(480).height(480)";
WebClient webClient = new WebClient();
string response = webClient.DownloadString(url);
dynamic json = JObject.Parse(response);
string urlPicture = json.picture.data.url;
return webClient.DownloadData(urlPicture);
}
catch (Exception)
{
return null;
}
}
Resolved changing my GetPhoto Function. I was having permission issues.
private byte[] GetPhoto()
{
try
{
var _fb = new FacebookClient(Session["FbuserToken"].ToString());
dynamic resultMe = _fb.Get(GetProfileId()+"?fields=picture.width(480).height(480)");
WebClient webClient = new WebClient();
string urlPicture = resultMe.picture.data.url;
return webClient.DownloadData(urlPicture);
}
catch (Exception)
{
return null;
}
}

how to consume ws security header in soap web service c#

I need some help.Firstly I wrote one soap web service with basic authentication.But I have to change with wssecurity in soap.How can I consume coming ws security header I have to read username and password and I have to compare my username and password in my webconfig file inside service. I write this code but I m not sure : I done this way.But how can I configure in webconfig.file
public class QuantityService : Microsoft.Web.Services3.WebServicesClientProtocol, IQuantityService
{
private OperationResult AuthCheck()
{
OperationResult retVal = new OperationResult()
{
ReturnCode = 0,
ReturnMessage = "OK"
};
string userName = ConfigurationManager.AppSettings["username"].ToString();
string password = ConfigurationManager.AppSettings["password"].ToString();
//UsernameToken token = new UsernameToken(userName,password,PasswordOption.SendPlainText);
QuantityService serviceProxy = new QuantityService();
SoapContext requestContext = serviceProxy.RequestSoapContext;
//requestContext.Security.Tokens.Add(token);
if (requestContext == null)
{
throw new ApplicationException("Non-SOAP request.");
}
foreach (SecurityToken tok in requestContext.Security.Tokens)
{
if (tok is UsernameToken)
{
if (userName == ((UsernameToken)tok).Username && password == ((UsernameToken)tok).Password)
{
retVal.ReturnCode = 0;
retVal.ReturnMessage = "OK";
}
else
{
retVal.ReturnCode = -2;
retVal.ReturnMessage = "Unauthorized.";
}
}
}
return retVal;
}

ASP.NET MVC not work with Forms Authentication

I'm trying to use Facebook for users authorization via Forms Authentication in ASP.NET MVC.
I'm getting access token from Facebook and user avatar url and pass these data to Controller, all of this is work just fine until the moment when I need to redirect user.
I did tried FormsAuthentication.RedirectFromLoginPage, RedirectToAction, Response.Redict. None of this methods are working as well as no errors.
Here is the controller:
[HttpPost]
public ActionResult Login(string Url, string AccessToken)
{
string username;
string fullname;
var client = new Facebook.FacebookClient(AccessToken);
dynamic result = client.Get("me", new { fields = "username,first_name,last_name" });
if (result.first_name == null | result.last_name == null)
{
username = result.username;
fullname = null;
}
else
{
username = result.username;
fullname = result.first_name + " " + result.last_name;
}
if (UserExist(username) == false)
{
CreateUser(username, Url, fullname);
//FormsAuthentication.SetAuthCookie(username, true);
//return RedirectToAction("Register", "Home");
FormsAuthentication.RedirectFromLoginPage(username, true);
}
else
{
HttpCookie c = Request.Cookies.Get("UserGuid");
if (c == null)
{
c = new HttpCookie("UserGuid")
{
Value = GetUserGuid(User.Identity.Name),
Expires = DateTime.Now.AddYears(1)
};
Response.Cookies.Add(c);
}
if (result.first_name == null || result.last_name == null)
{
username = result.username;
}
else
{
username = result.first_name + " " + result.last_name;
}
try
{
//FormsAuthentication.SetAuthCookie(username, true);
//Response.Redirect(FormsAuthentication.DefaultUrl);
FormsAuthentication.RedirectFromLoginPage(username, true);
}
catch (Exception)
{
throw new Exception();
}
}
return View();
}
You can't do a simple redirect when accessing your action method through AJAX. You need to do a redirect in your JS code by providing a response url from your controller action.
You can simply return a redirect url from your controller and do the following in JS:
$.ajax({
url: url,
data: data,
success: function(resp) {
window.location.href = resp.Url;
}
})
And in your controller:
return Json(new {Url = "/Home/Index"});

Asp.Net webresource.axd open redirection security flaw?

Running WebResource.axd through Burpe Suite’s active scan gave indication of a possible open redirection flaw in the function WebForm_DoCallback. This function does a post based upon a generated url. The generated url is based upon the form action url or document.location.pathname
I have not figured out where my site is using this method, nor have I found a way to abuse it.
How can anyone abuse this?
This is the relevant function. The comments include the potential problem.
var xmlRequest,e;
try {
xmlRequest = new XMLHttpRequest();
}
catch(e) {
try {
xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
}
}
var setRequestHeaderMethodExists = true;
try {
setRequestHeaderMethodExists = (xmlRequest && xmlRequest.setRequestHeader);
}
catch(e) {}
var callback = new Object();
callback.eventCallback = eventCallback;
callback.context = context;
callback.errorCallback = errorCallback;
callback.async = useAsync;
var callbackIndex = WebForm_FillFirstAvailableSlot(__pendingCallbacks, callback);
if (!useAsync) {
if (__synchronousCallBackIndex != -1) {
__pendingCallbacks[__synchronousCallBackIndex] = null;
}
__synchronousCallBackIndex = callbackIndex;
}
if (setRequestHeaderMethodExists) {
xmlRequest.onreadystatechange = WebForm_CallbackComplete;
callback.xmlRequest = xmlRequest;
// action is set to the url of the form or current path.
//fragmentIndex is set to the index of # in the url
var action = theForm.action || document.location.pathname, fragmentIndex = action.indexOf('#');
if (fragmentIndex !== -1) {
//action is set to index of start to the position of fragmentIndex
action = action.substr(0, fragmentIndex);
}
//From somewhere else in the script.
//var __nonMSDOMBrowser = (window.navigator.appName.toLowerCase().indexOf('explorer') == -1)
if (!__nonMSDOMBrowser) {
var queryIndex = action.indexOf('?');
if (queryIndex !== -1) {
var path = action.substr(0, queryIndex);
if (path.indexOf("%") === -1) {
action = encodeURI(path) + action.substr(queryIndex);
}
}
else if (action.indexOf("%") === -1) {
action = encodeURI(action);
}
}
//post to the generated url.
xmlRequest.open("POST", action, true);
xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
xmlRequest.send(postData);
return;
}

404 Error When Accessing URL through AJAX

Not sure why, everything seems formatted fine, but I get the HTTP 404 error when attempting to access a function in my controller. Here's the aspx:
function CheckIfPacked() {
if ($("#OrderNumber").val() != "") {
var url = "/Packing/PackageTracking/CheckIfPacked";
$.ajax({
url: url,
cache: false,
data: "orderNumber=" + $("#OrderNumber").val() + "&actionyes=GetSalesOrder()",
success: function (data) {
var domElement = $(data);
if (data != "") {
$('#MessageDiv').append(domElement);
}
});
}
}
And here's the controller:
public Result CheckIfPacked(string orderNumber) {
var mesEntity = new MESEntities();
var packh = from packhead in mesEntity.Packing_Transaction_Headers
where packhead.Order_No_ == orderNumber
select packhead.Completed_by_Packer;
if (packh.First() == 0)
{
return new Result { Success = true, Message = string.Format("You have not finished packing order {0}, are you sure you want to navigate away from this page?", orderNumber) };
}
else
{
return null;
}
}
I think I've just stared at this too long. Thanks.
your method should be static and you should use webmethod attribute for your function :
[WebMethod]
public static Result CheckIfPacked(string orderNumber) {
var mesEntity = new MESEntities();
var packh = from packhead in mesEntity.Packing_Transaction_Headers
where packhead.Order_No_ == orderNumber
select packhead.Completed_by_Packer;
if (packh.First() == 0)
{
return new Result { Success = true, Message = string.Format("You have not finished packing order {0}, are you sure you want to navigate away from this page?", orderNumber) };
}
else
{
return null;
}
}

Categories