Can you use LiveSDK from Console Application? - c#

I'm trying to make a console application which accesses my SkyDrive account, however I cannot figure out how to get the Live SDK working.
I'm running on Live SDK version 5.4 and this is the code I'm trying to run - the loginResult.Status is always "Unknown":
private static async Task<LiveConnectClient> ConnectToLive()
{
LiveAuthClient authClient = new LiveAuthClient("my live ID");
var loginResult = await authClient.IntializeAsync(new[] { "wl.basic" });
if (loginResult.Status == LiveConnectSessionStatus.Connected)
return new LiveConnectClient(loginResult.Session);
return null;
}
A few things I'm not certain about (since the SDK documentation is somewhat lackluster at best):
"My live ID" - is this just my e-mail address used for my personal Live account, or is it some sort of application specific ID that you have to create somewhere ?
Is InitializeAsync the proper method to call for authenticating ? All examples I've found mention a "LoginAsync", but that method is not available in the DLL.
Is it even possible to use the SDK outside of Windows Phone / Metro apps ?

I got the following code to work using a SkyDriveClient downloaded from http://skydriveapiclient.codeplex.com/releases/view/103081
static void Main(string[] args)
{
var client = new SkyDriveServiceClient();
client.LogOn("YourEmail#hotmail.com", "password");
WebFolderInfo wfInfo = new WebFolderInfo();
WebFolderInfo[] wfInfoArray = client.ListRootWebFolders();
wfInfo = wfInfoArray[0];
client.Timeout = 1000000000;
string fn = #"test.txt";
if (File.Exists(fn))
{
client.UploadWebFile(fn, wfInfo);
}
}

Related

Fetching more than 1000 rows from Domino LDAP server using .NET Core 5 and Novell.Directory.Ldap.NETStandard

I want to fetch all the users from a large location of our Domino LDAP, around ~2000 users altogether. Since .NET Core sadly doesn't have a platform independent LDAP library, I'm using Novell.Directory.Ldap.NETStandard with this POC:
var cn = new Novell.Directory.Ldap.LdapConnection();
cn.Connect("dc.internal", 389);
cn.Bind("user", "pw");
string filter = "location=MyLoc";
var result = cn.Search("", Novell.Directory.Ldap.LdapConnection.ScopeOne, filter, new string[] { Novell.Directory.Ldap.LdapConnection.AllUserAttrs }, typesOnly: false);
int count = 0;
while (result.HasMore()) {
var entry = result.Next();
count++;
Console.WriteLine(entry.Dn);
}
It prints me a lot of entries, but not all. When count = 1000 I got an Size Limit Exceeded exception. I guess this is because I need to use some kind of pagination, so not all entries woult be returned in a single request. There are different questions like this or this one. Both in Java, the .NET Core API seems somehow different.
Approach 1: Try to find out how LdapSearchRequest works in .NET Core
byte[] resumeCookie = null;
LdapMessageQueue queue = null;
var searchReq = new LdapSearchRequest("", LdapConnection.ScopeOne, filter, new string[] { LdapConnection.AllUserAttrs },
LdapSearchConstraints.DerefNever, maxResults: 3000, serverTimeLimit: 0, typesOnly: false, new LdapControl[] { new SimplePagedResultsControl(size: 100, resumeCookie) });
var searchRequest = cn.SendRequest(searchReq, queue);
I'm trying to figure out how the Java examples can be used in .NET Core. This looks good, however I can't figure out how to fetch the LDAP entries. I only get an message id. By looking into the source it seems that I'm on the right way, but they're using MessageAgent which cannot be used outside since it's internal sealed. This is propably the reason why searching for LdapRearchRequest in the source code doesn't give many results.
Approach 2: Using SimplePagedResultsControlHandler
var opts = new SearchOptions("", LdapConnection.ScopeOne, filter, new string[] { LdapConnection.AllUserAttrs });
// For testing purpose: https://github.com/dsbenghe/Novell.Directory.Ldap.NETStandard/issues/163
cn.SearchConstraints.ReferralFollowing = false;
var pageControlHandler = new SimplePagedResultsControlHandler(cn);
var rows = pageControlHandler.SearchWithSimplePaging(opts, pageSize: 100);
This throws a Unavaliable Cricital Extension exception. First I thought that this is an issue of the .NET port, which may doesn't support all the features of the original Java library yet. It seems complete and according to further researches, it looks like to be an LDAP error code. So this must be something which has to be supported by the server, but is not supported by Domino.
I couldn't make at least one of those approachs work, but found another way: Cross platform support for the System.DirectoryServices.Protocols namespace was was added in .NET 5. This was missing for a long time in .NET Core and I guess this is the main reason why libraries like Novell.Directory.Ldap.NETStandard were ported to .NET Core - in times of .NET Core 1.x this was the only way I found to authenticate against LDAP wich works on Linux too.
After having a deeper look into System.DirectoryServices.Protocols, it works well out of the box, even for ~2k users. My basic POC class looks like this:
public class DominoLdapManager {
LdapConnection cn = null;
public DominoLdapManager(string ldapHost, int ldapPort, string ldapBindUser, string ldapBindPassword) {
var server = new LdapDirectoryIdentifier(ldapHost, ldapPort);
var credentials = new NetworkCredential(ldapBindUser, ldapBindPassword);
cn = new LdapConnection(server);
cn.AuthType = AuthType.Basic;
cn.Bind(credentials);
}
public IEnumerable<DominoUser> Search(string filter, string searchBase = "") {
string[] attributes = { "cn", "mail", "companyname", "location" };
var req = new SearchRequest(searchBase, filter, SearchScope.Subtree, attributes);
var resp = (SearchResponse)cn.SendRequest(req);
foreach (SearchResultEntry entry in resp.Entries) {
var user = new DominoUser() {
Name = GetStringAttribute(entry, "cn"),
Mail = GetStringAttribute(entry, "mail"),
Company = GetStringAttribute(entry, "companyname"),
Location = GetStringAttribute(entry, "location")
};
yield return user;
}
yield break;
}
string GetStringAttribute(SearchResultEntry entry, string key) {
if (!entry.Attributes.Contains(key)) {
return string.Empty;
}
string[] rawVal = (string[])entry.Attributes[key].GetValues(typeof(string));
return rawVal[0];
}
}
Example usage:
var ldapManager = new DominoLdapManager("ldap.host", 389, "binduser", "pw");
var users = ldapManager.Search("objectClass=person");
But it's not solved with Novell.Directory.Ldap.NETStandard as the title said
This doesn't solve my problem with the Novell.Directory.Ldap.NETStandard library as the title suggested, yes. But since System.DirectoryServices.Protocols is a official .NET package maintained by Microsoft and the .NET foundation, this seems the better aproach for me. The foundation will take care to keep it maintained and compatible with further .NET releases. When I wrote the question, I was not aware of the fact that Linux support is added now.
Don't get me wrong, I don't want to say that third packages are bad by design - that would be completely wrong. However, when I have the choice between a official package and a third party one, I think it makes sense to prefer the official one. Except there would be a good reason against that - which is not the case here: The official package (which doesn't exist in the past) works better to solve this issue than the third party one.

How to use Google Cloud Speech (V1 API) for speech to text - need to be able to process over 3 hours audio files properly and efficiently

I am looking for documentation and stuff but could not find a solution yet
Installed NuGet package
Also generated API key
However can't find proper documentation how to use API key
Moreover, I want to be able to upload very long audio files
So what would be the proper way to upload up to 3 hours audio files and get their results?
I have 300$ budget so should be enough
Here my so far code
This code currently fails since I have not set the credentials correctly at the moment which I don't know how to
I also have service account file ready to use
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var speech = SpeechClient.Create();
var config = new RecognitionConfig
{
Encoding = RecognitionConfig.Types.AudioEncoding.Flac,
SampleRateHertz = 48000,
LanguageCode = LanguageCodes.English.UnitedStates
};
var audio = RecognitionAudio.FromStorageUri("1m.flac");
var response = speech.Recognize(config, audio);
foreach (var result in response.Results)
{
foreach (var alternative in result.Alternatives)
{
Debug.WriteLine(alternative.Transcript);
}
}
}
}
I don't want to set environment variable. I have both API key and Service Account json file. How can I manually set?
You need to use the SpeechClientBuilder to create a SpeechClient with custom credentials, if you don't want to use the environment variable. Assuming you've got a service account file somewhere, change this:
var speech = SpeechClient.Create();
to this:
var speech = new SpeechClientBuilder
{
CredentialsPath = "/path/to/your/file"
}.Build();
Note that to perform a long-running recognition operation, you should also use the LongRunningRecognize method - I strongly suspect your current RPC will fail, either explicitly because it's trying to run on a file that's too large, or it'll just time out.
You need to set the environment variable before create the instance of Speech:
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "text-tospeech.json");
Where the second param (text-tospeech.json) is your file with credentials generated by Google Api.

creating a github issue in octokit.net

I am trying to write a script that will open an issue typed in the console.
For some reason the issue variable comes back empty in the debugger.
class Program
{
public async static Task Main()
{
var client = new GitHubClient(new ProductHeaderValue("test-app"));
var user = await client.User.Get("medic17");
var tokenAuth = new Credentials(APIKeys.GithubPersinalAccessToken);
client.Credentials = tokenAuth;
var exampleIssue = new NewIssue("test body");
var issue = await client.Issue.Create("owner","name", exampleIssue);
}
}
APIKeys holds my token.
Thanks
I found a solution hope this helps someone else as well.
class Program
{
public async static Task Main()
{
// client initialization and authentication
var client = new GitHubClient(new ProductHeaderValue("<anything>"));
var user = await client.User.Get("<user>");
var tokenAuth = new Credentials(APIKeys.GithubPersinalAccessToken);
client.Credentials = tokenAuth;
// user input
Console.WriteLine("Give a title for your issue: ");
string userIssueTitle = Console.ReadLine().Trim();
Console.WriteLine("Describe your issue:", Environment.NewLine);
string userIssue = Console.ReadLine().Trim();
// input validation
while (string.IsNullOrEmpty(userIssue) || string.IsNullOrEmpty(userIssueTitle))
{
Console.WriteLine("ERROR: Both fields must contain text");
Console.ReadLine();
break;
}
var newIssue = new NewIssue(userIssueTitle) { Body = userIssue };
var issue = await client.Issue.Create(<owner>, <repo> newIssue);
var issueId = issue.Id;
Console.WriteLine($"SUCCESS: your issue id is {issueId} ");
Console.ReadLine();
}
}
Note
You need to store your keys in a separate file and write a class for it so your authentication flow might be different.
Note 2
You must replace all text with real values.
Still a little confused the app is OpenSource for transport since it deals with HIPPA data, users who want to use it need GitHub account if they want to do any error reporting. I assume I don’t share the authToken in the source of the project but the desktop Binary needs it plus the users GitHub login and password. Any pointers? I have tried just using username password that gets entered when creating issue but that fails with “not found”. It seems like any secret that gets deployed with binary app is potentially an issue.

VersionOne API Client not recognizing asset types?

I am running into a problem with the VersionOneAPIClient in that it will not recognize anything I give it ass an asset type. I understand the Attribute definitions probably don't make any sense but I've been trying pretty much everything. My end goal would be to query TeamRooms and get team names from all the teams in the team room.
It's my understanding from the documentation on asset types and how to query that this should work but that's what we all say.
I am using:
C# ASP.NET, VersionOneAPIClient 15.0.0.0
Strings I have tried:
TeamRoom
Task
Scope
Project
public bool APIgetTeams()
{
IAssetType teamroomType = services.Meta.GetAssetType("Task");
Query query = new Query(teamroomType);
IAttributeDefinition teamAttribute = teamroomType.GetAttributeDefinition("Children:Room.Team.Name");
query.Selection.Add(teamAttribute);
IAttributeDefinition scheduleAttribute = teamroomType.GetAttributeDefinition("Children:Scope.Room.Schedule.Name");
query.Selection.Add(scheduleAttribute);
query.Find = new QueryFind(scheduleName, new AttributeSelection(scheduleAttribute));
query.Paging.PageSize = 1;
query.Paging.PageSize = 0;
teamRoomAsset = (Asset)services.Retrieve(query).Assets.ToArray().GetValue(0);
return true;
}
My definition of services and the connector:
public static V1Connector connector = V1Connector
.WithInstanceUrl("http://versionone.cscinfo.com/VersionOneProd/")
.WithUserAgentHeader("New Dashboard?", "1.0")
.WithWindowsIntegrated()
.Build();
public IServices services = new Services(connector);
And these are my Errors / Stack Traces:
The error is likely simple and right in my face but I can't figure it out.
You have a couple of things going on here. I will address your statement "My end goal would be to query TeamRooms and get team names from all the teams in the team room."
Here is a working chunk of code that reads all of your TeamRooms and prints the name of the Team Room and the Team Name. Once you get this working on your machine, attempt to do the paging. Add filtering incrementally to keep the debug cycles low.
static void Main(string[] args)
{
V1Connector connector = V1Connector
.WithInstanceUrl("https://www.MyV1INstance")
.WithUserAgentHeader("HappyApp", "0.1")
.WithUsernameAndPassword("login", "pwd")
.Build();
IServices services = new Services(connector);
IAssetType trType = services.Meta.GetAssetType("TeamRoom");
Query query = new Query(trType);
IAttributeDefinition teamAttribute = trType.GetAttributeDefinition("Team.Name");
IAttributeDefinition nameAttribute = trType.GetAttributeDefinition("Name");
query.Selection.Add(teamAttribute);
query.Selection.Add(nameAttribute);
QueryResult result = services.Retrieve(query);
Asset teamRooms = result.Assets[0];
foreach (Asset story in result.Assets)
{
Console.WriteLine(story.Oid.Token);
Console.WriteLine(story.GetAttribute(teamAttribute).Value);
Console.WriteLine(story.GetAttribute(nameAttribute).Value);
Console.WriteLine();
}
Addendum
I just realized that you were using WithWindowsIntegrated() instead of WithUsernameAndPassword().
Just change that in my sample but then confirm that you are logged into the machine as a Member that is already setup in VersionOne. The windows int auth is trusting IIS' decision to trust you but then immediately after allowing auth, you have to have an active Member account in VersionOne to have access to VersionOne assets.

Facebookclient Object doesn't contain the "Get" method yet all examples do. WP7

I am writing a test app which will simply ask the user to login to facebook via a webbrowser control. Then on the Navigated event a message box will appear relaying the user name of the user. The example I have been following uses a a FacebookClient.Get() method and so do many other examples on the net. My problem is that the FacebookClient doesn't even contain a Get().
I am using C#4.0, and I referenced the Facebook C# SDK from NuGet.
private void wb_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult result;
if (FacebookOAuthResult.TryParse(e.Uri, out result))
{
if (result.IsSuccess)
{
var accesstoken = result.AccessToken;
var fb = new FacebookClient(accesstoken);
var _result = (IDictionary<string, object>)fb.Get("/me");
var name = (string)_result["name"];
MessageBox.Show("Hi " + name);
}
else
{
var errorDescription = result.ErrorDescription;
var errorReason = result.ErrorReason;
}
}
}
The Facebook C# SDK isn't really optimised for WP7, I recommend using the facebook API without going through the sdk c#

Categories