Blazored/LocalStorage working in a service class? - blazored

Is there an example to Inject the Blazored/LocalStorage in a Singleton Service Class? Or how can I get an instance of the Blazored/LocalStorage within the Service Class as needed? (So not injected but on-demand)
I had an example of the code I wrote, but was asked to reduce the detail in the question so making it a more broad question.
I am new to coding in Blazor, so apologize if I didn't provide the right information, or this is a stupid question and I am guessing there is something simple I am missing.
Any help would be greatly Appreciated.

Ok. So I had to do a couple of things to make this work, but seems to be working.
For some reason I had to close my VS and reopen because all my breakpoints were being captured by the browser instead of VS.
I modified the code to have:
private IlocalStorageService localStorage;
public AppSettingsService(IlocalstorageService inLocalStorage)
{ localStorage = inLocalStorage; }
In my progam.cs I have
builder.Services.AddBlazoredLocalStorage();
builder.Services.AddScoped<IAppSettingsService, AppSettingsService>();
FYI.. AppSettingsService is a new service I created that each component will Inject so that component can get to the local storage, and will use this AppSettingsService to raise events any time a value changes from another component so all other components can update their state.
As I continue to learn, apologize if I wasted anyone's time.
Thanks

Related

Cannot resolve dependency in a custom ValidationAttribute, IServiceProvider is set to null on the ValidatationContontext parameter

An ASP.NET Core 2.1 MVC app, using Autofac following their documentation on setup (https://autofaccn.readthedocs.io/en/latest/integration/aspnetcore.html).
I am trying to resolve a dependency in a custom ValidationAttribute. The returned value from valicationContext.GetService is always returning null. Inspecting the validatationContext the private member serviceProvider is always null.
what am I missing in the setup that this isnt working. The dependancies resolve everywhere else in the app, just not in the ValidationAttributes.
public class MyCustomAttribute : ValidationAttribute
{
public MyCustomAttribute ()
{
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// THIS IS ALWAYS RETURNING NULL
var IMyService service = (IMyService)validationContext.GetService(typeof(IMyService));
return ValidationResult.Success;
}
}
I can't say I've tried this before, but doing some searching I found this issue which seems to indicate that the service provider (not the ServiceContainer property, but the service provider that will respond to GetService calls) should always be populated. Granted, that's from an archived repo from early on in .NET Core, but it should still hold.
Looking at the source for ValidationContext I see that the private serviceProvider field is actually a function that needs to be instantiated somewhere; it's not actually a reference to a provider proper. That means if it's null, one of two things is happening:
The path through ASP.NET Core that's instantiating that ValidationContext is not passing in the IServiceProvider required to provide services.
Something is broken.
If it's #1, I'd guess there are a variety of potential reasons. I'd think about things like...
The attribute is being used by something running outside the "ASP.NET Pipeline" - like a manually invoked validation or possibly something at application startup where there's no request at the moment.
The attribute is being used in a test where the full pipeline isn't in effect.
Something like that. I'm not saying this is what's happening, but I've seen questions like this before where it appears something isn't working right when it's actually an application code problem. For example, there are lots of questions about why "instance-per-request" dependencies aren't working and it turns out the code is running on a background thread where there's no request so... yeah. I don't know how your app works, but that sort of "I'm doing something I forgot to mention because I didn't think it was relevant" stuff comes into play here.
Let's assume you've got a super vanilla ASP.NET Core app, though. Based on the issue I mentioned earlier and the code you've posted, this looks like it should work but it's not. There shouldn't be anything you need to wire up for this, it should just work. Given that, you might want to file an issue about it. You may have found something that legitimately isn't working.
Before you do that, you might want to debug a little more. You can step right into ASP.NET Core source code and that could help you figure out what's up. The article I linked there explains how to set it up. It's not a two step process and needs screen shots to help or I'd put it right in here.
Set a breakpoint on your failing statement up there and then switch over to the Visual Studio "call stack" window. Click on the call stack frames higher up in the stack and see what's actually creating that context object. With a little clicking around and intuition you can probably figure out where the issue is. Maybe it'll point to something in your app you didn't realize you were doing, maybe it'll point to a bug in ASP.NET Core. If it's a bug in ASP.NET Core, having the information you found from your debugging session will be really helpful to that team.
Finally, I'd be remiss if I didn't mention that manually resolving a service in an attribute like this is technically service location rather than dependency injection and it'd be a better all-around solution if you avoided it entirely. There's an extremely similar question to yours right here walking through how to get around this with Simple Injector, though the principle holds for Autofac, too. Setting up model validators and using a model validator provider rather than attributes might be a better, more testable way to go. The answer in that question has more explanation on this.

testing ASP.net MVC 3 business/data logic

What is the best way to test data access layers and business logic in mvc 3 solutions?
I currently have a project where I am using repository classes to access databases, which in turn use hibernate. When I try to create a unit test for them in the auto generated unit tests, they always fail since the configuration for nhibernate is in web.config and and it doesnt try to look there. What am i doing wrong? This particular method returns this error
"The Web request 'http://localhost:35601/' completed
successfully without running the test"
The test methods look like this
[TestMethod()]
[HostType("ASP.NET")]
[AspNetDevelopmentServerHost("C:\\Users\\...", "/")]
[UrlToTest("http://localhost:35601/")]
public void GetByIdTest()
{
string someid= "..";
SomeObj actual = MyRepository.GetById(someid);
Assert.AreEqual(some, SomeObj.id);
}
How do i get this to work properly?
Putting the settings in the app.config should solve the issue you posed above however, the more correct answer is that you should be using a mocking framework to mock the nHibernate session.
The fact that you found an area that you would need to change to accomodate testing is great!!! That is one advantage of unit testing; you find coupling in your code that should be refactored.
I found another post that addresses what you are trying to do directly Mocking an NHibernate ISession with Moq. There are two answers in the post that offer to approaches which may be helpful.
I hope this helps. I havent used nHibernate so I can't speak authoritatively about it or that the link above will provide you with an answer, but each answer has ten upvotes so it looks like it was a solid post!

WCF Services - splitting code into multiple classes

I'm currently looking at developing a WCF Service for the first time, but am a bit confused.
Say I've got a windows application that is going to call into this web service, that service is then going to call our data methods to retrieve and save the data.
Now, say for example we have 2 classes in our solution, Customer and Product. Do all methods within the service have to go into the same class file (e.g. MyService.svc), or can they be split into several classes replicating the main data layer, i.e. Customer.cs and Product.cs. If they can be split, how do these get called from within the windows forms application? Would each class be a different end point?
At the moment I can access the methods within the main class (e.g. MyService.svc), but I can't see any of the methods in the other classes, even though I have attributed them with "ServiceContract" and "OperationContract".
I have a feeling I'm missing something simple somewhere, just not sure what.
I would be grateful if some nice person could point me in the direction of a tutorial on doing this, as every tutorial I've found only includes the single class :)
Thanks in advance.
What you need to define is Data Contracts for your service
Theoretically, these data contracts could be your business entities (since 3.5 SP1 and its WCF poco support)
It's better though to create separate entities for your service and then to create conversion classes that can convert your business entities into service entities and the other way around
Actually, after loads of searching, I finally seemed to find what I was looking for just after posting my question (typical).
I've found the following page - http://www.scribd.com/doc/13136057/ChapterImplementing-a-WCF-Service-in-the-Real-World
Although I've not gone through it yet, it does look like it will cover what I'm after.
Apologies for wasting anyones time :) Hopefully this will be useful to someone else looking for the same thing.
It sounds like you only need one service. However, if you need to create multiple services. Consider this as an example.
[ServiceContract(Name = "Utility", Namespace = Constants.COMMON_SERVICE_NAMESPACE)]
public interface IService
[ServiceContract(Name="Documents", Namespace = Constants.DOCUMENTS_SERVICE_NAMESPACE)]
public interface IDocumentService
[ServiceContract(Name = "Lists", Namespace = Constants.LISTS_SERVICE_NAMESPACE)]
public interface IListService
Remember that you can create multiple data contracts inside a single service, and it is the best solution for a method that will require a reference to Customer(s) and Product(s).
It might help to take a look at MSDN's data contract example here.

Documentation of the lesser know AS3 properties

Over the past three weeks, I have lost at least 120 man hours because of some lesser known functionality in ActionScript 3. One of the problems was that, with Internet Explorer, if there are too many messages sent through LocalConnections, it will slow the messages sent through, but in the standalone player and in Firefox, this threshold is significantly higher. Another was that the static values of a class are instantiated even if the member itself is not being used:
import path.to.FooClass;
private function thisIsNeverCalledButItEnsuresThatFooClassIsImported():void
{
var f:FooClass = new FooClass();
}
Since FooClass had a static reference to a Singleton, that Singleton was instantiated so when I loaded a Module which used that Singleton, it would bind to values in an unpredictable way.
Additional cases where things behave in an unexpected way:
MovieClip.addFrameScript
flash.trace.Trace as a class
int is a faster incrementer class, Number is faster for mathematics, and uint is incredibly slow.
PrintDataGrid, if it has only one page, needs to have an empty value appended to the end of its dataProvider
If you use try...catch around two LocalConnections and connect them to the same channel, you will force garbage collection without needing System.gc
So here's the question (and I'm sorry for omitting this in the original post), is there any consolidated documentation for this type of behavior anywhere? Is there any (even non-Adobe) documentation on these issues (websites, forums, books, ANYTHING)? I know that these things are definitely easy enough TO document, but has anyone done so?
If not, am I missing anything? Are there other issues which I should know about?
This kind of useful information is very often not "centralized". Moreover, what you are looking for is something related to the experience of the programmer (more than to official docs).
FYI, there are two other methods for ensuring a class is included.
#1 - This syntax is actually used in the Flex source code:
import path.to.FooClass; FooClass; // note double reference
public class References
{
// No references needed in this class
}
#2 - Use the includes command line argument
-includes path.to.FooClass
You can always submit your experience using the "feedback" section in the help. Unfortunately, this is less obvious than the link that used to be at the bottom of each page in the older help files (which also served the useful function of opening a browser window with the web version of that help page).
Adobe says that it incorporates the comments from previous versions of the help into new versions, but my own observation suggests that there are instances where it does not happen. However, that and the appropriate cookbook are still the best avenue for those who believe that this kind of information should be centralized.
Note that the whole purpose behind modules is to avoid compiling code multiple times, so importing FooClass kind of defeated the purpose. The problems you had in this instance are just one of the many that happen if you use Singletons, and it's unfortunate that the first official Framework, Cairngorm, encouraged their widespread use. Check out http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/ .

Looking for a simple explanation on using trace logging

I have seen several projects that use the Trace functionality to capture events and stream them out to a log file. I have been unsuccessful in finding a simple to follow guide that will show me how to configure Trace to capture and write said logfile. Does anyone have a link recommendations, or provide some simple steps to follow?
The Trace object writes the statements to any attached TraceListeners. You can build your own, but there are a number already defined in the System.Diagnostics namespace, including:
ConsoleTraceListener (Console)
DefaultTraceListener (Visual Studio / Debugger)
DelimitedListTraceListener (TextWriter, special formatting)
EventLogTraceListener (EventLog - anything that inherits from System.Diagnostics.EventLog)
TextWriterTraceListener (TextWriter - think file)
You can, of course, inherit your own from the TraceListener class that writes to where ever you want. For example, you could log to a database, have it send e-mails or pages in certain situations, or write the statements back to a logging platform like log4net.
The big thing is that you need to create an instance of whatever listeners you want and then add them to the Trace' class Listeners collection. You can add as many as you need and Trace will write to all of them. This way, you can write your logging code once using a well-supported and understood object that's part of the framework, and you can attach anything you need to it.
I stumbled into a MSDN article that really helps. Sorry I didn't find it before posting the question but perhaps others may have the same question and haven't found this link.
Take a look at logging frameworks. We rolled out own, but are now migrating over to log4net available free at http://logging.apache.org/log4net/
Im looking for a way to set the Category of the EventLog, the FormattedEventLogTraceListener writes into (not the category of the message).
But I can't find an appropriate property of this class.
Is it possible to set this?

Resources