How can I create instance of HttpRequestHeaders class - asp.net-web-api2

I have to unit test class that use HttpRequestHeaders as parameter.
public HeaderValueProvider(HttpRequestHeaders headers)
{
_headers = headers;
}

HttpRequestHeaders has only internal constructor.
But you can do it by creating HttpRequestMesssage object:
using var headers = new HttpRequestMessage().Headers;

You can get a blank instance of HttpRequestHeaders via:
var headers = new HttpClient().DefaultRequestHeaders;

Related

Override WebApiConfig formatting

In the Register method of my Web API 2 project I've added this bit of code so that the returned JSON is automatically camel cased:
public static void Register(HttpConfiguration config) {
var settings = config.Formatters.JsonFormatter.SerializerSettings;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
settings.Formatting = Formatting.Indented;
I have one or two methods, though, where I do not want it to do that, and really want the casing to be left alone. From an individual route's method is there a way to override that?
I have hundreds of methods that want it, and just a couple that don't.
You can try something like below to bypass Global Formatters settings,
public HttpResponseMessage Get()
{
Person content = new Person() { PersonID = 1, PersonName = "name" };
HttpResponseMessage resposne = new HttpResponseMessage();
resposne.Content = new ObjectContent(content.GetType(), content, new JsonMediaTypeFormatter());
return resposne;
}

Cannot populate POJO with JSON using Jackson

I'm trying to populate a POJO from a JSON that doesn't really match in any way and am having trouble getting this resolved. I can't change the JSON since it is an external service but I maybe able to modify the POJO if needed.
Below is an example JSON:
{"Sparse":[{"PixId":1,"PixName":"SWE","Description":"Unknown"},{"PixId":2,"PixName":"PUMNW","Description":"Power Supplement"}],"Status":0,"Message":null}
Below is the POJO:
#JsonIgnoreProperties(ignoreUnknown = true)
public class Pix {
#JsonProperty("Description")
private String description;
#JsonProperty("PixId")
private int pixId;
#JsonProperty("PixName")
private String pixName;
// getters and setters
}
And here is my code to do the conversion:
ObjectMapper om = new ObjectMapper();
om.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
om.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
List<Pix> pixList = om.readValue(pixJson, new TypeReference<List<Pix>>() {});
The pixList contains only 1 element (should be 2 using the JSON above) and all the properties have not been populated. I'm using Jackson 1.9.9. Any ideas on how to get this to work? TIA.
You have to create new POJO class for main object which contains the List<Pix>. It could looks like this:
class Root {
#JsonProperty("Status")
private int status;
#JsonProperty("Message")
private String message;
#JsonProperty("Sparse")
private List<Pix> sparse;
//getters/setters
}
And now your deserialization code could looks like this:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
List<Pix> pixList = mapper.readValue(pixJson, Root.class).getSparse();

Ninject manual initialization with constructor injection

How do I do constructor injection when I'm manually initializing the class?
public class ApiKeyHandler : DelegatingHandler
{
private IApiService apiService;
public ApiKeyHandler(IApiService apiService)
{
this.apiService = apiService;
}
}
Initializing:
var apiKey = new ApiKeyHandler(/*inject here */);
How do I accomplish this? My bindings and everything is already setup.
You want to do something like this:
var apiKey = new ApiKeyHandler(kernel.Get<IApiService>());
However, why not inject the ApiKeyHandler itself?
var apiKey = kernel.Get<ApiKeyHandler>();
Here is an article about Ninject:
You basically want to set this up at the beginning of your code and have it available globally:
public IKernel kernel = new StandardKernel();
...
kernel.Bind<IApiService>()
.To<SomeConcreteApiService>();

composing MEF parts in C# like a simple Funq container

In Funq and probably most other IoC containers I can simply do this to configure a type:
container.Register<ISomeThing>(c => new SomeThing());
How could I quickly extend MEF (or use existing MEF functionality) to do the same without using attributes.
Here is how I thought I could do it:
var container = new CompositionContainer();
var batch = new CompositionBatch();
batch.AddExport<ISomeThing>(() => new SomeThing());
batch.AddExportedValue(batch);
container.Compose(batch);
With this extension method for CompositionBatch:
public static ComposablePart AddExport<TKey>(this CompositionBatch batch, Func<object> func)
{
var typeString = typeof(TKey).ToString();
return batch.AddExport(
new Export(
new ExportDefinition(
typeString,
new Dictionary<string, object>() { { "ExportTypeIdentity", typeString } }),
func));
}
If I later do:
var a = container.GetExport<ISomeThing>().Value;
var b = container.GetExport<ISomeThing>().Value;
Both instance are the same. How can I force (configure) them to be different instances?
If this is not the way to go, how would I do this in MEF?
I would imagine the key is to add the delegate to the container, e.g.:
container.AddExportedValue<Func<ISomething>>(() => new Something());
That way you can grab the delegate and execute it:
var factory = container.GetExport<Func<ISomething>>();
ISomething something = factory();
Of course, MEF (Silverlight) does provide a native ExportFactory<T> (and ExportFactory<T,TMetadata> type that supports the creation of new instances for each call to import. You can add support for this by downloading Glen Block's ExportFactory for .NET 4.0 (Desktop) library.
If you don't want to use attributes, you can use this trick (based on Mark Seemann's blogpost).
First, create a generic class like this:
[PartCreationPolicy(CreationPolicy.NonShared)]
public class MefAdapter<T> where T : new()
{
private readonly T export;
public MefAdapter()
{
this.export = new T();
}
[Export]
public virtual T Export
{
get { return this.export; }
}
}
Now you can register any class you want in the container, like this:
var registeredTypesCatalog = new TypeCatalog(
typeof(MefAdapter<Foo>),
typeof(MefAdapter<Bar>),
...);
var container = new CompositionContainer(catalog);
Alternatively, you could implement your own export provider derived from ExportProvider, which allows you to pretty much duplicate Funq's way of working:
var provider = new FunqyExportProvider();
provider.Register<IFoo>(context => new Foo());
var container = new CompositionContainer(provider);
Both instance are the same. How can I force (configure) them to be different instances?
Simply mark the SomeThing class like this:
[Export(typeof(ISomeThing)]
[PartCreationPolicy(CreationPolicy.NonShared]
public class SomeThing : ISomeThing
{
...
}
And then you will get different instances wherever you import ISomeThing.
Alternatively, you can also set a required creation policy on an import:
[Export(typeof(IFoo))]
public class Foo : IFoo
{
[Import(typeof(ISomeThing),
RequiredCreationPolicy = CreationPolicy.NonShared)]
public ISomething SomeThing { private get; set; }
}
In Glen Block's Skydrive directory linked to in Matthew Abbott's answer I found something that seems simple and lightweight: A FuncCatalog. Download it here: FuncCatalogExtension.
Using the few little classes from that project I could now do this:
var funcCatalog = new FuncCatalog();
funcCatalog.AddPart<ISomeThing>(ep => new SomeThing());
var container = new CompositionContainer(funcCatalog);
var batch = new CompositionBatch();
batch.AddExportedObject<ExportProvider>(container);
container.Compose(batch);
var a = container.GetExportedObject<ISomeThing>();
var b = container.GetExportedObject<ISomeThing>();

How to share variables between feature runs in Karate?

I have an application that creates a token once by using karate.callSingle() in my karate-config file.
This token however expires after some time, so I might need to recreate it after some tests.
My plan would be to set the time of creation in a variable that can be shared in subsequent iterations of the karate-config file, so that I can recreate the token if the time difference is big enough.
Is there a way in Karate in which I can set a variable in the karate-config that can be shared in subsequent iterations ?
In the end I followed Peter Thomas' advice and used Java by "caching" properties between features. Here's my implementation :
var tokenRefreshTimeInMinutes = 5;
var myToken = {};
var KarateCache = Java.type('KarateCache');
var lastRefreshTime = KarateCache.get('lastRefreshTime');
if (!lastRefreshTime || differenceInMinutes(new Date(lastRefreshTime), new Date()) >= tokenRefreshTimeInMinutes) {
myToken = karate.call('theFileRefreshingTheToken');
KarateCache.add('lastRefreshTime', new Date().toUTCString());
KarateCache.add('myToken', JSON.stringify(myToken));
} else {
myToken = JSON.parse(KarateCache.get('myToken'));
}
with this simple KarateCache Java class
private static final Map<String, String> KARATE_CACHE = new ConcurrentHashMap<>();
public static void add(String key, String value) {
KARATE_CACHE.put(key, value);
}
public static String get(String key) {
return KARATE_CACHE.get(key);
}
Are you storing the result of callSingle() to a variable? Like:
var tokenResult = karate.callSingle('createToken.feature', config);
If you save the expiration time to a variable expirationTime inside createToken.feature, you can access it in karate-config.js as tokenResult.expirationTime.