C# facebook application - c#

[ My humble request: please don't ignore this question just by adding some reference question link. I read all the reference i can, but i didnt get what i need]
I am trying to make a windows/console application where i need to access the user details offline. So i tried the following code.
String finalRedirectUri = "https://www.facebook.com/dialog/oauth?client_id=" +
_appKey2 + "&redirect_uri=" + _SiteURL + "&scope=email,read_stream";
String GraphUri = "https://graph.facebook.com/oauth/access_token?client_id=" +
_appKey2 + "&redirect_uri=" + _SiteURL + "&scope=email,read_stream";
FacebookClient client = new FacebookClient(_appKey2, _secret2);
FacebookOAuthClient oAuthClient =
new FacebookOAuthClient(FacebookApplication.Current);
oAuthClient.AppId = _appKey2;
oAuthClient.AppSecret = _secret2;
oAuthClient.RedirectUri = new Uri(finalRedirectUri);
String Uri = oAuthClient.GetLoginUrl().ToString();
try
{
dynamic tokenResult =
oAuthClient.ExchangeCodeForAccessToken("offline_access");
}
catch (Exception exp)
{
MessageBox.Show("" + exp.Message);
}
I am always getting error message: " (OAuthException) Invalid verification code format"
I searched many links in stackoverflow and http://developers.facebook.com/docs/authentication/ also but it didnt helped me to find the solution. I dont even know which uri to use.
I am using Visual Studio 2010 [ Please donot simply ignore this question just by marking as duplicate]
Be gentle to me please..

It's possible that if you downloaded the compiled facebook dll (from NuGet for example), that it's badly built. Try downloading the source and compiling it yourself and using that dll.
Here is an example of a post with the same problem.
note even though their problem is giving a different error, it's possible this is precisely the problem you have, as it's in the same function your variant may just be running into another one of their mistakes.
here are two other possible problems you may be having:
Sometimes, redirect uri should be null
OAuth really likes the '/' at the end of a uri

Related

Application.persistenDataPath not working anymore

Since yesterday evening my Application.persistenDataPath is not working anymore on one place in code. I am using it 2 times. On the first place it works on the second it doesnt work anymore...
Maybe a hint for you is, that I saved json very often yesterday. Also I had infinite loops what maybe caused the Application Settings to Crash.
On Android Build it is working fine. (I get the right Path on both usages)
What I have tried below the code
Both in the same Class.
Unity 2021.3.2f
Using Google Firebase
Visual Studio 2022 Community Edition
This the code where it works:
I am saving a Photo to the given Path.
//then Save To Disk as PNG
byte[] bytes = avatarTexture.EncodeToPNG();
var dirPath = Application.persistentDataPath + "/Resources/User/";
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
if (File.Exists(dirPath + "avatar" + ".png"))
{
File.Delete(dirPath + "avatar" + ".png");
}
File.WriteAllBytes(dirPath + "avatar" + ".png", bytes);
saveUserDataAsJson(getUserToken(user.DisplayName, user.Email));
_warningLoginText.text = "";
_confirmLoginText.text = Translation.authManager_login_notification_loginSucceeded;
This is the code where it does not work:
I am saving a JSON File with User Information.
DataSnapshot snapshotYear = taskYear.Result;
_year = Convert.ToInt32(snapshotYear.Value);
FirebaseDatabaseUser tempUser = new FirebaseDatabaseUser(_token, _day, _month, _year);
var json = JsonConvert.SerializeObject(tempUser);
Debug.Log("Can see it in Console");
//After pressing Play Button in Unity
//Editor i get no Debug outprint here
Debug.Log(Application.persistentDataPath);
var folderPath = Application.persistentDataPath + "/Resources/User/";
Debug.Log("Can not see it in Console");
//HERE THE CODE STOPS AND NOTHING HAPPEN
//NO ERROR NO LOG NO FURTHER CODE WORKING
//HERE NOT WORKING ANYMORE
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
if (File.Exists(folderPath + "userdata" + ".json"))
{
File.Delete(folderPath + "userdata" + ".json");
}
File.WriteAllText(folderPath + "userdata" + ".json", json);
I have tried:
rebuild Project Settings
Print the Path in Console it was empty ""
Cleaned GI Cache
Restarted my PC
Cloned the project new
Tried using Application.dataPath (only for debugging tests, not to use it in my code) also not working in Unity Play Mode but on Android it points right to the APK.
First usage (Place in Code where it works) I get Path:
Computer: C:\Users\{user}\AppData\LocalLow\{company}\{app}\Resources\User\
Android: .\Android\data\com.{company}.{app}\...\Resources\User\
Second usage (Place in Code where does not work) I get Path:
Computer: ""
Android: ".\Android\data\com.{company}.{app}\...\Resources\User\"
I hope someone can explain the issue. I cannot solve the problem from myself. Need someone who has more background knowledge.
so the anwer was based on the Help of #derHugo :
Some of the Unity API is using only the Unity main thread. Application.persistentDataPath is one piece of this Unity API elements.
So the problem was, that in the first code snippet i was using the Unity Main Thread, but in the second code snippet i used a Background Thread. Was really easy to fix. Instead of using another thread, i used:
`<myasyncfunction>.ContinueWithOnMainThread(task => {....
//second code snippet
})`
Refactoring tips of this Code:
File.Exists can be removed, it is totally redundant. WriteAllText creates or overwrites the file by default anyway.
The Construction of data paths over and over again makes no sense. Better way is to create public static readonly paths and use them instead.
Hope the Solution of #derHugo can help someone else.
Have a nice Day if you read this :)

Sharp.xmpp - File Transfer (It always get aborted)

I tried using Sharp.xmpp as a library for my console application. When I tried to transfer file, it initiates the file transfer and the receiver can accept it (another client using spark), but right after accepting it through the other client, the file transfer gets aborted. I just followed the sample code in documentation.
client.InitiateFileTransfer(recipient, "path_to_file_to_send", "description of the file", FileTransferCallback);
and here is the callback
static void FileTransferCallback(bool accepted, FileTransfer transfer)
{
Console.WriteLine(transfer.To + " has " + (accepted == true ? "accepted " : "rejected ") + "the transfer of " + transfer.Name + ".");
}
same thing happens on here..
I found
client = listener.AcceptTcpClient(timeout);
in Socks5Server.cs and I think this section causes the problem.
There's an exception which is like this.
Exception : 'System.ArgumentNullException'(System.Core.dll)
it occurs when TcpListener.AcceptTcpClient() run after.
if someone found the solution, please share it.
and Solved!
Client.FileTransferSettings.UseUPnP = true;
Client.FileTransferSettings.ForceInBandBytestreams = true;
add this code to anywhere.

Need simple Powershell output appended to Google sheet

I'm having a very hard time with what I feel should be a simple task. Every week, our team queries VMware vCenter for three pieces of output: VM counts in three different locations. Here is what it looks like:
Name Value
---- -----
locationA 1433
locationB 278
locationC 23
The information is emailed to our team, as well as some of the higher-ups who like to see the data. This is all automated with a Powershell script and Windows Task Scheduler running on a server, no problems.
That data is also placed in a Google sheet. We just append a new row with the date, and copy and paste the data into the three existing columns. It takes 30 seconds, once a week. Seems silly given how little time it takes to copy it over to the Google sheet but I really want to automate that last process using Google Sheets API.
I seem to keep finding and persuing what feel are online wild goose chases, in the Google scripting to accessing and editing Google sheets. I've downloaded and installed the Sheets API libraries, Drive API libraries, the Google .net library, set up the Google developer site, and run through the Google sheets API documentation and OAuth authenticating. I'm using Visual Studio 2013 because I figured that would play the best with Powershell and calling the .net commands.
I have pretty much no coding experience outside of Powershell (if you can call that coding). I can't even figure out how to pull the Google sheet, much less do anything to it. Nothing I've tried is working so far, and for what little time it takes to copy this info manually every week I've already spent so much more time than is probably worth it. I feel like if I can get a handle on this, that would open the door for further Google automation in the future since we operate with a Google domain. At any rate, help is very much appreciated.
Here is my latest scripting attempt in Visual Studio:
using System;
using Google.GData.Client;
using Google.GData.Spreadsheets;
namespace MySpreadsheetIntegration
{
class Program {
static void Main(string[] args)
{
string CLIENT_ID = "abunchofcharacters.apps.googleusercontent.com";
string CLIENT_SECRET = "secretnumber";
string REDIRECT_URI = "https://code.google.com/apis/console";
OAuth2Parameters parameters = new OAuth2Parameters();
parameters.ClientId = CLIENT_ID;
parameters.ClientSecret = CLIENT_SECRET;
parameters.RedirectUri = REDIRECT_URI;
parameters.Scope = SCOPE;
string authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
Console.WriteLine(https://code.google.com/apis/console);
Console.WriteLine("Please visit the URL above to authorize your OAuth "
+ "request token. Once that is complete, type in your access code to "
+ "continue..."));
parameters.AccessCode = Console.ReadLine();
OAuthUtil.GetAccessToken(parameters);
string accessToken = parameters.AccessToken;
Console.WriteLine("OAuth Access Token: " + accessToken);
GOAuth2RequestFactory requestFactory =
new GOAuth2RequestFactory(null, "MySpreadsheetIntegration-v1", parameters);
SpreadsheetsService service = new SpreadsheetsService("MySpreadsheetIntegration-v1");
service.RequestFactory = requestFactory;
var driveService = new DriveService(auth);
var file = new File();
file.Title = "VSI - VM Totals by Service TEST";
file.Description = string.Format("Created via {0} at {1}", ApplicationName, DateTime.Now.ToString());
file.MimeType = "application/vnd.google-apps.spreadsheet";
var request = driveService.Files.Insert(file);
var result = request.Fetch();
var spreadsheetLink = "https://docs.google.com/spreadsheets/d/GoogleDoc_ID";
Console.WriteLine("Created at " + spreadsheetLink);
End Class;
End Namespace;
}
}
}
For anyone still following this, I found a solution. I was going about this entirely the wrong way (or at least a way that I could comprehend). One solution to my issue was to create a new Google Script that only accessed my email once a week (after we got the report) and teased out everything but the data I was looking for and sent it to the Google spreadsheet.
Here's the script:
function SendtoSheet(){
var threads = GmailApp.search("from:THESENDER in:anywhere subject:THESUBJECTOFTHEEMAILWHICHNEVERCHANGES")[0];
var message = threads.getMessages().pop()
var bodytext = message.getBody();
counts = []
bodytext = bodytext.split('<br>');
for (var i=0 ; i < bodytext.length; i++){
line = bodytext[i].split(':');
if (line.length > 0){
if (!isNaN(line[1])){counts.push(line[1]);}}}
var now = new Date()
counts.unshift(Utilities.formatDate(now, 'EST', 'MM/dd/yyyy'))
var sheet = SpreadsheetApp.openById("GoogleDocID")
sheet = sheet.setActiveSheet(sheet.getSheetByName("Data by Week"))
sheet.appendRow(counts)
}
That Counts array contains the magic to extract the numeric data by breaking up by line breaks and :'s. Works perfectly. It didn't involve figuring out how to use Visual Studio, or the .net Google libraries, or editing the running PowerShell script. Clean and easy.
Hope this helps someone.

How to get user info using C# FacebookSDK

I'm trying to get user info using the FacebookSDK, but its not working.
This is what i try to do:
var fb = new FacebookClient("my_access_code");
dynamic result = fb.Get("me");
var name = result.name;
MessageBox.Show("Hi " + name);
This is not working, because fb hase no get method. But every tutorial and code snippets i looked at are using get.
Is this code deprecated? If this is whats the new method of getting info?
So, as we established in the comments - for Windows Phone 8 there are async calls that should be used instead of the old Get call. That's why you're not seeing the Get call, but the GetTaskAsync call. For this simple example, you use it the same way
dynamic result = await fb.GetTaskAsync("me");
var name = result.name;
MessageBox.Show("Hi " + name);
Other examples may vary. More about async calls with Facebook C# can be found in the official documentation, but that's not exactly for the Windows Phone 8, but Windows Phone 7 which used a different async pattern. Still, it may be helpful to you. There's a link to a supposedly more updated documentation for async/await calls but for some reason I'm seeing a 'Page not found' error.
try this instead
var fb = new FacebookClient("my_access_code");
dynamic result = await fb.GetTaskAsync("/me");
var name = result.name;
MessageBox.Show("Hi " + name);

C# HASP login code

I want to try out hasp api to build my custom security behaviour but when I use code generated by Sentinel HASP ToolBox it does not work.
I pasted this code from Toolbox to onLoad Form method:
HaspFeature feature = HaspFeature.Default;
string vendorCode =
"AzIceaqfA1hX5wS+M8cGnYh5ceevUnOZIzJBbXFD6dgf3tBkb9cvUF/Tkd/iKu2fsg9wAysYKw7RMAsV" +
"vIp4KcXle/v1RaXrLVnNBJ2H2DmrbUMOZbQUFXe698qmJsqNpLXRA367xpZ54i8kC5DTXwDhfxWTOZrB" +
"rh5sRKHcoVLumztIQjgWh37AzmSd1bLOfUGI0xjAL9zJWO3fRaeB0NS2KlmoKaVT5Y04zZEc06waU2r6" +
"AU2Dc4uipJqJmObqKM+tfNKAS0rZr5IudRiC7pUwnmtaHRe5fgSI8M7yvypvm+13Wm4Gwd4VnYiZvSxf" +
"8ImN3ZOG9wEzfyMIlH2+rKPUVHI+igsqla0Wd9m7ZUR9vFotj1uYV0OzG7hX0+huN2E/IdgLDjbiapj1" +
"e2fKHrMmGFaIvI6xzzJIQJF9GiRZ7+0jNFLKSyzX/K3JAyFrIPObfwM+y+zAgE1sWcZ1YnuBhICyRHBh" +
"aJDKIZL8MywrEfB2yF+R3k9wFG1oN48gSLyfrfEKuB/qgNp+BeTruWUk0AwRE9XVMUuRbjpxa4YA67SK" +
"unFEgFGgUfHBeHJTivvUl0u4Dki1UKAT973P+nXy2O0u239If/kRpNUVhMg8kpk7s8i6Arp7l/705/bL" +
"Cx4kN5hHHSXIqkiG9tHdeNV8VYo5+72hgaCx3/uVoVLmtvxbOIvo120uTJbuLVTvT8KtsOlb3DxwUrwL" +
"zaEMoAQAFk6Q9bNipHxfkRQER4kR7IYTMzSoW5mxh3H9O8Ge5BqVeYMEW36q9wnOYfxOLNw6yQMf8f9s" +
"JN4KhZty02xm707S7VEfJJ1KNq7b5pP/3RjE0IKtB2gE6vAPRvRLzEohu0m7q1aUp8wAvSiqjZy7FLaT" +
"tLEApXYvLvz6PEJdj4TegCZugj7c8bIOEqLXmloZ6EgVnjQ7/ttys7VFITB3mazzFiyQuKf4J6+b/a/Y";
Hasp hasp = new Hasp(feature);
HaspStatus status = hasp.Login(vendorCode);
if (HaspStatus.StatusOk != status)
{
//handle error
Application.Exit();
}
Next I inserted demo HASP HL Net key 10 to try it out. I always get error while using this code in Visual Studio sample project but when I try it in ToolBox then I receive proper answer(HASP_STATUS_OK). Certainly I included reference to hasp .net assembly and added namespace.
What is the reason, that it can't login to hasp hl key from runtime api in c#?
I found solution. First I had to include reference to hasp_windows_demo.dll because hasp_net_windows.dll is just a wrapper lib for hasp_windows_demo.dll. Second: I used VirtualBox to test so when I plugged dongle to usb port usb virtualbox driver crashed - needed reinstall(Mac/Linux issue only).

Categories