Exception occurred while initializing the database. Login failed for user on re-creation after deletion - entity-framework-6

On the first run my program creates the database and log file correctly in the user's folder.
If I then delete the database and log file and run the program again I get an error.
using System;
using blocks6.Module.BusinessObjects;
namespace BlocksConsole
{
class Program
{
static void Main(string[] args)
{
try
{
AddToTable();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
private static void AddToTable()
{
using (var db = new blocks6DbContext())
{
var inf = new ModuleInfo();
db.ModulesInfo.Add(inf);
db.SaveChanges();
}
Console.WriteLine("Fin");
}
}
}
and
using System.Data.Entity;
namespace blocks6.Module.BusinessObjects
{
public class blocks6DbContext : DbContext
{
public blocks6DbContext()
: base("name=ConnectionString")
{
// Database.SetInitializer(new DbInitializer()); uncommenting makes no difference
}
public DbSet<ModuleInfo> ModulesInfo { get; set; }
}
public class DbInitializer : CreateDatabaseIfNotExists<blocks6DbContext>
{
}
public class ModuleInfo
{
public int Id { get; set; }
}
}
app.config is
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<connectionStrings>
<add name="ConnectionString" connectionString="Integrated Security=SSPI;MultipleActiveResultSets=True;Data Source=(localdb)\mssqllocaldb;Initial Catalog=blocksConsole" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
The project file is
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{477EDA75-B7F0-4D45-866F-0AB92CE38783}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>BlocksConsole</RootNamespace>
<AssemblyName>BlocksConsole</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="BlocksDbContext.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="EntityFramework">
<Version>6.2.0</Version>
</PackageReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
My Win10 OS is Version 1809 Build 17763.194
Rebooting does not help.
[Update]
I created a new console program on a different computer running VS 15.8.1
The program locks up on the line
db.ModulesInfo.Add(inf);
When I upgraded to 15.9.4 the lock up ceased. However the error re-creating the database repeats on this computer too.
Winver on the second computer shows 1803 17134.471
Emptying the recycle bin does not help.

It turns out that the deleted database still shows as a node in SQL Server Object Explorer ( inside Visual Studio)
If I delete it
then the program runs successfully to re-create the database.

Related

Can't upload large files ASP.NET / IIS 6.2

I can not upload large files. My page is base in ASP.NET.
In IIS I have 2 sites;
-1 for web service
-1 for web page
I try many ways that I found, but no work
Web service config;
////////////////////////////
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appSettings>
...
</appSettings>
<connectionStrings>
...
</connectionStrings>
<system.web>
<httpRuntime maxRequestLength="50097151" />
<compilation debug="true" targetFramework="4.5.2" />
<authentication mode="Windows" />
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID" />
</system.web>
</configuration>
////////////////////////////
////////////////////////////
Web page config;
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath=".\....exe" arguments="" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="true">
<environmentVariables />
</aspNetCore>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="50741824" />
</requestFiltering>
</security>
</system.webServer>
</configuration>
I expect upload large files, but the actual is that I only can upload small files.
[HttpPost]
[DisableRequestSizeLimit]
public ActionResult uplo(string filename, string base64)
{
if (base64 != null && filename != null)
{
Models.filemodel archmod = new Models.filemodel ();
var xxx= archmod .namefunction(filename, base64);
return new EmptyResult();
}
return new EmptyResult();
}
It works with [DisableRequestSizeLimit] tag !!!

confirm-ack and confirm-nack channel not getting invoked

I am trying to configure the ack & nack channel and am getting the error like
"Only one confirm call back channel can be configured at a time"
Below are the things which I tried:
1. confirm-correlation-expression="#root" //no result found
2. Changed the amqp template like below
<rabbit:connection-factory id="connectionFactory" host="localhost" publisher-confirms="true" publisher-returns="true" />
<rabbit:template id="amqpTemplate" connection-factory="connectionFactory" mandatory="true" /> <!-- for nacks -->
<rabbit:admin connection-factory="connectionFactory" />
/>
The error was not there but the ack channel is not getting invoked.
Can anyone help me on this?
Here the MQ config
<rabbit:template id="nonTransactionalRabbitTemplate"
connection-factory="nonTransactionalConnectionFactory"
mandatory="true"
channel-transacted="false"
confirm-callback="confirmCallback"
return-call`enter code here`back="returnCallback" />
<rabbit:connection-factory id="nonTransactionalConnectionFactory"
connection-factory="rabbitClientConnectionFactory"
publisher-confirms="true"
publisher-returns="true"/>
<rabbit:connection-factory id="nonTransactionalConnectionFactory"
connection-factory="rabbitClientConnectionFactory"
publisher-confirms="true"
publisher-returns="true"/>
<bean id="rabbitClientConnectionFactory" class="com.rabbitmq.client.ConnectionFactory" >
<property name="uri" value="${mq.uri}" />
<property name="requestedHeartbeat" value="30" />
</bean>
Here is my outbound adapter
<int-amqp:outbound-channel-adapter channel="abc"
routing-key="xyz"
amqp-template="amqpTemplate"
confirm-correlation-expression="payload"
confirm-ack-channel="successRespTransformChannel"
confirm-nack-channel="failureRespTransformChannel"
return-channel="failureRespTransformChannel"
mapped-request-headers="*"
Here is my service activator
<chain input-channel="successRespTransformChannel">
<int:header-enricher>
<error-channel ref="failed-publishing" />
</int:header-enricher>
<service-activator id="successResp" expression="#abc.addRequestTracking(payload.id,'success')"/>
</chain>
When using the template in the adapter, you must NOT set your own callbacks
confirm-callback="confirmCallback"
return-callback="returnCallback" />
The adapter sets itself as the callback for both confirms and returns. This fails since you have already set the callbacks.
<rabbit:template id="amqpTemplate" connection-factory="connectionFactory" mandatory="true" /> <!-- for nacks -->
mandatory enables returns, not nacks.
EDIT
I have no idea what you are doing wrong. I just wrote a quick test case...
#SpringBootApplication
#ImportResource("context.xml")
public class So36546646Application {
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext ctx = SpringApplication.run(So36546646Application.class, args);
ctx.getBean("out", MessageChannel.class).send(new GenericMessage<>("foo"));
boolean received = ctx.getBean(MyService.class).latch.await(10, TimeUnit.SECONDS);
if (!received) {
System.err.println("Did not receive ack");
}
ctx.getBean(RabbitAdmin.class).deleteQueue(ctx.getBean(Queue.class).getName());
ctx.close();
}
public static class MyService {
private final CountDownLatch latch = new CountDownLatch(1);
public void handle(Message<?> ack) {
System.out.println("ack:" + ack);
latch.countDown();
}
}
}
and
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:rabbit="http://www.springframework.org/schema/rabbit"
xmlns:int-amqp="http://www.springframework.org/schema/integration/amqp"
xmlns:int="http://www.springframework.org/schema/integration"
xsi:schemaLocation="http://www.springframework.org/schema/integration/amqp http://www.springframework.org/schema/integration/amqp/spring-integration-amqp.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd">
<rabbit:connection-factory id="cf" publisher-confirms="true" publisher-returns="true" host="localhost" />
<rabbit:template id="t" connection-factory="cf" mandatory="true" />
<rabbit:admin connection-factory="cf" />
<rabbit:queue id="anon" />
<int:channel id="out" />
<int-amqp:outbound-channel-adapter
channel="out"
amqp-template="t"
routing-key="#{anon.name}"
confirm-correlation-expression="payload"
confirm-ack-channel="acks"
confirm-nack-channel="acks"
return-channel="returns" />
<int:service-activator input-channel="acks" ref="service" />
<bean id="service" class="com.example.So36546646Application$MyService" />
<int:channel id="returns">
<int:queue />
</int:channel>
</beans>
and it worked fine:
ack:GenericMessage [payload=foo, headers={amqp_publishConfirm=true, id=5eed89bf-11b6-76a5-34ed-0091c6bac2c8, timestamp=1460464254229}]

Web.config partial search and replace

I have App.config file in C# application.
I want to partially replace all Keys matching ".UAT" with ".PROD" using xdt tranform.
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<appSettings>
<add key="MyParam1.UAT" value="param1"/>
<add key="MyParam2.UAT" value="param2"/>
<add key="MyParam2.UAT" value="param3"/>
</appSettings>
</configuration>
Here is the output I want
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<appSettings>
<add key="MyParam1.PROD" value="param1"/>
<add key="MyParam2.PROD" value="param2"/>
<add key="MyParam2.PROD" value="param3"/>
</appSettings>
</configuration>
So far I've tried this using CustomTransform but it replaces only one element instead of all element. How can i get this to replace all elements
<?xml version="1.0"?>
<!-- For more information on using web.config transformation visit http://go.microsoft.com/fwlink/?LinkId=125889 -->
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<appSettings>
<add xdt:Locator="Condition(contains(#key, '.UAT'))" xdt:Transform="AttributeRegexReplace(Attribute='key', Pattern='.UAT',Replacement='.PROD')" />
</appSettings>
</configuration>
I found the answer here where I had to replace the Apply method with this method that iterates over all attributes
protected override void Apply()
{
foreach (XmlNode target in this.TargetNodes)
{
foreach (XmlAttribute att in target.Attributes)
{
if (string.Compare(att.Name, this.AttributeName, StringComparison.InvariantCultureIgnoreCase) == 0)
{ // get current value, perform the Regex
att.Value = Regex.Replace(att.Value, this.Pattern, this.Replacement);
}
}
}
}

WCF SOAP to WCF REST conversion in MVC giving end point error

Problem Statement:
Performing MVC CRUD operations using WCF Service.Everything was working fine with SOAP,but when i changed from SOAP to REST it is giving end point error.I suspect that there might be some problem with my webconfig..!!!
Exception Details:
"There was no endpoint listening at http://localhost:8733/Design_Time_Addresses/ALCMS.MasterConfigurationService/Service1/InsertAssetType that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details."
WCF REST service is hosting properly and it is running.I'm getting the exception mentioned above in WCF REST Service method calls in controller like :
objSvcMasterConfig.InsertAssetType(objAssetTypeDC);
objSvcMasterConfig.UpdateAssetType(objAssetTypeDC);
objSvcMasterConfig.DeleteAssetType(objAssetTypeDC);
What i'm doing wrong??
I'm having two projects in Solution
WCF Service library
MVC Razor application
1. WCF Service Library:
IService1.cs
Data Contract:
[DataContract]
public class AssetTypeDC
{
[DataMember]
public int ID { get; set; }
[DataMember]
public int AssetTypeID { get; set; }
[DataMember]
public string Name { get; set; }
}
Service Contract:
[ServiceContract]
public interface IService1
{
#region Asset Type
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "InsertAssetType")]
bool InsertAssetType(AssetTypeDC objAssetTypeDC);
[WebInvoke(Method = "PUT",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "UpdateAssetType")]
[OperationContract]
bool UpdateAssetType(AssetTypeDC objAssetTypeDC);
[WebInvoke(Method = "DELETE",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "DeleteAssetType")]
[OperationContract]
bool DeleteAssetType(AssetTypeDC objAssetTypeDC);
#endregion
}
Service.cs
public bool InsertAssetType(AssetTypeDC objAssetTypeDC)
{
try
{
objAssetType.ID = objAssetTypeDC.ID;
objAssetType.AssetTypeID = objAssetTypeDC.AssetTypeID;
objAssetType.Name = objAssetTypeDC.Name;
dbEntity.AssetTypes.Attach(objAssetType);
var entry = dbEntity.Entry(objAssetType);
dbEntity.AssetTypes.Add(objAssetType);
dbEntity.SaveChanges();
return true;
}
catch
{
return false;
}
}
public bool UpdateAssetType(AssetTypeDC objAssetTypeDC)
{
try
{
objAssetTypeID = ID;
objAssetType.AssetTypeID = objAssetTypeDC.AssetTypeID;
objAssetType.Name = objAssetTypeDC.Name;
dbEntity.AssetTypes.Attach(objAssetType);
var entry = dbEntity.Entry(objAssetType);
entry.Property(e => e.Name).IsModified = true;
dbEntity.SaveChanges();
return true;
}
catch
{
return false;
}
}
public bool DeleteAssetType(AssetTypeDC objAssetTypeDC)
{
try
{
objAssetType.AssetTypeID = objAssetTypeDC.AssetTypeID;
objAssetType.ID = objAssetTypeDC.ID;
dbEntity.AssetTypes.Attach(objAssetType);
dbEntity.Entry(objAssetType).State = EntityState.Deleted;
dbEntity.SaveChanges();
return true;
}
catch
{
return false;
}
}
App.Config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" />
</system.web>
<system.serviceModel>
<services>
<service name="ALCMS.MasterConfigurationService.Service1" behaviorConfiguration="ALCMS.MasterConfigurationService.Service1Behaviour">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8733/Design_Time_Addresses/ALCMS.MasterConfigurationService/Service1/" />
</baseAddresses>
</host>
<endpoint address="" binding="webHttpBinding" contract="ALCMS.MasterConfigurationService.IService1" behaviorConfiguration="ALCMS.MasterConfigurationService.RESTEndpointBehaviour">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="ALCMS.MasterConfigurationService.RESTEndpointBehaviour">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ALCMS.MasterConfigurationService.Service1Behaviour">
<serviceMetadata httpGetEnabled="True" httpsGetEnabled="True" />
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
<connectionStrings><add name="DB_V2Entities" connectionString="metadata=res://*/Entities.MasterConfigurationEntity.csdl|res://*/Entities.MasterConfigurationEntity.ssdl|res://*/Entities.MasterConfigurationEntity.msl;provider=System.Data.SqlClient;provider connection string="data source=SQL-PC\SQLEXPRESS;initial catalog=DB_V2;user id=sa;password=Sql#123;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /></connectionStrings></configuration>
2.MVC Application
Controller:
Insert Operation:
[HttpPost]
public ActionResult Create(AssetTypeModel assettypemodel)
{
if (ModelState.IsValid)
{
objAssetTypeDC.ID = 1;
objAssetTypeDC.AssetTypeID = assettypemodel.ID;
objAssetTypeDC.Name = assettypemodel.Name;
objSvcMasterConfig.InsertAssetType(objAssetTypeDC);
return RedirectToAction("Index");
}
return View(assettypemodel);
}
Update Operation:
[HttpPost]
public ActionResult Edit(AssetTypeModel assettypemodel, int id, int ID)
{
if (ModelState.IsValid)
{
objAssetTypeDC.ID = assettypemodel.ID = ID;
objAssetTypeDC.AssetTypeID = assettypemodel.AssetTypeID = id;
objAssetTypeDC.Name = assettypemodel.Name;
objSvcMasterConfig.UpdateAssetType(objAssetTypeDC);
return RedirectToAction("Index");
}
return View(assettypemodel);
}
Delete Operation:
public ActionResult Delete(int id = 0, int ID = 0)
{
AssetTypeModel assettypemodel = db.AssetType.Find(id, ID);
if (assettypemodel == null)
{
return HttpNotFound();
}
return View(assettypemodel);
}
Web.Config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DB" connectionString="Data Source=SQL-PC\SQLEXPRESS;initial catalog=DB_V2;Persist Security Info=True;User ID=sa;Password=Sql#123;Pooling=False;" providerName="System.Data.SqlClient" />
<add name="DBEntities" connectionString="metadata=res://*/Entities.WebEntity.csdl|res://*/Entities.WebEntity.ssdl|res://*/Entities.WebEntity.msl;provider=System.Data.SqlClient;provider connection string="data source=SQL\SQLEXPRESS;initial catalog=DB_V2;user id=sa;Password=Sql#123;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /></connectionStrings>
<appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5"><assemblies><add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /></assemblies></compilation>
<httpRuntime targetFramework="4.5" />
<authentication mode="Forms">
<forms loginUrl="~/Login" protection="All" timeout="2880" />
</authentication>
<sessionState mode="InProc" timeout="30" stateConnectionString="tcpip=SQL-PC\SQLEXPRESS,1433" cookieless="false" regenerateExpiredSessionId="false" />
<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.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="WebHttpBinding_IService1" />
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="ALCMS.MasterConfigurationService.RESTEndpointBehaviour">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<client>
<endpoint address="http://localhost:8733/Design_Time_Addresses/ALCMS.MasterConfigurationService/Service1/" binding="webHttpBinding" bindingConfiguration="WebHttpBinding_IService1" behaviorConfiguration="ALCMS.MasterConfigurationService.RESTEndpointBehaviour" contract="MasterConfigurationServiceReference.IService1" name="WebHttpBinding_IService1" />
</client>
</system.serviceModel>
</configuration>
Mr Vishal,
Instead of converting, you can develop in REST only.

Struts2 parameters is coming null in action class when using Interceptors

When I am using Interceptors, the values on Action class coming as null. I have removed the Interceptors, the values coming perfect from the JSP page.
Login.jsp
<s:form id="loginFrm" name="loginFrm" action="LoginAction">
<s:textfield key="username"/>
<s:password key="password"/>
<s:submit/>
</s:form>
LoginAction.java
public class LoginAction {
private static Logger LOGGER = Logger.getLogger(LoginAction.class);
private String username;
private String password;
public String execute() throws Exception {
LOGGER.info("LoginAction : authenticate()");
LOGGER.info("LoginAction : {[" + username + "],["+password+ "]}");
return "success";
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Bulk Fund Switching</display-name>
<context-param>
<param-name> org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG </param-name>
<param-value>/WEB-INF/tiles.xml</param-value>
</context-param>
<listener>
<listener-class>org.apache.struts2.tiles.StrutsTilesListener </listener-class>
</listener>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>jsp/Login.jsp</welcome-file>
</welcome-file-list>
</web-app>
struts.xml (working version)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="false" />
<constant name="struts.custom.i18n.resources" value="BFSView,BFSMessages" />
<package name="home-default" extends="struts-default" namespace="/">
<result-types>
<result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" />
</result-types>
<interceptors>
<interceptor name="AuthenticationInterceptor" class="com.lv.bfs.controller.interceptor.AuthenticationInterceptor"></interceptor>
<interceptor-stack name="SecureStack">
<interceptor-ref name="AuthenticationInterceptor" />
</interceptor-stack>
</interceptors>
<action name="LoginAction" class="com.lv.bfs.controller.action.LoginAction">
<result name="success">jsp/Welcome.jsp</result>
<result name="error">/jsp/Login.jsp</result>
</action>
</package>
</struts>
struts.xml (Not working version )
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="false" />
<constant name="struts.custom.i18n.resources" value="BFSView,BFSMessages" />
<package name="home-default" extends="struts-default" namespace="/">
<result-types>
<result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" />
</result-types>
<interceptors>
<interceptor name="AuthenticationInterceptor" class="com.lv.bfs.controller.interceptor.AuthenticationInterceptor"></interceptor>
<interceptor-stack name="SecureStack">
<interceptor-ref name="AuthenticationInterceptor" />
</interceptor-stack>
</interceptors>
<action name="LoginAction" class="com.lv.bfs.controller.action.LoginAction">
<interceptor-ref name="SecureStack"></interceptor-ref>
<result name="success">jsp/Welcome.jsp</result>
<result name="error">/jsp/Login.jsp</result>
</action>
</package>
</struts>
AuthenticationInterceptor.java
public class AuthenticationInterceptor extends AbstractInterceptor {
private static Logger LOGGER = Logger.getLogger(AuthenticationInterceptor.class);
private static final long serialVersionUID = 1844249996954274967L;
public String intercept(ActionInvocation invocation) throws Exception {
LOGGER.info("intercept : START");
return invocation.invoke();
}
}
Logs statements (both cases)
12:39:05,533 INFO [AuthenticationInterceptor] intercept : START
12:39:05,533 INFO [LoginAction] LoginAction : authenticate()
12:39:05,533 INFO [LoginAction] LoginAction : {[null],[null]}
12:09:05,533 INFO [LoginAction] LoginAction : authenticate()
12:09:05,533 INFO [LoginAction] LoginAction : {[admin],[admin]}
Any suggestions?
When you define an interceptor stack for a specific action you must define all the interceptors for that action. In this case, you are only defining your custom interceptor, meaning the "params" interceptor doesn't run, so the action properties won't be set.
Either define a new stack that includes the normal S2 interceptors, or include those interceptors (or stack) in your action configuration.

Resources