I am using xamamrin for developing apps for android using c#, the IDE I am using is Visual studio.
I want to use zxing in my app, so I add zxing packet to both core and ui layers.
As you see in the below code, I can instantiate some classes, but I do not have any access to
PlatformChecks.IsPermissionInManifest
I need it to check weather the required permissions are granted or not. Please have a look at the error message I am getting
Please let me know how to use it.
error
Error CS0103: The name 'PlatformChecks' does not exist in the current context (CS0103) (MITScan.UI.Droid)
code:
public static readonly string[] RequiredPermissions = new[] {
Android.Manifest.Permission.Camera
};
protected override async void OnCreate(Android.OS.Bundle bundle)
{
base.OnCreate(bundle);
this.Window.AddFlags(WindowManagerFlags.KeepScreenOn);
SetContentView(Resource.Layout.ZxingLibTestView);
_scannerFragment = new ZXingScannerFragment();
SupportFragmentManager.BeginTransaction().Replace(Resource.Id.tscan_4_view_relativelayout_cameraPreview, _scannerFragment, "Scannerfragment").Commit();
var permissionsToRequest = new List<string>();
// Check and request any permissions
foreach (var permission in RequiredPermissions)
{
if (PlatformChecks.IsPermissionInManifest(this,
permission))
{
if (!PlatformChecks.IsPermissionGranted(this,
permission))
permissionsToRequest.Add(permission);
}
}
if (permissionsToRequest.Any())
{
_waitingForPermission =
PlatformChecks.RequestPermissions(this,
permissionsToRequest.ToArray(), 101);
}
}
Note:
I am using Zxing for scanning bar codes.
I was going through the Zebra Crossing's(ZXing) docs after I read this question since I knew there is no such Android class and found that PlatformChecks is a Custom Class as below:
public class PlatformChecks
{
public const string PERMISSION_CAMERA = "android.permission.CAMERA";
public const string PERMISSION_FLASHLIGHT = "android.permission.FLASHLIGHT";
public static bool HasCameraPermission(Context context)
{
return HasPermission (context, PERMISSION_CAMERA);
}
public static bool HasFlashlightPermission(Context context)
{
return HasPermission (context, PERMISSION_FLASHLIGHT);
}
static bool HasPermission(Context context, string permission)
{
PermissionInfo pi = null;
try { pi = context.PackageManager.GetPermissionInfo (PERMISSION_CAMERA, PackageInfoFlags.Permissions); }
catch { }
return pi != null;
}
}
And has the following using's
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Content.PM;
Related
I have a weird error in Redis on .Net 6. When I run the test code here:
https://github.com/redis-developer/redis-graph-dotnet-basic-app/blob/main/Program.cs
It works perfectly fine. In this case the code is running in the program.cs file.
When I port that code to a class, in order to better manage encapsulation and complexity. It does not work. What it does is run the code and when it gets to the: await graph.QueryAsync part, it just stops the debugger. Very strange indeed.
Here is the code I am using. Any thoughts or suggestions:
//Program.cs (Relevant Bits)
using RedisTest //PROGRAM //WRITE TO REDIS ENTERPRISE CLOUD Process_LoadGraph process_LoadGraph = new Process_LoadGraph(); process_LoadGraph.Controller(results);
//SHARED CONNECTION CLASS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StackExchange.Redis;
namespace RedisTest
{
public class RedisSharedConnection
{
public static ConnectionMultiplexer Connection
{
get
{
return lazyConnection.Value;
}
}
private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
{
ConnectionMultiplexer connectionMultiplexer = ConnectionMultiplexer.Connect(ConfigData.dbConnectionString);
return connectionMultiplexer;
});
}
}
//USAGE CLASS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NRedisGraph;
namespace RedisTest
{
public class Process_LoadGraph
{
public async void Controller(List<Result> results)
{
//Setup
var redisConnection = RedisSharedConnection.Connection;
//var redisConnection = ConnectionMultiplexer.Connect(ConfigData.dbConnectionString);
var db = redisConnection.GetDatabase(ConfigData.dbId);
var graph = new RedisGraph(db);
string graphName = ConfigData.graphName;
//Test Transaction
// Create Bob
// CRASHES HERE
var createBobResult = await graph.QueryAsync("pets", "MERGE(:human{name:'Bob',age:32})");
}
}
}
Turns out the solution is to use Redis in a static class. Along the following lines:
internal static class WriteToDB
{
public static async Task WriteAsync(List<string> querieS)
{
//Load Graph
//Setup
var redisConnection = RedisSharedConnection.Connection;
//var redisConnection = ConnectionMultiplexer.Connect(ConfigData.dbConnectionString);
var db = redisConnection.GetDatabase(ConfigData.dbId);
var graph = new RedisGraph(db);
string graphName = ConfigData.graphName;
// ** DEBUG
//Test Transaction
// Create Bob
var createBobResult = await graph.QueryAsync("pets", "MERGE(:human{name:'Bob',age:32})");
{ }
//Clear Graph
await graph.QueryAsync(graphName, "MATCH(n) DETACH DELETE n");
{ }
}
}
i am developing an app using xamarin forms and firebase authentication
with xamarin.firebase.auth and xamarin.firebase.core
when i want to create a new user the code works fine but it gives me the exception
Java.Lang.IllegalStateException: 'Task is not yet complete'
when i trace the code line by line every thing works just fine and i get no errors but when running the app after creating user it gives me the exception.
this is my code:
inerface in pcl:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace XamarinFirebaseAuth
{
public interface IAuth
{
Task<string> LoginWithEmailPassword(string email, string password);
bool SignUpWithEmailPassword(string email, string password);
}
}
android implementation:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Foundation;
using UIKit;
using XamarinFirebaseAuth;
using XamarinFirebaseAuth.iOS;
using Firebase.Auth;
using System.Threading.Tasks;
using Xamarin.Forms;
[assembly: Dependency(typeof(AuthIOS))]
namespace XamarinFirebaseAuth.iOS
{
public class AuthIOS : IAuth
{
public async Task<string> LoginWithEmailPassword(string email, string password)
{
try
{
var user = await Auth.DefaultInstance.SignInWithPasswordAsync(email, password);
var token = user.User.GetIdTokenAsync();
return token.ToString();
}
catch(Exception e)
{
return "";
}
}
public bool SignUpWithEmailPassword(string email, string password)
{
try
{
var signUpTask = Auth.DefaultInstance.CreateUserAsync(email, password);
return true;
}
catch (Exception e)
{
throw;
//return false;
}
}
}
}
and this is my sign up page :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace XamarinFirebaseAuth
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SignUpPage : ContentPage
{
IAuth auth;
public SignUpPage()
{
InitializeComponent();
auth = DependencyService.Get<IAuth>();
}
private async void btnRegister_Clicked(object sender, EventArgs e)
{
try
{
bool created = auth.SignUpWithEmailPassword(EmailInput.Text, PasswordInput.Text);
if (created)
{
await DisplayAlert("Success", "Your account created successfully", "OK");
await Navigation.PopAsync();
}
else
{
await DisplayAlert("Error", "Something went wrong. Try again later!", "OK");
}
}
catch
{
throw;
}
}
}
}
I think you should await the CreateUserAsync method to know whether the account is created successfully or not:
AuthDataResult signUpTask = await Auth.DefaultInstance.CreateUserAsync(email, password);
Then you can get the user info:
await signUpTask.User.GetIdTokenAsync();
On this page, https://cloud.google.com/docs/authentication/production, there is a guide with examples on how to set up google API authentication. However, my IDE doesn't seem to understand or be able to find the "ToChannelCredentials()" method needed for verification. Is there something specific I haven't imported? Here is my code
using System;
using System.IO;
using Grpc.Core;
using Google.Apis.Auth.OAuth2;
using Google.Cloud.Vision.V1;
namespace ClassLibrary1
{
public class Class1
{
public static void Main(String[] args)
{
var credential = GoogleCredential.FromFile("myPath").CreateScoped(ImageAnnotatorClient.DefaultScopes);
var channel = new Grpc.Core.Channel(ImageAnnotatorClient.DefaultEndpoint.ToString(), credential.;
var client = ImageAnnotatorClient.Create();
var image = Image.FromFile("myImage");
var response = client.DetectLabels(image);
foreach (var annotation in response)
{
if (annotation.Description != null)
{
Console.WriteLine(annotation.Description);
}
}
}
}
}
Add:
using Grpc.Auth;
And you'll need to reference Google.Apis.Core.
I have been locking for a long time on how to get a user's role so I can set permissions for commands. This is my code. I am using Discord.NET in the newer version.
using Discord.Commands;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AmberScript2.Modules
{
public class Kick : ModuleBase<SocketCommandContext>
{
[Command("kick")]
public async Task KickUser(string userName)
{
if (Context.Guild.GetRole(Context.Message.Author.Id).Name == "Administrator")
{
await Context.Channel.SendMessageAsync("Success!");
}
else
{
await Context.Channel.SendMessageAsync("Inadequate permisions.");
}
}
}
}
The error i am getting is object reference not set to an instance of an object. I have been trying to find the source of it and i can't. Thanks.
(And yes i have yet to get rid of excess usings. This code isn't done yet.)
If you want to try to get a role of the user, try using SocketGuildUser instead of a string. (Use var role = (user as IGuildUser).Guild.Roles.FirstOrDefault(x => x.Name == "Role");)
using Discord.Commands;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AmberScript2.Modules
{
public class Kick : ModuleBase<SocketCommandContext>
{
[Command("kick")]
public async Task KickUser(SocketGuildUser userName)
{
var user = Context.User as SocketGuildUser;
var role = (user as IGuildUser).Guild.Roles.FirstOrDefault(x => x.Name == "Role");
if (!userName.Roles.Contains(role))
{
// Do Stuff
if (user.GuildPermissions.KickMembers)
{
await userName.KickAsync();
}
}
}
}
}
That is most of my code for kicking.
With the line RequireUserPermission(GuildPermission.KickMembers) you check whether or not the user has the permission to kick members.
Within GuildPermission there are many different permissions.
Like GuildPermission.ManageRoles etc.
using Discord.Commands;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AmberScript2.Modules
{
public class Kick : ModuleBase<SocketCommandContext>
{
[Command("kick"), RequireUserPermission(GuildPermission.KickMembers)]
public async Task KickUser(SocketGuildUser userName)
{
var user = Context.User as SocketGuildUser;
var role = (user as IGuildUser).Guild.Roles.FirstOrDefault(x => x.Name == "Role");
if (!userName.Roles.Contains(role))
{
// Do Stuff
if (user.GuildPermissions.KickMembers)
{
await userName.KickAsync();
}
}
}
}
I have the same problem...
To my knowledge Linq needs to be used with IGuildUser or SocketGuildUser.
I have not yet been able to create functioning code to check if the person performing the command does have a role named "Admin"or some other name
Edit: This might be helpful
https://discord.foxbot.me/docs/api/Discord.WebSocket.SocketGuildUser.html
I'm trying to implement the use of Google Drive in my app but I seem to be getting the following error "Method 'get_Error' in type 'Google.Apis.Drive.v2.Data.FileList' from assembly 'Google.Apis.Drive.v2, Version=1.2.4647.29713, Culture=neutral, PublicKeyToken=null' does not have an implementation". Does anyone know as to why this is occurring? I based my code on the example that Google provides for its tasks API.
Code below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Util;
using System.Diagnostics;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Authentication;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Util;
using PrepHub.PrepHub;
using System.Web.Services;
using System.Threading;
using Google.Apis;
using Google.Apis.Drive.v2.Data;
using Google.Apis.Drive.v2;
using Google.Apis.Drive;
namespace DriveExample
{
public partial class GDrive : System.Web.UI.Page
{
private static DriveService _service; // We don't need individual service instances for each client.
private OAuth2Authenticator<WebServerClient> _authenticator;
private IAuthorizationState _state;
private IAuthorizationState AuthState
{
get
{
return _state ?? HttpContext.Current.Session["AUTH_STATE"] as IAuthorizationState;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (_service == null)
{
_service = new DriveService(_authenticator = CreateAuthenticator());
}
if (HttpContext.Current.Request["code"] != null)
{
_authenticator = CreateAuthenticator();
_authenticator.LoadAccessToken();
}
var ni = _service.Files.List().Fetch();
}
private OAuth2Authenticator<WebServerClient> CreateAuthenticator()
{
var provider = new WebServerClient(GoogleAuthenticationServer.Description);
provider.ClientIdentifier = ClientCredentials.ClientID;
provider.ClientSecret = ClientCredentials.ClientSecret;
var authenticator =
new OAuth2Authenticator<WebServerClient>(provider, GetAuthorization) { NoCaching = true };
return authenticator;
}
private IAuthorizationState GetAuthorization(WebServerClient client)
{
// If this user is already authenticated, then just return the auth state.
IAuthorizationState state = AuthState;
if (state != null)
{
return state;
}
// Check if an authorization request already is in progress.
state = client.ProcessUserAuthorization(new HttpRequestInfo(HttpContext.Current.Request));
if (state != null && (!string.IsNullOrEmpty(state.AccessToken) || !string.IsNullOrEmpty(state.RefreshToken)))
{
// Store and return the credentials.
HttpContext.Current.Session["AUTH_STATE"] = _state = state;
return state;
}
string scope = DriveService.Scopes.Drive.GetStringValue();
OutgoingWebResponse response = client.PrepareRequestUserAuthorization(new[] { scope });
response.Send();
return null;
}
}
}
I'm guessing some of your assemblies are out of date. That error will occur when you have an assembly for example, lets say foo.dll (v1) and that assembly is being referenced by bar.dll (v2). A class in bar.dll is expecting something in to be present on a class in Foo and its not there. In your case, its the get accessor for a property called Error on the class FileList. Double check all your assemblies to make sure they are all at their most recent version (s).