LiveConnectException using live sdk - c#

i'm new to Live SDK and i'm trying to use it to connect to a user's profile and get data from it
i have read about it and used the following code to login to user's account
private async void btnSignin_SessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
{
if (e.Status == LiveConnectSessionStatus.Connected)
{
session = e.Session;
client = new LiveConnectClient(session);
try
{
LiveAuthClient auth = new LiveAuthClient(btnSignin.ClientId);
//LiveLoginResult initializeResult = await auth.InitializeAsync();
try
{
LiveLoginResult loginResult = await auth.LoginAsync(new string[] { "wl.basic" });
if (loginResult.Status == LiveConnectSessionStatus.Connected)
{
LiveConnectClient connect = new LiveConnectClient(auth.Session);
LiveOperationResult operationResult = await connect.GetAsync("me");
dynamic result = operationResult.Result;
if (result != null)
{
this.infoTextBlock.Text = string.Join(" ", "Hello", result.name, "!");
}
else
{
this.infoTextBlock.Text = "Error getting name.";
}
}
}
catch (LiveAuthException exception)
{
this.infoTextBlock.Text = "Error signing in: " + exception.Message;
}
catch (LiveConnectException exception)
{
MessageBox.Show("Error calling API: " + exception.Message);
}
}
catch (LiveAuthException exception)
{
this.infoTextBlock.Text = "Error initializing: " + exception.Message;
}
}
else
{
client = null;
}
}
it logs in on my emulator and one of my 2 lumia 620 devices but with the other device it gives me the following Exception
**
*> {client_error: Microsoft.Live.LiveConnectException: Exception of type
'Microsoft.Live.LiveConnectException' was thrown. at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at PhoneApp2.MainPage.d__6.MoveNext()}*
**

Related

CreateCatalogImageAsync doesn't create images in Square

I'm trying to create images in Square but it's stuck at 1336, when I have more than 4000 images to upload at the moment.
Here's the code:
public async Task<bool> CreateOrDeleteImagesAsync(string url, string imageId, bool isDelete)
{
var squareClient = await GetSquareClientAsync();
if (isDelete)
{
try
{
await Task.Delay(500);
await squareClient.CatalogApi.DeleteCatalogObjectAsync(imageId);
return true;
}
catch (ApiException exception)
{
exception.Errors.ForEach(async error =>
{
await _globalLogger.ErrorAsync($"Error Category: {error.Category} Code: {error.Code} Detail: {error.Detail}");
_logger.LogError($"Error Category: {error.Category} Code: {error.Code} Detail: {error.Detail}");
});
}
catch (Exception e)
{
await _globalLogger.ErrorAsync($"An error ocurred: {e.Message}");
_logger.LogError($"An error ocurred: {e.Message}");
}
return false;
}
var imageData = new CatalogImage.Builder()
.Name(imageId)
.Build();
var catalogObject = new CatalogObject.Builder("IMAGE", $"#{imageId}")
.ImageData(imageData)
.Build();
var request = new CreateCatalogImageRequest.Builder(idempotencyKey: Guid.NewGuid().ToString(), image: catalogObject)
.Build();
_logger.LogInformation(JsonConvert.SerializeObject(request, Formatting.Indented));
try
{
var imageFile = new FileStreamInfo(new MemoryStream(await _downloadService.GetDownloadBitsImageUrl(new Uri(url))));
await Task.Delay(500);
await squareClient.CatalogApi.CreateCatalogImageAsync(request: request, imageFile: imageFile);
return true;
}
catch (ApiException exception)
{
exception.Errors.ForEach(async error =>
{
await _globalLogger.ErrorAsync($"Error Category: {error.Category} Code: {error.Code} Detail: {error.Detail}");
_logger.LogError($"Error Category: {error.Category} Code: {error.Code} Detail: {error.Detail}");
});
}
catch (Exception e)
{
await _globalLogger.ErrorAsync($"An error ocurred: {e.Message}");
_logger.LogError($"An error ocurred: {e.Message}");
}
return false;
}
In debugging, when the line
await squareClient.CatalogApi.CreateCatalogImageAsync(request: request, imageFile: imageFile);
is executed, return successful response and returns true. But then, I check how many images are created in Square and returns the same amount
Honestly, I don't know what to do anymore. If someone can help me, I'll be eternally grateful

Session.SaveChanges() does not work on latest page

Have a quote application, which we fill the data and send from source system to receiver system. That receiver system will be sending status of that quote(Success/Failed) as Acknowledgement to source system. We have an option to revise the same quote. whenever we revise the quote, the Status is inherited from previous quote. we need to clear the latest revision's status. which is not happening. but it clears previous revision's status. Could anyone help me.
if (plm == "PLM")
{
if (id.Revision != 0)
{
var javascriptSerializer = new JavaScriptSerializer();
var urn = line.CustomProperties?.FirstOrDefault(k => k.Key.ToLower() == "urn")?.Value;
oRecordLog.WriteToLogFile("Updating DBValue");
//initilizing document store object to query the documents from database.
IDocumentStore ravenDB = new DocumentStore { Url = "http://localhost:8072", DefaultDatabase = "Configit.Quote" }.Initialize();
try
{
List<Document> docs;
using (var session = ravenDB.OpenSession())
{
oRecordLog.WriteToLogFile("Opened RavenDB session");
//getting the URN value.
var javaScriptSerializer = new JavaScriptSerializer();
string urnString = urn;
ModelKeyValuePair urnKeyValue = new ModelKeyValuePair();
urnKeyValue.Key = "URN";
urnKeyValue.Value = javaScriptSerializer.Serialize(urnString);
//wait for 5 seconds before the next query
docs = session.Query<Document>().Customize(x => x.WaitForNonStaleResults(TimeSpan.FromSeconds(5))).Where(x => x.Lines.Any(l => l.Properties.Any(ID => ID == urnKeyValue))).ToList();
try
{
oRecordLog.WriteToLogFile("docs " + docs.Count);
//processing one by one document from RavenDB.
foreach (var doc in docs)
{
string quoteGuid = null;
if (doc.LinesCount > 0)
{
int lineCnt = doc.LinesCount;
// processing each line in the docuement getting the quoteID
foreach (var quoteline in doc.Lines)
{
if ((quoteline.Properties.ContainsKey("Urn")) || (quoteline.Properties.ContainsKey("URN")) || (quoteline.Properties.ContainsKey("urn")))
{
Guid lGuid = quoteline.LineId;
var quote_ForID = _quoteStorage.GetQuote(new QuoteRevisionId(id.QuoteId, id.Revision));
var urn_ForQuoteId = quoteline.Properties?.FirstOrDefault(k => k.Key == "URN")?.Value;
if (GetUniqueRefnum(quote_ForID, quoteline) == urn_ForQuoteId)
{
quoteGuid = doc.DocumentId.ToString();
oRecordLog.WriteToLogFile("quoteGuid " + quoteGuid);
var TransferStatus = quoteline.Properties?.FirstOrDefault(p => p.Key == "TransferStatus");
var PLMDetailedStatus = quoteline.Properties?.FirstOrDefault(p => p.Key == "PLMDetailedStatus");
TransferStatus.Value = "";
PLMDetailedStatus.Value = "";
}
}
}
}
else
{
oRecordLog.WriteToLogFile("Quote ID not found");
}
}
session.SaveChanges();
}
catch (Exception e)
{
//printing error logs in Acknowledgement.txt.
oRecordLog.WriteToLogFile(" exception caught main Stacktrace-----" + e.StackTrace);
oRecordLog.WriteToLogFile(" exception caught main Message-----" + e.Message);
oRecordLog.WriteToLogFile(" exception caught main Inner Exception-----" + e.InnerException);
return null;
}
}
}
catch (Exception e)
{
//printing error logs in Acknowledgement.txt.
oRecordLog.WriteToLogFile(" exception caught main Stacktrace-----" + e.StackTrace);
oRecordLog.WriteToLogFile(" exception caught main Message-----" + e.Message);
oRecordLog.WriteToLogFile(" exception caught main Inner Exception-----" + e.InnerException);
return null;
}
orderupdateservice.BeginUpload(lineCount, linid, TargetSystem.Plm);
}
else
{
oRecordLog.WriteToLogFile("This is new quote");
orderupdateservice.BeginUpload(lineCount, linid, TargetSystem.Plm);
}
}

Exception raised while accessing keyvault in Azure through C#

I had below code to fetch key vault secrets in Azure:
var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetToken));
var sec = await kv.GetSecretAsync(ConfigurationManager.AppSettings["SomeURI"]);
secretValue = sec.Value ;
In App Config I had:
<add key="SomeURI" value="https://baseURL/KeyName/b75cabsdf45667nhjhe516c674457" />
Since I have been using this many times in my application, I have created a class and called that class. The class looks like this:
public static class KeyVaultFetch
{
public async static Task<string> GetCachedSecret(string secretname)
{
try
{
string BaseUri = ConfigurationManager.AppSettings["keyvaultBaseURI"].ToString();
var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetToken));
var secretbundle = await kv.GetSecretAsync($"{BaseUri}{secretname}").ConfigureAwait(false);
return secretbundle.Value;
}
catch (Exception ex)
{
log.Error("Exception raised in GetCachedSecret.");
log.Error("Exception Details: " + ex.Message);
log.Error("Inner Exception Details: " + ex.InnerException);
throw;
}
}
public static async Task<string> GetToken(string authority, string resource, string scope)
{
try
{
var authContext = new AuthenticationContext(authority);
ClientCredential clientCred = new ClientCredential(clientId, clientSecret);
AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientCred);
if (result == null)
throw new InvalidOperationException("Failed to obtain the JWT token");
return result.AccessToken;
}
catch (Exception ex)
{
log.Error("Exception raised while Getting token : " + ex.Message);
log.Error("Inner Exception Details: " + ex.InnerException);
throw;
}
}
}
And I have written below line to get the secret every time:
secretValue = await KeyVaultFetch.GetCachedSecret(keyName);
But I'm geeting the below exception , when I run my code :
Exception raised in GetCachedSecret.
Exception Details: Invalid ObjectIdentifier: https://baseURL/. Bad number of segments: 2
What am I doing wrong?
You should use GetSecretAsync with 2 parameters:
await kv.GetSecretAsync(BaseUri, secretname);
At least that's how it is in our apps :)

Outbound Dialer SIP configuration

I am trying to build a UCMA standalone outbound dialer. Unfortunately I can't find much information on how to connect to a SIP or how to configure this to begin with. I got a GetOnSIP and would like to associate it with my application. Any help would be appreciated!
Thanks
//set up my application
internal void Start()
{
_applicationId = ConfigurationManager.AppSettings["applicationId"];
_recipientSipUri = ConfigurationManager.AppSettings["recipientSipUri"];
//string urisToDialString = ConfigurationManager.AppSettings["numbersToDial"];
_urisToDial.Add("phone number goes here");
ServerPlatformSettings platformSettingsObj = new ServerPlatformSettings(_applicationId, Dns.GetHostEntry("localhost").HostName,
5060, string.Empty /* empty string for the GRUU */);
Utils.WriteDebug("Endpoint: " + platformSettingsObj.Localhost);
_platform = new CollaborationPlatform(platformSettingsObj);
_platform.AllowedAuthenticationProtocol = SipAuthenticationProtocols.None;
try
{
_platform.BeginStartup(ar =>
{
try
{
_platform.EndStartup(ar);
Console.WriteLine("Platform started.");
StartEndpoint();
Console.WriteLine("Platform Endpoint Initiated.");
CallSession sessionObj = new CallSession(_urisToDial.First(), _endpoint);
sessionObj.InitiateCall();
}
catch (RealTimeException ex)
{
Console.WriteLine(ex);
}
}, null);
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex);
}
}
private void StartEndpoint()
{
// Create a placeholder URI for the endpoint.
ApplicationEndpointSettings endpointSettings =
new ApplicationEndpointSettings("sip:default#" +
Dns.GetHostEntry("localhost").HostName);
// Make this a default routing endpoint, so that
// all requests sent to the listening port on this IP,
// regardless of To URI, will come to the endpoint.
endpointSettings.IsDefaultRoutingEndpoint = true;
// Create a new endpoint and register for AV calls.
_endpoint = new ApplicationEndpoint(_platform, endpointSettings);
_endpoint.RegisterForIncomingCall<AudioVideoCall>(OnCallReceived);
try
{
_endpoint.BeginEstablish(ar =>
{
try
{
_endpoint.EndEstablish(ar);
Console.WriteLine("Endpoint started.");
}
catch (RealTimeException ex)
{
Console.WriteLine(ex);
}
}, null);
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex);
}
}
public CallSession(string number, ApplicationEndpoint endpointObj)
{
// Set the host and port to which the INVITE should be sent
// i'm going to guess that this is where the sbc ip goes
ConnectionContext connectionContextObj = new ConnectionContext("192.168.0.56", 5060);
optionsObj.ConnectionContext = connectionContextObj;
//configure this to use udp
_phoneNumber = number;
_endpoint = endpointObj;
}
public bool InitiateCall()
{
bool isInitiated = true;
try
{
Utils.WriteDebug("About to Initiate a phone Call");
Conversation convObj = new Conversation(_endpoint);
AudioVideoCall avcallObj = new AudioVideoCall(convObj);
// Establish the call using the options we created
//avcall.BeginEstablish("sip:test#test.greenl.ee", optionsObj,
avcallObj.BeginEstablish("tel:+" + _phoneNumber, optionsObj,
ar =>
{
try
{
avcallObj.EndEstablish(ar);
Console.WriteLine("The call with Local Participant: " + avcallObj.Conversation.LocalParticipant + " and Remote Participant: " + avcallObj.RemoteEndpoint.Participant + " is now in the established state.");
}
catch (RealTimeException ex)
{
isInitiated = false;
Utils.LogError(ex);
}
},
null);
}
catch (InvalidOperationException ex)
{
isInitiated = false;
Utils.LogError(ex);
}
return isInitiated;
}

LiveConect Auth (for SkyDrive) NullReferenceException (WTH)?

I followed a 43 minute video tutorial on the Channel 9 site and read the LiveConnect page where it shows code and I don't see what I'm doing wrong. It keeps giving me a NullReferenceException error and it doesn't even bring up the "Do you want to allow app X to access skydrive" thing, it just breaks immediately. I've set breakpoints everywhere but there is nothing. Just null, null everywhere.
OnNavigatedTo event:
LoadProfile();
private async void LoadProfile()
{
try
{
LiveAuthClient auth = new LiveAuthClient();
LiveLoginResult loginResult = await auth.LoginAsync(new string[] { "wl.basic" });
if (loginResult.Status == LiveConnectSessionStatus.Connected)
{
this.pageTitle.Text = "Signed in.";
}
}
catch (LiveAuthException exception)
{
this.pageTitle.Text = "Error signing in: " + exception.Message;
}
}
And the exception says:
I finally found a solution.
Subscribe to a button-click event or whatever, then use this code:
LoadProfile();
which calls this method:
public async void LoadProfile()
{
try
{
LiveAuthClient auth = new LiveAuthClient();
LiveLoginResult initializeResult = await auth.InitializeAsync();
try
{
LiveLoginResult loginResult = await auth.LoginAsync(new string[] { "wl.basic" });
if (loginResult.Status == LiveConnectSessionStatus.Connected)
{
LiveConnectClient connect = new LiveConnectClient(auth.Session);
LiveOperationResult operationResult = await connect.GetAsync("me");
dynamic result = operationResult.Result;
if (result != null)
{
this.pageTitle.Text = string.Join(" ", "Hello", result.name, "!");
}
else
{
this.pageTitle.Text = "Error getting name.";
}
}
}
catch (LiveAuthException exception)
{
this.pageTitle.Text = "Error signing in: " + exception.Message;
}
catch (LiveConnectException exception)
{
this.pageTitle.Text = "Error calling API: " + exception.Message;
}
}
catch (LiveAuthException exception)
{
this.pageTitle.Text = "Error initializing: " + exception.Message;
}
}
Before you debug, add your app to the Windows Store Dashboard. Then go back to Visual Studio, find Package.appxmanifest in Solution Explorer and add the Internet Capability. Then go to the Project menu > Store > Associate App with the Store.
Find your app's name in the list of apps that appears, select it and click Next/Finish and then debug. It should now be working.
Please try this code instead of yours:
LiveAuthClient auth = new LiveAuthClient();
LiveLoginResult loginResult = await auth.InitializeAsync(new string[] { "wl.basic" });
if ( loginResult.Status == LiveConnectSessionStatus.Connected )
{
LiveConnectClient connect = new LiveConnectClient( auth.Session );
...

Categories

Resources