How To Map A Domain To Tomcat’s Web Application

When you deployed your application in Tomcat server you can view your app by the link like: http://localhost:port/appName. You can mapping a domain to Tomcat’s web application to access your application according by your domain (ex: http://yourdomain.com) after you reference the domain to your ip server.
To do this you flow theses steps:
Step 1: Open file server.xml in folder C:/Tomcat7.2/conf.
Setp 2: Change port of http tomcat to 80. This look like:

<Connector port="80" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />

Step 3: Add new virtual host entry just before last closing Engine tag

<Host name="yourdomain.com" 
		  appBase="C:/Tomcat7.2/webapps/yourapp"
		  unpackWARs="true" 
		  autoDeploy="true" 
		  xmlValidation="false" 
		  xmlNamespaceAware="false">
	   
		   <Alias>doithoaitructuyen.msb.com.vn</Alias>

		   <Context path="" docBase="C:/Tomcat7.2/webapps/yourapp" 
			   debug="0" reloadable="false"/>
		   <Context path="/yourapp" docBase="C:/Tomcat7.2/webapps/yourapp" 
			  debug="0" reloadable="false"/>
	 </Host>

Step 3: Save file and restart apache tomcat.

Happy coding!

Posted in Uncategorized | Leave a comment

How to fix error HTTP Status 500 – java.lang.ClassCastException: org.apache.jasper.el.ELContextImpl cannot be cast to org.apache.jasper.el.ELContextImpl in Tomcat version 7.x

After run tomcat server and then view tomcat manager screen I received error:
HTTP Status 500 – java.lang.ClassCastException: org.apache.jasper.el.ELContextImpl cannot be cast to org.apache.jasper.el.ELContextImpl
type Exception report
message java.lang.ClassCastException: org.apache.jasper.el.ELContextImpl cannot be cast to org.apache.jasper.el.ELContextImpl
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: java.lang.ClassCastException: org.apache.jasper.el.ELContextImpl cannot be cast to org.apache.jasper.el.ELContextImpl
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:549)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
root cause
java.lang.ClassCastException: org.apache.jasper.el.ELContextImpl cannot be cast to org.apache.jasper.el.ELContextImpl
org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:1023)
org.apache.jsp.index_jsp._jspService(index_jsp.java:85)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.42 logs.

To fix this error you opens file context.xml in floder C:\Tomcat7.2\conf ( note: I store tomcat in C disk) and add new tag

<Loader delegate="true" /> 

in

<Context></Context> 

tag. This look like:

<?xml version='1.0' encoding='utf-8'?>
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -->
<!-- The contents of this file will be loaded for each web application -->
<Context>
	<Loader delegate="true" />
    <!-- Default set of monitored resources -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>

    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->

    <!-- Uncomment this to enable Comet connection tacking (provides events on session expiration as well as webapp lifecycle) -->
    <!--
    <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
    -->

</Context>

After that restart tomcat server.

Happy coding!

Posted in Tomcat | Leave a comment

Config dcomcnfg to download Excel file using Microsoft.Office.Interop.Excel library

When I used Microsoft.Office.Interop.Excel library to download excel file from website is hosted in IIS, I received error:
“Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered”.
This is a COM permissions problem. To solve this problem we will follow these steps:
1. Start > Run > dcomcnfg (or “MMC comexp.msc /32″ if Microsoft Office Excel is installed 32bit version) and find Microsoft Excel Application in DCOM Config folder.

2. Right lick Microsoft Excel Application and select Properties

3. In Launch and Activation Permissions panel select Customize option and then click Edit button, so add and set permission for IIS_IUSRS user as picture below
LaunchPermission

4. In Access Permissions panel select Customize option and then click Edit button, so add and set permission for IIS_IUSRS user as picture below
AccessPermissions

5. In Configuration Permission select Customize option and then click Edit button, so add and set permission for IIS_IUSRS user as picture below
ConfigurationPermission

6. In Identity tab, select this user option and enter username and password as picture below.
IdentityUser

Finally click OK.

Happy coding!

Posted in Uncategorized | Leave a comment

Error: The target “GatherAllFilesToPublish” does not exist in the project

When I publish web application project in vs 2012, i have received error: “The target “GatherAllFilesToPublish” does not exist in the project”.

This is the solution to fix this bug:
1. Right click project and select Unload Project.
2. Right click project and select Edit. Edit “Import” tag in project.
Before edit:

<PropertyGroup>
    <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
    <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
  </PropertyGroup>
  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
  <!-- <Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />-->
  <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" />

After edit:

<PropertyGroup>
    <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
    <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
  </PropertyGroup>
  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
  <Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />
  <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" />

3. Save and Reload Project.

Happy coding!

Posted in Uncategorized | Leave a comment

WebAPI Save not working – 405 Method Not Allowed

I have a web api controller with a Save method. The method executes fine on my local machine running IIS Express (Windows 8) but as soon as I deployed it to the live IIS server (Windows Server 2008 R2) it stopped working and throws the following error message: “Error 405 – Method Not Allowed”.

This is the solution for this error:
My web config has the following settings:

<system.webServer>
    <handlers accessPolicy="Read, Execute, Script">
          <remove name="WebDAV" />
      <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" />
      <add name="WebDAV" path="*" verb="PROPFIND,PROPPATCH,MKCOL,PUT,COPY,DELETE,MOVE,LOCK,UNLOCK" modules="WebDAVModule" resourceType="Unspecified" requireAccess="None" />
    </handlers>
  </system.webServer>

Addition tangs “validation” and “modules” above tang “handlers” in “system.webServer”. This look like:

<system.webServer>
	<validation validateIntegratedModeConfiguration="false"/>
	<modules runAllManagedModulesForAllRequests="true">
		<remove name="WebDAVModule"/>
	</modules>
    <handlers accessPolicy="Read, Execute, Script">
            <remove name="WebDAV" />
      <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" />
      <add name="WebDAV" path="*" verb="PROPFIND,PROPPATCH,MKCOL,PUT,COPY,DELETE,MOVE,LOCK,UNLOCK" modules="WebDAVModule" resourceType="Unspecified" requireAccess="None" />
    </handlers>
  </system.webServer>

Happy coding!

Posted in Uncategorized | 1 Comment

Entity framework with Oracle inserting parent with child

To insert data to two tables have parent and child relationship we will doing flow steps:

1. Create two tables:

Table CUSTOMER

-- Create table
create table CUSTOMER
(
CUSTOMER_ID   NUMBER(10) not null,
CUSTOMER_NAME NVARCHAR2(1024),
EMAIL         NVARCHAR2(512) not null,
PHONE         NVARCHAR2(100),
ADDRESS       NVARCHAR2(1000),
CUSTOMER_TYPE NVARCHAR2(100)
)
tablespace USERS
pctfree 10
initrans 1
maxtrans 255
storage
(
initial 64K
next 1M
minextents 1
maxextents unlimited
);
-- Create/Recreate primary, unique and foreign key constraints
alter table CUSTOMER
add constraint PK12 primary key (CUSTOMER_ID)
using index
tablespace USERS
pctfree 10
initrans 2
maxtrans 255
storage
(
initial 64K
next 1M
minextents 1
maxextents unlimited
);

Table INVOICE

-- Create table
create table INVOICE
(
INVOICE_ID       NUMBER(19) not null,
INVOICE_CODE     VARCHAR2(512),
INVOICE_STATUS   NUMBER(4),
ORDER_CODE       VARCHAR2(256),
PAY_VALUE        NUMBER(19),
PAY_DATE         TIMESTAMP(6),
PAYMENT_TYPE     VARCHAR2(256),
TRANSACTION_CODE VARCHAR2(256),
RECEIVE_URL      VARCHAR2(636),
RESPONSE_URL     VARCHAR2(512),
DESCRIPTION      VARCHAR2(512),
CREATED_BY       NUMBER(19),
CREATED_DATE     TIMESTAMP(6),
PROVIDER_ID      NUMBER(38) not null,
CUSTOMER_ID      NUMBER(10) not null
)
tablespace USERS
pctfree 10
initrans 1
maxtrans 255
storage
(
initial 64K
next 1M
minextents 1
maxextents unlimited
);
-- Create/Recreate primary, unique and foreign key constraints
alter table INVOICE
add constraint PK30 primary key (INVOICE_ID)
using index
tablespace USERS
pctfree 10
initrans 2
maxtrans 255
storage
(
initial 64K
next 1M
minextents 1
maxextents unlimited
);
alter table INVOICE
add constraint REFCUSTOMER4 foreign key (CUSTOMER_ID)
references CUSTOMER (CUSTOMER_ID);
alter table INVOICE
add constraint REFPROVIDER2 foreign key (PROVIDER_ID)
references PROVIDER (PROVIDER_ID);
-- Create/Recreate indexes
create index REF102 on INVOICE (PROVIDER_ID)
tablespace USERS
pctfree 10
initrans 2
maxtrans 255
storage
(
initial 64K
next 1M
minextents 1
maxextents unlimited
);
create index REF124 on INVOICE (CUSTOMER_ID)
tablespace USERS
pctfree 10
initrans 2
maxtrans 255
storage
(
initial 64K
next 1M
minextents 1
maxextents unlimited
);

2. Create sequences

create sequence CUSTOMER_SEQ
minvalue 1
maxvalue 9999999999999999999999999999
start with 0
increment by 1
cache 20;

create sequence INVOICE_SEQ
minvalue 1
maxvalue 9999999999999999999999999999
start with 0
increment by 1
cache 20;

3. Create Triggers

CREATE OR REPLACE TRIGGER CUSTOMER_INS_TRG
  BEFORE INSERT ON CUSTOMER  
  FOR EACH ROW
BEGIN
  IF(:NEW.CUSTOMER_ID IS NULL OR :NEW.CUSTOMER_ID < 0) THEN
      SELECT "CUSTOMER_SEQ".NEXTVAL INTO :NEW."CUSTOMER_ID" FROM DUAL;
  END IF;
END CUSTOMER_INS_TRG;

CREATE OR REPLACE TRIGGER INVOICE_INS_TRG
  BEFORE INSERT ON INVOICE  
  FOR EACH ROW
BEGIN
  IF(:NEW.INVOICE_ID IS NULL OR :NEW.INVOICE_ID < 0) THEN
     SELECT "INVOICE_SEQ".NEXTVAL INTO :NEW."INVOICE_ID" FROM DUAL;
  END IF;
END INVOICE_INS_TRG;

3. Create a Entity Data Model

image

4. Open .edmx file with the XML editor and look the section that begins with the flowing line:

<!-- SSDL content -->

Below should be an EntityType tag and in it is a definition of the database table. Make sure that the property for your ID column has StoreGeneratedPattern=”Identity” in it.

It is look like:

<EntityType Name="CUSTOMER">
	  <Key>
		<PropertyRef Name="CUSTOMER_ID" />
	  </Key>
	  <Property Name="CUSTOMER_ID" Type="number" StoreGeneratedPattern="Identity" Nullable="false" Precision="10" />
	  <Property Name="CUSTOMER_NAME" Type="nvarchar2" MaxLength="1024" />
	  <Property Name="EMAIL" Type="nvarchar2" Nullable="false" MaxLength="512" />
	  <Property Name="PHONE" Type="nvarchar2" MaxLength="100" />
	  <Property Name="ADDRESS" Type="nvarchar2" MaxLength="1000" />
	  <Property Name="CUSTOMER_TYPE" Type="nvarchar2" MaxLength="100" />
	</EntityType>

<EntityType Name="INVOICE">
	  <Key>
		<PropertyRef Name="INVOICE_ID" />
	  </Key>
	  <Property Name="INVOICE_ID" Type="number" StoreGeneratedPattern="Identity" Nullable="false" Precision="19" />
	  <Property Name="INVOICE_CODE" Type="varchar2" MaxLength="512" />
	  <Property Name="INVOICE_STATUS" Type="number" Precision="4" />
	  <Property Name="ORDER_CODE" Type="varchar2" MaxLength="256" />
	  <Property Name="PAY_VALUE" Type="number" Precision="19" />
	  <Property Name="PAY_DATE" Type="timestamp" />
	  <Property Name="PAYMENT_TYPE" Type="varchar2" MaxLength="256" />
	  <Property Name="TRANSACTION_CODE" Type="varchar2" MaxLength="256" />
	  <Property Name="RECEIVE_URL" Type="varchar2" MaxLength="636" />
	  <Property Name="RESPONSE_URL" Type="varchar2" MaxLength="512" />
	  <Property Name="DESCRIPTION" Type="varchar2" MaxLength="512" />
	  <Property Name="CREATED_BY" Type="number" Precision="19" />
	  <Property Name="CREATED_DATE" Type="timestamp" />
	  <Property Name="PROVIDER_ID" Type="number" Nullable="false" />
	  <Property Name="CUSTOMER_ID" Type="number" Nullable="false" Precision="10" />
	</EntityType>

5. In code behind

//Create Customer
CUSTOMER customer = new CUSTOMER {
	CUSTOMER_NAME = buyerDetail.NAME,
	ADDRESS = buyerDetail.ADDRESS_TEXT,
	PHONE = buyerDetail.PHONE,
	EMAIL =  "abc@xyz.com",
	CUSTOMER_TYPE = "P"
};

//Create invoice
INVOICE invoice = new INVOICE
{
	ORDER_CODE = orderCode,
	DESCRIPTION = description,
	PAY_VALUE = payValue,
	PROVIDER_ID = 1, 
	INVOICE_STATUS = 1, 
	CREATED_DATE = System.DateTime.Now,
	CUSTOMER = customer
};

// insert and commit
unitOfWork.Invoice.Insert(invoice);
unitOfWork.Commit();

Happy coding!

Posted in Entity framework | Leave a comment

Using Entity framework to call Oracle Stored Procedure in ASP.NET MVC3

This tutorial I will intro about how to using Entity framework to call Oracle Stored Procedure in ASP.NET MVC3. In this tutorial I use oracle database with username is SCOTT.

Requirements:

  • Oracle client 11g
  • ODAC 11.2.0.3 for visual studio.

you can download them from website of oracle.

1. Create a new ASP.NET MVC3 project with razor view engine and set named MvcApplications.EFCallOracleProcedure

image

2. Create a new Stored Procedure to return list of EMP

CREATE or REPLACE
PROCEDURE EMP_GETLIST
(
o_cursor out SYS_REFCURSOR
)
IS
BEGIN
open o_cursor for
SELECT * FROM EMP;
END EMP_GETLIST;

3. Create a new ADO.NET Entity Data Model and set named ScottModel under Models folder

image

Click Next button

image

Choose Generate  from database and click Next button

image

Click New Connection… and enter parameter to connect to database after that click OK button.

image

image

Click Next button

image

Click Finish.

4. Add Function Import

In ScottModel.Edmx right click and choose Model Browser. In Model Brower right click EMP_GETLIST so choose Add Function Import…

image

In Return a Collection Of choose Entities is EMP entity.

image

You can see function is imported in ScottModel.Designer.cs

image

5. Open web.config and add the following code in <configuration/> section

<oracle.dataaccess.client>
    <settings>
      <add name="SCOTT.EMP_GETLIST.RefCursor.o_cursor" value="implicitRefCursor bindinfo='mode=Output'" />
    </settings>
  </oracle.dataaccess.client>

6. Create a new action in Home controller

public ActionResult Emp()
        {
            using (ScottEntities context = new ScottEntities())
            {
                ObjectResult<EMP> emps = context.EMP_GETLIST();
                List<EMP> emplist = new List<EMP>();
                foreach (var emp in emps)
                {
                    emplist.Add(emp);
                }
                return View(emplist);
            }
        }

7. Create a view to show list of EMP

image

8. Build and run website

image

Happy coding!

Posted in ASP.NET MVC | 4 Comments