I'm beginner with C#. I've wrote a very simple Console project to get location coordinates on my PC.
using LocationProvider;
using System;
using System.Threading.Tasks;
namespace TestLocationProvider
{
class Program
{
static void Main(string[] args)
{
obtenerPosicion();
Console.ReadKey();
}
public async static void obtenerPosicion()
{
GPSAccess gps = new GPSAccess();
Task<GPSData> longRunningTask = gps.GetCurrentPosition();
GPSData result = await longRunningTask;
Console.WriteLine(result);
}
}
}
The LocationProvider namespace is as follows:
using System;
using System.Threading.Tasks;
using Windows.Devices.Geolocation;
namespace LocationProvider
{
public class GPSAccess
{
public async Task<GPSData> GetCurrentPosition()
{
GPSData data;
Geolocator loc = new Geolocator();
try
{
data = new GPSData();
loc.DesiredAccuracy = PositionAccuracy.High;
Geoposition pos = await loc.GetGeopositionAsync();
var lat = pos.Coordinate.Point.Position.Latitude;
var lang = pos.Coordinate.Point.Position.Longitude;
data.latitud = Math.Truncate(lat) * 100 + (lat - Math.Truncate(lat)) * 60;
data.longitud = Math.Truncate(lang) * 100 + (lang - Math.Truncate(lang)) * 60;
return data;
}
catch (System.UnauthorizedAccessException)
{
// handle error
}
return null;
}
}
}
Im using references for Windows 8.1
- Windows.Devices
- Windows.Foundations
and .NET 4.5
- System.Threading.Tasks
However Im getting an error on the line
Geoposition pos = await loc.GetGeopositionAsync();
that says:
IAsyncOperation<Geoposition> does not contain a definition for
GetAwaiter and not extension method GetAwaiter accepting a first
argument of type IAsyncOperation<Geoposition> could be found (are
you missing a using directive for System?)
Am I forgetting some reference?
Related
I'm using this guide to implement an autocomplete funcionality in an app I'm working on, but when I try to test it in different computers it returns me a different hash https://www.c-sharpcorner.com/article/verify-otp-automatically-in-android-without-sms-read-permission-using-xamarin-fo/
The helper class used is the following:
using System.Text;
using Android.Content;
using Android.Content.PM;
using Android.Util;
using Java.Security;
using Java.Util;
namespace InteliMobile.App.Droid.Service
{
public class AppHashKeyHelper
{
private static string HASH_TYPE = "SHA-256";
private static int NUM_HASHED_BYTES = 9;
private static int NUM_BASE64_CHAR = 11;
private static string GetPackageSignature(Context context)
{
var packageManager = context.PackageManager;
var signatures = packageManager.GetPackageInfo(context.PackageName, PackageInfoFlags.Signatures).Signatures;
return signatures.First().ToCharsString();
}
public static string GetAppHashKey(Context context)
{
string keystoreHexSignature = GetPackageSignature(context);
string appInfo = context.PackageName + " " + keystoreHexSignature;
try
{
var messageDigest = MessageDigest.GetInstance(HASH_TYPE);
messageDigest.Update(Encoding.UTF8.GetBytes(appInfo));
byte[] hashSignature = messageDigest.Digest();
hashSignature = Arrays.CopyOfRange(hashSignature, 0, NUM_HASHED_BYTES);
string base64Hash = Android.Util.Base64.EncodeToString(hashSignature, Base64Flags.NoPadding | Base64Flags.NoWrap);
base64Hash = base64Hash.Substring(0, NUM_BASE64_CHAR);
return base64Hash;
}
catch (NoSuchAlgorithmException e)
{
return null;
}
}
}
}
How can I get the hash without using a bash script, since the server runs in a Windows machine? Is it safe to deploy the app to production with the helper class in it?
You don't compute the hash client side. It's sent from the server, and the instructions to do so are at https://developers.google.com/identity/sms-retriever/verify#computing_your_apps_hash_string
You don't do it in code at all, you do it via command line tools.
Langage : C# /
Codded Using : Visual Studio /
Using The System.Net.Http.dll
Hello , Please help Me I have 4 error in my code source project created in C# here is all error :
(I am a beginner) but if you can post the code cleaned fixed I thank you very much
Error 1
Error 1 (Code)
Error 2
Error 2 (Code)
Error 3
Error 3 (Code)
Error 4
Error 4 (Code)
using System;
using System.ComponentModel;
using System.Drawing;
using System.Net;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Text;
using System.Windows.Forms;
namespace CheckerProject
{
public partial class Checker
{
public Checker()
{
InitializeComponent();
}
private async void Check()
{
string text = this.textBox1.Text;
using (HttpClientHandler httpClientHandler = new HttpClientHandler
{
AutomaticDecompression = (DecompressionMethods.GZip | DecompressionMethods.Deflate)
})
{
using (HttpClient httpClient = new HttpClient(httpClientHandler))
{
TaskAwaiter<HttpResponseMessage> taskAwaiter = httpClient.PostAsync("https:\\API.com", new StringContent("{\"onlineId\":\"" + text + "\",\"reserveIfAvailable\":false}".ToString(), Encoding.UTF8, "application/json")).GetAwaiter();
if (!taskAwaiter.IsCompleted)
{
await taskAwaiter;
TaskAwaiter<HttpResponseMessage> taskAwaiter2;
taskAwaiter = taskAwaiter2;
taskAwaiter2 = default(TaskAwaiter<HttpResponseMessage>);
}
HttpResponseMessage result = taskAwaiter.GetResult();
taskAwaiter = default(TaskAwaiter<HttpResponseMessage>);
HttpResponseMessage httpResponseMessage = result;
HttpResponseMessage httpResponseMessage2 = httpResponseMessage;
httpResponseMessage = null;
TaskAwaiter<string> taskAwaiter3 = httpResponseMessage2.Content.ReadAsStringAsync().GetAwaiter();
if (!taskAwaiter3.IsCompleted)
{
await taskAwaiter3;
TaskAwaiter<string> taskAwaiter4;
taskAwaiter3 = taskAwaiter4;
taskAwaiter4 = default(TaskAwaiter<string>);
}
string result2 = taskAwaiter3.GetResult();
taskAwaiter3 = default(TaskAwaiter<string>);
string text2 = result2;
string text3 = text2;
text2 = null;
if (httpResponseMessage2.StatusCode.ToString() == "429")
{
//Function
}
if (httpResponseMessage2.StatusCode != HttpStatusCode.BadRequest)
{
if (httpResponseMessage2.StatusCode == HttpStatusCode.Created)
{
//Function
}
else
{
//Function
}
}
else
{
//Function
if (text3.Contains("Online id already exists"))
{
//Function
}
if (text3.Contains("Improper"))
{
//Function
}
}
httpResponseMessage2 = null;
text3 = null;
}
HttpClient httpClient = null;
}
HttpClientHandler httpClientHandler = null;
}
}
}
I will answer the first two errors (they are the same problem).
You should remove the following 2 lines:
HttpClient httpClient = null;
HttpClientHandler httpClientHandler = null;
What you do here is you declare 2 NEW variables and assign the value 'null' to both of them.
What you meant to do is propably to assign 'null' to the existing variables. However that's not needed, since they are declared inside a 'using' block, which will automatically call the 'Dispose' method.
I try to get balance in address.
It is my code:
`using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Nethereum.Web3;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Bananas().Wait();
}
static private async Task Bananas()
{
var publicKey = "0xC0b4ec83028307053Fbe8d00ba4372384fe4b52B";
var web3 = new Nethereum.Web3.Web3("https://ropsten.infura.io/myInfura");
//var txCount = await web3.Eth.Transactions.GetTransactionCount.SendRequestAsync(publicKey);
var balance = await web3.Eth.GetBalance.SendRequestAsync(publicKey);
var etherAmount = Web3.Convert.FromWei(balance.Value);
Console.WriteLine(web3);
Console.WriteLine("Get txCount ", etherAmount);
Console.ReadLine();
}
}
}`
I installed Nethereum via PM console: Nethereum.
I use a normal link of infura.
Why don`t I get a next result without the balance in address?
I have just made a console application with your code and all the data is coming back fine from Nethereum.
Your issue is with your Console.WriteLine(... You are passing the etherAmount as a arg0 property into the Console.WriteLine which will not output correctly on the console when you run it.
Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Nethereum.Web3;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Bananas().Wait();
}
static private async Task Bananas()
{
var publicKey = "0xC0b4ec83028307053Fbe8d00ba4372384fe4b52B";
var web3 = new Nethereum.Web3.Web3("https://ropsten.infura.io/myInfura");
//var txCount = await web3.Eth.Transactions.GetTransactionCount.SendRequestAsync(publicKey);
var balance = await web3.Eth.GetBalance.SendRequestAsync(publicKey);
var etherAmount = Web3.Convert.FromWei(balance.Value);
Console.WriteLine(web3);
Console.WriteLine("Get txCount " + etherAmount);
Console.ReadLine();
}
}
}
ps nice 1110.337873197299357846 ETH ;) (i know it is only test ETH but we can dream)
I had a working "save reader" that would strip unwanted data out of a winform, then return a list of strings referred to as "items" .
My problem is that when converting this for use with a winstore app; I cannot call an async task, and I need to use one to access the file.
im not 100% sure how to do this, so any help is appreciated; this is what I have so far.
the public SaveGame(StorageFile file)
{
File = promptUser();
}
throws an error, I have tried making the constructor async to, but that throws more errors
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Windows.Storage;
using Windows.Storage.Pickers;
namespace save_game_reader
{
class SaveGame
{
private StorageFile File { get; set; }
public SaveGame(StorageFile file)
{
File = promptUser();
Task<StorageFile> returnedTaskTResult = promptUser();
StorageFile intResult = await promptUser();
}
public async Task<List<string>> GetAllItems()
{
string WholeSaveString = await Windows.Storage.FileIO.ReadTextAsync(File);
List<string> ToReturn = new List<string>();
List<string> SplitList = WholeSaveString.Split(new string[] { "data" }, StringSplitOptions.None).ToList();
foreach (string line in SplitList)
{
var start = line.IndexOf("value") + 6;
var end = line.IndexOf("type", start);
if (end != -1)
{
string substring = line.Substring(start, (end - start) - 8);
if (substring.Length >= 4)
{
ToReturn.Add(substring);
}
}
}
return ToReturn;
}
private async Task<StorageFile> promptUser()
{
var picker = new FileOpenPicker();
picker.ViewMode = PickerViewMode.Thumbnail;
picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
StorageFile sf = await picker.PickSingleFileAsync();
return sf;
}
}
}
It's pretty rare to need to do so, but the typical way to work around constructors in async is to just use a static method:
class SaveGame
{
SaveGame(StorageFile file)
{
File = file;
}
public async Task<SaveGame> Create()
{
return new SaveGame(await promptUser());
}
}
SaveGame g = await SaveGame.Create();
It may be worth it in your case to consider a cleaner separation between UI code and backend code. If something seems weird or difficult to do, it's often a sign of design flaw.
Also, one does not "call an async task". You call an async method and await a Task.
Constructors cannot be async, change your code as follows:
public SaveGame()
{}
public async Task Init(Storage file)
{
File = promptUser();
Task<StorageFile> returnedTaskTResult = promptUser();
StorageFile intResult = await promptUser();
}
somewhere else in an async method you call it like this:
var save = new SaveGame();
await save.Init(file);
I am creating a cutomization software which will do all the standardization to a mst file.
Below is the code of class that will change product name and genrate transform.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WindowsInstaller;
using System.Data;
namespace Automation
{
class CustomInstaller
{
public CustomInstaller()
{
}
public Record getInstaller(string msiFile,MsiOpenDatabaseMode mode,string query)
{
Type type = Type.GetTypeFromProgID("WindowsInstaller.Installer");
Installer inst = (Installer)Activator.CreateInstance(type);
Database db = inst.OpenDatabase(msiFile, mode);
WindowsInstaller.View view = db.OpenView(query);
view.Execute(null);
Record record = view.Fetch();
db.Commit();
return record;
}
public bool generateTrans(string file1, string file2,string transName)
{
Type type = Type.GetTypeFromProgID("WindowsInstaller.Installer");
Installer inst = (Installer)Activator.CreateInstance(type);
Database db1 = inst.OpenDatabase(file1, MsiOpenDatabaseMode.msiOpenDatabaseModeReadOnly);
try
{
Database db2 = inst.OpenDatabase(file2, MsiOpenDatabaseMode.msiOpenDatabaseModeReadOnly);
return db2.GenerateTransform(db1, transName);
}
catch (Exception e) { }
return false;
}
public int editTransform(string msiFile, MsiOpenDatabaseMode mode, string query)
{
Type type = Type.GetTypeFromProgID("WindowsInstaller.Installer");
Installer inst = (Installer)Activator.CreateInstance(type);
Database db = inst.OpenDatabase(msiFile, mode);
WindowsInstaller.View view = db.OpenView(query);
view.Execute(null);
db.Commit();
int o=(int)db.DatabaseState;
db = null;
inst = null;
type = null;
return 1;
}
}
}
First editTransform() is called which will create a copy of original msi and do some changes in it, then generateTrans() is called which will get difference detween two msi files and create a transform file.
Now issue is when genrateTrans() is called, then it goes to catch block of it as inst.OpenDatabase return "MSI Api Error".
It seems to me that the copy of file crated by editTransform is still locked by it and is not available for use for generateTrans() menthod.
Please help here.
PS: mode used for edit transform is transact.
Instead of doing the COM Interop, checkout the far superior interop library ( Microsoft.Deployment.WindowsInstaller ) found in Windows Installer XML Deployment Tools Foundation. You'll find it much easier to use.
using System;
using System.IO;
using Microsoft.Deployment.WindowsInstaller;
namespace ConsoleApplication1
{
class Program
{
const string REFERENCEDATABASE = #"C:\orig.msi";
const string TEMPDATABASE = #"C:\temp.msi";
const string TRANSFORM = #"c:\foo.mst";
static void Main(string[] args)
{
File.Copy(REFERENCEDATABASE, TEMPDATABASE, true);
using (var origDatabase = new Database(REFERENCEDATABASE, DatabaseOpenMode.ReadOnly))
{
using (var database = new Database(TEMPDATABASE, DatabaseOpenMode.Direct))
{
database.Execute("Update `Property` Set `Property`.`Value` = 'Test' WHERE `Property`.`Property` = 'ProductName'");
database.GenerateTransform(origDatabase, TRANSFORM);
database.CreateTransformSummaryInfo(origDatabase, TRANSFORM, TransformErrors.None, TransformValidations.None);
}
}
}
}
}