Microsoft.SharePoint.Client.ClientContext in UWP APP fails after reset - c#

I am trying to connect to a SharePointOnline 2013.
In my C# Console Application everything works fine, but if I try (nearly) the same code in an Universal App, it is not possible to create multiple instances of a ClientContext nor setting the credentials multiple times.
Im using the Microsoft.SharepointOnline.CSOM Version: 16.1.4727.1204 (released on 11.12.2015)
class Program
{
static void Main(string[] args)
{
UseContextMultipleTime();
UseContextMultipleTime();
}
public static void UseContextMultipleTime()
{
using (var context = new ClientContext("https://something.sharepoint.com"))
{
var securePassword = new SecureString();
foreach (char c in "password".ToCharArray()) securePassword.AppendChar(c);
context.Credentials = new SharePointOnlineCredentials("username", securePassword);
try
{
context.ExecuteQuery();
string status = "OK";
}
catch (Exception ex)
{
string test = ex.ToString();
}
}
}
}
Below the Universal App version, which crashes in the second method call:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
UseContextMultipleTime();
UseContextMultipleTime();
}
public void UseContextMultipleTime()
{
using (var context = new ClientContext("https://something.sharepoint.com"))
{
context.Credentials = new SharePointOnlineCredentials("username", "password");
try
{
context.ExecuteQueryAsync().Wait();
string status = "OK";
}
catch (Exception ex)
{
string test = ex.ToString();
}
}
}
}
When I set the credentials only once, it will work.
Does anybody know a solution for this problem? I will appreciate every kind of hints.

The Problem was solved in the latest CSOM update. Everything works fine now.

Related

Xamarin.Forms TextToSpeech

I'm trying to develop a mobile app with a SpeechToText feature, I found an example here Original Post and i tried to follow its steps, but when i run the application and i tap on the button to record, i get a message saying "Unhandled Exception occurr, No body on method..".
I tried to debug and what I get is that its something related to the DependecyService running the SpeechToTextAsync method from the ISpeecehToText interface.
Now I dont use interfaces too much so i'm a bit stuck understanding what is causing this error and how to solve it.
namespace LiveScoring {
public partial class MainPage : ContentPage {
public MainPage() {
InitializeComponent();
}
public void RecordBtn_Clicked(object sender, EventArgs e) {
WaitForSpeechToText();
}
private async void WaitForSpeechToText() {
Output_lbl.Text = await DependencyService.Get<ISpeechToText>().SpeechToTextAsync();
>> here I get the error
}
}
}
using System.Threading.Tasks;
namespace LiveScoring {
public interface ISpeechToText {
Task<string> SpeechToTextAsync();
}
}
namespace LiveScoring.Droid {
public class SpeechToText : ISpeechToText {
private const int VOICE = 10;
public static string SpeechText;
public static AutoResetEvent autoEvent = new AutoResetEvent(false);
public SpeechToText() { }
public async Task<string> SpeechToTextAsync() {
var tcs = new TaskCompletionSource<string>();
try {
var voiceIntent = new Intent(RecognizerIntent.ActionRecognizeSpeech);
voiceIntent.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelFreeForm);
voiceIntent.PutExtra(RecognizerIntent.ExtraPrompt, "Talk now");
voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputCompleteSilenceLengthMillis, 1500);
voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputPossiblyCompleteSilenceLengthMillis, 1500);
voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputMinimumLengthMillis, 15000);
voiceIntent.PutExtra(RecognizerIntent.ExtraMaxResults, 1);
voiceIntent.PutExtra(RecognizerIntent.ExtraLanguage, Java.Util.Locale.Default);
SpeechText = "";
autoEvent.Reset();
try {
((Activity)Forms.Context).StartActivityForResult(voiceIntent, VOICE);
} catch (ActivityNotFoundException a) {
tcs.SetResult("Device doesn't support speech to text");
}
await Task.Run(() => { autoEvent.WaitOne(new TimeSpan(0, 2, 0)); });
return SpeechText;
} catch (Exception ex) {
tcs.SetException(ex);
}
return "";
}
}
}
Try to add this above your namespace LiveScoring.Droid { line, ie:
[assembly: Dependency(typeof(SpeechToText))]
namespace LiveScoring.Droid {
...
}
This way it will register the dependency service, so it will be called when you use the DependencyService.Get<>() method.

C# how can I check that is asp.net webapi running

I have an asp.net webapi which sometimes crashes, or it does not give a response. I am trying to solve this problem. However, I temporarily reset the IIS until the problem is solved.
My IIS reset console application;
class Program
{
static void Main(string[] args)
{
while (true)
{
Thread.Sleep(500);
if (CheckConnection() == false)
{
System.Diagnostics.Process.Start(#"C:\Windows\System32\iisreset.exe");
Console.WriteLine("Restarting");
Thread.Sleep(30000);
}
}
}
public static bool CheckConnection(string webApiAddress = null)
{
try
{
using (var client = new WebClient())
{
using (var stream = client.OpenRead("http://localhost:8885/"))
{
return true;
}
}
}
catch
{
return false;
}
}
}
I check per 500 milliseconds. Sometimes my reset application, resets the IIS, probably my asp.net web api crashing. But I am not sure about WebClient.OpenRead() method is best check method.
Thank you for best practice

Xamarin app crash when attempting to sync SyncTable

I making an app using xamarin and azure mobile service. I am attempting to add offline sync capabilities but I am stuck. I have a service which looks like this
class AzureService
{
public MobileServiceClient Client;
AuthHandler authHandler;
IMobileServiceTable<Subscription> subscriptionTable;
IMobileServiceSyncTable<ShopItem> shopItemTable;
IMobileServiceSyncTable<ContraceptionCenter> contraceptionCenterTable;
IMobileServiceTable<Member> memberTable;
const string offlineDbPath = #"localstore.db";
static AzureService defaultInstance = new AzureService();
private AzureService()
{
this.authHandler = new AuthHandler();
this.Client = new MobileServiceClient(Constants.ApplicationURL, authHandler);
if (!string.IsNullOrWhiteSpace(Settings.AuthToken) && !string.IsNullOrWhiteSpace(Settings.UserId))
{
Client.CurrentUser = new MobileServiceUser(Settings.UserId);
Client.CurrentUser.MobileServiceAuthenticationToken = Settings.AuthToken;
}
authHandler.Client = Client;
//local sync table definitions
//var path = "syncstore.db";
//path = Path.Combine(MobileServiceClient.DefaultDatabasePath, path);
//setup our local sqlite store and intialize our table
var store = new MobileServiceSQLiteStore(offlineDbPath);
//Define sync table
store.DefineTable<ShopItem>();
store.DefineTable<ContraceptionCenter>();
//Initialize file sync context
//Client.InitializeFileSyncContext(new ShopItemFileSyncHandler(this), store);
//Initialize SyncContext
this.Client.SyncContext.InitializeAsync(store);
//Tables
contraceptionCenterTable = Client.GetSyncTable<ContraceptionCenter>();
subscriptionTable = Client.GetTable<Subscription>();
shopItemTable = Client.GetSyncTable<ShopItem>();
memberTable = Client.GetTable<Member>();
}
public static AzureService defaultManager
{
get { return defaultInstance; }
set { defaultInstance = value; }
}
public MobileServiceClient CurrentClient
{
get { return Client; }
}
public async Task<IEnumerable<ContraceptionCenter>> GetContraceptionCenters()
{
try
{
await this.SyncContraceptionCenters();
return await contraceptionCenterTable.ToEnumerableAsync();
}
catch (MobileServiceInvalidOperationException msioe)
{
Debug.WriteLine(#"Invalid sync operation: {0}", msioe.Message);
}
catch (Exception e)
{
Debug.WriteLine(#"Sync error: {0}", e.Message);
}
return null;
}
public async Task SyncContraceptionCenters()
{
ReadOnlyCollection<MobileServiceTableOperationError> syncErrors = null;
try
{
//await this.Client.SyncContext.PushAsync();
await this.contraceptionCenterTable.PullAsync(
//The first parameter is a query name that is used internally by the client SDK to implement incremental sync.
//Use a different query name for each unique query in your program
"allContraceptionCenters",
this.contraceptionCenterTable.CreateQuery());
}
catch (MobileServicePushFailedException exc)
{
if (exc.PushResult != null)
{
syncErrors = exc.PushResult.Errors;
}
}
// Simple error/conflict handling. A real application would handle the various errors like network conditions,
// server conflicts and others via the IMobileServiceSyncHandler.
if (syncErrors != null)
{
foreach (var error in syncErrors)
{
if (error.OperationKind == MobileServiceTableOperationKind.Update && error.Result != null)
{
//Update failed, reverting to server's copy.
await error.CancelAndUpdateItemAsync(error.Result);
}
else
{
// Discard local change.
await error.CancelAndDiscardItemAsync();
}
Debug.WriteLine(#"Error executing sync operation. Item: {0} ({1}). Operation discarded.", error.TableName, error.Item["id"]);
}
}
}
I am getting this error:
System.NullReferenceException: Object reference not set to an instance of an object. When the SyncContraceptionCenters() is run. As far as I can tell I reproduced the coffeeItems example in my service But I am stuck.
I think I found the solution. The issue was the way the tables were being synced.
by calling SyncContraceptionCenters() and SyncShop() at the same time shopItemtable.PullAsync and contraceptionTable.PullAsync were happening at the same time. Which is bad apparently bad. So but putting them in the same method and awaiting them they run separately and they work as expected.

Linq2twitter asp.net c# not working

Hey guys i followed the tutorial here for a school project, https://www.dougv.com/2015/08/posting-status-updates-to-twitter-via-linqtotwitter-part-2-plain-text-tweets/
But when i run it with google chrome nothing is showing up and it just stuck in http://localhost:2860/linq2twitter.aspx which is a blank page, i've checked my twitter the tweet has not been made as well.. from the other sample i've tried i think it is suppose to send me to a authentication page which requires me to login and stuff.. any help is appreciated. Here's my code :
namespace WebApplication3
{
public partial class linq2twitter : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
class Program
{
static void Main()
{
Console.WriteLine("Program started.");
try
{
var result = Task.Run(() => SendTweet());
result.Wait();
if(result == null) {
Console.WriteLine("Tweet failed to process, but API did not report an error");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine("Program completed.");
Console.Read();
}
static async Task<Status> SendTweet()
{
var auth = new SingleUserAuthorizer
{
CredentialStore = new SingleUserInMemoryCredentialStore
{
ConsumerKey = "<Twitter consumer key>",
ConsumerSecret = "<Twitter consumer secret>",
AccessToken = "<Twitter access token>",
AccessTokenSecret = "<Twitter access token secret>"
}
};
var context = new TwitterContext(auth);
var status = await context.TweetAsync(
"Hello World! I am testing #dougvdotcom's #LinqToTwitter demo, at " +
"https://www.dougv.com/2015/08/posting-status-updates-to-twitter-via-linqtotwitter-part-2-plain-text-tweets"
);
return status;
}
}
}
}
Fixed after regenerating my secrets and keys.. and removed unintentional spacebar for my keys in the code. Thx

Making throwing exceptions work

I've been trying to write a small program with these instructions:
In this assignment you should write a simple web application with one link on the front page of the web. If the link is clicked, the user will simply be routed to the front page again (using RedirectToAction). However, occasionally, the action method might throw an exception (but not always). Occasionally (one in every 5 occasions) the method should throw an ArgumentException, and occasionally (again, in maybe 1 in a 5), it should throw a custom Exception object you should declare yourself, called MyApplicationException.
In HomeController I have:
public class HomeController : Controller
{
List<Logger> m_loggers = new List<Logger>();
protected override void OnException(ExceptionContext fc)
{
base.OnException(fc);
Exception ex = fc.Exception;
Logger.Instance.Log(ex);
}
public ActionResult Index()
{
string strLogFile = System.Configuration.ConfigurationManager.AppSettings["LogFile"];
string strEmail = System.Configuration.ConfigurationManager.AppSettings["Email"];
try
{
RedirectToAction("Index");
using(MailMessage message = new MailMessage())
{
message.To.Add(strEmail);
message.Subject = "Villuskilaboð";
message.Body = "Upp hefur komið villa frá Skilaverkefni 4!";
using(SmtpClient client = new SmtpClient())
{
client.EnableSsl = true;
client.Send(message);
}
}
}
catch(Exception ex)
{
Random r = new Random();
int rand = r.Next(1000);
if(rand % 5 == 0)
{
throw new System.ArgumentException("Randon villuskilaboð handa þér!");
}
Debug.WriteLine(ex.Message +
Environment.NewLine +
ex.StackTrace);
}
return View();
}
Logger class:
public class Logger
{
List<LogMedia>m_loggers = new List<LogMedia>();
private static Logger theInstance = null;
public static Logger Instance
{
get
{
if (theInstance == null)
{
theInstance = new Logger();
}
return theInstance;
}
}
private Logger()
{
m_loggers = new List<LogMedia>();
//m_loggers.Add(new TextFileLogMedia { });
//m_loggers.Add(new EmailLogMedia { });
}
public void Log(Exception ex)
{
foreach(LogMedia log in m_loggers)
{
log.LogMessage(ex.Message + Environment.NewLine);
}
}
}
LogMedia
public class LogMedia
{
public virtual void LogMessage(string Message)
{
}
public class OutputWindowLogMedia: LogMedia
{
public override void LogMessage(string Message)
{
System.Diagnostics.Debug.WriteLine(Message);
}
}
public class TextFileLogMedia: LogMedia
{
public override void LogMessage(string Message)
{
//File.AppendAllText("c:\\Temp.Log.txt", Message);
}
}
public class EmailLogMedia: LogMedia
{
public override void LogMessage(string Message)
{
}
}
}
I´m stuck for now and seems not getting it to work, my Visual Studio crash and I get error up, don't think that is the exception, I´m so new to it so maybe it´s the box that should come up :) But the email never get to my account.
What am I still missing to make everything work? I know the file-thing isn't in this code, trying to make the other things to work first.
I've added information about my eMail in web.config.
You really need to rework your Index() method. I'm not in front of my computer with Visual Studio, but I'm surprised you code gets past the first line in your try. Having the RedirectToAction("Index") should throw a warning that the rest of the method will never be reached, and create an infinite loop when you try to access the method. The RedirectToAction("Index")` you have in your code does nothing as you don't return the results of that. Thank you Erik Noren
This would be how I'd structure your method instead:
public ActionResult Index() {
// No need to go higher, as it's always just as random with a modulo
int rnd = (new Random()).Next(5);
try {
switch (rnd) {
case 1: // Or any of the 5 numbers you want.
throw new ArgumentException();
case 4: // Again, any of the 5 numbers
throw new MyApplicationException();
default:
return RedirectToAction("Index");
}
}
catch (Exception ex) {
// Do your error logging here.
}
}

Categories