HttpContext.Current.Session.SessionID is throwing "Object reference error" when instantiated outside of the project - httpcontext

I have web application project name say project1 in which i have class Class A. Inside which i have a field
readonly string sessionId = HttpContext.Current.Session.SessionID;
my sample class looks like this
public class A
{
readonly string sessionId = HttpContext.Current.Session.SessionID;
--other code;
}
Now i am having webapi and referencing the project in the API controller.
i am trying to create an instance of the class A using new keyword
this is throwing the object reference error at line the HTTPContext in the class.
Please let us know how to resolve the dependency on this httpcontext object.

Related

Unable to resolve service for type 'System.String' while attempting to activate in .net core

I have a factory class and it has a constructor where dependency injection is implemented. When trying to register the factory method in program.cs file I get the below error when running the application. "Unable to resolve service for type 'System.String' while attempting to activate 'Factory".
public class Factory : IFactory
{
private readonly A _a;
private readonly string _test;
public Factory(A a, string sample)
{
_a= a;
_test= string.IsNullOrEmpty(sample) ? string.Empty : Path.GetFullPath(sample);
}
private string Create(long id)
{
var b = _test.make(id);
return b;
}
}
In program.cs file how can we register this string element _test? Can anyone help!
It is because your Factory constructor is not parameter-less, and when the service provider tries to instantiate the Factory, it has no value to pass for the "sample" variable.
There are two possible solutions to this:
1- Changing the design of your factory, and passing the "sample" as a variable to Create method instead of the constructor.
OR
2- Registering the factory like this:
services.AddSingleton(s => new Factory(s.GetService<A>(), "desired string"));
Btw, I don't know what is the use case that you have for implementing this factory class, but it doesn't seem the right way of implementing it. I suggest you take a look at this beforehand:
Factory Design Pattern

Privately declared properties in C# don't show up in TypeScript in SPA

So, i'm not sure what i'm doing wrong here but for some reason the callback function in TypeScript that i have doesn't have anything but _proto in the response's .data property whenever i set private properties in C# and new up an object that is filled with constructed properties. However, if the properties are public and i don't use a constructor then i can see the response's .data property is filled like i would expect it to be. Here is an example of what works:
public class ThisWorks{
public string MyProperty{get;set;}
}
Inside application layer:
ThisWorks example = new ThisWorks();
example.MyProperty = myReflectedProperty;
return example;
However, this does not work:
public class ThisDoesNotWork{
private string MyPrivateProperty {get;set;}
public ThisDoesNotWork(string myPrivateProperty){
MyPrivateProperty = myPrivateProperty;
}
}
What's causing this to happen? My TypeScript service has not changed but for some reason the data isn't coming across from the service call...Any help would be greatly appreciated!

Entity Framework errors while saving base class if there is any inheritance

I am using EF 6.1. I have a model "Request" built from the wizard directly from my database. In my context file (EMContext.vb) I have
Public Overridable Property Requests As DbSet(Of Request)
When I type in
Dim db As New EMContext
Dim req As New Request()
With req
.RequestedBy = "bar"
.EventName = "Goo"
.RequestedOn = Now
.RequestStatusID = 1
End With
db.Requests.Add(req)
db.SaveChanges()
everything works exactly as expected. No problems. It saves.
However, if I add a class (anywhere in the app)
Class foo
Inherits Request
Public Property s As String
End Class
and then run the exact same code I get
{"An error occurred while updating the entries. See the inner exception for details."}
Looking at the inner exception:
{"Invalid column name 's'.
Invalid column name 'Discriminator'."}
Why in the heck is it even looking at the inherited class properties?
BTW, if I remove all the properties from the inherited class, I still get the Invalid Column 'Discriminator' error.
Then create a custom class that the json parses to and then you can call the Entity and make it from this class.
<Serializable()>
Public Class jSonParsedObject
'properties that match the Entity object
'custom properties you need for other work
End Class
Usage:
Dim jsonObj As jSonParsedObject = SomeMethodThatParsesAndReturnsData()
Dim req As New Request()
With req
.RequestedBy = jsonObj.RequestedBy
.EventName = jsonObj.EventName
.RequestedOn = jsonObj.RequestedOn
.RequestStatusID = jsonObj.RequestStatusID
End With
...

asp.net c# Automap a class from within that class

To best describe what I want to happen, i'll show what i'm doing, as to me it makes sense that this would work ...
public class foo()
{
public foo()
{
MyContext db = new MyContext();
foobar = db.foobar.first();
this = Mapper.Map<bar, foo>(foobar);
}
}
Basically, I want to use automapper within the destination class to map from the source class within the destination classes constructor.
Is there a way to do this?
You cannot do this because this is read only in C#. You cannot assign this a value in the constructor. Not cool to try to change the reference of an object in its constructor. You will have to do the mapping manually and assign each individual property. I would also question if it as a good practice to assign an object values from a database or service in a default constructor. It is not very transparent to the user of the object what is going on and you can get an exception in your constructor.

Dozer BeanFactory: How to implement it?

I have looked at the Dozer's FAQs and docs, including the SourceForge forum, but I didn't see any good tutorial or even a simple example on how to implement a custom BeanFactory.
Everyone says, "Just implement a BeanFactory". How exactly do you implement it?
I've Googled and all I see are just jars and sources of jars.
Here is one of my BeanFactories, I hope it helps to explain the common pattern:
public class LineBeanFactory implements BeanFactory {
#Override
public Object createBean(final Object source, final Class<?> sourceClass, final String targetBeanId) {
final LineDto dto = (LineDto) source;
return new Line(dto.getCode(), dto.getElectrified(), dto.getName());
}
}
And the corresponding XML mapping:
<mapping>
<class-a bean-factory="com.floyd.nav.web.ws.mapping.dozer.LineBeanFactory">com.floyd.nav.core.model.Line</class-a>
<class-b>com.floyd.nav.web.contract.dto.LineDto</class-b>
</mapping>
This way I declare that when a new instance of Line is needed then it should create it with my BeanFactory. Here is a unit test, that can explain it:
#Test
public void Line_is_created_with_three_arg_constructor_from_LineDto() {
final LineDto dto = createTransientLineDto();
final Line line = (Line) this.lineBeanFactory.createBean(dto, LineDto.class, null);
assertEquals(dto.getCode(), line.getCode());
assertEquals(dto.getElectrified(), line.isElectrified());
assertEquals(dto.getName(), line.getName());
}
So Object source is the source bean that is mapped, Class sourceClass is the class of the source bean (I'm ignoring it, 'cause it will always be a LineDto instance). String targetBeanId is the ID of the destination bean (too ignored).
A custom bean factory is a class that has a method that creates a bean. There are two "flavours"
a) static create method
SomeBean x = SomeBeanFactory.createSomeBean();
b) instance create method
SomeBeanFactory sbf = new SomeBeanFactory();
SomeBean x = sbf.createSomeBean();
You would create a bean factory if creating and setting up your bean requires some tricky logic, like for example initial value of certain properties depend on external configuration file. A bean factory class allows you to centralize "knowledge" about how to create such a tricky bean. Other classes just call create method without worying how to correctly create such bean.
Here is an actual implementation. Obviously it does not make a lot of sense, since Dozer would do the same without the BeanFactory, but instead of just returning an object, you could initialized it somehow differently.
public class ComponentBeanFactory implements BeanFactory {
#Override
public Object createBean(Object source, Class<?> sourceClass,
String targetBeanId) {
return new ComponentDto();
}
}
Why do you need a BeanFactory anyways? Maybe that would help understanding your question.