Desktop app to create event through a facebook page - c#

I have a facebook fanpage and I am trying to make a desktop application which can create events through this fanpage, however I'm having trouble understanding how the story goes with acces tokens, id, user permissions... If I am not mistaken once I have the accesstoken I can create an event using the facebookSDK from codeplex and the following function:
public string CreateEvent(string accessToken)
{
FacebookClient facebookClient = new FacebookClient(accessToken);
Dictionary<string, object> createEventParameters = new Dictionary<string, object>();
createEventParameters.Add("name", "My birthday party )");
createEventParameters.Add("start_time", DateTime.Now.AddDays(2).ToUniversalTime().ToString());
createEventParameters.Add("end_time", DateTime.Now.AddDays(2).AddHours(4).ToUniversalTime().ToString());
createEventParameters.Add("owner", "Balaji Birajdar");
createEventParameters.Add("description", " ( a long description can be used here..)");
//Add the "venue" details
JsonObject venueParameters = new JsonObject();
venueParameters.Add("street", "dggdfgg");
venueParameters.Add("city", "gdfgf");
venueParameters.Add("state", "gfgdfgfg");
venueParameters.Add("zip", "gfdgdfg");
venueParameters.Add("country", "gfdgfg");
venueParameters.Add("latitude", "100.0");
venueParameters.Add("longitude", "100.0");
createEventParameters.Add("venue", venueParameters);
createEventParameters.Add("privacy", "OPEN");
createEventParameters.Add("location", "fhdhdfghgh");
Add the event logo image
FacebookMediaObject logo = new FacebookMediaObject()
{
ContentType = "image/jpeg",
FileName = #"C:\logo.jpg"
};
logo.SetValue(File.ReadAllBytes(logo.FileName));
createEventParameters["#file.jpg"] = logo;
JsonObject resul = facebookClient.Post("/me/events", createEventParameters) as JsonObject;
return resul["id"].ToString();
}
Do I always need an application to do this?
I have a test application and I can get an access token from it using:
public string getToken(string strURL)
{
string strURL = "https://graph.facebook.com/oauth/access_token?client_id=149585851811979&client_secret=blablablablabalalbal&grant_type=client_credentials";
Uri Uri = new Uri(strURL);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Uri);
HttpWebResponse HWResponse = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(HWResponse.GetResponseStream());
string token = sr.ReadToEnd();
sr.Close();
token = token.Replace("access_token=", "");
return token;
}
I tried it like this but it obviously didn't work.
So my questions:
Do I always need an application? If yes, how do i connect it to my existing fan page?
Where do I set my user permissions? And how do I then login with the user?
I just think the documentation is a bit vague :s Sorry if my questions are stupid.
Any help/pseudocode is appreciated!

I am using BatchFB to create events in an App Engine app, it works for me, here is the code
// Some Date math that is from my App, but I am using Joda DateTime for output
// formatting.. I have found that if the start_time is malformed by FB standards it will
// to create an event, and give you an eventid, but the event never really gets created.
long hour = { your data }
DateTime start_time = new DateTime(d).plusHours((int)hour);
String stime = start_time.toString(ISODateTimeFormat.dateTime());
Batcher batcher = new FacebookBatcher(token);
Later<NewFeedItem> event = batcher.post(
"/events", NewFeedItem.class,
new Param("name", edata.getStringProperty(EventData.Schema.Name)),
new Param("start_time", stime )
);
long eventid = event.get().id;
I generate token on the client side with FBJS, and pass it to the server.
NewFeedItem is just a class defining an long variable, see batchFB's site..
With that said, I am thinking of switching to RestFB because I can't get BatchFB to support binary parameters with trying to post images. Also RestFB is documented better.. They seem to be related projects and refer to each other often.
I am not adding in Venue data yet, but I have read that for the GraphAPI to work, they need to be top level parameters. i.e. add in street, city, state at the same level as location and privacy..
When you try to read the event it will come in the venue parameter, but it needs to be top level when creating.. Also fallback to just using name and start_time, the only required parameters and add to that once it's working.
-John Gentilin

Related

How to create new AutoML DataSet for simple classification (C#)

As part of ML automation process I want to dynamically create new AutoML model. I'm using C# (.net framework) and Google.Cloud.AutoML.V1.
After trying to run CreateDataSet code:
var autoMlClient = AutoMlClient.Create();
var parent = LocationName.FromProjectLocation(_projectId, _locationId);
var dataset = new Google.Cloud.AutoML.V1.Dataset();
dataset.DisplayName = "NewDataSet";
var response = autoMlClient.CreateDataset(parent, dataset);
I get the following error:
Field: dataset.dataset_metadata; Message: Required field not set
According to this user manual I should set Dataset Metadata Type, but the list contains only specific types of classifications (Translation/ImageClassifications etc.), I can't find a simple classification type.
How do I create a simple classification data set with the API ? in the AutoML UI its just with a simple button click ("NEW DATASET") - and have to provide only name & region - no classification type.
I also tried to set:
dataset.TextClassificationDatasetMetadata =
new TextClassificationDatasetMetadata() { ClassificationType = ClassificationType.Multiclass };
But I was unable to import data to it (got too many errors of invalid inputs from the input CSV file), I guess its related to the reason that the input format is not suitable for Text Classification.
UPDATE
I've just notice that the Nuget works with AutoML v1 but v1 beta does contains TablesDatasetMetadata Dataset Metadata Type for normal classifications. I'm speechless.
I also experienced this scenario today while creating a dataset using the NodeJS client. Since the Google AutoML table service is in the beta level you need to use the beta version of the AutoML client. In the Google cloud documentation they have used the beta client to create a dataset.
In NodeJS importing the beta version require('#google-cloud/automl').v1beta1.AutoMlClient instead of importing the normal version (v1) require('#google-cloud/automl').v1 worked for me to successfully execute the create dataset functionality.
In C# you can achieve the same through a POST request. Hope this helps :)
After #RajithaWarusavitarana comment, and my last question update , below is the code that did the trick. The token is being generated by GoogleClientAPI nuget and AutoML is handled by REST.
string GcpGlobalEndPointUrl = "https://automl.googleapis.com";
string GcpGlobalLocation = "us-central1"; // api "parent" parameter
public string GetToken(string jsonFilePath)
{
var serviceAccountCredentialFileContents = System.IO.File.ReadAllText(jsonFilePath);
var credentialParameters = NewtonsoftJsonSerializer.Instance.Deserialize<JsonCredentialParameters>(serviceAccountCredentialFileContents);
var initializer = new ServiceAccountCredential.Initializer(credentialParameters.ClientEmail)
{
Scopes = new List<string> { "https://www.googleapis.com/auth/cloud-platform" }
};
var cred = new ServiceAccountCredential(initializer.FromPrivateKey(credentialParameters.PrivateKey));
string accessToken = cred.GetAccessTokenForRequestAsync("https://oauth2.googleapis.com/token").Result;
return accessToken;
}
public void GetDataSetList(string projectId, string token)
{
var restClient = new RestClient(GcpGlobalEndPointUrl);
var createDataSetReqUrl = $"v1beta1/projects/{projectId}/locations/{GcpGlobalLocation}/datasets";
var createDataSetReq = new RestRequest(createDataSetReqUrl, Method.GET);
createDataSetReq.AddHeader("Authorization", $"Bearer {token}");
var createDatasetResponse = restClient.Execute(createDataSetReq);
createDatasetResponse.Dump();
}
I took the token generation code from google-api-dotnet-client Test File

Send xsl doc in body of email

Programming would be much easier without users...
What I really need to be able to do is:
Put the content of a web page (including styles) into the body of an email and also set the subject.
OR
Send the current user an email containing the body of a web page.
I really don't care how this is implemented -- server or client side. I've not come up with any good way of client side besides trying to push the web page into the clipboard for the users to then paste into their email.
App Background
I wrote a web site using c#, ts, angular. The site manages xml documents.
The users can select a document and click the "Human Readable" button or the "XML" button. The "Human Readable" is xml with xsl to make it look pretty for the humans. The XML button is apparently for non-humans.
The "Human Readable" version opens in another browser tab.
The users want a new "email" button for emailing the human readable. The person clicking the email button has access to my web site but the recipient may not.
I've attempted educating my users to do Ctrl+A, Ctrl+C, open email, Ctrl+V but this is beyond most of their capabilities.
I have tried so many different ways to accomplish this and all have failed.
I currently do a mailto link which opens their email and the body contains a link to the Human Readable.
Here's what I've tried so far -- this may not be a conclusive list of my attempts as I've been at this for a few days now.
I've tried putting a button in the human readable (xsl with javascript) in an attempt to copy the resulting html into the clipboard for the users to paste.
A button on the web site to scrape an iFrame into the clipboard
Many iterations of javascript copy/paste techniques
a c# controller that does a ReadAsStringAsync().Result function (which I will post below because I like that solution the best so far...
Option #4 I'm partial to and I got almost working -- if it weren't for that pesky xsl not getting formatted it would probably work. My results are the data being presented without xml tags and no styles.
[ActionName("PostEmailHumanReadable")]
public void EmailHumanReadable(List<DocumentVM> documents)
{
foreach (var document in documents)
{
var docId = document.document.DocId;
var docTypeId = document.document.DocTypeId;
var co = string.Empty;
var order = string.Empty;
var name = string.Empty;
var po = string.Empty;
// get the data for the subject line
using (var efUoW = new EFUnitOfWork(EDIEnvironment.EDIEnvironment.Instance.ConnectionString))
{
var doc = efUoW.DocumentRepository.GetById(docId);
co = doc.CompanyId.ToString();
var orders = efUoW.DocumentOrderRepository.GetByDocumentID(docId).ToList();
if (!string.IsNullOrEmpty(doc.Source_Order))
order = doc.Source_Order;
else
order = "n/a";
foreach (var o in orders)
order += string.Format("{0} ", o.OrderId);
//order = string.Join(",", doc.DocumentOrders.Select(q => q.OrderId).ToList());
name = doc.BillToName;
name = doc.PurchaseOrder;
}
var subject = string.Format("{0}, {1}, {2}, {3}", co, order, name, po);
// get the human readable
var hrResponse = GetFile(docId, docTypeId);
var hrText = hrResponse.Content.ReadAsStringAsync().Result;
// format the url
var url = string.Format("<a href='/api/Documents/Getfile?DocId={0}&DocTypeId={1}'>click here to open the jEDI Human Readable</a><br><br>", docId, docTypeId);
// find the current user's email address
var users = new List<string>();
users.Add(AppUser.ADUserName);
//var to = EmailUtility.GetEmailID(users);
// and finally send the email
EmailUtility.SendEmail(EmailUtility.GetEmailID(users), null, subject, url + hrText);
}
}
[ActionName("GetFile")]
public HttpResponseMessage GetFile(int DocId, int DocTypeId)
{
if (DocTypeId == (int)DocumentTypeEnum.EDI850)
{
using (var efUoW = new Factory_UOW().EF_UOW())
{
var doc = efUoW.DocumentRepository.GetById(DocId);
var xdoc = XDocument.Parse(doc.Message);
var proc = new XProcessingInstruction("xml-stylesheet", "type='text/xsl' href='/EDI850.xsl'");
xdoc.Root.AddBeforeSelf(proc);
var response = new HttpResponseMessage();
response.Content = new System.Net.Http.StringContent(xdoc.ToString());
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/xml");
response.Content.Headers.Add("X-UA-Compatible", "IE=edge");
return response;
}
I would be very grateful for any assistance in getting this to work.
And, yes, I know I shouldn't do the Async().Result -- blocking and all that... Let's just get this working first, shall we?

Cache player with GameSparks and Unity

I am new to gamesparks, but so far I have set up a login/register function, which works like it should, but... How do I ensure that the user don't have to login next time he or she opens the app?
I found this in which I read that I can just run this:
GameSparkssApi.isAuthenticated().
First off all, in all other tutorials it states that it should be: GameSparks.Api.xxxx. Even when trying this I do not find isAuthenticated() anywhere.
GameSparks.Api.isAuthenticated();
I am hoping that someone can cast some light on this.
You can use Device Authentication for this purpose. This method of auth sets an access token for the device you are on. This token is stored and the client and gotten in the request. these requests are structured like so:
new GameSparks.Api.Requests.DeviceAuthenticationRequest()
.SetDeviceId(deviceId)
.SetDeviceModel(deviceModel)
.SetDeviceName(deviceName)
.SetDeviceOS(deviceOS)
.SetDeviceType(deviceType)
.SetDisplayName(displayName)
.SetOperatingSystem(operatingSystem)
.SetSegments(segments)
.Send((response) => {
string authToken = response.AuthToken;
string displayName = response.DisplayName;
bool? newPlayer = response.NewPlayer;
GSData scriptData = response.ScriptData;
var switchSummary = response.SwitchSummary;
string userId = response.UserId;
});
You can find more on this method in our documentation: https://api.gamesparks.net/#deviceauthenticationrequest
Regards Patrick, GameSparks.

Google Analytics API in C# -Execution of request failed: https://www.google.com/analytics/feeds/accounts/default

i want to access Google analytic data and i got samples from Google data API SDK. but these coding does not working and throws exception
Execution of request failed: https://www.google.com/analytics/feeds/accounts/default
so i found the reason for this is Google updated it's to v3.0. i searched updated coding for the C#, but i couldn't find solution for this.
i have same problem as this, but with C#.
Exception thrown when using GData .NET Analytics API
i tried coding with doing changes as follows as it says in Google developer - https://developers.google.com/analytics/resources/articles/gdata-migration-guide#appendix_a
string userName = this.Username.Text;
string passWord = this.Password.Text;
AnalyticsService service = new AnalyticsService("AnalyticsSampleApp");
service.setUserCredentials(userName, passWord);
string googleAccountWebId = "AIXXXXXXXXXXXXXXXXXXXXXXXXXXX";
string profileFeedUrl = "https://www.googleapis.com/analytics/v2.4/data?key=" + googleAccountWebId;
DataQuery query2 = new DataQuery(profileFeedUrl);
query2.Ids = "12345678";
query2.Metrics = "ga:visits";
query2.Sort = "ga:visits";
query2.GAStartDate = DateTime.Now.AddMonths(-1).AddDays(-2).ToString("2011-08-01");
query2.GAEndDate = DateTime.Now.ToString("2013-09-01");
query2.StartIndex = 1;
DataFeed data = service.Query(query2);
foreach (DataEntry entry in data.Entries)
{
string st=entry.Metrics[0].Value;
}
but even i change this it throws exception in
DataFeed data = service.Query(query2);
this line. exception is as follows:
Execution of request failed: https://www.googleapis.com/analytics/v2.4/data?key=AIXXXXXXXXXXXXXXXXXXXXXX-8&start-index=1&end-date=2013-09-01&ids=12345678&metrics=ga:visits&sort=ga:visits&start-date=2011-08-01
i'm using following DLL
Google.GData.Analytics.dll
Google.GData.Client.dll
Google.GData.Extensions.dll
My Questions :
how can i correct this error?
how can i access Google analytic data? is this correct? or else what is the way to doing it??
for a example i want to get available ProfileId and their values. (Title and Page views)
Analytics Account:
I am assuming you have an analytics account already if you don't then create one, and sign up your domain here:
http://www.google.com/intl/en/analytics/
To get your API Key do this:
Follow the instructions on https://developers.google.com/analytics/resources/articles/gdata-migration-guide (Create a Project in the Google APIs Console) to generate your key Once you have it set it as part of the querystring to request to Google Analytics service, in this case:
YourAPIkEStringabcdefghijklmno
To get the profileId (Ids on the code) you should do this:
Log into your analytics account, select the desired domain on your list (blue link) click on the administrator button and on the profiles tab find the profile
configuration subtab, right there you will find the profile id in this case the eight characters long id:
12345678
Here you have some C# code to help you getting the number of visits for that Id:
public string VisitsNumber()
{
string visits = string.Empty;
string username = "youremailuser#domain.com";
string pass = "yourpassword";
string gkey = "?key=YourAPIkEYYourAPIkEYYourAPIkEYYourAPIkE";
string dataFeedUrl = "https://www.google.com/analytics/feeds/data" + gkey;
string accountFeedUrl = "https://www.googleapis.com/analytics/v2.4/management/accounts" + gkey;
AnalyticsService service = new AnalyticsService("WebApp");
service.setUserCredentials(username, pass);
DataQuery query1 = new DataQuery(dataFeedUrl);
query1.Ids = "ga:12345678";
query1.Metrics = "ga:visits";
query1.Sort = "ga:visits";
//You were setting 2013-09-01 and thats an invalid date because it hasn't been reached yet, be sure you set valid dates
//For start date is better to place an aprox date when you registered the domain on Google Analytics for example January 2nd 2012, for an end date the actual date is enough, no need to go further
query1.GAStartDate = new DateTime(2012, 1, 2).ToString("yyyy-MM-dd");
query1.GAEndDate = DateTime.Now.ToString("yyyy-MM-dd");
query1.StartIndex = 1;
DataFeed dataFeedVisits = service.Query(query1);
foreach (DataEntry entry in dataFeedVisits.Entries)
{
string st = entry.Title.Text;
string ss = entry.Metrics[0].Value;
visits = ss;
}
return visits;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Response.Write("Visits:" + this.VisitsNumber());
}
}
Since the 2.4 API is not so flexible anymore, I have another post here hacking it to get the profile Id:
Getting an specific ProfileId from registered Accounts using GData .NET Analytics API 2.4 if you need to convert the code to C# you can use the Telerik converter: http://converter.telerik.com/
I think this suffice to use the 2.4 API. If you need extra help let me know.

C#-Facebook-SDK WP7, the principles of how Facebook works?

Apologies if this is somewhere, but I'm struggling to find the details I need for wp7.
I have created the application on Facebook as required, and am retrieving an access token. The following code posts to Facebook but I cannot get a response, nor can I work out how to monitor the response?
public bool fbUpload(string accessToken, Picture pic)
{
try
{
Stream s = null;
s = PicturesLoader.LoadFileFromStorage(pic.Url);
//Sets the byte array to the correct number of bytes
byte[] imageData = new byte[s.Length];
s.Read(imageData, 0, System.Convert.ToInt32(s.Length));
FacebookApp app = new FacebookApp();
IDictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("access_token", accessToken);
parameters.Add("message", "TEST - WP7 application [upload pic and comment on wall...]");
var mediaObject = new FacebookMediaObject { FileName = pic.Name, ContentType = "image/jpeg" };
mediaObject.SetValue(imageData);
parameters["source"] = mediaObject;
FacebookAsyncResult postResult;
FacebookAsyncCallback fbCB = new FacebookAsyncCallback();
app.PostAsync(parameters, fbCB);
return true;
}
catch (InvalidCastException ex)
{
return false;
}
}
The other question I have, is how do you allow users to allow access based upon their own Facebook account. I want to store a user's account details so they only have to set up the account details once, and then they can use my phone app with having to sign in?
You can handle the post result something like this:
FacebookAsyncCallback callBack = new FacebookAsyncCallback(postResult);
fbApp.PostAsync(parameters, args, callBack);
private void postResult(FacebookAsyncResult asyncResult)
{
// Do something with asyncResult here;
}
Regarding the second question, you must ask for permissions to access this data.
You usually do that in the FacebookOAuthClient.GetLoginUrl(<appId>, null, <permissions>) method call.
Once that's done, you can store the files you have permissions to locally in your app.

Categories