Code sample not compiling - c#

I have been trying to use some sample code provided by Microsoft. I
Downloaded the file
Hit unblock on the file
Unzipped the file
Clicked on the solution called QuizGame sample
The solution opened in Visual Studio 2015
The solution automatically registered hundreds of errors
I opened the C# files in the solution explorer to see what was going on and each C# file had tons of errors. Each error was some how related to the System reference.
Error CS0246 The type or namespace name 'System' could not be found
(are you missing a using directive or an assembly reference?)
The warning was
Warning Cannot resolve Assembly or Windows Metadata file 'System.Runtime.dll'
It also shows all the System imports with red lines underneath them. It sounds like it is not recognizing the System reference.
Here is the code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Networking.Sockets;
namespace P2PHelper
{
public class P2PSessionHost : P2PSession, IDisposable
{
private Dictionary<Guid, P2PClient> ClientMap { get; set; }
private StreamSocketListener SessionListener { get; set; }
private Timer Timer { get; set; }
public P2PSessionHost(P2PSessionConfigurationData config) : base(config)
{
this.SessionListener = new StreamSocketListener();
this.ClientMap = new Dictionary<Guid, P2PClient>();
}
public void Dispose()
{
this.SessionListener.Dispose();
this.SessionListener = null;
}
public async Task<bool> CreateP2PSession(SessionType type)
{
if (this.SessionListener == null) return false;
if (type != SessionType.LocalNetwork) throw new NotSupportedException(
"SessionType.LocalNetwork is the only SessionType supported.");
this.SessionHost = true;
this.SessionListener.ConnectionReceived += async (s, e) => await OnConnectionReceived(e.Socket);
await this.SessionListener.BindEndpointAsync(null, Settings.tcpPort);
this.InitializeNetworkInfo();
return await this.InitializeMulticast(null);
}
public bool RemoveClient(Guid clientID)
{
return this.ClientMap.Remove(clientID);
}
private bool AcceptingConnections { get; set; }
public void StartAcceptingConnections()
{
AcceptingConnections = true;
this.Timer = new Timer(async state => await SendMulticastMessage(""), null, 0, 500);
}
public void StopAcceptingConnections()
{
AcceptingConnections = false;
this.Timer.Dispose();
}
private async Task OnConnectionReceived(StreamSocket socket)
{
byte[] message = await RetrieveMessage(socket);
var newClient = new P2PClient { clientTcpIP = socket.Information.RemoteAddress.ToString() };
if (AcceptingConnections)
{
if (GetGuid(newClient).ToString() == (new Guid()).ToString())
{
Guid newGuid = Guid.NewGuid();
this.ClientMap.Add(newGuid, newClient);
this.OnConnectionComplete(newGuid);
}
}
this.OnMessageReceived(message, GetGuid(newClient));
}
private Guid GetGuid(P2PClient client)
{
return this.ClientMap.FirstOrDefault(
kvp => kvp.Value.clientTcpIP == client.clientTcpIP).Key;
}
protected async Task SendMulticastMessage(string output)
{
using (var multicastOutput = await this.MulticastSocket.GetOutputStreamAsync(
new Windows.Networking.HostName(Settings.multicastIP),
this.MulticastSocket.Information.LocalPort))
{
await multicastOutput.WriteAsync(Encoding.UTF8.GetBytes(output).AsBuffer());
}
}
public async Task<bool> SendMessage(Guid clientID, object message, Type type = null)
{
P2PClient client;
if (this.ClientMap.TryGetValue(clientID, out client))
{
return await base.SendMessage(message, client.clientTcpIP, Settings.tcpPort, type ?? typeof(object));
}
return false;
}
public async Task<bool> SendMessageToAll(object message, Type type = null)
{
var messageTasks = this.ClientMap.Keys.Select(guid => this.SendMessage(guid, message, type));
// When all the tasks complete, return true if they all succeeded.
return (await Task.WhenAll(messageTasks)).All(value => { return value; });
}
}
}

Not recognizing .NET references and namespaces like System.Generics, System, etc, usualy caused by compiling in Client Profile or referencing DLLs that are compiled using different versions of .NET.
Go to the project settings and validate you are compiling to the right version of .NET with no Client Profile turned on.

Related

Debugger skipping methods after organizing code into new solutions

I had a perfectly working API that was making http calls & a UI that was using that API.
Everything was working and it was built really ugly ( 2 solutions for everything), so I wanted to separate everything so it would be more organized.
UI
DataManagerService
DataManager
Contracts
After a lot of copy paste & dependencies references it all looked like its working with 0 errors.
BUT now something weird happens, A method is being skipped and I have NO IDEA WHY.
I am not on release mode.
If anyone has any ideas I would appreciate it!
The method that is being skipped :
private static List<Actor> ReadActorsFromJson(string json)
{
List<Actor> celebListReadFromFile;
try
{
var celebJson = File.ReadAllText(json);
celebListReadFromFile = JsonConvert.DeserializeObject<List<Actor>>(celebJson);
}
catch (Exception ex)
{
celebListReadFromFile = new List<Actor>();
// Empty list/whatever it got in it
}
return celebListReadFromFile;
}
Which is being invoked by :
public static async Task SaveOriginal()
{
foreach (var currceleb in ReadActorsFromJson(filePath))
{
var curr = currceleb;
originalList.TryAdd(currceleb.name, currceleb);
}
}
and this method is being invoked by the classes static constructor:
static Logic()
{
originalList = new ConcurrentDictionary<string, Actor>();
filePath = ConfigurationManager.AppSettings["tempList"];
File.Copy(filePath, BACKUP, true);
// invoking the method
SaveOriginal();
}
The API:
using Contracts;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace WebApplication12.Controllers
{
public class ValuesController : Controller
{
public ILogic _Ilogic;
public ValuesController(ILogic logic)
{
_Ilogic = logic;
}
// GET api/values
public async Task<ActionResult> GetActors()
{
return Json(await _Ilogic.GetAllActorsAsync(), JsonRequestBehavior.AllowGet);
}
public async Task<ActionResult> RemoveActorAsync(Actor actor) {
await _Ilogic.RemoveActorAsync(actor.name);
return Json(await _Ilogic.GetAllActorsAsync());
}
public async Task<ActionResult> ResetAsync()
{
await _Ilogic.ResetAsync();
return Json(await _Ilogic.GetAllActorsAsync());
}
}
}
The business logic :
using System;
using System.Collections.Generic;
using System.IO;
using System.Configuration;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using System.Linq;
using Newtonsoft.Json;
using Contracts;
namespace DataManager
{
public class Logic : ILogic
{
static string filePath;
private static ConcurrentDictionary<string, Actor> originalList;
const string BACKUP = #"C:\tempList\backup.txt";
static Logic()
{
originalList = new ConcurrentDictionary<string, Actor>();
filePath = ConfigurationManager.AppSettings["tempList"];
File.Copy(filePath, BACKUP, true);
SaveOriginal();
}
public async static Task<List<Actor>> GetCelebritiesInner()
{
return originalList.Values.ToList();
}
public async Task<List<Actor>> GetAllActorsAsync()
{
return await GetCelebritiesInner();
}
// Try to read the data from the Json and initialize it. if failed , initialize with whatever it got. return
private static List<Actor> ReadActorsFromJson(string json)
{
List<Actor> celebListReadFromFile;
try
{
var celebJson = File.ReadAllText(json);
celebListReadFromFile = JsonConvert.DeserializeObject<List<Actor>>(celebJson);
}
catch (Exception ex)
{
celebListReadFromFile = new List<Actor>();
// Empty list/whatever it got in it
}
return celebListReadFromFile;
}
public async Task RemoveActorAsync(string name)
{
if (originalList.TryRemove(name, out Actor removedActor))
{
var jsonToWrite = JsonConvert.SerializeObject(await GetCelebritiesInner());
try
{
File.WriteAllText(filePath, jsonToWrite);
}
catch (Exception ex)
{
//Unable to remove due to an error.
}
}
}
public async Task ResetAsync()
{
originalList.Clear();
await UpdateFile();
await SaveOriginal();
}
//Saving the actor, adding the name as key & object as value.
public static async Task SaveOriginal()
{
foreach (var currceleb in ReadActorsFromJson(filePath))
{
var curr = currceleb;
originalList.TryAdd(currceleb.name, currceleb);
}
}
public static async Task UpdateFile()
{
File.Copy(BACKUP, filePath, true);
}
}
}
When running the program, the static ctor is being invoked and should invoke the SaveOriginal method. which it doesn't.
Static constructor calls when the first access is made. You are using dependency injection which is lazy loading. It doesn't create object until first access is made.
So, Try to get/set any property or method, static constructor will be called first.
Ok so I cleaned and re built every solution one by one ( I don't know if it helped) & then I ran the API, sent a request from POSTMAN instead of opening the UI, in postman I got the following error:
Could not load file or assembly 'Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies
I looked at the versions in the Nuget packages and there was no 12.0.0.0 in there, so I removed Newtonsoft.Json from all solutions, re-installed Newtonsoft.Json in every solution and it worked.
turns out somehow when opening the new solutions, I installed different Newtonsoft.Json versions. and this caused the program to skip the method without giving the stack trace like postman did, weird.

Async/Await deadlock

I can't seem to get my code work, although I tried several different approaches. Here is my preferred code snippet:
var client = await ApiClientProvider.GetApiClient();
var freeToPlayChampions = await client.GetChampionsAsync(true, Region);
var championsData = freeToPlayChampions.Select(x =>
client.GetStaticChampionByIdAsync(
(int)x.Id,
platformId: Region));
ConsoleTable.From(await Task.WhenAll(championsData)).Write();
When debugging I see that the code hangs on await Task.WhenAll(championsData). So i tried to make the code more easy:
var client = await ApiClientProvider.GetApiClient();
var freeToPlayChampions = await client.GetChampionsAsync(true, Region);
var table = new ConsoleTable();
foreach(var freeToPlayChampion in freeToPlayChampions)
{
var championsData = client.GetStaticChampionByIdAsync(
(int)freeToPlayChampion.Id,
platformId: Region);
table.AddRow(await championsData);
}
table.Write();
Unfortunately this hangs, as well. Again on the same code part, e.g. await championsData.
How can this 'easy' usage of async/await lead to an deadlock? Thanks in advance for help!
EDIT:
Here is the whole class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ConsoleTables;
using Mono.Options;
using RiotNet.Models;
using RiotShell.Properties;
namespace RiotShell
{
public class FreeToPlay : IShellCommand
{
public IEnumerable<string> Names { get; }
public OptionSet Options { get; }
public bool ShowHelp { get; private set; }
public string Region { get; private set; }
public FreeToPlay()
{
Names = new List<string>
{
"freetoplay",
"ftp"
};
Options = new OptionSet
{
{ "r|region=" , "The region to execute against", x => Region = x},
{ "h|help|?" , "Show help", x => ShowHelp = true }
};
}
public async Task Execute(IEnumerable<string> args)
{
if (ShowHelp)
{
Options.WriteOptionDescriptions(Console.Out);
return;
}
if (args.Any())
{
throw new Exception(Resources.TooManyArgumentsProvided);
}
if (Region == null)
{
throw new Exception(string.Format(Resources.RequiredOptionNotFound, "region"));
}
if (!PlatformId.All.Contains(Region))
{
throw new Exception(string.Format(Resources.InvalidRegion, Region));
}
var client = await ApiClientProvider.GetApiClient();
var freeToPlayChampions = await client.GetChampionsAsync(true, Region);
var championsData = freeToPlayChampions.Select(x =>
client.GetStaticChampionByIdAsync(
(int)x.Id,
platformId: Region));
ConsoleTable.From(await Task.WhenAll(championsData)).Write();
}
}
}
And here is the caller code, my main method:
using System;
using System.Threading.Tasks;
using RiotShell.Properties;
namespace RiotShell
{
public class Program
{
public static async Task Main()
{
while (true)
{
Console.Write(Resources.RiotShellLineString);
var input = Console.ReadLine();
try
{
var parsedArgs = InputParser.Parse(input);
(var command, var commandArgs) = ArgsToIShellCommandCaster.GetCommand(parsedArgs);
await command.Execute(commandArgs);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
}
Since it was wished, here the code for the ApiProvider:
using RiotNet;
using System.Threading.Tasks;
namespace RiotShell
{
public class ApiClientProvider
{
private static IRiotClient _client;
public static async Task<IRiotClient> GetApiClient()
{
if (_client != null)
{
_client.Settings.ApiKey = await KeyService.GetKey();
return _client;
}
_client = new RiotClient(new RiotClientSettings
{
ApiKey = await KeyService.GetKey()
});
return _client;
}
}
}

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.

Using webbackgrounder nuget in MVC to run background task for long time

I need to implement a task in background so what is my task? I have a table that stores the rent amount of each customers, so I need to calculate the rent price in each month after a specific datetimeackf so I googled it and I found a piece of code that (it is nuget called webbackgrounder) I added it to my solution and it gives me this part of code to handle my task:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace WebBackgrounder.DemoWeb
{
public class SampleJob : Job
{
public SampleJob(TimeSpan interval, TimeSpan timeout)
: base("Sample Job", interval, timeout)
{
}
public override Task Execute()
{
return new Task(() => Thread.Sleep(3000));
}
}
}
I want to know how can I program my task ?
More details : Here
I found this article but in fact I don't know can I use this method for longtime ??
Best regards .
any ideas will be appreciated.
You need to also add in a class to the App_Start folder of your application that will start the Job and manage it's lifetime. You can see an example here... https://github.com/NuGet/WebBackgrounder/tree/master/src/WebBackgrounder.DemoWeb
Here is the code from the demo app
using System;
using Elmah;
using WebBackgrounder.Jobs;
[assembly: WebActivator.PostApplicationStartMethod(typeof(WebBackgrounder.DemoWeb.App_Start.WebBackgrounderSetup), "Start")]
[assembly: WebActivator.ApplicationShutdownMethod(typeof(WebBackgrounder.DemoWeb.App_Start.WebBackgrounderSetup), "Shutdown")]
namespace WebBackgrounder.DemoWeb.App_Start
{
public static class WebBackgrounderSetup
{
static readonly JobManager _jobManager = CreateJobWorkersManager();
public static void Start()
{
_jobManager.Start();
}
public static void Shutdown()
{
_jobManager.Dispose();
}
private static JobManager CreateJobWorkersManager()
{
var jobs = new IJob[]
{
new SampleJob(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(20)),
/* new ExceptionJob(TimeSpan.FromSeconds(15)), */
new WorkItemCleanupJob(TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5), new WorkItemsContext())
};
var coordinator = new WebFarmJobCoordinator(new EntityWorkItemRepository(() => new WorkItemsContext()));
var manager = new JobManager(jobs, coordinator);
manager.Fail(ex => Elmah.ErrorLog.GetDefault(null).Log(new Error(ex)));
return manager;
}
}
}
However I found it simpler to just use the parts of Webbackgrounder that I needed as follows. Place this class in the App_Start folder
using System;
using BombaySapphireCds.Jobs;
using Elmah;
[assembly: WebActivator.PostApplicationStartMethod(typeof(BombaySapphireCds.App_Start.PodMonitorConfig), "Start")]
[assembly: WebActivator.ApplicationShutdownMethod(typeof(BombaySapphireCds.App_Start.PodMonitorConfig), "Shutdown")]
namespace BombaySapphireCds.App_Start
{
public static class PodMonitorConfig
{
private static PodMonitorJob m_job;
public static void Start()
{
m_job = new PodMonitorJob(TimeSpan.FromSeconds(20));
}
public static void Shutdown()
{
m_job.Dispose();
}
}
}
and the class to do the actual work... (put this anywhere you like)
using System;
using System.Threading;
using System.Threading.Tasks;
namespace BombaySapphireCds.Jobs
{
public class PodMonitorJob : IDisposable
{
private CancellationTokenSource m_cancel;
private Task m_task;
private TimeSpan m_interval;
private bool m_running;
public PodMonitorJob(TimeSpan interval)
{
m_interval = interval;
m_running = true;
m_cancel = new CancellationTokenSource();
m_task = Task.Run(() => TaskLoop(), m_cancel.Token);
}
private void TaskLoop()
{
while (m_running)
{
//
// Do monitoring work here.
//
Thread.Sleep(m_interval);
}
}
public void Dispose()
{
m_running = false;
if (m_cancel != null)
{
try
{
m_cancel.Cancel();
m_cancel.Dispose();
}
catch
{
}
finally
{
m_cancel = null;
}
}
}
}
}
This has become the new standard for background task execution on the web. It's a NuGet package and it's called HangFire - https://github.com/HangfireIO/Hangfire. The tasks persist even beyond apppool recycling.

Calling async method does not set member variable

This code it´s write in C# in visual studio 2012 I ´ve using winrt tool kit
Hi I tried create this loadGrupos to catch the file grupo.txt and read and load his content in to the class Grupos but I don´t know what´s happen the list grupos recive the content from the json but when I callend the loadGrupos the variable grupos don´t expose nothing.
I really don´t know what´s going on. I tried debug and I didn´t found any error.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Windows.Storage;
using Windows.ApplicationModel;
using WinRTXamlToolkit.IO.Extensions;
using Windows.UI.Popups;
namespace xxx;
public class MyJConverter
{
public String _Path;
//private Windows.ApplicationModel.Package package;
// private Windows.Storage.StorageFolder installedLocation;
private StorageFolder _Folder = Windows.Storage.ApplicationData.Current.LocalFolder;
//KnownFolders.DocumentsLibrary
public MyJConverter() {
// package = Windows.ApplicationModel.Package.Current;
// installedLocation = package.InstalledLocation;
}
public void save(Object obj)
{
_Path = JsonConvert.SerializeObject(obj);
gravandoUmDocumento("data",_Path);
}
public void saveGrupo(Object obj)
{
_Path = JsonConvert.SerializeObject(obj);
gravandoUmDocumento("grupo", _Path);
}
public async void gravandoUmDocumento(String nomeDoArquivo,String menssagem) {
// var _Folder = Windows.Storage.ApplicationData.Current.LocalFolder;
// var _Folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
//await menssagem.WriteToFile(nomeDoArquivo + "1.txt", KnownFolders.DocumentsLibrary);
await menssagem.WriteToFile(nomeDoArquivo + ".txt", _Folder);
}
private List<Ano> anos;
public List<Ano> load()
{
leituraDeUmArquivo("data").Wait();
if (anos != null)
{
return anos;
}
return null;
}
private List<Grupos> grupos;
public List<Grupos> Grupos
{
get { return grupos; }
set { grupos = value; }
}
public List<Grupos> loadGrupos()
{
leituraDeUmArquivo("grupo").Wait();
{
if (grupos != null)
{
return grupos;
}
else
return null;
}
}
public async Task leituraDeUmArquivo(String arquivoASerLido)
{
String leitura = "";
//leitura do data
try
{
// settings
var _Path =arquivoASerLido + ".txt";
// acquire file
var _File = await _Folder.GetFileAsync(_Path);
// read content
leitura = (String) await Windows.Storage.FileIO.ReadTextAsync(_File);
// leitura = (String)_ReadThis;
}
catch {
// leituraDeUmArquivo(arquivoASerLido);
}
if (leitura != "")
{
if (arquivoASerLido.Equals("data"))
{
try
{
anos = JsonConvert.DeserializeObject<List<Ano>>(leitura);
}
catch {
}
}
if (arquivoASerLido.Equals("grupo"))
{
try{
grupos = JsonConvert.DeserializeObject<List<Grupos>>(leitura);
}
catch { }
}
}
}
}
HI I did the modifications you recomend but the problem didn´t solved so I post all my code.
I really didn´t found why the winrt can´t load the file, some time win 8 load some times no.
Now with the modificiations the app block and do go to front.
if I go with debug the visual found the file, if I go only run no.
There should be warning about "calling async method without awaiting" (or something like this).
You need to await for completion of async method instead of just calling it.
I.e. cheap and dirty (not good idea for WinRT) approach is to call Task.Wait on result of leituraDeUmArquivo (the method need to be updated to return Task):
leituraDeUmArquivo("grupo").Wait();
Better approach is to make code properly asynchronous and just await call to leituraDeUmArquivo (your loadGrupos function will likely need to be marked async too and handled appropriately).
Note: to make await/ .Wait() working leituraDeUmArquivo should return Task.
public async Task leituraDeUmArquivo(String arquivoASerLido)
// don't need to touch body of the method.

Categories