- ASP.NET
- Running ASP.NET applications
- ASP.NET hosting with Apache
- ASP.NET hosting with Nginx
- ASP.NET hosting with XSP
- Configuration
- Other extensions
- Debugging
- Supported Versions
- Limitations
- Установка и настройка mono на Linux Ubuntu
- Установка и запуск mono
- Совместное использование с веб-сервером
- NGINX
- Apache
- Дополнительные настройки
- Добавить веб-приложение
- Смена порта сервера
- Porting ASP.NET Applications
- Introduction
- Getting started
- Prerequisite software
- Porting the code
- Required assemblies
- Configuration files
- DbProviderFactory configuration
- Npgsql and
- Connection string
- Membership/Roles provider configuration
- Filesystem paths
- machineKey storage
- File access permissions
- Markup
- URL case
- Code-Behind
- Filesystem path syntax
- File name case
- Porting the data
- MDF files
- Npgsql data provider
- Membership/Roles/Profile provider schema
- Source code
- Data provider changes
- XSD files
- Annotated files
- Modifying annotated files
- Editing queries
- SQL syntax differences
- SQL type mapping
- Stored procedures
- Tips for porting
- Running the application on Unix
- Supporting Multiple Platforms
ASP.NET
Mono has an implementation of ASP.NET, ASP.NET MVC and ASP.NET AJAX.
Mono’s ASP.NET implementations supports two kinds of applications:
- Web Forms (Web Applications infrastructure).
- Web Services (the SOAP-based RPC system).
Status and tests for ASP.NET 2.0 are available in our ASPTests page.
Running ASP.NET applications
To run your ASP.NET applications with Mono, you have three classes of options:
- Apache hosting: use mod_mono, a module that allows Apache to serve ASP.NET applications.
- FastCGI hosting: use the FastCGI hosting if you have a web server that supports the FastCGI protocol (for example Nginx) for extending the server. You also may use a web server that only has support for CGI using cgi-fcgi.
- XSP: this is a simple way to get started, a lightweight and simple webserver written in C#.
For deploying applications, we recommend the use of the mod_mono or FastCGI approaches, as that will give you all the configuration options and flexibility that come with using Apache or a FastCGI server.
For quickly getting started, get familiar with Mono and ASP.NET, XSP is the ideal solution. Keep in mind that XSP is a very limited server and is only useful to get acquainted with ASP.NET and Mono, it only support HTTP 1.0 and does not provide much extensibility or configuration.
More advanced users can use the HttpListener and the ASP.NET hosting to create their own hosts for ASP.NET applications.
ASP.NET hosting with Apache
The mod_mono Apache module is used to run ASP.NET applications within the Apache web server.
The mod_mono module runs within an Apache process and passes all the requests to ASP.NET applications to an external Mono process that actually hosts your ASP.NET applications. The external ASP.NET host is called “mod-mono-server” and is part of the XSP module.
To use this, you must download and install the mod_mono and xsp components of Mono. mod_mono contains the actual Apache module, and xsp contains the actual ASP.NET hosting engine, both are available from our download page.
See the mod_mono page for details on installation and configuration.
ASP.NET hosting with Nginx
Nginx is a high-performance HTTP server which support running ASP.NET and ASP.NET MVC web applications through FastCGI protocol. See the FastCGI Nginx page for details on installation and configuration.
ASP.NET hosting with XSP
XSP is a standalone web server written in C# that can be used to run your ASP.NET applications with minimal effort. XSP works under both the Mono and Microsoft runtimes. The code is available from our download page (look for XSP web server) or from the Git repository (module name: xsp).
The easiest way to start XSP is to run it from within the root directory of your application. It will serve requests on port 8080. Place additional assemblies in the bin directory. Other XSP options can be set on the command line, such as the application directory and the port to listen on.
XSP comes with a set of pages, controls and web services that you can use to test the server and see what ASP.NET looks like.
For example, once you install XSP, you can try some samples like this:
You can now browse to http://localhost:8080 and see various sample programs
Configuration
Applications can be configured through the web.config file, the full documentation is available from MSDN, and also a Mono-specific version is available on this site here.
Additionally, you can configure Mono-specific ASP.NET settings (to have applications that behave differently depending on the operating system they are deployed in) using the ASP.NET Settings Mapping engine.
Other extensions
Check out ASP.NET Modules for details on how to support deflate/gzip encodings and authentication.
Debugging
By default xsp and xsp2 run in Release mode, which means that debugging line-number information will not be available in stack traces when errors occur.
To obtain line numbers in stack traces you need to do two things:
- Enable Debug code generation in your page. 2. Run Mono with the –debug command line option.
You must enable debug code generation in your page using the Debug=”true” in the top of your page, or setting the compilation flag in Web.config (compilation option).
Use the –debug command line option to Mono, this is done by setting the MONO_OPTIONS environment variable, like this:
To do the same with the Apache mod_mono module, use the MonoDebug true directive in your apache configuration file.
Supported Versions
Mono supports ASP.NET 2.0, ASP.NET AJAX and a handful of 3.5 controls.
Limitations
Mono’s ASP.NET does not implement the following features:
- Precompiled updatable web sites.
- WebParts APIs.
Источник
Установка и настройка mono на Linux Ubuntu
Проект mono позволяет реализовать платформу .NET Framework на системах Linux. В данной инструкции мы разберем процесс его установки на Ubuntu.
Установка и запуск mono
Установку выполняем командой:
apt-get install mono-complete mono-xsp4 asp.net-examples
* пакет mono-complete содержит все возможности Mono; mono-xsp4 предоставляет поддержку ASP.NET; asp.net-examples — содержит примеры скриптов ASP и скрипт для автоматической конфигурации веб-приложения.
Разрешаем автозапуск и стартуем сервис:
systemctl enable mono-xsp4
systemctl start mono-xsp4
Если мы используем брандмауэр, добавим правило:
iptables -I INPUT 1 -p tcp -m tcp —dport 8084 -j ACCEPT
* где 8084 — порт, по умолчанию для mono-xsp4.
Сохраняем правила iptables любым способом, например:
* если данная команда вернет ошибку, устанавливаем iptables-persistent командой apt-get install iptables-persistent.
Для проверки работы сервиса открываем браузер и переходим по адресу http:// :8084/samples/ — мы должны увидеть страницу «Welcome to Mono XSP»:
* не обращаем внимания на некрасивый вид страницы и отсутствующее изображение — это происходит по причине того, что демо верстка немного не коррелирует с настройкой веб-приложения.
Совместное использование с веб-сервером
Рассмотрим процесс настройки mono с веб-серверами NGINX и Apache2 путем проксирования запросов.
NGINX
Открываем файл настройки виртуального домена по умолчанию:
Находим опцию location / и приводим ее к виду:
location / <
proxy_pass http://127.0.0.1:8084/;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
>
* где proxy_pass перенаправляет все запросы на внутренний сервер mono-xsp4.
Проверяем корректность настроек:
. и перезапускаем nginx:
systemctl restart nginx
Теперь открываем браузер и заходим по адресу http:// /samples/ (без указания порта). Мы должны увидеть веб-приложение, настроенное на mono.
Apache
Включаем модули для проксирования:
a2enmod proxy proxy_http
* где proxy — главный модель для перенаправления запросов; proxy_http — проксирование HTTP.
Настраиваем виртуальный домен с сайтом — в данном примере для сайта по умолчанию:
Добавляем строки внутри VirtualHost:
.
ProxyPreserveHost On
ProxyPass / http://127.0.0.1:8084/
ProxyPassReverse / http://127.0.0.1:8084/
.
* где опция ProxyPreserveHost включаем проксирование для виртуального домена; ProxyPass позволяет перенаправить все запросы на данный сервер (в данном примере, на локальный mono-xsp4); ProxyPassReverse задает правило для возврата ответа — при такой настройке ответ будет возвращаться обратно веб-серверу.
Проверяем корректность настроек:
. и перезапускаем веб-сервер:
systemctl restart apache2
Теперь открываем браузер и переходим по адресу без указания порта — http:// /samples/. Мы должны увидеть веб-приложение, настроенное на mono.
Дополнительные настройки
Разберем некоторые настройки, которые могут пригодится при конфигурировании сервера.
Добавить веб-приложение
Открываем файл webapp:
- web-application — секция с настройками приложения.
- name — имя приложения.
- vpath — путь URL, при обращении по которому приложение доступно.
- path — путь на сервере, где находятся скрипты приложения.
. также можно использовать дополнительные опции:
- vhost — имя виртуального хоста, если будем его применять.
- vport — номер сетевого порта, на котором слушает приложение.
- enabled — принимает значение true или false. Позволяет включить или отключить приложение.
systemctl restart mono-xsp4
Смена порта сервера
Открываем настройки mono-xsp4:
Ищем опцию port= и меняем ее значение на порт, на котором должен работать сервис:
Источник
Porting ASP.NET Applications
by Marek Habersack
This guide is meant to help Linux and Windows developers alike in porting ASP.NET 2.0 applications from Windows to Unix operating systems.
Introduction
By their nature, Web applications tend to be more portable to other platforms than traditional desktop applications. The interaction with the user is done through the web browser the user is running, which in most cases, guarantees interface portability nearly without effort. There exist incompatibilities in the DOM (Document Object Model), JavaScript, CSS and HTML implementations in the web browsers, but for the sake of this guide we will assume that all the browsers work in the same way in this regard.
In this guide we will focus on issues arising from differences between the Unix and Windows platforms, as well as between the database systems (RDBMS) in common use by developers on each of the platforms.
In this guide I will demonstrate the porting process based on the Blog Starter Kit application (you can download the original C# source from http://www.shankun.com/BlogStarterKit.aspx):
Getting started
No assumptions as to the experience level of the developer porting an ASP.NET application are made throughout the guide. The information presented here should be useful both to a Windows developer and a Unix developer porting the application to run on a Unix platform.
Windows developers. If you are a working in the Windows environment, it is advised that you download the VMWare Virtual Image to have it handy when you get to the testing phase of your porting effort. The VMware virtual machine comes with the latest release of Mono preinstalled.
If your application uses MS SQL then on your Unix system you will need to install the PostgreSQL RDBMS, as this is the product which will be used to port MS SQL databases to. It is recommended that you use PostgreSQL 8.0 or newer.
Prerequisite software
- Npgsql version from CVS.
The CVS version is required, since the ASP.NET 2.0 Membership classes rely on the DbProviderFactories model which is not available in Npgsql shipped with Mono. - ASP.NET PostgreSQL Membership/Role providers. I recommend the version from Nauck, It, which is the code I use in all the ported starter kits. Make sure that you use the version of the above provider from the Mono branch as it contains changes necessary for the provider to work correctly with the CVS version of Npgsql.
- PostgreSQL 8.2
Porting the code
When initially testing the application on Unix, you might choose not to deal with case-sensitivity issues described below, but instead use the MONO_IOMAP approach. By using the MONO_IOMAP feature, you can ignore the differences between the Windows file system (case insensitive, and uses \ as a path separator) and the Unix file system (case sensitive, and uses / as the path separator).
Required assemblies
Put the Npgsql and PostgreSQL providers assemblies in the bin/ subdirectory of your application.
Configuration files
DbProviderFactory configuration
As we’re using Npgsql from CVS, which is not configured for use with ADO.NET 2.0 in Mono by default, we need to add the section shown below to the Web.config file:
Remember the Npgsql invariant name, as it will be used below.
Npgsql and
Make sure that Npgsql is included in the set of assemblies to link with code compiled from
/App_Code and/or generated from your ASP.NET files by adding the following fragment to your Web.config file:
Connection string
Change the connection string to point to your PostgreSQL server and database. The code below shows the string for the Blog Starter Kit database named blogstarterkit , user login test , password test :
Membership/Roles provider configuration
The Membership/Roles provider requires a few changes to the application configuration. The XML below shows the relevant segment of the section for the Blog Starter Kit:
A point to note above is that we’re clearing the list of providers. This is done because we’re overriding the standard ASP.NET provider name string, to minimize the set of changes required to port the application.
Filesystem paths
Avoid specifying paths to files in the .config files. If you can’t avoid them, either provide a separate version for every supported platform with appropriate paths, or provider commented-out versions in a single .config file.
Another option is to use application relative URIs of the form:
Alternatively, you can provide the setting versions with different names, auto-detect the platform on the runtime and choose the appropriate setting (make sure you use proper file/directory name case in the Unix version of the setting):
The runtime detection code could look like this:
machineKey storage
Currently (as of June 2007) no Mono version supports persisting of the auto-generated machineKey values. For that reason, if you want your user sessions/logins to survive application restarts, you need to put the key values explicitly in the application top-level Web.config file.
Very useful utilities to generate the machineKey section can be found here and here
A sample element to put in the section:
Make sure that you generate your own set of keys for your site security.
File access permissions
Make sure your files which contain sensitive information are owned by a trusted user and have safe file permissions:
Note that the Web.config files should be owned by the user under which the webserver (XSP or Apache) runs.
Markup
URL case
All the markup elements that refer to resources external to a file they are in should use proper case — matching the file/directory name on disk. Mirosoft Windows and IIS are case-insensitive in that respect whereas Unix systems and webservers are not. It might be a good idea to make all the web-accessible file names all lower case.
Code-Behind
Filesystem path syntax
The issue you should pay great attention to is the platform-specific filesystem paths. Windows systems use a backslash ( «\» ) as path separator, while Unix systems use the forward slash ( «/» ) for the same purpose.
There are two ways of dealing with the issue:
System.IO.Path.DirectorySeparatorChar
System.IO.Path.Combine
File name case
Make sure that names of files you access from within your code-behind files are in proper case. Remember — Unix systems are case-sensitive.
Porting the data
It is assumed that your application uses MS SQL and you are porting the database to PostgreSQL.
MDF files
MS SQL/SQLExpress allow the developer to attach to a database stored in a file (usually located in the
/App_Data/ directory). This feature is not available with PostgreSQL so all your data must live in a database stored on the machine where the RDBMS runs.
Npgsql data provider
At the time of this writing (June 2007), you will need to use the CVS version of the Npgsql data provider, as the one shipped with Mono does not support ADO.NET 2.0.
Membership/Roles/Profile provider schema
The providers require specific database schema to be present in your database. Make sure you execute the script below in the context on your database before using the Blog Starter Kit for the first time:
Source code
Make sure that any queries issued directly from your source code use the correct syntax for PostgreSQL (modify them as described below).
Remember to modify your connection strings to use Npgsql format.
Data provider changes
Search and replace all the instances of SqlClient data access classes with their Npgsql counterparts. The code samples below come from Blog Starter Kit’s
- Make sure your code uses Npgsql.
- Use Npgsql versions of the database access classes.
- Modify command parameters to use syntax understood by Npgsql by replacing the @ marker character with :
- If you encounter references to @@IDENTITY in the queries made by your application, replace them with a call to the lastval() function.
XSD files
XSD files define in a, theoretically, database provider independent fashion the structure of the database. The files can be placed in the
/App_Code/ directory for automatic conversion into compilable code, or they can be processed from the command line with the XSD utility to produce compilable source code which contains type-safe DataSets for each table defined in the .xsd file:
The resulting .cs (or .vb if you chose VisualBasic for the output) file can be put in
/App_Code/ to be automatically compiled at the application startup.
Annotated files
Mono version of the xsd utility supports the standard contents of the .xsd files and generates correct code for it. However, if the input file contains a section which looks as follows, the generated code will not be as expected by your application:
If this is the case with your file(s), you should generate the code using the Microsoft version of the xsd utility, put the generated code in
/App_Code and remove (or rename) the corresponding .xsd file(s) so that their extension is different.
Modifying annotated files
Before processing the .xsd file on Windows you need to edit it to make sure the generated code is compatible with Npgsql. There are two sets of changes that need to be made in order to achieve the goal:
- Make sure the provider mentioned in the file is Npgsql
To do so, locate the section within the element and modify each element’s Provider attribute to say Npgsql - Edit the queries and parameters as described below
Editing queries
The annotation section of the .xsd file may contain elements shown below:
With the sample section shown above, you need to make several changes in order for the generated code to work properly with Npgsql:
- Make sure the DbType value is a valid type in Npgsql
- Change the ParameterName by replacing the @ character with : which is the standard parameter quoting character for Npgsql. Also any ocurrence of the parameter name in the query text needs to be modified in the same way.
- Remove all [ and ] characters from the query text.
- Make sure the query is syntactically correct for PostgreSQL (refer to PostgreSQL documentation at [1])
SQL syntax differences
Information below is based on this document
The information below is only an excerpt from the document referenced above containing the most commonly occurring issues. It is advised that you read the above document in addition to this guide.
- Remove all the [ and ] characters from the table definitions and/or queries
- Remove all the dbo. owner prefixes
- Remove all the file group keywords (ON PRIMARY, TEXTIMAGE_ON, CLUSTERED
- Remove all occurrences of SET ANSI_NULLS and SET QUOTED_IDENTIFIERS
- Remove all occurrences of WITH NOCHECK
- Replace all instances of the GO keyword with semicolons (;)
SQL type mapping
Information below is based on this document
The information below is only an excerpt from the document referenced above containing the most commonly occurring issues. It is advised that you read the above document in addition to this guide.
nvarchar
replace with varchar
ntext
replace with text
datetime and smalldatetime
replace with timestamptz
bit
can be replaced with either of boolean, int2 or smallint. The difference is in the syntax when referring to the field’s value in the queries (boolean accepts ‘0’, ‘1’, TRUE, FALSE, while the two integer fields accept only 0 and 1)
image
replace with bytea
decimal
even though PostgreSQL supports this type, it is deprecated in favor of numeric
tinyint
replace with smallint
UniqueIdentifier
replace with text in the SQL definition and String in the .xsd file. Typically, the ASP.NET apps will use this type to store the value of a Guid. If it is so in your case, make sure any and all code in your application that passes a value of type Guid to a method, first converts this value to a string (using the .ToString() method called on the Guid object). If your application does not use the field to store Guid values, you can replace the type with bigint. Also, see the document referenced at the start of this section for more information about the type.
int IDENTITY(1,1) : replace withserial(orbigserialif you expect to have a very large number of rows)
Stored procedures
Porting the stored procedures is the most time consuming and the most difficult task in the process of moving to PostgreSQL. First of all, you must make sure that your target database has the PL/pgsql language created. You must issue the command below as a PostgreSQL superuser:
PL/pgsql is the most similar to the MS SQL stored procedure language, so in theory it should be the easiest way to port the database. In practice, if you’re more familiar with Perl, Tcl, Python or C, you can write your procedures from scratch in any of those languages (making sure to previously create the language in the database in the way shown above).
Steps to port the stored procedures:
Replace all the CREATE PROCEDURE statements with CREATE FUNCTION. PostgreSQL functions need to have return types, so if you want to return no value, you need to define the procedure as follows:
Tips for porting
- Contrary to what the document quoted at the top of the section says, PostgreSQL 8.1 and newer stored procedures do support output parameters.
Default values for parameters are not supported. If you want to emulate them, overload the procedure:
If you plan to return only a subset of columns from a table, you should create a new type with only those columns and declare your function to return the new type:
Try not to use temporary tables in your PostgreSQL stored procedure. MS SQL procedures can contain code like the one shown below:
Instead of using CREATE TEMPORARY TABLE , you should rather create a new type and return result sets from a query limited to the columns you’re interested in.
Conditional execution blocks in PL/pgsql do not use BEGIN/END, instead they use the following syntax:
Running the application on Unix
Using MONO_IOMAP
On Unix systems, Mono supports an I/O compatibility mode which allows you to ignore the file name case when accessing files on disk. The mode also takes care of disk designators (e.g. c: ). Enabling the translation carries, obviously, some performance penalty, but is a good way to get your application up and running quickly. To enable the compatibility mode, make sure your web server’s (XSP’s or Apache’s) environment contains the MONO_IOMAP variable set to all:
If you’re using mod_mono , put the following line in your virtual host config file:
Supporting Multiple Platforms
Some applications require advanced configuration settings that are OS-specific or deployment specific. For example, Mono uses this to set the default membership and role managers on Linux to use SQLite by default, as opposed to a larger database.
Источник