HttpContext.GetGlobalResourceObject not exist in Class Library - c#

I'm writing various class libraries (tools and helpers) for my future ASP.Net project.
Right now my solution doesn't have web project, but it's not supposed to be a problem.
I added reference to System.Web to project and now I able to access HttpContext in code.
Below my code for resource manager class that suppose to get application global resources:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
namespace ResourceManager
{
public class ResourceManager : IResourceManager
{
HttpContext context;
public ResourceManager(HttpContext ctx)
{
context = ctx;
}
public string GetError(string key)
{
return context.GetGlobalResourceObject("Errors", key).ToString();
}
//And so on........
}
}
But unfortunately Visual Studio intellisense can't find GetGlobalResourceObject.
Hitting F12 and I can see this static function inside HttpContext class.
After running build I'm getting this error message:
Member 'HttpContext.GetGlobalResourceObject(string, string)' cannot be accessed with an instance reference; qualify it with a type name instead
It's strange behaviour and interesting for me why it's happening.
Thanks for help

This is untested, but from the error message I think the usage should be as below.
Essentially you just use the static HttpContext rather than creating an instance of it.
using System.Web;
namespace ResourceManager
{
public class ResourceManager : IResourceManager
{
public string GetError(string key)
{
return HttpContext.GetGlobalResourceObject("Errors", key).ToString();
}
//And so on........
}
}

Related

Adding Akavache Static Linker class or Initializer error

I'm currently using Visual Studio Mac 2019 for to build my iOs Xamarin Forms Application.
My Application Akavache to store persistent data specifically credentials which I utilizes its BlobCache.Secure storage, but sadly the data doesn't persist.
I found that I should add either of the following:
1. Linker Class
using System;
using Akavache.Sqlite3;
namespace NameSpace.iOS
{
[Preserve]
public static class LinkerPreserve
{
static LinkerPreserve()
{
var persistentName = typeof(SQLitePersistentBlobCache).FullName;
var encryptedName = typeof(SQLiteEncryptedBlobCache).FullName;
}
}
public class PreserveAttribute : Attribute
{
}
}
or
2. Initializer
Akavache.Registrations.Start("FollowTheDrop");
Akavache: saved value not available after iOS app restart
but every time I add the solution above the following error below occurs during the build
MTOUCH : error MT2101: Can't resolve the reference 'System.Int32
SQLitePCL.raw::sqlite3_bind_blob(SQLitePCL.sqlite3_stmt,System.Int32,System.Byte[])',
referenced from the method 'System.Void
Akavache.Sqlite3.BulkInsertSqliteOperation/<>c__DisplayClass7_0::b__0()'
in 'SQLitePCLRaw.core, Version=1.1.13.388, Culture=neutral,
PublicKeyToken=1488e028ca7ab535'.
Am I missing something that causes this error?
It was solved by updating the following Nuget Packages below which has dependencies on each other:
Akavache 9.0.1
Splat 14.3.1
fusillade 2.4.47
Lastly when adding the linker static class consider adding a Preserve Attribute as shown below:
[Preserve]
public static class LinkerPreserve
{
static LinkerPreserve()
{
var persistentName = typeof(SQLitePersistentBlobCache).FullName;
var encryptedName = typeof(SQLiteEncryptedBlobCache).FullName;
}
}
public class PreserveAttribute : Attribute
{
}

Trying to establish sqlite connection results in null reference

Xamarin forms newbie here, and I am trying to establish an SQLite connection so that I may interact with a created database in my application.
I get no flags on this in the IDE, but when I compile, I'm getting a null reference error! Specifically, my _SQLiteConnection var is null, and I think it may have something to do with not setting the path properly?
I've referenced a few guides on doing this online, and although a little dated, they go about setting this up in the same manner I am.
Heres some code:
UserDb.cs:
using PluralBuddy.Models;
using SQLite;
using System.Collections.Generic;
using System.Linq;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace PluralBuddy.Data
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public class UserDB
{
private SQLiteConnection _SQLiteConnection;
public UserDB()
{
_SQLiteConnection = DependencyService.Get<ISQLiteInterface>().GetConnection();
_SQLiteConnection.CreateTable<User>();
}
ISQLiteInterface.cs:
using SQLite;
namespace PluralBuddy.Models
{
public interface ISQLiteInterface
{
SQLiteConnection GetConnection();
}
}
References:
https://code.tutsplus.com/tutorials/an-introduction-to-xamarinforms-and-sqlite--cms-23020
https://dzone.com/articles/register-and-login-using-sqlite-in-xamarinforms
As always, any help is appreciated!
So for anyone who stumbles across this post looking for an answer to a similar problem, make sure that you are initializing your database and giving it a path. Be very careful following guides as they will often leave out vital context, either on purpose or by mistake.
Here is what I did
in App.Xaml
using PluralBuddy.Data;
using PluralBuddy.Views;
using System;
using System.IO;
using Xamarin.Forms;
namespace PluralBuddy
{
public partial class App : Application
{
static UserDB userDB;
public static UserDB UserDB
{
get
{
if (userDB == null)
{
userDB = new UserDB(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "user.db3"));
}
return userDB;
}
}
UserDB.cs
namespace PluralBuddy.Data
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public class UserDB
{
private readonly SQLiteConnection _SQLiteConnection;
public UserDB(string dbPath)
{
_SQLiteConnection = new SQLiteConnection(dbPath);
_SQLiteConnection.CreateTable<User>();
}
and just in case anyone needs it, here is a more up to date guide from one of the same guys as referenced in the original post:
https://xmonkeys360.com/2019/07/10/register-login-and-update-using-sqlite-in-xamarin-forms/

How to access GetSystemService(AudioService) in the UI layer

I am developing android App in Xamarin. I want to create an interface and its implementing class in the UI layer. As you see in the below code,
I am getting an error when ever, I use
this.GetSystemService(AudioService);
it is never recognized.
please have a look at the imports below. please let me know how to get it working.
code:
public class ImplClass :
InterfaceFile
{
public bool IsAllowed(Context ctx)
{
AudioManager audioMgr =
(AudioManager)this.GetSystemService(AudioService);
}
}
import:
using System;
using System.Runtime.Remoting.Contexts;
using Android.Media;
using MvvmCross.Platform;
using Android.Content.PM;
You can use the "Application Context".
Example:
public class ImplClass : InterfaceFile
{
public bool IsAllowed(Context ctx)
{
AudioManager audioMgr = (AudioManager)Application.Context.GetSystemService(AudioService);
}
}
I am using this and it works.
global::Android.App.Application.Context.GetSystemService

Error activating Interface

I am new to .NET. I am create a internet shop but i have a problems
My Error:
Error activating IBookRepository No matching bindings are
available, and the type is not self-bindable. Activation path: 2)
Injection of dependency IBookRepository into parameter repo of
constructor of type BooksController 1) Request for BooksController
Suggestions: 1) Ensure that you have defined a binding for
IBookRepository. 2) If the binding was defined in a module, ensure
that the module has been loaded into the kernel. 3) Ensure you have
not accidentally created more than one kernel. 4) If you are using
constructor arguments, ensure that the parameter name matches the
constructors parameter name. 5) If you are using automatic module
loading, ensure the search path and filters are correct.
I using 3 project in Solution I have a interface IBookRepository in c# Class Library Domain and using asp.net mvc in controller
IBookRepository:
using Domain.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Domain.Abstract
{
public interface IBookRepository
{
IEnumerable<Book> Books { get; }
}
}
BooksController:
using Domain.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebUI.Controllers
{
public class BooksController : Controller
{
private IBookRepository repository;
public BooksController(IBookRepository repo)
{
repository = repo;
}
public ViewResult List()
{
return View(repository.Books);
}
}
}
I have a bindings for all the constructor parameter types:
private static void RegisterServices(IKernel kernel)
{
System.Web.Mvc.DependencyResolver.SetResolver(new WebUI.Infrastructure.NinjectDependencyResolver(kernel));
}
How can I fix this problem?
So you have the first step of dependency injection down, but you need to tell your code what concrete class to use when your interface is requested. To do that you need to create a binding for your concrete class.
To do this you need to navigate to your Ninject bindings file and add this:
Bind<IBookRepository>().To<NameOfYourClassThatImplementsIBookRepository>();
Obviously NameOfYourClassThatImplementsIBookRepository should be replaced with the actual name of your concrete class (i.e the class that implements your interface).
I am not aware of Ninject, but looking at the code above, BookController constructor needs an instance of class which implements IBookRepository. Think of constructor chaining or have one more default constructor to pass instance to above written constructor.
using Domain.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebUI.Controllers
{
public class BooksController : Controller
{
private IBookRepository repository;
public BooksController():this(new BookRepository())
{
}
public BooksController(IBookRepository repo)
{
repository = repo;
}
public ViewResult List()
{
return View(repository.Books);
}
}
}

The name 'ninja' does not exist in the current context

With the below code I get thee following error:
NinjaSteps.cs(16,13): error CS0103: The name 'ninja' does not exist in the current context
The command line I use to compile is:
csc /target:library /reference:C:\Ruby193\lib\ruby\gems\1.9.1\gems\
cuke4nuke-0.4.0\dotnet\Cuke4Nuke.Framework.dll /reference:C:\Fitnesse\FitNesseRo
ot\jediwhale-fitsharp-a78d820\binary\tools\nunit\framework\nunit.framework.dll /
reference:C:\Users\Rahul\Documents\Visual~1\Projects\ConsoleApplication3\Console
Application3\Ninja.dll NinjaSteps.cs
The code I am trying to compile is from a tutorial on Cucumber automation technology:
NinjaSteps.cs:
http://cuke4ninja.com/sec_ninja_survival_net.html
using System;
using System.Collections.Generic;
using System.Text;
using Cuke4Nuke.Framework;
using NUnit.Framework;
using NinjaSurvivalRate;
namespace ConsoleApplication3
{
class NinjaSteps
{ [Given(#"^the ninja has a ([a-z]*) level black-belt$")]
public void TheNinjaHasABlackBelt(String level)
{ ninja = new Ninja(level);
}
[When(#"^attacked by [a\s]*(.*)$")]
public void AttackedBy(String opponent)
{
actions = ninja.AttackedBy(opponent);
}
[Then("^the ninja should (.*)$")]
public void TheNinjaShould(String action)
{
Assert.IsTrue(actions.Contains(action));
}
}
}
Ninja.cs is below, compiled to Ninja.dll:
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
namespace NinjaSurvivalRate
{
public class Ninja
{
public Ninja(String beltLevel)
{
}
public List<String> AttackedBy(String opponent)
{
if ("Chuck Norris" == opponent)
return new List<string>(
new String[] { "run for his life" });
else
return new List<string>(
new String[] { "engage the opponent" });
}
}
}
Answers and feedback will be appreciated. Going through similar threads, I found that the resolution depended on a case by case basis and their was no consistent root cause, and felt I had to detail exact code details to get an understanding of the cause. You time and help will be greatly appreciated. Thanks.
You haven't defined the variable ninja. You need:
var ninja = new Ninja(level);
Do the same for actions.
EDIT:
Actually both the variables are supposed to be fields/properties in the class itself, if I understand your intentions correctly.
The tutorial is not telling you the whole history. If you go to the source code you will see that there is actually a field ninja declared that is initialized in the method TheNinjaHasABlackBelt (that you already have).

Categories