GooglePlus Authentication in Windows Phone 8.1 - c#

I am writing a Windows Phone 8.1 App (WINRT).
How to do GooglePlus Authentication (SignIn via GooglePlus) in Windows Phone 8.1 App** without using MVVM/MVC**?
I used Web Authentication via Webbrowser control in Windows Phone 8.0 App but Windows Phone 8.1 WebView Control does not have Navigating event.
Can anyone help me?
According to Mr. Filip Skakun, I wrote:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;
using Windows.Data.Json;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Security.Authentication.Web;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Web.Http;
namespace webbrokerFinal
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
Connect();
this.NavigationCacheMode = NavigationCacheMode.Required;
}
string FacebookClientIDString = "000000000000";
string FacebookCallbackUrlString = " https://www.facebook.com/connect/login_success.html";
private void Connect()
{
try
{
String FacebookURL = "https://www.facebook.com/dialog/oauth?client_id=" + FacebookClientIDString + "&redirect_uri=" + Uri.EscapeUriString(FacebookCallbackUrlString) + "&scope=read_stream&display=popup&response_type=token";
System.Uri StartUri = new Uri(FacebookURL);
System.Uri EndUri = new Uri(FacebookCallbackUrlString);
WebAuthenticationBroker.AuthenticateAndContinue(StartUri, EndUri, null, WebAuthenticationOptions.None);
}
catch (Exception Error) >> The remote procedure call failed. (Exception from HRESULT: 0x800706BE)
{
//
// Bad Parameter, SSL/TLS Errors and Network Unavailable errors are to be handled here.
//
}
}
public async void ContinueWebAuthentication(WebAuthenticationBrokerContinuationEventArgs args)
{
WebAuthenticationResult result = args.WebAuthenticationResult;
if (result.ResponseStatus == WebAuthenticationStatus.Success)
{
await GetFacebookUserNameAsync(result.ResponseData.ToString());
}
else if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
{
}
else
{
}
}
private async Task GetFacebookUserNameAsync(string webAuthResultResponseData)
{
//Get Access Token first
string responseData = webAuthResultResponseData.Substring(webAuthResultResponseData.IndexOf("access_token"));
String[] keyValPairs = responseData.Split('&');
string access_token = null;
string expires_in = null;
for (int i = 0; i < keyValPairs.Length; i++)
{
String[] splits = keyValPairs[i].Split('=');
switch (splits[0])
{
case "access_token":
access_token = splits[1]; //you may want to store access_token for further use. Look at Scenario5 (Account Management).
break;
case "expires_in":
expires_in = splits[1];
break;
}
}
//Request User info.
HttpClient httpClient = new HttpClient();
string response = await httpClient.GetStringAsync(new Uri("https://graph.facebook.com/me?access_token=" + access_token));
JsonObject value = JsonValue.Parse(response).GetObject();
string facebookUserName = value.GetNamedString("name");
}
}
}
But giving me error:
The remote procedure call failed. (Exception from HRESULT: 0x800706BE)

I'd start with WebAuthenticationBroker. It's a sort of wrapper around WebView you use for all OAuth.

Related

lavalink not working when making discord bot with DSharpPlus. not throwing any errors

command class, no errors when running
using DSharpPlus;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using DSharpPlus.Lavalink;
namespace MusicBot
{
public class MediaCommands : BaseCommandModule
{
[Command("join"), Description("joins user voice channel")]
public async Task JoinVC(CommandContext ctx, DiscordChannel chn)
{
var lava = ctx.Client.GetLavalink();
if (!lava.ConnectedNodes.Any())
{
await ctx.RespondAsync("The Lavalink connection is not established");
return;
}
var node = lava.ConnectedNodes.Values.First();
if (chn.Type != ChannelType.Voice)
{
await ctx.RespondAsync("Not a valid voice channel");
return;
}
await node.ConnectAsync(chn);
await ctx.RespondAsync($"Joined {chn}");
}
program class no error when running
using System;
using DSharpPlus;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using DSharpPlus.CommandsNext;
using DSharpPlus.Lavalink;
using DSharpPlus.Net;
using LortBasic;
using LortMusic;
namespace Lort
{
class Program
{
static void Main(string[] args)
{
MainAsync().GetAwaiter().GetResult();
}
static async Task MainAsync()
{
var LortBot = new DiscordClient(new DiscordConfiguration()
{
Token = "mytoken",
TokenType = TokenType.Bot,
Intents = DiscordIntents.All,
MinimumLogLevel = LogLevel.Debug
});
//lavalink
var endpoint = new ConnectionEndpoint
{
Hostname = "127.0.0.1",
Port = 25565
};
var lavalinkconfig = new LavalinkConfiguration
{
Password = "youshallnotpass",
RestEndpoint = endpoint,
SocketEndpoint = endpoint,
};
var lavalink = LortBot.UseLavalink();
await LortBot.ConnectAsync();
await lavalink.ConnectAsync(lavalinkconfig);
await Task.Delay(-1);
I'm following this guide to make a discord bot with c# using DSharpPlus https://dsharpplus.github.io/articles/audio/lavalink/setup.html and everything works up until trying to get the bot to join a voice channel. it has admin rights and no errors in lavalink console, bot console, vs, none anywhere. nothing happens though... at all

opening sap and then proceeding to login screen through c# Automation

I am trying to open sap and connect to the gui using the following code . I Had to remove the earlier post due to some mistakes in post . I want to open sap logon 730 screen and then proceed to logon screen where i want to login using some credentials.I am getting some errors of connection entry point not found in the first code named opensap . login is working now. BUt still i cant make the SapBOX screen automatically process to the login screen. Please help in the code . Any help will be highly appreciated . Thanks
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SAPFEWSELib;
using SapROTWr;
using AVTAR.SAPLibrary;
using AVTAR.CustomLibrary;
namespace AvatarTest1 {
public class Sap {
public static GuiApplication SapGuiApp { get; set; }
public static GuiConnection SapConnection { get; set; }
public static GuiSession SapSession { get; set; }
public static void openSap(string env) {
Sap.SapGuiApp = new GuiApplication();
string connectString = null;
if (env.ToUpper().Equals("DEFAULT")) {
connectString = "1.0 Test ERP (DEFAULT)";
//connectString = "ASHOST = n7p.naan.as.com SYSNR = N7P
CLIENT =
460 _USER = ***** PASSWD = ****";*******";
} else {
connectString = env;
}
Sap.SapConnection = Sap.SapGuiApp.OpenConnection(connectString,
Sync: true); //creates connection
//Sap.SapSession = (GuiSession)Sap.SapConnection.Sessions.Item(0);
//creates the Gui session off the connection you made
}
public void Login(string userId,string pass,string clientid) {
try {
for (int i = 0; i <= 50; i++) {
Sap.SapSession = SapGuiApp.ActiveSession;
}
// System.Diagnostics.Process.Start(#"C:\Program
Files\SAP\FrontEnd\SAPgui\saplogon.exe");
GuiTextField Clientfield =
(GuiTextField)SapSession.ActiveWindow.FindById("wnd[0] / usr / txtRSYST -
MANDT");
GuiTextField UserIDField =
(GuiTextField)SapSession.ActiveWindow.FindById("wnd[0]/usr/txtRSYST-BNAME");
GuiTextField PassField =
(GuiTextField)SapSession.ActiveWindow.FindById("wnd[0]/usr/pwdRSYST-BCODE");
//GuiTextField LanguageField =
(GuiTextField)SapSession.ActiveWindow.FindById("wnd[0]/usr/txtRSYST-BNAME");
Clientfield.SetFocus();
Clientfield.Text = clientid;
UserIDField.SetFocus();
UserIDField.Text = userId;
PassField.SetFocus();
PassField.Text = pass;
//Sap.SapSession ssn= new SapSession.FindById("wnd[0]")
GuiButton enter =
(GuiButton)SapSession.ActiveWindow.FindById("wnd[0]");
enter.Press();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
In your Code you commented out "System.Diagnostics.Process.Start(#"C:\Program
Files\SAP\FrontEnd\SAPgui\saplogon.exe");"
Go with this aproach, but use "sapshcut.exe" from the same Folder instead!
(this will be available on the most systems)
In this case it could be as simple as that:
string strProg="C:\Program Files\SAP\FrontEnd\SAPgui\sapshcut.exe";
string strParam="-system=N7P -client=460 -user=youruser -password=yourpassword -language=EN";
System.Diagnostics.Process.Start(strProg,strParam);
Find an (VBA)Examle with some pre-Tests on the Commanline at trouble using excel macro for access to sap
Hope this will do ist for you!

Using Google shortenurl API to make short urls

I am trying to use google shorten url to shorten a lot of urls for our project and keep getting an HTTPRequestException unhandled error. The first time I ran it it was asking to locate a .cs file which was not there so I am guessing it is due to that. I just used nugget installer to get this in visual studio. Any ideas?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.Apis.Urlshortener.v1;
using Google.Apis.Oauth2;
using Google.Apis.Services;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
namespace ShortenURL
{
class Program
{
static void Main(string[] args)
{
var originalURL = "https://www.google.com/maps/place/Desert+Christian+Schools/#32.2367293,-110.8339121,16.75z/data=!4m7!1m4!3m3!1s0x86d66f1806d996d7:0xe8ac20e8cebb38b9!2s7525+E+Speedway+Blvd,+Tucson,+AZ+85710!3b1!3m1!1s0x86d66f1806d996d7:0x7b90764e4e6a25d8";
string shortUrl = Shorten(originalURL);
Console.WriteLine(shortUrl);
Console.WriteLine("FINISHED");
Console.ReadLine();
}
private const string key = "AIzaSyB3pfstkvAZzEVOy4dNHaKTuNmtDaG3XsI";
public static string Shorten(string url)
{
UrlshortenerService service = new UrlshortenerService(new BaseClientService.Initializer()
{
ApiKey = key,
ApplicationName = "ShortenUrlAHLI"
});
var m = new Google.Apis.Urlshortener.v1.Data.Url();
m.LongUrl = url;
return service.Url.Insert(m).Execute().Id;
}
}
}
//The code workable in my case :)
//VS2017
private static string shorten(string url)
{
UrlshortenerService service = new UrlshortenerService(
new BaseClientService.Initializer() {
ApiKey = "<google-api-key>",
ApplicationName = "<google-app-id>", });
var m = new Google.Apis.Urlshortener.v1.Data.Url();
m.LongUrl = url;
return service.Url.Insert(m).Execute().Id;
}

How to integrate Google Bigquery with c# console application

If it is possible to integrate Google big query with C# console application?.
If yes how we can do, i searched over internet i could not find proper answer for that.
I want connection string format? I have created Client ID from Google Developer console how authentication has done? It is one time configuration or every time we need to login in google account to authenticate.
If there is any sample application to connect sample data it would be helpful.
Thanks,
Selvakumar S
Here's a working sample based on another question in StackOverflow:
using DotNetOpenAuth.OAuth2;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Bigquery.v2;
using Google.Apis.Bigquery.v2.Data;
using Google.Apis.Util;
using System;
using System.Diagnostics;
using System.Collections.Generic;
namespace BigQueryConsole
{
public class BigQueryConsole
{
// Put your client ID and secret here (from https://developers.google.com/console)
// Use the installed app flow here.
// Client ID looks like "9999999.apps.googleusercontent.com"
static string clientId = "YOURCLIENTID";
static string clientSecret = "YOURSECRET";
// Project ID is in the URL of your project on the APIs Console
// Project ID looks like "999999";
static string projectId = "YOURPROJECTID";
// Query in SQL-like form
static string query = "SELECT state, count(*) from [publicdata:samples.natality] GROUP BY state ORDER BY state ASC";
public static void Main(string[] args)
{
// Register an authenticator.
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
provider.ClientIdentifier = clientId;
provider.ClientSecret = clientSecret;
// Initiate an OAuth 2.0 flow to get an access token
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
// Create the service.
var service = new BigqueryService(auth);
JobsResource j = service.Jobs;
QueryRequest qr = new QueryRequest();
qr.Query = query;
QueryResponse response = j.Query(qr, projectId).Fetch();
foreach (TableRow row in response.Rows)
{
List<string> list = new List<string>();
foreach (TableRow.FData field in row.F)
{
list.Add(field.V);
}
Console.WriteLine(String.Join("\t", list));
}
Console.WriteLine("\nPress enter to exit");
Console.ReadLine();
}
private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
{
// Get the auth URL:
IAuthorizationState state = new AuthorizationState(new[] { BigqueryService.Scopes.Bigquery.GetStringValue() });
state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
Uri authUri = arg.RequestUserAuthorization(state);
// Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString());
Console.Write(" Authorization Code: ");
string authCode = Console.ReadLine();
Console.WriteLine();
// Retrieve the access token by using the authorization code:
return arg.ProcessUserAuthorization(authCode, state);
}
}
}
In your answer i could not able to add namespace
"using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;"
But i manage to retrieve results from BigQuery using below code, you need to update Project Name, Project Id and Query.
Download Client ID (I am using Installed Application - Other category ) generate JSON file and add into your Debug folder.
using Google.Apis.Auth.OAuth2;
using System.IO;
using System.Threading;
using Google.Apis.Bigquery.v2;
using Google.Apis.Bigquery.v2.Data;
using System.Data;
using Google.Apis.Services;
using System;
namespace GoogleBigQuery
{
public class Class1
{
private static void Main()
{
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open,
FileAccess.Read))
{
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { BigqueryService.Scope.Bigquery },
"user", CancellationToken.None).Result;
}
// Create and initialize the Bigquery service. Use the Project Name value
// from the New Project window for the ApplicationName variable.
BigqueryService Service = new BigqueryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "PROJECT NAME"
});
string query = "YOUR QUERY";
JobsResource j = Service.Jobs;
QueryRequest qr = new QueryRequest();
qr.Query = query;
DataTable DT = new DataTable();
int i = 0;
QueryResponse response = j.Query(qr, "PROJECT ID").Execute();
if (response != null)
{
int colCount = response.Schema.Fields.Count;
foreach (var Column in response.Schema.Fields)
{
DT.Columns.Add(Column.Name);
}
foreach (TableRow row in response.Rows)
{
DataRow dr = DT.NewRow();
for (i = 0; i < colCount; i++)
{
dr[i] = row.F[i].V;
}
DT.Rows.Add(dr);
}
}
else
{
Console.WriteLine("Response is null");
}
}
}
}
Thanks.

Error adding SharePoint subsite

I'm using an SSIS script task to try and create a SharePoint subsite. The errors don't tell me anything. I know the problem lies in the ClientContext line. The SQL Server server with SSIS is a separate server from my SharePoint server. Any ideas?
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;
using System.Collections.Generic;
using Microsoft.SharePoint.Client.Utilities;
namespace ST_a1ecfb3e46dc4211ac17435ad3bb67ec
{
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
public void Main()
{
try
{
string SiteDescription = "This is my first site creation using Client Object Model.";
int SiteLanguage = 1033;
string SiteTitle = "Test Site";
string SiteUrl = "Test";
bool SitePermissions = true;
string mywebTemplate = "STS#0";
ClientContext clientContext = new ClientContext("http://extranet.domain.local/");
//Retreive the web from the Client Context. This web is the root web by default.
/*Web oWebsite = clientContext.Web;
//Create a new webCreateInformation object to specify the properties of the new site being created.
WebCreationInformation webCreateInfo = new WebCreationInformation();
webCreateInfo.Description = SiteDescription;
webCreateInfo.Language = SiteLanguage;
webCreateInfo.Title = SiteTitle;
webCreateInfo.Url = SiteUrl;
webCreateInfo.UseSamePermissionsAsParentSite = SitePermissions;
webCreateInfo.WebTemplate = mywebTemplate;
//Adding a new site under the root web
Web oNewWebsite = oWebsite.Webs.Add(webCreateInfo);*/
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButtons.OK);
}
}
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
}
}

Categories

Resources