MSAL TokenCacheHelper.cs failes to build because of "Protect" and "Unprotect" - c#

I'm am trying to use the provided C# MS Graph/MSAL application to create an application that utilizes the OneDrive API. I literally copy/pasted from the provided example code into my solution and I can't get the solution to build now.
I've ensured that the following NuGet packages are installed:
Microsoft.Graph
Microsoft.Identity.Client
Microsoft.Identity.Client.Desktop
Microsoft.Identity.Client.Extensions.Msal
Microsoft.Identity.Web.TokenCache
Microsoft.Windows.SDK.Contracts
I'm brand new to using MSAL and I'm sure this is just a dumb mistake on my part but any assistance would be greatly appreciated!
Error Received:
Severity Code Description Project File Line Suppression State
Error CS1061 'object' does not contain a definition for 'Unprotect' and no accessible extension method 'Unprotect' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) Test Case Designer D:\code\Test Case Designer\TokenCacheHelper.cs 54 Active
Severity Code Description Project File Line Suppression State
Error CS1061 'object' does not contain a definition for 'Protect' and no accessible extension method 'Protect' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) Test Case Designer D:\code\Test Case Designer\TokenCacheHelper.cs 70 Active
using System.IO;
using System.Security.Cryptography;
using Microsoft.Identity.Client;
using Microsoft.Identity.Client.Desktop;
using System.Windows;
using System.Security;
using Microsoft.Identity.Web.TokenCacheProviders;
using Microsoft.Identity.Client.Extensions.Msal;
namespace Test_Case_Designer
{
static class TokenCacheHelper
{
// <summary>
// Path to the token cache
// </summary>
public static string CacheFilePath { get; private set; }
public static object ProtectedData { get; private set; }
private static readonly object FileLock = new object();
private static void BeforeAccessNotification(TokenCacheNotificationArgs args)
{
lock (FileLock)
{
args.TokenCache.DeserializeMsalV3(File.Exists(CacheFilePath)
? ProtectedData.Unprotect(File.ReadAllBytes(CacheFilePath),
null,
DataProtectionScope.CurrentUser)
: null);
}
}
public static void AfterAccessNotification(TokenCacheNotificationArgs args)
{
// if the access operation resulted in a cache update
if (args.HasStateChanged)
{
lock (FileLock)
{
// reflect changes in the persistent store
File.WriteAllBytes(CacheFilePath,
ProtectedData.Protect(args.TokenCache.SerializeMsalV3(),
null,
DataProtectionScope.CurrentUser)
);
}
}
}
internal static void EnableSerialization(ITokenCache tokenCache)
{
tokenCache.SetBeforeAccess(BeforeAccessNotification);
tokenCache.SetAfterAccess(AfterAccessNotification);
}
}
}

In your code, ProtectedData is defined as an object.
This should have been System.Security.Cryptography.ProtectedData
change
public static object ProtectedData { get; private set; }
to
private static ProtectedData protectedData;
public static ProtectedData GetProtectedData(){
return protectedData;
}
should fix your issue.

Related

Does not contain definition for AddAsync()

I am working on .Net razor pages. I have created a form on submit of form i am handling it using a post handler in .cs file but i am getting an error. I can add AddAsync in my handeler. Error is:-
Severity Code Description Project File Line Suppression State
Error CS1061 'object' does not contain a definition for 'AddAsync' and no accessible extension method 'AddAsync' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) youtubeproject C:\Users\lenovo\Desktop\MXN_INTERN\youtubeproject\youtubeproject\Pages\Categories\Create.cshtml.cs 22 Active
Here is my code of .cs file
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using youtubeproject.Model;
using youtubeproject.Data;
namespace youtubeproject.Pages.Categories
{
public class CreateModel : PageModel
{
public readonly ApolicationDbContext _db;
[BindProperty]
public Category Category { get; set; }
public CreateModel(ApolicationDbContext db)
{
_db = db;
}
public void OnGet()
{
}
public async Task<IActionResult>OnPost()
{
await _db.Category.AddAsync(Category);
await _db.SaveChangesAsync();
return RedirectToPage("Index");
}
}
}

Namespace not found error when trying to compile

Edit: Changing the class name or namespace name so that the namespace and class don't have the same name doesn't fix this issue.
I have this super simple code:
Program.cs:
using System;
using CodeCleaner;
class Program
{
private static void Main(string[] args)
{
Console.WriteLine("DocTypeChecker instantiated");
var codeCleaner = new CodeCleaner.CodeCleaner();
}
}
CodeCleaner.cs:
using System;
namespace CodeCleaner
{
public class CodeCleaner
{
public CodeCleaner()
{
Console.WriteLine("CodeCleaner instantiated");
}
}
}
This produces the following error when I try to compile when I run $ csc Program.cs:
Program.cs(4,7): error CS0246: The type or namespace name 'CodeCleaner' could not be found (are you missing a using directive or an assembly reference?).
I'm definitely not missing a using directive for CodeCleaner, but what it means with assembly reference I have no idea. Other solutions on the web didn't help me in this case. Anyone know the issue here?
Running csc Program.cs won't compile CodeCleaner.cs, so your assembly will be missing the CodeCleaner class and namespace. Using csc Program.cs CodeCleaner.cs should do the trick.

Using Topshelf and Quartz.NET

I'm having problems setting up a basic Quartz.NET and Topshelf integration.
Errors appear when accessing ScheduleQuartzJob:
Error 1 Delegate 'System.Func<ServiceTest.MyService>' does not take 1 arguments
Error 2 Not all code paths return a value in lambda expression of type 'System.Func<Topshelf.Runtime.HostSettings,ServiceTest.MyService>'
Error 3 'Topshelf.Runtime.HostSettings' does not contain a definition for 'ConstructUsing' and the best extension method overload 'Topshelf.ServiceConfiguratorExtensions.ConstructUsing<T>(Topshelf.ServiceConfigurators.ServiceConfigurator<T>, System.Func<T>)' has some invalid arguments
Error 4 Instance argument: cannot convert from 'Topshelf.Runtime.HostSettings' to 'Topshelf.ServiceConfigurators.ServiceConfigurator<ServiceTest.MyService>'
Error 5 'Topshelf.Runtime.HostSettings' does not contain a definition for 'WhenStarted' and no extension method 'WhenStarted' accepting a first argument of type 'Topshelf.Runtime.HostSettings' could be found (are you missing a using directive or an assembly reference?)
Error 6 'Topshelf.Runtime.HostSettings' does not contain a definition for 'WhenStopped' and no extension method 'WhenStopped' accepting a first argument of type 'Topshelf.Runtime.HostSettings' could be found (are you missing a using directive or an assembly reference?)
Error 7 'Topshelf.ServiceConfigurators.ServiceConfigurator<ServiceTest.MyService>' does not contain a definition for 'ScheduleQuartzJob' and no extension method 'ScheduleQuartzJob' accepting a first argument of type 'Topshelf.ServiceConfigurators.ServiceConfigurator<ServiceTest.MyService>' could be found (are you missing a using directive or an assembly reference?)
I think I am missing something obvious here...
Side question: Is there a simpler way to set up a Quartz/Topshelf configuration?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using NLog;
using Quartz;
using Quartz.Impl;
using Common.Logging.Configuration;
using Common.Logging.NLog;
using Topshelf;
namespace ServiceTest
{
public class MyService
{
public bool Start(HostControl control)
{
return true;
}
public bool Stop(HostControl control)
{
return true;
}
}
public class Program
{
private static Logger log = LogManager.GetCurrentClassLogger();
public static void Main(string[] args)
{
var config = new NameValueCollection();
var adaptor = new NLogLoggerFactoryAdapter(config);
Common.Logging.LogManager.Adapter = adaptor;
HostFactory.Run(x =>
{
x.Service<MyService>(sc =>
{
sc.ConstructUsing(() => new MyService());
sc.WhenStarted((service, control) => service.Start(control));
sc.WhenStopped((service, control) => service.Stop(control));
sc.ScheduleQuartzJob(q =>
q.WithJob(() =>
JobBuilder.Create<MyJob>().Build())
.AddTrigger(() => TriggerBuilder.Create()
.WithSimpleSchedule(b => b
.WithIntervalInSeconds(10)
.RepeatForever())
.Build()));
});
x.RunAsLocalSystem()
.DependsOnEventLog()
.StartAutomatically()
.EnableServiceRecovery(rc => rc.RestartService(1));
x.SetDescription("Checker Service");
x.SetDisplayName("Checker Service");
x.SetServiceName("CheckerService");
x.UseNLog();
});
}
}
public class MyJob : IJob
{
private static Logger log = LogManager.GetCurrentClassLogger();
public void Execute(IJobExecutionContext context)
{
log.Info("It is {0} and all is well", DateTime.UtcNow);
}
}
}
Needed to add a reference to Topshelf.Quartz!
I knew it was something stupid and simple.

HttpContext.GetGlobalResourceObject not exist in Class Library

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........
}
}

C# MVC7 DNX5 MSSQL

Got a Noob question. I am trying to write a C# MVC Application to connect to an MS SQL DB using the Entity Framework. But I am getting the following error.
Severity Code Description Project File Line Suppression State
Error CS1061 'DatabaseFacade' does not contain a definition for 'SqlQuery' and no extension method 'SqlQuery' accepting a first argument of type 'DatabaseFacade' could be found (are you missing a using directive or an assembly reference?) HAPI.DNX 4.5.1, HAPI.DNX Core 5.0
My Code is as follows
DB Context Class which flags no issues.
using Microsoft.Data.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Something.Models
{
public class RulesDbContext: DbContext
{
public DbSet<Rules> Rules { get; set; }
}
}
Calling Class with errors on the Sql Statements highlighted in bold
using System.Collections.Generic;
using System.Linq;
using Microsoft.Data.Entity;
namespace Something.Models
{
public class ReadRules
{
private RulesDbContext db = new RulesDbContext();
private void Rules()
{
List<Rules> rulesMeta = db.Database.**SqlQuery**<Rules>("GetRuleMetaData #deviceID",
new **SqlParameter**("deviceID", deviceID)).ToList();
}
}
}

Categories