Tumgik
aprenticedev · 7 years
Text
Mismatched and Ambiguous lifestyles - DI in .Net with SimpleInjector
I have added a new service to exiting solution. It was diligently registered in entry (startup) project like:
container.Register(Lifestyles.Scoped);
I injected it in an Web API controller, pressed F5 and boo… got this exception:
SimpleInjector.DiagnosticVerificationException occurred HResult=0x80131500 Message=The configuration is invalid. The following diagnostic warnings were reported: -[Short Circuited Dependency] FabulousApiController might incorrectly depend on unregistered type FabulousConcept (Transient) instead of IFabulousConcept (Web Request). -[Ambiguous Lifestyles] The registration for FabulousConcept (Transient) maps to the same implementation (FabulousConcept) as the registration for IFabulousConcept (Web Request) does, but the registration maps to a different lifestyle. This will cause each registration to resolve to a different instance. -[Ambiguous Lifestyles] The registration for IFabulousConcept (Web Request) maps to the same implementation (FabulousConcept) as the registration for FabulousConcept (Transient) does, but the registration maps to a different lifestyle. This will cause each registration to resolve to a different instance. See the Error property for detailed information about the warnings. Please see https://simpleinjector.org/diagnostics how to fix problems and how to suppress individual warnings. Source=SimpleInjector StackTrace: at SimpleInjector.Container.ThrowOnDiagnosticWarnings() at SimpleInjector.Container.Verify(VerificationOption option) at Fabulous.Website.Startup.ConfigureDependencyResolution() in C:\Source\Fabulous.Website\App_Start\Startup.DI.cs:line 31 at Fabulous.Website.Startup.Configuration(IAppBuilder app) in C:\Source\Fabulous.Website\Startup.cs:line 24
I was baffeled, as I think I know a bit about SimpleInjector. After beating around the bush for sometime, I hit it.
It was rather innocent (really?) mistake of declaring:
private readonly FabulousConcept _fc;
and then using Resharper to take care of initing it from constructor of the function. There it was! Instead of interface IFabulousConcept
, which was registered with SimpleInjector, I was asking for FabulousConcept class which was unregistered and thus treated as a transient lifestyle.
Changing above declaration (and initializing code in constructor) to following fixed it:
private readonly IFabulousConcept _fc;
Happy Coding!
0 notes
aprenticedev · 7 years
Text
Assigning File Permission For ApplicationPoolIdentity in IIS 8
Everything was going fine after publishing a new web application to IIS 8 on Windows Server 2014. Then suddenly I saw few errors in logs like:
System.UnauthorizedAccessException Access to the path 'C:\inetpub\wwwroot\wodnerful-app\reports\Q1 2017.pdf' is denied. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode) at WonderfulApp.Controllers.Api.Reports.d__4.MoveNext()
The files were under root application folder. The application was running under ApplicationPoolIdentity in its own application pool.
I checked the permissions on folder for following principals/groups:
IIS_User
IUSR
Authenticated Users
Network Service
Well, all had the read and execute permissions.
Clearly the ApplicationPoolIdentity under which the website was running was not (or part of) anyone of the above.
I looked at it in Task Manager and it showed WonderfulApp as user running this (w3wp.exe) process.
It seemed straightforward at this point: go to the folder, right-click select Properties>Security>Advanced>Add>Select a principal> type user name in the box and click Check Names button.
But whatever I did, it was not getting the WonderfulApp user/principal that was shown in Task Manager.
After fiddling around and googling about it, I stumbled upon this answer on Severfault. It required to type IIS APPPOOL Yep those are 3 Ps before the WonderfulApp like this: IIS APPPOOL\WonderfulApp.
Giving appropriate permissions to IIS APPPOOL\WonderfulApp made it work
So in short, if your app is running under ApplicationPoolIdentity and you are not impersonating, your user name should be IIS APPPOOL\ApplictaionPoolName
Happy Coding!
0 notes
aprenticedev · 7 years
Text
Making hubot work in Docker!
Hubot is a scriptable bot by Slack. I had attended an online introductory course on Docker.
I was not able to keep up live with the excercise as I got issues with setting up docker at first (pending for another post).
Once I was able to setup docker container, the bot never went up :(
I checked the logs from container. It said something like:
hubot stderr | supervisor: couldn't exec /data/app/bin/hubot-env: ENOENT
After googling for sometime, I got a pointer that this happens if some script is not there or not running for some reason.
I logged into bash shell of container.
docker exec -it bot /bin/bash
After trying to run the bot using hubot script. It compalained about coffeescript, as this is what it uses to run scripts.
/usr/bin/env: coffee: No such file or directory
Turns out hubot uses system coffeescript to do stuff!
Now, the problem was how to make sure it is installed on the container before running hubot.
I tried to write it into few scripts like:
added RUN npm install -g coffee startup script that calls hubot: did not work
added packag coffee to packages.json: installed coffeescript but hubot did not work
add RUN npm install -g coffee: Worked!
Now we had Coffee Script on the container image but the bot still did not come to life. I went into bash shell again. When I tried to run the startup script I was hit with this issue:
bash: /bin/bash^M: bad interpreter: No such file or directory
Well this seemed easy at first. It was compalining becuase I was editing the startup script in VS Code and was saved with Windows line ending(CR-LF). I changed it to use Unix/Linux line ending (LF). But for some reason container still complained about it.
Again looking for a solution, I found out about dos2unix package. I added following two lines to my Dockerfile:
RUN apt-get install dos2unix
RUN dos2unix /path-to-script/hubot-env
At last, this did the trick and I was able to see my bot go green!
0 notes
aprenticedev · 8 years
Text
404 in WebAPI
I've just wasted an hour struggling with 404 error in an Asp.Net WebAPI. I have enabled attriburte routing and already have few controllers working with attribute routes.
But this particular one was not working and I was clueless. I tried adding a simple action like:
[HttpGet] [Route("test/{a:int}")] public string Test(int a) { return "Works!"; }
But nothing worked.
Well it turned out to be simple case of wrong using statements :(
Instead of using System.Web.Http; there was using System.Web.Mvc; I had added file as WebApi2 Controller, but don't know how it turned out to be there. The RoutePrefix and Route attributes were from Mvc assembly so WebAPI was not picking them.
0 notes
aprenticedev · 8 years
Video
<strong>20160321_100534 <a href="https://www.flickr.com/photos/amantur/">by Amandeep Singh</a></strong>
0 notes
aprenticedev · 8 years
Video
<strong>Grampians National Park <a href="https://www.flickr.com/photos/amantur/">by Amandeep Singh</a></strong>
0 notes
aprenticedev · 8 years
Text
Package Id “Project_Name” contains invalid characters - nuget
I was trying to compile Dapper.SimpleCRUD package for .Net 5.4. After fixing the references and packages, I tried to build nuget package once project was successfully building. I started giving following error:
The package ID 'Dapper.SimpleCRUDNET 5' contains invalid characters. Examples of valid package IDs include 'MyPackage' and 'MyPackage.Sample'.
Luckily the solution was easy. The space in path for the project was causing the problem. Once `Dapper.SimpleCRUDNET 5` was converted to `Dapper.SimpleCRUDNET5` it successfully created the package.
Happy Coding!!!
0 notes
aprenticedev · 8 years
Video
Derek Sivers from Chris Guillebeau on Vimeo.
0 notes
aprenticedev · 9 years
Text
Using System.Tuple with many arguments!
It starts looking mess soon when you have some thing like this:
Tuple<IList<Type1>, IList<Type2>, IList<Type3>, IList<Type4>, IList<Type5>> tuple;
and you have to pass this as an argument to few function or is returned from some functions, it gets messy quickly with function definitions wrapped into multiple lines.
Well, we can give it s sweet-short name via a using statement:
using MyTuple = Tuple<IList<Type1>, IList<Type2>, IList<Type3>, IList<Type4>, IList<Type5>>
Happy Coding!
2 notes · View notes
aprenticedev · 9 years
Text
Openssl for Windows: Unable to read configuration file
I was generating some certificates for testing on my windows machine and kept getting following error:
D:\tools\openssl\openssl req -new -x509 -key test.pem -out testPublicKey.cer -days 365 WARNING: can't open config file: D:\tools\openssl\openssl.cfg Unable to load config info from D:\tools\openssl\openssl.cfg
Though the cfg file was there in the folder. But turned out OpenSSL reads from environment variable OPENSSL_CONF. So setting it to correct path resolved the issue:
SET OPENSSL_CONF=D:\tools\openssl\openssl.cfg
Ref: Stackoverflow and tbs-certificates faq page
0 notes
aprenticedev · 9 years
Photo
Tumblr media
Tying the Turban: A young photographer turns his lens toward Sikhs and their turbans, strengthening his own faith in the process.
76 notes · View notes
aprenticedev · 9 years
Text
Session getting reset on redirecting from Login Page
I had made some changes to existing web site by adding a base page and recactoring boilerplate code from all pages to that one. But something strange happened. Aftre the changes, I was not able to login and view any page when debugging from Visual Studio :( Surprisingly though, same stuff worked on production server.
After redirecting from login page:
Session[User.SessionKey]=user; Response.Redirect("~/UserHome.aspx");
I read over something stackoverflow and here. It recommended to use following overload of Response.Redirect:
Session[User.SessionKey]=user; Response.Redirect("~/UserHome.aspx", false);
But still I was getting null values and Sesson_Start was called on every page request. So session was not getting stored anywhere (We use InProc session).
After careful examination of
web.config
I came across following line.
<httpCookies httpOnlyCookies="true" requireSSL="true"/>
So it explained the whole thing. Someone had added requireSSL="true" to check local SSL certificate and checed in the file. So when running from VS over HTTP, no cookies were stored and session was started with every request.
Changing it to following made things work:
<httpCookies httpOnlyCookies="true" requireSSL="false"/>
0 notes
aprenticedev · 9 years
Text
Tip: KnockoutJS Click Binding
Directly binding a method in ViewModel causes KO to call the function while binding. So you need to wrap it into anonymous function in binding expression like:
Wrong Way to Bind
<a data-bind="click:showAlert">Alert</a>
Correct Way
<a data-bind="click:function(){showAlert();}">Alert</a>
2 notes · View notes
aprenticedev · 9 years
Text
Using MySQL with EF6. DbConfiguration Error
I was trying my hands on using MySQL with Entity Framework 6. All went well, until I ran it ;)
After installing MySQL.Data, MySQL.Data.Entities and coding my DbContext, I pressed F5. I was greeted by following:
Server Error in '/' Application. The default DbConfiguration instance was used by the Entity Framework before the 'MySqlEFConfiguration' type was discovered. An instance of 'MySqlEFConfiguration' must be set at application start before using any Entity Framework features or must be registered in the application's config file. See http://go.microsoft.com/fwlink/?LinkId=260883 for more information. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The default DbConfiguration instance was used by the Entity Framework before the 'MySqlEFConfiguration' type was discovered. An instance of 'MySqlEFConfiguration' must be set at application start before using any Entity Framework features or must be registered in the application's config file. See http://go.microsoft.com/fwlink/?LinkId=260883 for more information. Source Error: Line 11: public class MySQLDbContext : DbContext Line 12: { Line 13: public MySQLDbContext() Line 14: : base("MyApp") Line 15: {
There are various things suggested on internet like updating packages, changing assembly binding redirects in web.config. But after going throught the documentation on MySql forum and some questions on StackOverflow, I was missing following in Application_Start():
DbConfiguration.SetConfiguration(new MySqlEFConfiguration());
0 notes
aprenticedev · 9 years
Text
KnockoutJS object - Serializing to JSON string
If you have a KnockoutJS model like:
function Person(f,l){ var that=this; that.FirstName=ko.observable(f); that.LastName=ko.observable(l); }
Then trying to stringify an object off type Person like following will not work:
var p=new Person('John','Doe'); var s = JSON.stringify(p);
You need to first convert from KO object to valid JSON object:
var j = ko.toJSON(p);
Now you can stringify for further consumption:
var s = JSON.stringify(j);
0 notes
aprenticedev · 9 years
Text
Increase Size of Virtual Hard-disk in Hyper-V
I have a habit of creating virtual machines with small virtual hard disks. While doing some R&D work I create a VM with 25GB hard disk. I had totally abandoned it after using for few weeks. Yesterday I had to do some research on Adobe InDesign Server. After installing IDS it quickly took up all the space and I started getting low disk space warning.
Now was the time to do the inevitable, that is to resize the virtual hard disk.
I had done the drill previously as well and it was (or seemed) quick. I performed following steps:
1. Fire Hyper V MMC and select "Edit Disk" from Actions.
Tumblr media
2. Select VHDX file to resize
Tumblr media
3. Select Expand operation
Tumblr media
4. Specify new size (52GB)
Tumblr media
I happily fired the VM. But it still complained about the disk space which was same again (24.66GB).
After some thought I remembered that I missed a vital step. I had to attach the virtual hard disk in Disk Management Console and resize it. Following is what is needed to get bigger hard disk.
1. Open Disk Management Console (diskmgmt.msc) and select Attach VHD from Action menu.
Tumblr media
It shows 24.66GB allocated for existing disk and 27GB of fresh space available for use.
Tumblr media
2. Right click on existing hard disk and choose Extend Volume from menu.
Tumblr media
3. Select all (or what ever you want to use) available space and click Next.
Tumblr media
After rebooting into VM, you will get bigger hard disk.
I had to struggle in past to figure out how to resize VHDs. Hope this writing will help me in future in case I miss something.
0 notes
aprenticedev · 10 years
Text
Enabling Autocomplete in SQL Management Studio
I had enabled autocomplete and all the settings were fine. But it never worked on my machine. After fooling around for many weeks, I got from somewhere that it does not work in SQLCMD mode. When checked I found that I had set option "By default, open new queries in SQLCMD mode" under Query Execution node. Disabling it returned my autocomplete.
0 notes