500 internal server error. CORS - c#

I have the following react component
import React, { Component } from 'react';
import { Row, Col } from 'antd';
import PageHeader from '../../components/utility/pageHeader';
import Box from '../../components/utility/box';
import LayoutWrapper from '../../components/utility/layoutWrapper.js';
import ContentHolder from '../../components/utility/contentHolder';
import basicStyle from '../../settings/basicStyle';
import IntlMessages from '../../components/utility/intlMessages';
import { adalApiFetch } from '../../adalConfig';
export default class extends Component {
constructor(props) {
super(props);
this.state = {tenantid: '', tenanturl: '', tenantpassword: '' };
this.handleChangeTenantUrl = this.handleChangeTenantUrl.bind(this);
this.handleChangeTenantPassword = this.handleChangeTenantPassword.bind(this);
this.handleChangeTenantId= this.handleChangeTenantId.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
};
handleChangeTenantUrl(event){
this.setState({tenanturl: event.target.value});
}
handleChangeTenantPassword(event){
this.setState({tenantpassword: event.target.value});
}
handleChangeTenantId(event){
this.setState({tenantid: event.target.value});
}
handleSubmit(event){
event.preventDefault();
const formData = new FormData();
formData.append("TenantId", this.state.tenantid);
formData.append("TenanrUrl", this.state.tenanturl);
formData.append("TenantPassword", this.state.tenantpassword);
const options = {
method: 'put',
data: formData,
config: {
headers: {
'Content-Type': 'multipart/form-data'
}
}
};
adalApiFetch(fetch, "/Tenant", options)
.then(response => response.json())
.then(responseJson => {
if (!this.isCancelled) {
this.setState({ data: responseJson });
}
})
.catch(error => {
console.error(error);
});
}
upload(e){
let data = new FormData();
//Append files to form data
let files = e.target.files;
for (let i = 0; i < files.length; i++) {
data.append('files', files[i], files[i].name);
}
}
render(){
const { data } = this.state;
const { rowStyle, colStyle, gutter } = basicStyle;
return (
<div>
<LayoutWrapper>
<PageHeader>{<IntlMessages id="pageTitles.TenantAdministration" />}</PageHeader>
<Row style={rowStyle} gutter={gutter} justify="start">
<Col md={12} sm={12} xs={24} style={colStyle}>
<Box
title={<IntlMessages id="pageTitles.TenantAdministration" />}
subtitle={<IntlMessages id="pageTitles.TenantAdministration" />}
>
<ContentHolder>
<form onSubmit={this.handleSubmit}>
<label>
TenantId:
<input type="text" value={this.state.tenantid} onChange={this.handleChangeTenantId} />
</label>
<label>
TenantUrl:
<input type="text" value={this.state.tenanturl} onChange={this.handleChangeTenantUrl} />
</label>
<label>
TenantPassword:
<input type="text" value={this.state.tenantpassword} onChange={this.handleChangeTenantPassword} />
</label>
<label>
Certificate:
<input onChange = { e => this.upload(e) } type = "file" id = "files" ref = { file => this.fileUpload } />
</label>
<input type="submit" value="Submit" />
</form>
</ContentHolder>
</Box>
</Col>
</Row>
</LayoutWrapper>
</div>
);
}
}
Then I get a 500 server error:
https://screencast.com/t/n7VRzxSSi6
Cors is already enabled on the web api.
https://screencast.com/t/3Fl70yX0awO
The web api code is like this:
public class TenantController : ApiController
{
public async Task<List<Tenant>> GetTenants()
{
var tenantStore = CosmosStoreFactory.CreateForEntity<Tenant>();
return await tenantStore.Query().Where(x => x.TenantId != null ).ToListAsync();
}
public async Task<IHttpActionResult> GetTenant(string tenantId)
{
var tenantStore = CosmosStoreFactory.CreateForEntity<Tenant>();
var tenant = await tenantStore.Query().FirstOrDefaultAsync(x => x.TenantId == tenantId);
if (tenant == null)
{
return NotFound();
}
return Ok(tenant);
}
public async Task<IHttpActionResult> PutTenant([FromBody]Tenant tenant, HttpPostedFile certificateFile)
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["AzureStorageKey"].ToString());
// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference(ConfigurationManager.AppSettings["certificatesContainer"].ToString());
// Retrieve reference to a blob named "myblob".
CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob");
// Create or overwrite the "myblob" blob with contents from a local file.
blockBlob.Properties.ContentType = certificateFile.ContentType;
blockBlob.UploadFromStream(certificateFile.InputStream);
var tenantStore = CosmosStoreFactory.CreateForEntity<Tenant>();
tenant.CertificatePath = blockBlob.Uri;
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
//if (id != tenant.TenantId)
//{
// return BadRequest();
//}
var added = await tenantStore.AddAsync(tenant);
return StatusCode(HttpStatusCode.NoContent);
}
public async Task<IHttpActionResult> PostTenant(string id, Tenant tenant)
{
var tenantStore = CosmosStoreFactory.CreateForEntity<Tenant>();
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var result = await tenantStore.UpdateAsync(tenant);
return Ok(result);
}
public async Task<IHttpActionResult> DeleteTenant(string tenantId)
{
var tenantStore = CosmosStoreFactory.CreateForEntity<Tenant>();
await tenantStore.RemoveByIdAsync(tenantId);// Removes an entity with the specified ID
return Ok(tenantId);
}
}
I attached the debugger after publishing, but the code is never hit in visual studio

You are initializing your state to this.state = { TenantId: '', TenanrUrl:'', TenantPassword:''}; but you are using tenantid, tenanturl, and tenantpassword in your code.
Since tenantid, tenanturl, and tenantpassword are not initially in your state, you will begin to give undefined to your inputs until you call setState and update it. This will make the inputs go from uncontrolled to controlled.
You can fix it by changing your initial state to have default values for tenantid, tenanturl, and tenantpassword instead:
constructor(props) {
super(props);
this.state = { tenantid: '', tenanturl: '', tenantpassword: '' };
this.handleChangeTenantUrl = this.handleChangeTenantUrl.bind(this);
this.handleChangeTenantPassword = this.handleChangeTenantPassword.bind(this);
this.handleChangeTenantId= this.handleChangeTenantId.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
};

Related

Redirect user after login

I'm making a react application that integrates with an aspnet api, and I want to make the user unable to access other pages, except the Login page, without being logged in, I tried to do the following coding
This is the code I made, (it doesn't work as it should):
import React, { Fragment, useContext, useEffect, useState } from 'react';
import axios from 'axios';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import SignIn from '../pages/SignIn';
import Home from '../pages/Home'
import CadastroEmpresa from '../pages/CadastroEmpresa';
import CadastroIntegrante from '../pages/CadastroIntegrante';
import Empresas from '../pages/Empresas';
import useAuth from '../hooks/useAuth';
import { LoginContext } from '../context/auth';
const Private = ({ Item }) => {
const signed = useAuth();
return signed > 0 ? <Item /> : <SignIn />;
}
export { Private }
const RoutesApp = () => {
return (
<BrowserRouter>
<Fragment>
<Routes>
<Route path='/' element={<SignIn />} />
<Route path="*" element={<SignIn />} />
<Route exact path='/home' element={<Private Item={Home} />} />
<Route exact path='/empresas' element={<Private Item={Empresas} />} />
<Route exact path='/cadastro-empresa' element={<Private Item={CadastroEmpresa} />} />
<Route exact path='/cadastro-funcionario' element={<Private Item={CadastroIntegrante} />} />
</Routes>
</Fragment>
</BrowserRouter>
)
}
export default RoutesApp;
useAuth() is my hook that uses the context below
This is my context:
import React, { createContext, useState } from 'react';
import axios from 'axios';
const LoginContext = createContext();
const LoginProvider = ({ children }) => {
const [loginData, setLoginData] = useState({ status: '', token: '' });
const validateLogin = (loginUser) => {
if (!loginUser.email || !loginUser.senha) {
return false;
}
return true;
};
const passwordSignIn = async (email, senha) => {
try {
const response = await axios.post('https://localhost:7223/v1/entrar', {
email,
senha
});
console.log(response.data)
return response.data;
} catch (error) {
console.error(error);
return {};
}
};
const generateToken = async (email, senha) => {
try {
const response = await axios.post('https://localhost:7223/v1/entrar', {
email,
senha
});
return response.data.token;
} catch (error) {
console.error(error);
return '';
}
};
const handleLogin = async (loginUser) => {
if (!validateLogin(loginUser)) {
return setLoginData({ status: 'error', token: '' });
}
const result = await passwordSignIn(loginUser.email, loginUser.senha);
if (result.succeeded) {
const token = await generateToken(loginUser.email);
return setLoginData({ status: 'success', token: '' });
}
if (result.isLockedOut) {
return setLoginData({ status: 'locked', token: '' });
}
console.log(loginUser.email)
console.log(loginUser.senha)
return setLoginData({ status: 'error', token: '' });
};
return (
<LoginContext.Provider value={{ loginData, handleLogin }}>
{children}
</LoginContext.Provider>
);
};
export { LoginContext, LoginProvider };

How do I send an IFormFile to a controller in an integration test for a C# ASP.NET MVC app?

I am trying to write an integration test in an ASP.NET MVC / C# app that tests a controller which processes an IFormFile. I have a view which uploads the file to the controller. This upload section of the view looks like this:
<form asp-action="UploadFiles" enctype="multipart/form-data">
<input type="hidden" name="profileId" value="#Model.Profile.Id">
<div id="add-files-modal" class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Send files</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<input name="files" type="file" />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary">Add file</button>
</div>
</div>
</div>
</div>
</form>
The controller function looks like this:
[HttpPost]
public IActionResult UploadFiles(Guid profileId, List<IFormFile> files)
{
if (profileId == Guid.Empty || !files.Any())
{
throw new Exception("Unable to add files");
}
var userId = _manager.GetUserId(User);
var profile = _db.Profiles
.FirstOrDefault(p => p.UserId == userId && p.Id == profileId);
foreach (var file in files)
{
string shasum = FileHelper.HashFile(file);
if (profileId == Guid.Empty)
{
throw new Exception("Unable to send files");
}
string signatureF = FileHelper.SignFile(profile, shasum);
var record = new Record
{
ProfileId = profile.Id,
FileName = file.FileName,
IsSent = false,
Shasum = shasum,
Signature = signatureF,
};
_db.Records.Add(record);
}
_db.SaveChanges();
return RedirectToAction(nameof(Manage), new { profileName = profile.Name });
}
Usually, in integration tests, I simply send relevant data to the controller with a Dictionary<string, string>. For example, I login in integration tests like this:
var postRequest = new HttpRequestMessage(HttpMethod.Post, "/Identity/Account/Login");
var formModel = new Dictionary<string, string>
{
{ "Email", "test2#example.com" },
{ "Password", "pas3w02!rRd" },
{ "__RequestVerificationToken", antiForgeryValues },
};
postRequest.Content = new FormUrlEncodedContent(formModel);
var response = await client2.SendAsync(postRequest);
response.EnsureSuccessStatusCode();
The following test is my best attempt at starting to write a test function that passes a List<IFormFile> to the controller. It clearly will not work as demonstrated by the fact that I put <IDK WHAT TO PUT HERE> for the files dictionary item.
[Fact]
public async Task TryToSendIFormFileToController()
{
var application2 = new WebApplicationFactory<Program>()
.WithWebHostBuilder(builder =>
{
// ... Configure test services
});
var client2 = application2.CreateClient();
var initResponse2 = await client2.GetAsync("/Identity/Account/Register");
initResponse2.EnsureSuccessStatusCode();
string registerResponseContent2 = await initResponse2.Content.ReadAsStringAsync();
var antiForgeryValues2 = AntiForgeryTokenExtractor.ExtractAntiForgeryToken(registerResponseContent2);
var postRequest2 = new HttpRequestMessage(HttpMethod.Post, "/Identity/Account/Login");
var formModel2 = new Dictionary<string, string>
{
{ "Email", "test2#example.com" },
{ "Password", "pas3w02!rRd" },
{ "__RequestVerificationToken", antiForgeryValues2 },
};
postRequest2.Content = new FormUrlEncodedContent(formModel2);
var response2 = await client2.SendAsync(postRequest2);
var loginResponseContent2 = await response2.Content.ReadAsStringAsync();
response2.EnsureSuccessStatusCode();
//var antiForgeryValuesReLogin = AntiForgeryTokenExtractor.ExtractAntiForgeryToken(loginResponseContent2);
var listOfFiles = new List<IFormFile>();
var filePath = "../../../AntiForgeryTokenExtractor.cs";
using var stream = new MemoryStream(File.ReadAllBytes(filePath).ToArray());
IFormFile? formFile = new FormFile(stream, 0, stream.Length, "streamFile", filePath.Split(#"\").Last());
listOfFiles.Add(formFile);
var uploadFilesReq = new HttpRequestMessage(HttpMethod.Post, "/Profile/UploadFiles");
var uploadFilesModel = new Dictionary<string, string>
{
{ "profileId", profileSelected.Id.ToString() },
{ "files", <IDK WHAT TO PUT HERE> },
{ "__RequestVerificationToken", antiForgeryValues2 },
};
uploadFilesReq.Content = new FormUrlEncodedContent(uploadFilesModel);
var uploadFilesResp = await client.SendAsync(uploadFilesReq);
var uploadFilesContent = await uploadFilesResp.Content.ReadAsStringAsync();
Console.WriteLine(uploadFilesContent);
}
listOfFiles actually works! Meaning it is an actual instance of a list of 1 FormFile, specifically the AntiForgeryTokenExtractor.cs file. So how do I pass this FormFile to the controller as an IFormFile?

MVC passing a file to a controller via $.ajax

I'm trying to achieve to pass a file from the client to my controller in mvc in order to transform the file to a ByteArray, I was thinking that was a simple task but it actually giving me some hard times.. so far I'm able to hit correctly my controller:
HTML
<form method="post" id="myform" enctype="multipart/form-data"
asp-controller="UploadFiles" asp-action="Index">
<div class="form-group">
<div class="col-md-10">
<p>Seleziona un file ORI ed un file MOD.</p>
<label for="fileOri">Seleziona ORI</label>
<input id="fileOri" type="file" name="fileOri" multiple />
<p></p>
<label for="fileMod">Seleziona MOD</label>
<input id="fileMod" type="file" name="fileMod" multiple />
<p></p>
<input id="check" name="checkBoxCorreggi" type="checkbox" />
<label for="check">Correggi Checksum</label>
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<p></p>
<input type="submit" id="VerificaChecksum" value="Verifica Checksum" />
<!--value= "Verifica Checksum-->
<p></p>
</div>
</div>
</form>
JavaScript
$(function () {
$('#VerificaChecksum').click(function () {
var file = document.getElementById('fileOri'),
formData = new FormData();
if (file.files.length > 0) {
for (var i = 0; i < file.files.length; i++) {
formData.append('file' + i, file.files[i]);
}
}
$.ajax({
url: '#Url.Action("UploadFiles", "UploadFiles")',
type: 'POST',
data: formData,
dataType: "json",
cache: false,
contentType: false,
processData: false
});
});
});
MVC CONTROLLER
public class UploadFilesController : Controller
{
int result = 0;
int count = 0;
byte[] fileOri;
byte[] fileMod;
[DllImport(#"c:\Windows\System32\inetsrv\dll194.dll", EntryPoint = "get_cks_XXX")]
public static extern int get_cks_XXX(byte[] pBuf_mod, byte[] pBuf_ori, int len_Buf, bool flag);
private readonly IHostingEnvironment _hostingEnvironment;
public UploadFilesController(IHostingEnvironment hostingEnvironment)
{
this._hostingEnvironment = hostingEnvironment;
}
#region snippet1
[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(IList<IFormFile> files, string[] checkBoxCorreggi)
{
long size = files.Sum(f => f.Length);
// full path to file in temp location
var filePath = Path.GetTempFileName();
foreach (var formFile in files)
{
if (formFile.Length > 0)
{
using (var stream = new MemoryStream())
{
await formFile.CopyToAsync(stream);
if (count == 0)
{
fileOri = stream.ToArray();
}
else
{
fileMod = stream.ToArray();
}
}
}
count++;
}
if (checkBoxCorreggi.Length == 1)
{
result = get_cks_XXX(fileMod, fileOri, fileOri.Length, true);
return File(fileMod, "application/force-download", "modCorretto.mod");
}
else
{
result = get_cks_XXX(fileMod, fileOri, fileOri.Length, false);
return Ok(new { count = files.Count, size, filePath });
}
}
#endregion
}
As I said before I'm currently able to hit my controller, but the problem is that the IList<IFormFile> files is actually null, where I'm getting wrong?
I hope this will work.
I have just only one file to send so i am doing this is Asp.Net Core
You can add your conditions as well like Files.Count or something you want.
Here is my code to save file
[HttpPost]
public async Task<JsonResult> SaveRegistration(string registration)
{
var message = "";
var status = "";
try
{
var path = Path.Combine(_hostingEnvironment.WebRootPath, "Files\\Images");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
path += "\\";
if (!string.IsNullOrEmpty(registration))
{
var reg = new Registration();
reg.Name = registration;
var file = Request.Form.Files[0];
if (file != null)
{
var fileName = file.FileName;
if (System.IO.File.Exists(path + fileName))
{
fileName = $"{DateTime.Now.ToString("ddMMyyyyHHmmssfff")}-{fileName}";
}
using (var fileStream = new FileStream(path + fileName, FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
reg.Picture = fileName;
}
_context.Registration.Add(reg);
await _context.SaveChangesAsync();
message = "Data is not saved";
status = "200";
}
}
catch (Exception ex)
{
message = ex.Message;
status = "500";
}
return Json(new
{
Message = message,
Status = status
});
}

file count is always zero in web API when trying to upload a document with angular 2

I'am trying to upload a file using a web API in C#. For that the code I have used in as follows.
httpRequest.Files.Count value always gets zero when i'm trying to upload a document.
What am I doing wrong?
mcDocuments.ts file
fileChange(event) {
debugger;
let fileList: FileList = event.target.files;
if (fileList.length > 0) {
let file: File = fileList[0];
let formData: FormData = new FormData();
formData.append('uploadFile', file, file.name);
let token = JSON.parse(Cookie.get('currentUser')).token
let headers = new Headers();
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Authorization', 'bearer ' + token);
headers.append('UserName',
JSON.parse(Cookie.get('currentUser')).username);
headers.append('Content-Type', 'multipart/form-data');
let options = new RequestOptions({ headers: headers });
let apiUrl1 = "http://localhost:53732/api/UploadFileApi";
this.http.post(apiUrl1, formData, options)
.map(res => res.json())
.catch(error => Observable.throw(error))
.subscribe(
data => console.log('success'),
error => console.log(error)
)
}
window.location.reload();
}
mcDocuments.html file
<input type="file" id="btnUpload" value="Upload" (change)="fileChange($event)" class="upload" />
web Api
using System.Net.Http;
using System.Web;
using System.Web.Http;
namespace FileUpload_WebAPI_Angular2.Controllers
{
public class UploadFileApiController : ApiController
{
[HttpPost]
public HttpResponseMessage UploadJsonFile()
{
HttpResponseMessage response = new HttpResponseMessage();
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath =
HttpContext.Current.Server.MapPath("~/UploadFile/" + postedFile.FileName);
postedFile.SaveAs(filePath);
}
}
return response;
}
}
}
module.ts file
declarations: [ McDocumentsComponent,],
providers: [{ provide: LocationStrategy, useClass: HashLocationStrategy }],
bootstrap: [McDocumentsComponent]
Check if your inteceptor class set a content-type. If so, remove it.
Try using Request.Files or Request.Form.Files instead of HttpContext.Current.Request.Files. A similar issue was experienced here: Request.Files is always null
This works for me:
component.html:
<input type="file" id="file" (change)="handleFileInput($event.target.files)">
Interface
export interface UploadDoc {
LlojiKampanjesId: number;
FileToUpload: File; }
component.ts
listToUpload: UploadDoc = {LlojiKampanjesId:0, FileToUpload:null};
handleFileInput(files: FileList) {
this.listToUpload.FileToUpload = files.item(0);}
public uploadList() {
this.disableSubmit = true;
this.rastetService.uploadFile(this.listToUpload, this.userInfo.Token).subscribe((result: string) => {
this.thisDialogRef.close('close');
this.disableSubmit = false;
},
error => {
if (error instanceof HttpErrorResponse) {
}
else {
}
this.spinnerService.hide();
this.disableSubmit = false;
});}
service.ts
uploadFile (listToUpload:UploadDoc,token: string ) {
let headers= new HttpHeaders({'Authorization':'Bearer ' + token});
const formData: FormData = new FormData();
formData.append('UploadDoc', listToUpload.FileToUpload, listToUpload.FileToUpload.name);
return this.$http
.post(this.endpointUploadFile, formData, {headers:headers})}
web api:
[System.Web.Http.HttpPost]
public HttpResponseMessage UploadList()
{
HttpResponseMessage response = new HttpResponseMessage();
var httpRequest = HttpContext.Current.Request;
//
// -----------------
//
return response;
}

In Facebook with C# /me/accounts with manage_pages permission does not show any pages

I am trying to fetch pages data in Facebook using c# MVC. Even though I give manage_pages permission (Scope) it does not show any pages when I run my code. Here is where pagelist is showing 0
string Accounts = "/me/accounts";
JSONObject pageData = api.Get(Accounts);
var data = pageData.Dictionary["data"];
List<JSONObject> pageList = data.Array.ToList<JSONObject>();
ViewBag.pageList = pageList;
Below is the Code that I tried
public ActionResult returnfromfb()
{
string app_id = "AppID";
string app_secret = "AppSecret";
string scope = "manage_pages,publish_stream,status_update,user_about_me,user_hometown,user_location,email,offline_access";
string code = Request.QueryString["code"];
if (code == null)
{
Response.Redirect(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope));
}
string AccessToken = "";
try
{
if (code != null)
{
string str = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(str);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] Param = Request.BinaryRead(System.Web.HttpContext.Current.Request.ContentLength);
string strRequest = System.Text.Encoding.ASCII.GetString(Param);
req.ContentLength = strRequest.Length;
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
if (strResponse.Contains("&expires"))
strResponse = strResponse.Substring(0, strResponse.IndexOf("&expires"));
AccessToken = strResponse.Replace("access_token=", "");
streamIn.Close();
}
Facebook.FacebookAPI api = new Facebook.FacebookAPI(AccessToken);
string requestEmail = "/me";
JSONObject fbemail = api.Get(requestEmail);
try
{
ViewBag.Email = fbemail.Dictionary["email"].String;
}
catch (Exception ex)
{
//errorLog.setError(ex, "LoginController.SaveFacebookData");
}
string Accounts = "/me/accounts";
JSONObject pageData = api.Get(Accounts);
var data = pageData.Dictionary["data"];
List<JSONObject> pageList = data.Array.ToList<JSONObject>();
ViewBag.pageList = pageList;
foreach (var page in pageList)
{
try
{
var id = page.Dictionary["id"].String;
string request = id;
JSONObject fbobject = api.Get(request);
try
{
ViewBag.BusinessName = fbobject.Dictionary["name"].String;
ViewBag.Address = fbobject.Dictionary["location"].ToDisplayableString();
ViewBag.PhoneNumber = fbobject.Dictionary["phone"].String;
}
catch (Exception ex)
{
//errorLog.setError(ex, "LoginController.SaveFacebookData");
}
}
catch (Exception ex)
{
//errorLog.setError(ex, "LoginController.SaveFacebookData");
}
}
I have Finally managed to get the desired result using #Remodal.js
<head>
<link rel="stylesheet" href="#Url.Content("~/Content/jquery.remodal.css")">
</head>
<body>
<script type="text/javascript" src="#Url.Content("~/Scripts/Home/jquery.remodal.js")"></script>
<div class="remodal" id="page-selector-remodal" data-remodal-id="pageselector">
<p>Please select a facebook page Share </p>
<div id="page-name-container">
<select id="page-name" class="form-control">
</select>
</div>
<a class="remodal-confirm" id="facebookPageSelectSubmit" href="#">OK</a>
<a class="remodal-cancel" id="remodal-cancel" href="#">CANCEL</a>
</div>
<div data-remodal-id="modal-status">
<p id="modal-status-content">
The Account you have selected does not have Email.
</p>
<br>
<a class="remodal-confirm" href="#">OK</a>
</div>
<script type="text/javascript>
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s);
js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
window.fbAsyncInit = function () {
FB.init({
appId: 'YOUR APP ID',
cookie: true, // enable cookies to allow the server to access
// the session
xfbml: true, // parse social plugins on this page
version: 'v2.2' // use version 2.1
});
};
var pageSelector = $('[data-remodal-id=pageselector]').remodal();
var modalstatus = $('[data-remodal-id=modal-status]').remodal();
function statusChangeCallback(response) {
if (response.status === 'connected') {
// Logged into your app and Facebook.
//testAPI();
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
$("#modal-status-content").empty().html(response.status);
modalstatus.open();
}
else {
$("#modal-status-content").empty().html(response.status);
modalstatus.open();
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
document.getElementById('status').innerHTML = 'Please log ' +
'into Facebook.';
}
}
function FacebookHandler() {
FB.login(function (result) {
if (result != null && result.authResponse != null && result.authResponse != undefined) {
facebookPageData = result;
FB.api('/me/accounts', function (accountsResult) {
if (accountsResult != null && accountsResult.data.length != 0) {
//open the remodal here
pageSelector.open();
facebookAccountsData = accountsResult;
var data = accountsResult['data'];
if (data != null) {
for (var i = 0; i < data.length; i++) {
$("#page-name").append('<option value="' + data[i].id + '">' + data[i].name + '</option>');
}
}
unblockUI('body');
$("#flip-container, #feature-container, #branding-container, #intro-arrow-container, #share-container, #copyright-text-container").hide();
$("body").css("padding-right", "0");
}
else {
$("#modal-status-content").empty().html("The Account you have selected does not have any facebook page,<br />Post to Wall.");
modalstatus.open();
pageSelector.open();
unblockUI('body');
}
});
}
else {
$("#modal-status-content").empty().html("Unable to retrieve your details from facebook, try again after sometime.");
modalstatus.open();
unblockUI('body');
}
}, { scope: 'manage_pages, publish_stream' });
}
$("#facebookPageSelectSubmit").on("click", function () {
var facebookpageId = $("#page-name option:selected").val();
if (facebookpageId != null) {
FB.api('/' + facebookpageId, function (identity) {
if (identity != null) {
FB.api('/' + facebookpageId, { fields: 'access_token' }, function (resp) {
if (resp.access_token != null) {
//Get the "resp"(Data) here
}
else {
}
});
}
else {
}
});
}
else {
}
});
</script>
//Finally call the "FacebookHandler()" function on click
</body>

Categories

Resources