XPath for element with namespace - xpath

What is the XPATH for attribute newVersion in the element
<dependentAssembly>
<assemblyIdentity name="System.Reactive.Linq" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.2.5.0" newVersion="2.2.5.0" />
</dependentAssembly>
I have tried my best to do it by myself. But don't know how to get XPATH for elements with namespace. Its very confusing. Somebody please provide me a XPATH.
XPATH which I came up with is
/configuration/runtime/assemblyBinding/dependentAssembly[2]/bindingRedirect[#newVersion='2.2.5.0']/#newVersion
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<legacyUnhandledExceptionPolicy enabled="1" />
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Reactive.Interfaces" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect name="Test1" oldVersion="0.0.0.0-2.2.5.0" newVersion="2.2.5.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Reactive.Linq" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.2.5.0" newVersion="2.2.5.0" />
</dependentAssembly>
</assemblyBinding>

The right xpath is
XPATH:
/configuration/runtime/ns:assemblyBinding/ns:dependentAssembly[ns:assemblyIdentity[#name='System.Reactive.Linq']]/ns:bindingRedirect/#newVersion
Where ns is the namespace urn:schemas-microsoft-com:asm.v1
I use a XmlPoke Task in the MSBuild tasks in the project file to modify the binding redirect.
Together with a XmlPoke Task the code goes like this:
<XmlPoke XmlInputPath="$(DestXmlFiles)"
Namespaces="<Namespace Prefix='ns' Uri='urn:schemas-microsoft-com:asm.v1' Name='DoNotKnowWhatThisIsFor-ButItIsRequired' />"
Query="/configuration/runtime/ns:assemblyBinding/ns:dependentAssembly[ns:assemblyIdentity[#name='System.Reactive.Linq']]/ns:bindingRedirect/#newVersion"
Value="$(BUILD_NUMBER)"/>

In XSLT 1.0 you must declare namespaces with a prefix in order to be able to use them in XPath.
For example (wrapped for legibility):
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:asm="urn:schemas-microsoft-com:asm.v1"
>
<xsl:template match="/">
<xsl:value-of select="
/configuration/
runtime/
asm:assemblyBinding/
asm:dependentAssembly[2]/
asm:bindingRedirect[#newVersion = '2.2.5.0']/#newVersion
" />
</xsl:template>
</xsl:stylesheet>
However, you don't have to specify the entire path, you could take shortcuts:
<xsl:value-of select="
//asm:assemblyIdentity[#name='System.Reactive.Linq']/
asm:bindingRedirect[#newVersion = '2.2.5.0']/#newVersion
" />

Related

WDS - cannot join domain with answer file

I struggle with Windows Deployment Services (WDS) right now.
So, what I want to achieve:
Create local admin account with given password.
Configure partition.
Join corporate domain my.domain.eu.
Skip OOBE.
For now, only first point is done - local admin account is created after initial setup, but somehow, I'm not able to achieve rest of it.
During installation, it first asks me for a language, and later on - for domain user & password. After I pass it - for partition config.
<?xml version="1.0" encoding="utf-8"?>
<unattend xmlns="urn:schemas-microsoft-com:unattend">
<settings pass="oobeSystem">
<component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<UserAccounts>
<LocalAccounts>
<LocalAccount wcm:action="add">
<Password>
<Value>password</Value>
<PlainText>false</PlainText>
</Password>
<DisplayName>localadmin</DisplayName>
<Group>Administrators</Group>
<Name>localadmin</Name>
</LocalAccount>
</LocalAccounts>
</UserAccounts>
</component>
<component name="Microsoft-Windows-International-Core" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SystemLocale>en-US</SystemLocale>
<UILanguage>en-US</UILanguage>
</component>
</settings>
<settings pass="windowsPE">
<component name="Microsoft-Windows-International-Core-WinPE" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SetupUILanguage>
<UILanguage>en-US</UILanguage>
</SetupUILanguage>
</component>
<component name="Microsoft-Windows-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<DiskConfiguration>
<Disk wcm:action="add">
<CreatePartitions>
<CreatePartition wcm:action="add">
<Order>1</Order>
<Type>Primary</Type>
</CreatePartition>
</CreatePartitions>
<ModifyPartitions>
<ModifyPartition wcm:action="add">
<Active>true</Active>
<Format>NTFS</Format>
<Label>Local Disk</Label>
<Letter>C</Letter>
<Order>1</Order>
<PartitionID>1</PartitionID>
</ModifyPartition>
</ModifyPartitions>
<DiskID>0</DiskID>
<WillWipeDisk>true</WillWipeDisk>
</Disk>
</DiskConfiguration>
</component>
</settings>
<settings pass="specialize">
<component name="Microsoft-Windows-UnattendedJoin" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Identification>
<Credentials>
<Domain>netbios_name</Domain>
<Password>password</Password>
<Username>domain_account</Username>
</Credentials>
<JoinDomain>my.domain.eu</JoinDomain>
<UnsecureJoin>true</UnsecureJoin>
<MachineObjectOU>OU=Deploy_TEST,OU=Computers</MachineObjectOU>
</Identification>
</component>
</settings>
<cpi:offlineImage cpi:source="/path/to/file.wim" xmlns:cpi="urn:schemas-microsoft-com:cpi" />
</unattend>
Nevermind, I fixed that:
<?xml version="1.0" encoding="utf-8"?>
<unattend xmlns="urn:schemas-microsoft-com:unattend">
<settings pass="windowsPE">
<component name="Microsoft-Windows-International-Core-WinPE" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SetupUILanguage>
<UILanguage>us-US</UILanguage>
</SetupUILanguage>
<InputLocale>us-US</InputLocale>
<SystemLocale>us-US</SystemLocale>
<UILanguage>us-US</UILanguage>
<UserLocale>us-US</UserLocale>
</component>
<component name="Microsoft-Windows-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<WindowsDeploymentServices>
<Login>
<Credentials>
<Domain>netbios</Domain>
<Username>domain_suer</Username>
<Password>password</Password>
</Credentials>
</Login>
</WindowsDeploymentServices>
</component>
</settings>
<settings pass="oobeSystem">
<component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<UserAccounts>
<LocalAccounts>
<LocalAccount wcm:action="add">
<Password>
<Value>password</Value>
<PlainText>false</PlainText>
</Password>
<DisplayName>admin</DisplayName>
<Group>Administrators</Group>
<Name>admin</Name>
</LocalAccount>
</LocalAccounts>
</UserAccounts>
</component>
</settings>
<cpi:offlineImage cpi:source="wim://path/to/file" xmlns:cpi="urn:schemas-microsoft-com:cpi" />
</unattend>

Connect Oracle DB with Entity Framework with Code First in VS2022

I need to connect with oracle database using entity framework in my MVC WebAPI project. I am using VS2022 with .Net Framework 4.8. I prefer working with code first approach and need to auto create the Database and Tables if not exists.
The packages I have added in my project for oracle are
My web.config of the project is as below
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="oracle.manageddataaccess.client" type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.122.21.1, Culture=neutral, PublicKeyToken=89b483f429c47342" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<oracle.manageddataaccess.client>
<version number="*">
<dataSources>
<!-- Customize these connection alias settings to connect to Oracle DB -->
<dataSource alias="OracleDataSource" descriptor="(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=175.16.2.1)(PORT=1521))(CONNECT_DATA=(SERVER = DEDICATED)(SERVICE_NAME=oracledb12c))) " />
</dataSources>
</version>
</oracle.manageddataaccess.client>
<connectionStrings>
<add name="OracleDbContext" providerName="Oracle.ManagedDataAccess.Client" connectionString="User Id=oracle_user;Password=oracle_user_password;Data Source=OracleDataSource" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.8" />
<httpRuntime targetFramework="4.8" />
</system.web>
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" />
<bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.7.0" newVersion="5.2.7.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Text.Json" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<publisherPolicy apply="no" />
<assemblyIdentity name="Oracle.ManagedDataAccess" publicKeyToken="89b483f429c47342" culture="neutral" />
<bindingRedirect oldVersion="4.122.0.0 - 4.65535.65535.65535" newVersion="4.122.21.1" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
<system.data>
<DbProviderFactories>
<remove invariant="Oracle.ManagedDataAccess.Client" />
<add name="ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client" description="Oracle Data Provider for .NET, Managed Driver" type="Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess, Version=4.122.21.1, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</DbProviderFactories>
</system.data>
<entityFramework>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="Oracle.ManagedDataAccess.Client" type="Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices, Oracle.ManagedDataAccess.EntityFramework, Version=6.122.21.1, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</providers>
</entityFramework>
</configuration>
My DBContext class and model class are
public class OracleDbContext : DbContext
{
public OracleDbContext() : base("OracleDbContext")
{
}
public DbSet<User> Users { get; set; }
}
public class User
{
public int UserId { get; set; }
public string UserName { get; set; }
}
After all this when I run add-migration m1, it runs successfully and created its cs file. After that when I run Update-Database, it is giving me an exception and DB not created. The exception I am getting is as follows
Oracle.ManagedDataAccess.Client.OracleException (0x80004005): ORA-01918: user 'dbo' does not exist
at OracleInternal.ServiceObjects.OracleConnectionImpl.VerifyExecution(Int32& cursorId, Boolean bThrowArrayBindRelatedErrors, SqlStatementType sqlStatementType, Int32 arrayBindCount, OracleException& exceptionForArrayBindDML, Boolean& hasMoreRowsInDB, Boolean bFirstIterationDone)
at OracleInternal.ServiceObjects.OracleCommandImpl.ExecuteNonQuery(String commandText, OracleParameterCollection paramColl, CommandType commandType, OracleConnectionImpl connectionImpl, Int32 longFetchSize, Int64 clientInitialLOBFS, OracleDependencyImpl orclDependencyImpl, Int64[]& scnFromExecution, OracleParameterCollection& bindByPositionParamColl, Boolean& bBindParamPresent, OracleException& exceptionForArrayBindDML, OracleConnection connection, Boolean isFromEF)
at Oracle.ManagedDataAccess.Client.OracleCommand.ExecuteNonQuery()
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.DbMigrator.ExecuteSql(MigrationStatement migrationStatement, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ExecuteSql(MigrationStatement migrationStatement, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinTransaction(IEnumerable`1 migrationStatements, DbTransaction transaction, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinNewTransaction(IEnumerable`1 migrationStatements, DbConnection connection, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements, DbTransaction existingTransaction)
at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, VersionedModel targetModel, IEnumerable`1 operations, IEnumerable`1 systemOperations, Boolean downgrading, Boolean auto)
at System.Data.Entity.Migrations.DbMigrator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
at System.Data.Entity.Infrastructure.Design.Executor.Update.<>c__DisplayClass0_0.<.ctor>b__0()
at System.Data.Entity.Infrastructure.Design.Executor.OperationBase.Execute(Action action)
ORA-01918: user 'dbo' does not exist
So, I don't understand why this user not exist error is coming. Any help regarding this will be beneficial.

Response to preflight: “No 'Access-Control-Allowed-Origin'” despite CORS-enabled

I am having trouble figuring out an issue with an angular 4 preflight request not passing a CORS access-control check: “No 'Access-Control-Allowed-Origin'”. I am able to successfully get data from the db but not able to post/save data. I am using VS code for my front end to access my visual studio 2015 back end. My Web Api controller has an attribute of:
[EnableCors(origins: "*", headers: "*", methods: "*")]
[HttpPost]
public async Task<IHttpActionResult> Post([FromBody]Employee employee)
{
_repo.Create(employee);
return Ok();
}
…but when request is made, I'm getting an error of:
XMLHttpRequest cannot load http://localhost:54429/api/createEmployee/.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:4200' is therefore not allowed
access
In my vs code, my service looks like this:
postEmployeeForm(employee: Employee): Observable<any>{
let body = JSON.stringify(employee);
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let options = new RequestOptions({ headers: headers });
console.log('posting employee ' , employee);
return this.http.post("http://localhost:54429/api/employees/", body, options)
.map(this.extractData)
.catch(this.handleError)
}
405 Response after removing the body and options from the post.
Not sure what I am missing.
web config
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-TBryant.WebAPI-20170303082842.mdf;Initial Catalog=aspnet-TBryant.WebAPI-20170303082842;Integrated Security=True" providerName="System.Data.SqlClient" />
<!--<add name="SampleEntities" connectionString="metadata=res://*/MyModels.csdl|res://*/MyModels.ssdl|res://*/MyModels.msl;provider=System.Data.SqlClient;provider connection string="data source=(localdb)\MSSQLLocalDB;initial catalog=Sample;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />-->
<add name="northwindEntities" connectionString="metadata=res://*/NorthwindModel.csdl|res://*/NorthwindModel.ssdl|res://*/NorthwindModel.msl;provider=System.Data.SqlClient;provider connection string="data source=(localdb)\MSSQLLocalDB;initial catalog=northwind;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="SampleEntities1" connectionString="metadata=res://*/EmployeeDataModel.csdl|res://*/EmployeeDataModel.ssdl|res://*/EmployeeDataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=(localdb)\MSSQLLocalDB;initial catalog=Sample;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<appSettings></appSettings>
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1" />
</system.web>
<system.webServer>
<!--<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="Content-Type"/>
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELTE,OPTIONS"/>
</customHeaders>
</httpProtocol>-->
<modules>
<remove name="FormsAuthentication" />
</modules>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Cors" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
</configuration>
I have managed to reproduce your problem. The solution that worked for me is to replace part of Web.config. Under system.webServer, either add or replace the existing <handlers> block with the following:
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
If you already have that exact content in place, try removing it, running the server, stopping the server, re-adding the content and then running the server again. I know that sounds odd but I think it's what ended up fixing it for me. Good luck.
UPDATE #1
Now that we have something happening on the server side of things, try removing the Content-Type header and JSON.stringify stuff in your Angular code. i.e.:
postEmployeeForm(employee: Employee): Observable<any>{
console.log('posting employee ' , employee);
return this.http.post("http://localhost:54429/api/employees/", employee)
.map(this.extractData)
.catch(this.handleError)
}
UPDATE #2
I think your IIS Express configuration may be overriding some of the changes we've made. Close Visual Studio, delete the .vs/config folder at the root of the solution in Windows Explorer and then try re-running the project. This should reset your IIS Express settings. If you're not completely comfortable with deleting the folder, just rename it and follow the same process.
UPDATE #3
I've managed to get your example project running. It demonstrates a problem with CORS, but this was fixed by using my initial suggestion of adding config.EnableCors:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
The problem seems to be on the server side.
Before any non-simple CORS request, the browser sends an OPTIONS preflight request to make sure that this server allows non-simple CORS requests. (POST requests with application/json are not considered simple)
In your case, as the error implies, only if the response to the preflight OPTIONS request contains the access-control-allow-origin header with the value 'http://localhost:4200' your original POST request will be sent. (The response in your screenshot doesn't contain this header)
You didn't write much about your server implementation, but if you're using asp.net-web-api here is a simple (a bit hacky) solution on how to make it respond to these preflight OPTIONS requests - link (Also see the comment there by Marcus Cunningham)
this is all about server side configuration. for your development side testing you can use Google chrome and its plugin.
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en
hope this helpful.

Ninject.ActivationException thrown only on first web request (WebAPI 2, OWIN 3, Ninject 3)

I am attempting to create a "barebones" Web API project that uses OWIN middleware, Ninject Depencency Injection, and ultimately to be hosted in IIS. I have followed instructions found in an article, "Befriending ASP.NET Web.API2, OWIN and Ninject," here: http://www.alexzaitzev.pro/2014/11/webapi2-owin-and-ninject.html, except I used an empty Web Application Project, and did not tick the "Include Web API references and folders" when creating the project.
When I fire up the new API and make a page request, I get the following Ninject.ActivationException thrown:
Server Error in '/' Application.
Error activating HttpConfiguration
More than one matching bindings are available.
Matching bindings:
1) binding from HttpConfiguration to method
2) binding from HttpConfiguration to constant value
Activation path:
1) Request for HttpConfiguration
Suggestions:
1) Ensure that you have defined a binding for HttpConfiguration only once.
This exception goes away when I refresh my browser. I really don't understand what is causing this exception. From my point of view, being somewhat inexperienced with WebAPI in OWIN context and Ninject, it's hard to know where the problem lies. Is it with Ninject...? Is it in OWIN...? Is it in WebAPI...?
This is the content of my Startup.cs file:
using System.Web.Http;
using LHD.API_2;
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Ninject.Web.Common.OwinHost;
using Ninject.Web.WebApi.OwinHost;
using Owin;
[assembly: OwinStartup(typeof(Startup))]
namespace LHD.API_2
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute("API Default", "api/1/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
app.UseNinjectMiddleware(() => NinjectConfig.CreateKernel.Value);
app.UseNinjectWebApi(config);
}
}
}
This is the content of my NinjectConfig.cs file:
using System;
using System.Reflection;
using Ninject;
namespace LHD.API_2
{
public static class NinjectConfig
{
public static Lazy<IKernel> CreateKernel = new Lazy<IKernel>(() =>
{
StandardKernel kernel = new StandardKernel();
kernel.Load(Assembly.GetExecutingAssembly());
RegisterServices(kernel);
return kernel;
});
private static void RegisterServices(KernelBase kernel)
{
// TODO - put in registrations here...
//kernel.Bind<IFakeService>().To<FakeService>();
}
}
}
This is the content of my packages.config:
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.AspNet.WebApi" version="5.0.0" targetFramework="net451" />
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net451" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net451" />
<package id="Microsoft.AspNet.WebApi.Owin" version="5.2.3" targetFramework="net451" />
<package id="Microsoft.AspNet.WebApi.WebHost" version="5.0.0" targetFramework="net451" />
<package id="Microsoft.Owin" version="3.0.1" targetFramework="net451" />
<package id="Microsoft.Owin.Host.SystemWeb" version="3.0.1" targetFramework="net451" />
<package id="Newtonsoft.Json" version="6.0.4" targetFramework="net451" />
<package id="Ninject" version="3.2.0.0" targetFramework="net451" />
<package id="Ninject.Extensions.ContextPreservation" version="3.2.0.0" targetFramework="net451" />
<package id="Ninject.Extensions.NamedScope" version="3.2.0.0" targetFramework="net451" />
<package id="Ninject.Web.Common" version="3.2.0.0" targetFramework="net451" />
<package id="Ninject.Web.Common.OwinHost" version="3.2.3.0" targetFramework="net451" />
<package id="Ninject.Web.WebApi" version="3.2.0.0" targetFramework="net451" />
<package id="Ninject.Web.WebApi.OwinHost" version="3.2.4.0" targetFramework="net451" />
<package id="Owin" version="1.0" targetFramework="net451" />
</packages>
... and, for the sake of completeness, the content of my web.config is similarly unspectacular:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5.1" />
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Http.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
</configuration>
Can anyone point me towards what I'm doing wrong, or more importantly, what I can change to get things working without the exception being thrown?
What version of the Ninject.Web.WebApi library are you using? it looks like 2 weeks ago a change was made to move some things around. before this change (v3.2.3 and earlier), HttpConfiguration bindings were present in 2 different modules in Ninject.Web.WebApi.OwinHost.OwinWebApiModule and Ninject.Web.WebApi.WebApiModule. after this change (new version is 3.2.4), this binding only happens once.
I had the same error, but for a different reason: for some reason I had installed both Ninject.Web.WebApi.WebHost and Ninject.Web.WebApi.OwinHost.
If you look in source for OwinWebApiModule.cs and WebApiWebHostModule.cs, both Ninject modules have a binding for HttpConfiguration.
I removed Ninject.Web.WebApi.WebHost and all is well.
Go to the Referances and search for Ninject.web.WebApi.WebHost and then remove this.Thats all it will start working.

Large File Uploads Fails in Chrome with Valums

I am using the valums ajax upload component (http://valums.com/ajax-upload/). My site is going to have users uploading files that are greater than 500MB in size. I have a strict pure HTML requirement. I can successfully upload files of this size in Internet Explorer. However, when I attempt to use Chrome, the file is never written on the server, but only in the case of large files. For smaller files, the file is successfully written. But for larger files, I get an "Maximum request length exceeded error".
Considering I can upload files of this size with IE, I know that the settings in my web.config are correct. This leads me to believe there is something in the XHR implementation that needs to be set to accommodate for files of this size. However, i'm not sure what that is. Can anyone provide a sample of values use with ASP.NET MVC that:
Allows for large (>500 mb) file uploads in IE AND Chrome
Shows the progress of an uploaded file in browsers that support XHR
Thank you so MUCH!
I am unable to reproduce your issue. Here's my setup in which I limited the files to 1GB.
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Upload(string qqfile)
{
var path = Server.MapPath("~/App_Data");
var file = Path.Combine(path, qqfile);
using (var output = System.IO.File.OpenWrite(file))
{
Request.InputStream.CopyTo(output);
}
return Json(new { success = true });
}
}
Index.cshtml view:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Test</title>
<link href="#Url.Content("~/Content/fileuploader.css")" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="file-uploader">
<noscript>
<p>Please enable JavaScript to use file uploader.</p>
</noscript>
</div>
<script src="#Url.Content("~/Scripts/fileuploader.js")" type="text/javascript"></script>
<script type="text/javascript">
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader'),
action: '#Url.Action("upload")'
});
</script>
</body>
</html>
web.config:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="webpages:Version" value="1.0.0.0"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
<system.web>
<httpRuntime maxRequestLength="1048576" executionTimeout="3600" />
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages"/>
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Things to notice in web.config is <httpRuntime>:
<httpRuntime maxRequestLength="1048576" executionTimeout="3600" />
and if you are hosting this site in IIS7+ (<requestLimits>) as well is required:
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
</system.webServer>
With this setup I am able to upload files up to 1GB of size in the latest versions of FireFox 8.0, IE9 and Chrome 16.
I have hosted the site locally using IIS Express.

Resources