ASP.NET vNext on OSX and Linux

Original post/curtsy: http://graemechristie.github.io/graemechristie/blog/2014/05/26/asp-dot-net-vnext-on-osx-and-linux/

So what is ASP.NET vNext ?

Microsoft have recently released a preview of the next iteration of their ASP.NET platform. I’m not going to go into the details here, people like Scott Hanselman have already done a fantastic job of that. I will however say that the changes, both technical and cultural, are huge. Two of those changes are particularly relevant to this blog post.

Firstly, ASP.NET vNext is fully open source. People like you and me are able to get in on the ground floor, try out the bits and pieces and even contribute – pretty much from the project’s inception.

Secondly, ASP.NET vNext is cross platform, and embraces non Windows hosts as first class citizens. Microsoft are fully integrating Mono and Linux into their build environment and test matrix, and are actively working with the community to make Mono a top class platform for hosting ASP.NET. That being said, these are early days, and the team is still ironing out issues with the Mono environment.

Getting ASP.NET vNext up and running on OSX and Linux

There are two main steps to getting to the point where we can run ASP.NET vNext applications on our non Windows system.

The first is to install Mono. Normally this would be a no brainer; however as all this stuff is very shiny and new there are fixes and features that are currently only in the bleeding edge source code of Mono and have not been released as a package as yet. In order to get these fixes we are going to need to build mono from the latest source code located in the mono git repository.

The second step is to install the “K Runtime Environment” or KRE. This is the command line environment that will build and run (not that there is really a distinction anymore) projects from their new project.json project files.

Installation of the KRE is handled by the “K Version Manager” (KVM). This is a simple app that can install multiple versions of the KRE side by side, and allow you to easily switch between them.

Building Mono

I don’t want to go into too much detail here. There are plenty of guides around the internet on installing mono from source.

  • Install Mono as per the instructions at The Mono Github page.
  • You will need an earlier mono release installed in order to build Mono from source (Mono uses Mono to build itself)
  • You will need autoconf, libtool and and a few other common dev tools installed on your system.
  • On some linux systems you may need to run the following before you run the mozroots command below.
1
2
3
 sudo certmgr -ssl -m https://go.microsoft.com
 sudo certmgr -ssl -m https://nugetgallery.blob.core.windows.net
 sudo certmgr -ssl -m https://nuget.org
  • If you are on linux, you will need to run mozroots --import --sync after installing mono to avoid certificate/trust issues down the line
  • If you are on OSX you will want to edit /private/etc/paths and move the line /usr/local/bin before the line /usr/bin so the system finds the new mono version on the path before the old one.

caveat: This may totally break your system if you have lots of crazy stuff in /usr/local/bin. If your not sure about this, wait for a supported official release of Mono

Once all this is done, run mono --version. You should see that you are running Mono version 3.4.1 or newer.

mono --version

If you do not, check your $PATH variable and go back over the mono install steps.

Installing KVM and the K Runtime Environment

Installing KVM is super simple. If you like you can go to the Readme for the AspNet Home project and follow the “Getting Started” instructions there, however that involves cloning the Home Repository which is only required for that quick start demo.

KVM can be installed on any Linux or OSX system (that has bash or zsh and curl installed) with a single line.

1
curl https://raw.githubusercontent.com/aspnet/Home/master/kvminstall.sh | sh && source ~/.kre/kvm/kvm.sh && kvm upgrade

This will:

  • download kvm.sh and save it in ~/.kre/kvm/kvm.sh
  • add the command to run kvm.sh on every login to bash/zsh.
  • kvm.sh will then be run via the source command. This adds the kvm command to the current shell.
  • run kvm upgrade. This will download the latest KRE package, extract it to .kre/packages and add the bin folder to your path.

Once this is done, all of the KRE commands will be available from shell prompt. Primarily this will be the k command used to run ASP.NET vNext Projects, and the kpm command used to restore packages.

Additionally the kvm command can be used to install other version of KRE side by side for the user, switch between versions, list the installed versions and set up aliases. See the ASP.NET Home Project Readme for examples of the various kvm commands.

Okay, so I’ve got a Shiny New KRE ….

So let’s point it at something. We could download one of the many samples from the aspnet repository, however just to prove we have everything we need to build and run ASP.NET vNext apps on OSX and Linux, lets create a very basic project from scratch.

  • Create a folder called HelloKRuntime somewhere on your system and cd into that folder
  • Create a file called project.json and copy the following text into it. This is your ASP.NET vNext project file .. and not an angle bracket to be seen !
1
2
3
4
5
6
7
8
9
  {
    "dependencies": {
      "System.Console": "4.0.0.0"
    },
    "configurations": {
      "net45": {},
      "k10": {}
    }
  }
  • Create a file called Program.cs and copy the following text into it.
1
2
3
4
5
6
7
8
9
  using System;

  public class Program
  {
      public static void Main()
      {
          Console.WriteLine("Hello K Runtime !");
      }
  }
  • type kpm restore -s https://www.myget.org/F/aspnetvnext/ The K Package Manager will head off to the nuget repository and fetch System.Console and all its dependencies, based on the entry in your project.json file. Note that there is no need to use Nuget to install this package. The project.json entry is all the info kpm needs to fetch your dependencies.

Note: Because the ASP.NET vNext project is currently using their own nuget feed, we need to supply the nuget source on the command line. This can be provided in a NuGet.Config file in your Solution folder, and once the vNext is released you shouldn’t need one at all unless you are using your own private nuget feeds.

kpm restore

  • Now type k run from the command line. You should see your system burst to life and utter those immortal words

Hello K Runtime

  • As an example of how the new Configuration system ties into the environment, try typing export KRE_TRACE=1 and then k run again. You will see the compiler output as well as the “Hello K Runtime” message.

Hello Compiler Output

In Summary

Hopefully this post has demonstrated that cross platform ASP.NET vNext functionality is available now. There are still rough edges, but progress is being made daily and first class support for OSX and Linux environments is on the horizon. If you are having issues getting this working, feel free to drop into the aspnetvnext room on Jabbr and someone should be able to help you out.

UPDATE: If you’d like to try something more involved than the trivial console application above, the simple Hello World V Next web example might be a good next step.

The Next Generation of .NET – ASP.NET vNext

Original post/ curtsy: https://blogs.msdn.microsoft.com/dotnet/2014/05/12/the-next-generation-of-net-asp-net-vnext/

The Next Generation of .NET – ASP.NET vNext

Updated (July 2015): See Announcing .NET Framework 4.6 to read about the latest version of the NET Framework.

Today at TechEd North America, we announced the latest set of innovations that are part of the next generation of .NET. The biggest of those is ASP.NET vNext, which is an updated version of ASP.NET that been optimized for cloud Web development. We’ve continued to improve the core .NET technologies that we shared at Build last month, specifically the .NET Native ahead-of-time compiler and the .NET Next Generation JIT (“RyuJIT”). Both have new releases you can try out. We also have a set of smaller announcements to share.

At Build last month, we announced the .NET Foundation. We are currently talking to over 25 community-based .NET projects and organizations about joining the foundation. The interest in the foundation has exceeded our expectations and is off to a great start.

We also announced the .NET Compiler Platform (“Roslyn”) at Build. It includes new C# and VB compilers and a preview of new language features being considered for C# 6. The project is open source on codeplex and has accepted its first pull requests from the community.

The final release of Visual Studio 2013 Update 2 is now available. Update 2 brings dozens of significant new features to Visual Studio developers, including tools for Windows Phone 8.1 and universal Windows apps.

While we’re looking forward, it’s also good to look at one of the current strengths of .NET. There are currently 1.8 billion active installs of .NET. That’s a very large number by any measure and a great base of desktop and server machines on which to run your apps.

TechEd .NET Announcements

Here’s a quick rundown of the .NET announcements that we shared at TechEd.

.NET vNext

TechEd is the first time we’re talking about .NET vNext, as the next major release of the .NET Framework. At Build and TechEd, we’ve shared many of the features and components that you can expect in the next release. You will be able to compile C# 6 and VB with the Roslyn compilers, host ASP.NET vNext apps on the server or cloud, compile your Windows Store apps with the .NET Native ahead of time compiler, and enjoy faster desktop and server apps with the Next Generation JIT.

We’ve optimized .NET for the mobile-first and cloud-first development options that have become more common today. Device and cloud apps come with significant user expectations around performance, and also run in more specialized hardware/virtual environments. For Windows Store apps, we built the .NET native ahead of time compiler. For cloud apps, we’ve developed a cloud optimized mode.

.NET vNext will have a cloud optimized mode that enables you to deploy your apps with a copy of the .NET Framework libraries they need. Since the runtime and framework libraries are deployed on an app-basis, each app can run different versions of .NET vNext side-by-side and upgrade separately, all on the same machine. These libraries have been slimmed down significantly to reduce the footprint of the framework, and will be distributed via NuGet. Also, libraries such as WPF and Windows Forms have been removed from this mode.

We’re developing this with cross-platform in mind, including an active collaboration with Xamarin to ensure that cloud-optimized .NET applications can run on Mac or Linux on top of the Mono runtime. The great productivity of .NET and ASP.NET can be available to teams working in mixed development environments.

ASP.NET vNext

ASP.NET vNext is our big announcement at TechEd. We’ve updated many aspects of ASP.NET to make ASP.NET apps easier to build and perform significantly better. We’ve considered sites and services that get infrequent traffic and those that get bombarded by visitors all day long. We’ve also opened up new scenarios that were just not possible with ASP.NET before.

We’ve designed ASP.NET with a key set of design principles in mind:

  • Cloud-ready out of the box
  • A single programming model for Web sites and services
  • Low-latency developer experience
  • Make high-performance and high-productivity APIs and patterns available – enable them both to be used and compose together within a single app
  • Fine-grained control available via command-line tools and standard file formats
  • Delivered via NuGet
  • Release as open source via the .NET Foundation
  • Can run on Mono, on Mac and Linux

ASP.NET vNext includes updated versions of MVC, Web API, Web Pages, SignalR and EF. The key improvement with these frameworks is that MVC, Web API and Web Pages have been merged into a single programming model. For example, there’s now unified controller and routing concepts between all three. You can now have a single controller that returns both MVC views and formatted Web API responses, on the same HTTP verb.

ASP.NET vNext apps are cloud ready by design. Services such as session state and caching adjust their behavior depending on whether the app is running in the cloud or in a traditional hosting environment, while providing a consistent API. We use dependency injection behind the scenes to provide your app with the correct implementation for these services. Using this approach, it is really easy to move your app from on-premises to the cloud, since our code changes, not yours.

You will be able to make changes to your web applications and see the results after a browser refresh, with no separate build step needed. This significant productivity enhancement is based on improvements to load times in the underlying CLR, as well as use of the new .NET Compiler Platform (“Roslyn”).

You can see the ASP.NET vNext in action in the images below. The first image shows an ASP.NET vNext Hello World app hosted from the command-line and drive from browser. Any edits in Visual Studio will be compiled and executed when the browser is next refreshed. This app is using .NET vNext cloud optimized mode.

You can also use Visual Studio with a more traditional Visual Studio F5 workflow that automatically starts the webserver and launches the browser. This is the same app as shown in the image above.

In the image below, the app has been re-configured to run on the full .NET vNext framework, instead of the cloud optimized mode. That’s just a setting on the project. The app now has access to all of the APIs in the .NET Framework. The browser refresh feature is available in this configuration, too.

The table below outlines the ASP.NET vNext scenarios we’ve built and where they are available.

ASP.NET vNext Feature On .NET vNext On .NET vNext (Cloud Optimized)
Cloud Ready * *
Modular Design * *
Dependency Injection * *
Consistent Tracing / Debugging * *
Faster Development (browser refresh) * *
Open Source * *
Full Side by Side (runtime and framework
deployed with application)
*
Faster startup, Lower memory / Higher throughput (best of class) *
Uses a smaller set of framework libraries   *
Enabled on Mono, on Mac and Linux   *

 

ASP.NET vNext will be open source and will be contributed to the .NET Foundation. This shouldn’t come as a big surprise since the ASP.NET Web stack is already open source. All of ASP.NET vNext will be delivered via NuGet, will be open source and will take contributions. Read ASP.NET vNext: the future of .NET on the Server to learn more.

Our announcement at TechEd is the first stop for .NET vNext and ASP.NET vNext. We’ll share much more in the months to come before we release the final versions. We’re looking forward to shipping pre-release versions in order to get your feedback.

Additional .NET Framework Updates and Improvements

We recently announced the .NET Framework 4.5.2. It including significant improvements in ASP.NET and Windows Forms and other areas of the product. You can start incorporating 4.5.2 features into your apps now.

We released several key improvements to ASP.NET Web Forms. These include support for ASP.NET Identity 2.0, Entity DataSource control for Entity Framework 6 and Roslyn support.

We have also added new features and scenarios to both .NET Native and the Next Generation JIT. .NET Native now support x86, in addition to ARM and x64 apps. The Next Generation JIT now supports Windows 7 and later for x64 apps. Both of these technologies are a critical part of our .NET vNext roadmap. Expect to hear more about both of them in the coming months.

Targeting Multiple Platforms

We’ve been working for several years to make it easier to write code for multiple platforms, both as apps and libraries. We started by enabling our PCL reference assemblies for Xamarin, who quickly moved forward with that change. More recently, we’ve been working closely with Xamarin to make our .NET NuGet packages work better with Xamarin tools, to make it easier to build .NET apps for iOS and Android. There’s still work to do, but the experience has gotten much better and will continue to improve.

At TechEd, we announced a new portability analysis tool, called ApiPort. It provides you with two main pieces of data: the platforms that you can easily/reasonably target with your code, and the dependencies that are preventing you from targeting additional platforms.

The command line tool generates an Excel report that provides you with two views of its portability analysis. It provides a high-level color-coded view for a given set of platforms. It also provides a very detailed list of all the types and members used within your code, and whether they are supported, per platform. Given that the report is in Excel, it is very easy to filter the list, build pivot tables and do whatever else you want to perform further analysis.

The image below shows a small sample of the high-level portability analysis view. Only one assembly is shown, but there can be multiple. Check out this sample portability analysis to get a first-hand view.

The tool has another function, too. All of the dependency data (not the assemblies) are uploaded to an Azure service that the .NET team maintains. The data that the tool uploads is the list of assemblies and APIs that your code relies on. We do not record where the data came from or by whom. We do not upload any of your actual code or binaries. We want to know which functionality we need to bring to each platform to make it easier to target all platforms.

If you are finding it difficult to target a particular platform, please “vote” for the APIs you want added to a particular platform by running the tool on your app and libraries. It’s really easy to run the tool on a whole directory.

This first release of tool is missing a few features that we are in the process of adding. The Xamarin/Mono platforms are currently missing from the tool. It also doesn’t yet take into consideration NuGet packages that make .NET Framework APIs available on other platforms, counting them as missing APIs.

Client Libraries for Microsoft Services

You’ve probably heard that Microsoft is both a “services first” and “devices first” company. At the nexus of those statements are client libraries that make it easy to target Microsoft services from apps. While Client libraries for Microsoft services are not new, we are more recently working to provide support for more platforms. We’ve started with Office 365 services, and intend to add more services over time.

At TechEd, we announced a preview release of a new set of client libraries for Office 365, for .NET and JavaScript. You can read the announcement for the new Office 365 client libraries on the Office Developer Blog. The .NET Client libraries support WPF, Windows Forms, Windows Store, Xamarin.iOS, Xamarin.Android and ASP.NET apps and Portable Class Libraries, and are delivered via NuGet.

We have also provided an integrated experience for adding these libraries to your apps within Visual Studio. Services require app registration, permission selection and a platform-specific user authentication experience. You also need to add the right client libraries to your app. The Visual Studio experience takes care of all of that for you, as part of the Connected Services Manager, displayed below.

You can learn how to start using this experience from the Office Developer blog. We are using StackOverflow as the community forum for this project, under the Office365APIs tag. Please tell us what you think about the client libraries and the new Visual Studio integration. Do note that these libraries, and the Office services they are targeting, are in Preview and don’t yet support production apps.

Summary

On the .NET team, we’re excited to be sharing the Next Generation of .NET. As you can see from this post and the one we published at Build, we are lining up a significant set of technologies, features and scenarios that will be part of .NET vNext, our next major release of the .NET Framework. In this post, we focused on ASP.NET vNext, our next generation Web and services platform.

For .NET vNext, we’ve been talking about major features and asking for feedback before we even announced the larger release. We’ve been actively engaging with experts and enthusiasts in our preview and pre-release programs to validate our ideas and product directions. It’s turned out to be a great approach. The feedback has been incredible. Thanks to everyone that has participated in our CTPs, developer previews, pre-releases and any other program we ran to collect feedback. We’ve also received great feedback in blog comments. It’s all been very helpful. Do expect multiple additional preview releases over the coming months, particularly for ASP.NET vNext. It’s going to be a fun time.

You can see how these technology investments come together into a single .NET Framework release, in the following slide that we showed at TechEd. Open Source is also an important part of our plans, as you can see with our ASP.NET vNext contribution plans with the .NET Foundation. The future looks very bright for .NET.

Running ASP.NET vNext on CentOS 7

Original post/ Curtsy: http://trydis.github.io/2015/01/06/running-aspvnext-centos7/

Running ASP.NET vNext on CentOS 7

For reference, here are the versions I used:

Mono: 3.10.0
KVM: Build 10017
KRE: 1.0.0-beta1
libuv: commit 3fd823ac60b04eb9cc90e9a5832d27e13f417f78

I created a new VM in Azure and used the image provided by OpenLogic. It contains an installation of the Basic Server packages.

Install Mono

Add the Mono Project GPG signing key:

$ sudo rpm --import "http://keyserver.ubuntu.com/pks/lookup?op=get&search=0x3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF"

Install yum utilities:

$ sudo yum install yum-utils

Add the Mono package repository:

$ sudo yum-config-manager --add-repo http://download.mono-project.com/repo/centos/

Install the mono-complete package:

$ sudo yum install mono-complete

Mono on Linux by default doesn’t trust any SSL certificates so you’ll get errors when accessing HTTPS resources. To import Mozilla’s list of trusted certificates and fix those errors, you need to run:

$ mozroots --import --sync

Install KVM

$ curl -sSL https://raw.githubusercontent.com/aspnet/Home/master/kvminstall.sh | sh && source ~/.kre/kvm/kvm.sh

Install the K Runtime Environment (KRE)

$ kvm upgrade

Running the samples

Install Git:

$ sudo yum install git

Clone the Home repository:

$ git clone https://github.com/aspnet/Home.git
$ cd Home/samples

Change directory to the folder of the sample you want to run.

ConsoleApp

Restore packages:

$ kpm restore

Run it:

$ k run
Hello World

That was easy!

HelloMvc

Restore packages:

$ kpm restore

Run it:

$ k kestrel
System.DllNotFoundException: libdl
(Removed big stack trace)

Ouch, so I went hunting for libdl:

$ sudo find / -name libdl*
/usr/lib64/libdl.so.2
/usr/lib64/libdl-2.17.so

Create symbolic link:

$ sudo ln -s /usr/lib64/libdl.so.2 /usr/lib64/libdl

Run it again:

$ k kestrel
System.NullReferenceException: Object reference not set to an instance of an object
  at Microsoft.AspNet.Server.Kestrel.Networking.Libuv.loop_size () [0x00000] in <filename unknown>:0
  at Microsoft.AspNet.Server.Kestrel.Networking.UvLoopHandle.Init (Microsoft.AspNet.Server.Kestrel.Networking.Libuv uv) [0x00000] in <filename unknown>:0
  at Microsoft.AspNet.Server.Kestrel.KestrelThread.ThreadStart (System.Object parameter) [0x00000] in <filename unknown>:0

Progress, but now we need to get libuv working.

Install libuv

$ sudo yum install gcc
$ sudo yum install automake
$ sudo yum install libtool
$ git clone https://github.com/libuv/libuv.git
$ cd libuv
$ sh autogen.sh
$ ./configure
$ make
$ make check
$ sudo make install

Run it again:

$ k kestrel
System.NullReferenceException: Object reference not set to an instance of an object
  at Microsoft.AspNet.Server.Kestrel.Networking.Libuv.loop_size () [0x00000] in <filename unknown>:0
  at Microsoft.AspNet.Server.Kestrel.Networking.UvLoopHandle.Init (Microsoft.AspNet.Server.Kestrel.Networking.Libuv uv) [0x00000] in <filename unknown>:0
  at Microsoft.AspNet.Server.Kestrel.KestrelThread.ThreadStart (System.Object parameter) [0x00000] in <filename unknown>:0

I knew it had to be a path issue or something, so I went hunting for libuv:

$ sudo find / -name libuv.so
/home/trydis/libuv/.libs/libuv.so
/usr/local/lib/libuv.so

I then checked the library name Kestrel was looking for on Linux here and based on that i created a symbolic link:

$ sudo ln -s /usr/local/lib/libuv.so /usr/lib64/libuv.so.1

Run it again:

$ k kestrel
Started

Navigate to http://your-web-server-address:5004/ and pat yourself on the back!

HelloWeb

Restore packages:

$ kpm restore

Run it:

$ k kestrel
Started

Navigate to http://your-web-server-address:5004/.

 

Mono Project

http://www.mono-project.com/docs/web/aspnet/

ASP.NET

Mono has an implementation of ASP.NET 2.0, ASP.NET MVC and ASP.NET AJAX.

Quick Resources:

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 advaned 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:

 $ cd /usr/lib/xsp/test
 $ xsp
 Listening on port: 8080
 Listening on address: 0.0.0.0
 Root directory: /home/cvs/mcs/class/corlib/Microsoft.Win32
 Hit Return to stop the server.

You can now browse to http://localhost:8080 and see various sample programs

SSL support in XSP

XSP supports SSL and TLS Client Certificates. For further details about setting it up, see the UsingClientCertificatesWithXSP document.

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:

  1. 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:

$ MONO_OPTIONS=--debug xsp2
Listening on port: 8080 (non-secure)
Listening on address: 0.0.0.0
Root directory: /tmp/us
Hit Return to stop the server.

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.

Work in Progress

git access

Users interested in the latest version of mod_mono and xsp can retrieve these from our public git repository. The module names are mod_mono and xsp respectively. You will also need to check out the mcs module as the System.Web classes are in mcs/class/System.Web.

Designer

There is work in progress on an ASP.NET Designer the designer will eventually be integrated into the MonoDevelop IDE.

ASP.NET Apache setup on CentOS

Original Post/ Curtsy: http://jharitesh.blogspot.com/2012/06/aspnet-apache-setup-on-centos.html

To run ASP.NET application on Apache mod_mono module should be installed and configured on Apache.
All .NET pages are actually processed by mono which runs in background along with Apache. Apache identify .Net request page with help of mod_mono module. I used centOS as OS and performed following steps to run ASP.NET application on Apache.

  • Mono installation
  • XSP installation
  • Apache installation
  • mod_mono installation
  • Configuration

Mono installation
1. yum install gcc bison pkgconfig glib2-devel gettext make

2. Please check latest mono version on site before installation and edit command with latest version.   wget http://ftp.novell.com/pub/mono/sources/mono/mono-2.10.2.tar.bz2

3. tar jxvf mono-2.10.2.tar.bz2

4. cd mono-2.10.2

5. ./configure -prefix=/opt/mono; make; make install

6. echo export PKG_CONFIG_PATH=/opt/mono/lib/pkgconfig:$PKG_CONFIG_PATH>>~/.bash_profile

7. echo export PATH=/opt/mono/bin:$PATH>>~/.bash_profile

8. source ~/.bash_profile

9. mono -V

to check mono is installed or not

10. cd ..
XSP installation

1. wget http://ftp.novell.com/pub/mono/sources/xsp/xsp-2.10.2.tar.bz2 2. tar jxvf xsp-2.10.2.tar.bz2 3. cd xsp-2.10.2 4. ./configure -prefix=/opt/mono; make; make install 5. cd ..

Apache installation

  1. yum -y install httpd-devel

mod_mono installation  

1. wget http://ftp.novell.com/pub/mono/sources/mod_mono/mod_mono-2.10.tar.bz2 2. tar jxvf mod_mono-2.10.tar.bz2 3.  cd  mod_mono-2.10 4. ./configure –prefix=/opt/mono; make; make install 5. cd ..

 Configuration

  1. mono_setup configuration: create mono_setup.conf under directory /etc/httpd/conf.d with below content.

Include /etc/httpd/conf/mod_mono.conf

MonoApplications “/:/var/www/html/”

MonoServerPath “/opt/mono/bin/mod-mono-server2”

 

Options FollowSymLinks

AllowOverride None

AddHandler mono .aspx .ascx .asax .ashx .config .cs .asmx .axd

 

  1. Apache configuration: 

1) Open /etc/httpd/conf/httpd.conf and uncomment below line(remove ‘#’).

NameVirtualHost *:80

Extra setting:

I like Ubuntu way to enable disable site so I added this in here too.

2) Add below line

Include /etc/httpd/sites-enabled/

3) Create two directory inside /etc/httpd using below command

mkdir /etc/httpd/sites-enabled
mkdir /etc/httpd/sites-available

4) Type following to create new file a2ensite
    1) cat > a2ensite
2) Type this line
ln -s /etc/httpd/sites-available/$1.conf   /etc/httpd/sites-enabled/$1.conf

3) Press enter to move cursor to a new line and press CTRL+D.
4) Type this  command to make a2ensite executable
chmod   +x   a2ensite
5) Copy into /usr/bin
cp a2ensite /usr/bin

Type following to create new file a2dissite
    1) cat > a2dissite
2) Type this line
rm       -f          /etc/httpd/sites-enabled/$1.conf

3) Press enter to move cursor to a new line and press CTRL+D.
4) Type this  command to make a2ensite executable
chmod   +x   a2dissite
5) Copy into /usr/bin
cp          a2dissite         /usr/bin

3.Config application

Each application will have own separate config in directory  /etc/httpd/sites-available
sample application config file: file path is /etc/httpd/sites-available/name.xyz.com

    ServerAdmin xxxx.yyy@name.xyz.com

DocumentRoot /var/www/name.xyz.com

DirectoryIndex Default.aspx

ServerName name.xyz.com

ServerPath /

MonoAutoApplication disabled

MonoApplications “/:/var/www/name.xyz.com”

MonoServerPath “/opt/mono/bin/mod-mono-server2”

AddHandler mono .aspx .ascx .asax .ashx .config .cs .asmx .axd

ErrorLog /var/log/httpd/ name.xyz.com-error_log

CustomLog /var/log/httpd/ name.xyz.com-access_log common

 

In sample config application root directory is var/www/name.xyz.com i.e all application files will be kept in folder name.xyz.com.

4. Deployment 
    1) create directory /var/www/name.xyz.com
2) Copy application folder content into directory /var/www/name.xyz.com
3) Type below command to enable web-application in apache

#a2ensite name.xyz.com

#service apache2 restart
4)  Type below command to disable web-application in apache.
#a2dissite name.xyz.com

#service apache2 restart
Note: file name should be same as what we create in /etc/apache2/sites-available.

5) Other useful commands
To start apache  #service httpd start
To restart apache #service httpd restart
To stop apache #service httpd stop
To check mono is running in background or not  #ps -ef |grep -i “mono”

I also came across few issues during setup and got good solution from other forums. Here are collectively all issues.

  1. After deployment & restart of apache when we try to access page ….it is shown as blank page.

Apache error log contains following errors:

[crit] (2)No such file or directory: Failed to create shared memory segment for backend ‘testing’ at ‘/var/run/mod_mono/mod_mono_dashboard_testing_2’.

It is actually thrown because it is failing to create shared memory. Mono run as user apache but only root can write to /var/run. So solution is to create a folder and make apache owner.

  1. After solving 1st error when we try to access page from browser it throws error “Service Temporarily Unavailable”. In apache error log below error is shown.

” [error] Failed to connect to mod-mono-server after several attempts to spawn the process.”

solution: This is because of SELinux. By disabling SELinux using following command this issue can be resolved.

# setenforce 0

Script for above two issue is as follows.

dir=”/var/run/mod_mono/”

echo “Disable SELinux”
setenforce 0
echo -n “SELinux status is ”
/usr/sbin/getenforce
echo “Stopping Apache”
apachectl stop
echo “Waiting 5 seconds”
sleep 5s
shopt -s dotglob
if [ -d “$dir” ]; then
echo “Removing $dir”
rm -rf “$dir”*
rmdir “$dir”
fi
echo “Creating $dir”
mkdir “$dir”
echo “Changing owernerhip of $dir to Apache”
chown apache “$dir”
chgrp apache “$dir”

chown             -R apache   /opt/mono/
mkdir   -p        ~apache/.mono
chown  -R        apache:apache    ~apache/.mono
chmod             u+rw    ~apache/.mono
echo “Starting Apache”
apachectl start
echo “Done!”

Above script will run only when system start or reboot.

  1. Error message “Make sure that your mod_mono module is loaded after the User/Group directives” is thrown when we start/restart apache. [1]

soln : Put below statement just above “Include conf.d/*.conf” in httpd.conf

User apache
Group apache

and then restart apache httpd service.

  1. Error message ” Starting httpd: httpd: Could not reliably determine the server’s fully qualified domain name, using localhost.localdomain for ServerName”

Do following
1) Edit /etc/hosts using your favourite editor The contents should look something like this: # Do not remove the following line, or various programs # that require network functionality will fail. 127.0.0.1 localhost.localdomain localhost ::1 localhost6.localdomain6 localhost6
2).
At the end of the file add: 192.168.20.100 Server1.example.com That’s a [tab] between the IP address and the host name.
3) Save the file
4) Restart the network services to apply your changes service network restart
5)
Restart Apache service httpd restart

  1. Error message “Auto generated encryption keys not saved: System.Security.SecurityException: No access to the given key”

Reason :ASP.NET is creating auto generated keys for the machine and failing to safe them. The only problem, other that seen that message, is that every time the application is started it will get new keys because they are not being saved.

The directory where this is trying to write is somewhere $SYSCONFDIR/mono/registry (usually /etc/mono/registry). If it allow the user running apache read, write, and execute permissions on that folder, Mono will be able to save the auto generated keys and will reuse them subsequently. Once the keys are written, the apache user will only need read and execute permission.

Solution:
chown             -R apache /opt/mono/
mkdir   -p        ~apache/.mono
chown  -R        apache:apache  ~apache/.mono
chmod             u+rw  ~apache/.mono

The auto-generated keys are now being stored at: “/var/www/.mono/registry/”

Setting up ASP.NET on CentOS 6.x

Original post/ curtsy: https://jefferytay.wordpress.com/2015/08/23/setting-up-asp-net-on-centos-6-x/

With vNext, we are now finally able to run asp.net on Linux!

 

This is done via the MONO framework, which has been around for ages. However as it is with bleeding edge technologies, the setup can be rather cumbersome.

 

Here is the script that you can use to install the latest version of everything and set it up nicely on a minimal setup CentOS box (which is what most servers typically use).

Full source can be found at http://pastebin.com/aTxQne2n

 

##################################################################
# For minimal setup of CentOS 6.5/6.6
##################################################################

##################################################################
# Basic Server essentials
##################################################################
yum -y update
yum -y install yum-utils epel-release
yum clean all && yum makecache
yum -y groupinstall ‘Development tools’

##################################################################
# Install Mono (Latest Version)
##################################################################
yum -y install git autoconf libtool automake build-essential gettext
git clone git://github.com/mono/mono.git
cd mono
./autogen.sh –prefix=/usr/local
make get-monolite-latest
make EXTERNAL_MCS=”${PWD}/mcs/class/lib/monolite/gmcs.exe
make
make install

##################################################################
# Install LibUV (Latest Version)
##################################################################
yum -y install gcc automake libtool
git clone https://github.com/libuv/libuv.git
cd libuv
sh autogen.sh
./configure
make
make install
ldconfig

##################################################################
# Install Node (Latest Version)
##################################################################
yum remove -y nodejs npm
curl -sL https://rpm.nodesource.com/setup | bash –
yum install -y nodejs

##################################################################
# Install Yeoman and Generator Support (Latest Version)
##################################################################
yum -y install npm

#update npm to latest
npm install -g npm@latest
npm install -g yo

#install Generator support
npm install -g generator-aspnet

##################################################################
# Install DNVM (Latest Version)
##################################################################
yum -y install unzip
curl -sSL https://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.sh | DNX_BRANCH=dev sh
source ~/.dnx/dnvm/dnvm.sh

##################################################################
# Update Mozilla Root Server Certificates
##################################################################
mozroots –import –sync

## for dnu restore to work more reliably, increase concurrent threads
echo -e ‘\r\n## Enable greater Mono concurrency (helps dnu restore)\r\nexport MONO_THREADS_PER_CPU=2000’ >> ~/.bashrc

## dnx needs this to load libuv on CentOS (why not on Ubuntu?)
echo -e ‘\r\n## dnx needs this to load libuv on CentOS (why not on Ubuntu?)\r\nexport LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH’ >> ~/.bashrc

## done – print final instructions
echo -e ‘\r\nDone installing ASP.NET 5 prerequisites and DNVM.\r\nOpen new shell environment\r\nor\r\n$ source .bashrc to keep using this one.\r\n’

JasperReports with PHP Example step by step using iReport

Original Post/ Curtsy: http://chathurangat.blogspot.com/2012/03/jasperreports-with-php.html

JasperReports with PHP

Today i am going to write this article on the use of JasperReports in PHP as a reporting tool. Here i have used IReport-4.5.0 IDE for designing the JasperReport Template (known as jrxml file).In addition, you require a PHP library(third party) that generates PDF reports from the given jrxml document. this library can be downloaded from the following Git Repository
or else you can downloaded through following link

In order to design the template, please follow the steps given below.

1. load the IReport Designer tool
(executable file is available inside the bin directory)

2.after loading the IReport Tool,select new report template to start the report designing.
(File -> New)
then you will get a new window with a list of available report templates. select a template out of the available templates. in my case i have selected the Blank A4 template. please refer below.

then click the Launch Report Wizard to load the selected report template.

3. then give a Report Name and browse a Location where the report file (jrxml file) should be saved.  Please refer below.

4. then click on Next to proceed with next phase. please refer below.

As you can see in the Screen-shot, you will be displayed a list of available data source connections that can be used in your report. if you wish to create a new data source connection, you are free to do so by clicking New button.

5. if you click the New button to create new data source, you will be shown the below screen to select the the data source type. ( the data source type should be selected based on the application requirements. ) since this is PHP based web application, i have selected Database JDBC Connection as the data source type.


6. once you select the data source, click on next to proceed with next step. next will be the below screen.
here you have to provide the JDBC connection details.
 Name : just give any name for this connection for later reference  identification purpose
JDBC Driver:  select the most suitable JDBC driver from the given list based on your database. since i am using MySQL server database, i have selected  MySQL-JDBC Driver.
JDBC URL: make sure to edit the jdbc url based on your sever and database name. the default value of the jdbc url does not change, based on the value you provided for server and database. therefore please edit it manually.
 
Server Address : IP Address of the database sever. if the database is in your local machine, use localhost as IP.
Database : Database name that you are going to connect.
username: Username of the database server.
password : Password of the database server.
after filling all the configuration details, you can test the database conncetion by clicking the Test button provided. sometimes it may ask you to re-enter the database password. if the connection is successful, you will get a successful message as follows. then you can Save your new data source connection.
 7. then you can use your newly created data source for designing the query for your report. select the newly created data source and press Design Query button. then you will get the below window for designing the Query.
you will see a list of tables available in the connected database. you can Drag and Drop these tables to the provided area for designing the Query. then customize the columns displayed in the report by using the check boxes provided for each column.

8. once the Query is designed, press OK to finish it. the click Next to proceed with next phase. then next step is to select the required fields for your report out of the available all resulted columns of the Query you designed. add and remove the required database columns for your report with the provided button. please refer the below screen shot.

9. after completing the above operation, you can press Next button for continue with next phase. next phase is for applying the Group By clause for the report view. then phase is optional and you can skip this step by clicking just Next button. then the initial process of the report design is finished and you will be notified with the below screen. jut click on finish button.

10. then it will load and display the created .jrxml file. you are required to remember that this is the file that contains your report template. you can design the report as you wish by providing preferable title, footer and other required fileds.

11. the designing utilities are available in the Report Inspector window. please refer below screen shot.

as you can see that the selected database column fields are available under the Fields. you can drag and drop the database fields in into the Detail1 Section of your Report.Once you drag a database field, its column header section will be automatically visible underColumn Header section. In addition, the data field is visible under the Detail 1 Section. you can edit the column name as you wish.

12. Once the Design is done, you can preview the design using the Preview button.

13. The Report design elements are available in the palette window. you can get the palette window Window -> Palette

14. Once all the design is done, the it is time to integrate with your PHP application. make sure to download and import the PhpJasperLibrary in your PHP script. (copy both.jasper and .jrxml files into a same directory and give the reference in the PHP script)

report_view.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php
//Import the PhpJasperLibrary
include_once('PhpJasperLibrary/tcpdf/tcpdf.php');
include_once("PhpJasperLibrary/PHPJasperXML.inc.php");
//database connection details
$server="192.168.0.11";
$db="lcs_ims";
$user="web";
$pass="abc123@#";
$version="0.8b";
$pgport=5432;
$pchartfolder="./class/pchart2";
//display errors should be off in the php.ini file
ini_set('display_errors', 0);
//setting the path to the created jrxml file
$xml=  simplexml_load_file("report/chathuReport.jrxml");
$PHPJasperXML= newPHPJasperXML();
//$PHPJasperXML->debugsql=true;
//$PHPJasperXML->arrayParameter=array("parameter1"=>1);
$PHPJasperXML->xml_dismantle($xml);
$PHPJasperXML->transferDBtoArray($server,$user,$pass,$db);
$PHPJasperXML->outpage("I");    //page output method I:standard output  D:Download file
?>

access the report_view.php file in your LAMP/WAMP server. yo will get the report in PDF format.

Hope this will helpful for you!

Thanks and Regards,

Md. Nazim Uddin
Original Post: http://www.webprogrammingtips.com/index.php/tag/jasper-reportsexample-step-by-step-using-ireport/

Jasper reports:Example step by step using iReport

JasperReports(iReport) run with PHP & Database Oracle

August 2015    Jasper, ORACLE, PHP, XML

You can run iReport in your Oracle based PHP Application

1.      PHP Jasper Library (No required Jasper Report Server)

2.      PHP JAVA Bridge

3.      Web Service(Required Jasper Report Server)

Now I describe how to run iReports with your Oracle Based PHP Application using PHP Jasper Library

1.      Download PHP Jasper Library

2.      Create a Report folder in your application

3.      Unzip it  into Report Folder

4.      Create a Sample iReport which fetch data from Oracle Database

5.      Create DSN to connect Oracle Using ODBC( No required DSN if DB is Mysql

Show Video for How to create DSN to connect Oracle Database using ODBC

6.      Create a report_view.php page with following Script

<?php

//Import the PhpJasperLibrary

include_once(‘PhpJasperLibrary/tcpdf/tcpdf.php’);

include_once(“PhpJasperLibrary/PHPJasperXML.inc.php”);

//database connection details

$server=”192.168.0.11″;

$db=”screen”;

$user=”screen”;

$pass=”abc123@#”;

$version=”0.8b”;// User for Mysql

$pgport=5432;

$pchartfolder=”./class/pchart2″;

//display errors should be off in the php.ini file

ini_set(‘display_errors’, 0);

//setting the path to the created jrxml file

$xml =  simplexml_load_file(“report/sampleReport.jrxml”);

$PHPJasperXML = new PHPJasperXML();

//$PHPJasperXML->debugsql=true;

//$PHPJasperXML->arrayParameter=array(“parameter1″=>1);

$PHPJasperXML->xml_dismantle($xml);

//Mysql

//$PHPJasperXML->transferDBtoArray($server,$user,$pass,$db);// Mysql Default

//Oracle

$odbc_name=’screen’;

// For using Oracle , DSN create  First

$PHPJasperXML->transferDBtoArray($server,$user,$pass,$odbc_name,’ODBC’);//

$PHPJasperXML->outpage(“I”);    //page output method I:standard output  D:Download file

?>

access the report_view.php file in your LAMP/WAMP server. yo will get the report in PDF format.

PHP Tutorial Laravel 4 Framework Install on Windows

Curtsy: http://www.bogotobogo.com/php/Laravel4/php_laravel4_framework_install_on_Windows.php
php version

The laravel requires php5.3.7+. So, we need to check, php -v:

PHP 5.4.27 (cli) (built: Apr  3 2014 00:56:21)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2014 Zend Technologies

It looks OK.

Download laravel from git

We need to download Laravel from: https://github.com/laravel/laravel/archive/master.zip.

Extract laravel

Extract Laravel into the C:\Apache2\htdocs\ which is a DocumentRoot:

Download composer

Download Composer from: https://getcomposer.org/Composer-Setup.exe

Enable openssl

Enable openssl from all php.ini

;extension=php_openssl.dll =>
extension=php_openssl.dll
Install composer

Install Composer into the directory where php.exe is located, C:\php
Composer_setup.png

Enabling PHP Extensions

The following PHP Extensions in C:\php\ext should be enabled: php_curl and php_socket.

Edit C:\php\php.ini file:

extension=php_curl.dll
extension=php_sockets.dll

 

Download and install the framework’s dependencies.

Now, run the composer install command in the root of our manually created project directory (where we extracted Laravel). So, on cmd prompt:

C:\Apache2\htdocs\bogotobogo\Laravel\auth>cd ..
C:\Apache2\htdocs\bogotobogo\Laravel>composer create-project laravel/laravel auth --prefer-dist
Install finished

Here are the directory and file structure under htdocs dir:
hpdocs_dir.png

bogo_dir.png

Laravel_dir.png

auth_dir.png

Let’s see how the browser will do when we type in
http://localhost/bogotobogo/Laravel/auth/public/:
public_dir_final.png

OK, that’s it!

Install phpMyAdmin

We need phpMyAdmin as well.
phpMyAdmin.png

If we want to bypass the login session and directly go into the phpMyAdmin, we need to renameconfig.sample.inc.php to <b.config.inc.php< b=””>and then edit it:

/*
 * Servers configuration
 */
$i = 0;

/*
 * First server
 */
$i++;
/* Authentication type */

$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'root_password'; 
$cfg['Servers'][$i]['auth_type'] = 'config';

Now, if we type in localhost/phpMyAdmin, we get this:
phpMyAdmin_direct.png

How you can run your codes online without installing any IDE/ software

[http://www.tutorialspoint.com/online_dev_tools.htm]

Here are some great websites for compiling and executing your code online

While some compilers are easy to install and use, some of them are expensive to memory and RAM. The solution is to compile the code online, run it and download the executable to your computer by using an online IDE. A list of such websites is following:

IDEOne

http://ideone.com/

Ideone is an online compiler and debugging tool which allows you to compile source code and execute it online in more than 60 programming languages. These include C, C++, C#, Objective C, Java, Pascal, Perl, PHP, Ada, COBOL, FORTRAN, Bash(Bash is a shell used in Linux) etc.’
IDE

CodePad

http://codepad.org/

codepad.org is an online compiler/interpreter, and a simple collaboration tool. It’s a pastebin that executes code for you. You paste your code, and codepad runs it and gives you a short URL you can use to share it. Paste the URL into chat or email to get help or to show someone how to do something. Or just try things out when you don’t have an interpreter handy. It works well on many phones.
The languages supported include C, C++, Perl, PHP, Python etc.
IDE

Compile-Online

It is another great online IDE with support for almost every well known programming languageIDE.

JDoodle

https://www.jdoodle.com/

“Online compiler and Editor for Java, C, C++, Perl, PHP, Python and More…”

IDE

With these sites you will just need an internet connection to run your code and you can avoid all issues which are invoked after installation of compiler or interpreter software.

If a website which deserves a place in this list and has been missed by us, let us know in the comments.

SQL Server: SELECT TOP Statement (TOP n th Position) by using WITH TIES

SELECT TOP 8000 WITH TIES  *
FROM [Hall_Info].[dbo].[ug_applicant_general_info]
ORDER BY HSC_TOTAL DESC, HSC_MATH_GP DESC, HSC_PHY_GP DESC, HSC_CHEM_GP DESC, HSC_ENG_GP DESC, SSC_GPA_MARKS_OBTAINED DESC

[Curtsy] Original Post: http://www.techonthenet.com/sql_server/select_top.php

SQL Server: SELECT TOP Statement

This SQL Server tutorial explains how to use the SELECT TOP statement in SQL Server (Transact-SQL) with syntax and examples.

Description

The SQL Server (Transact-SQL) SELECT TOP statement is used to retrieve records from one or more tables in SQL Server and limit the number of records returned based on a fixed value or percentage.

Syntax

The syntax for the SELECT TOP statement in SQL Server (Transact-SQL) is:

SELECT TOP (top_value) [ PERCENT ] [ WITH TIES ]
expressions
FROM tables
[WHERE conditions]
[ORDER BY expression [ ASC | DESC ]];

Parameters or Arguments

TOP (top_value)
Returns the top number of rows in the result set based on top_value. For example, TOP(10) would return the top 10 rows from the full result set.
PERCENT
Optional. If PERCENT is specified, then the top rows are based on a percentage of the total result set (as specfied by the top_value). For example, TOP(10) PERCENT would return the top 10% of the full result set.
WITH TIES
Optional. If the WITH TIES clause is specified, then rows tied in last place within the limited result set are returned. This may result in more rows be returned than the TOP parameter permits.
expressions
The columns or calculations that you wish to retrieve.
tables
The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.
WHERE conditions
Optional. The conditions that must be met for the records to be selected.
ORDER BY expression
Optional. It is used in the SELECT TOP statement so that you can order the results and target those records that you wish to return. ASC is ascending order and DESC is descending order.

Example – Using TOP keyword

Let’s look at a SQL Server example, where we use the TOP keyword in the SELECT statement.

For example:

SELECT TOP(5)
employee_id, last_name, first_name
FROM employees
WHERE last_name = 'Anderson'
ORDER BY employee_id;

This SQL Server SELECT TOP example would select the first 5 records from the employees table where the last_name is ‘Anderson’. If there are other records in the employees table that have a last_name of ‘Anderson’, they will not be returned by the SELECT statement.

You could modify this example to include the WITH TIES clause as follows:

SELECT TOP(5) WITH TIES
employee_id, last_name, first_name
FROM employees
WHERE last_name = 'Anderson'
ORDER BY employee_id;

The WITH TIES clause would include rows that may be tied in last place within the limited result set. So if the 5th top record is a tie, then all records in this tie position would be returned by the SELECT TOP statement. This will result in more than 5 records being returned.

Example – Using TOP PERCENT keyword

Let’s look at a SQL Server example, where we use the TOP PERCENT keyword in the SELECT statement.

For example:

SELECT TOP(10) PERCENT
employee_id, last_name, first_name
FROM employees
WHERE last_name = 'Anderson'
ORDER BY employee_id;

This SQL Server SELECT TOP example would select the first 10% of the records from the full result set. So in this example, the SELECT statement would return the top 10% of records from the employees table where the last_name is ‘Anderson’. The other 90% of the result set would not be returned by the SELECT statement.

You could modify this example to include the WITH TIES clause as follows:

SELECT TOP(10) PERCENT WITH TIES
employee_id, last_name, first_name
FROM employees
WHERE last_name = 'Anderson'
ORDER BY employee_id;

The WITH TIES clause would include rows that may be tied in last place within the limited result set. So if the last position in the SELECT TOP(10) PERCENT record set is a tie, then these tied records would be returned by the SELECT TOP statement. This will result in more than 10% of the full record set being returned.

 

How to install squid proxy on centos 6 and 7

How to Install Squid (Caching / Proxy) on CentOS 7

yum clean all

yum -y update

yum -y install squid

squid -h

squid -v

systemctl start squid

systemctl enable squid

systemctl status squid

systemctl stop squid

Proxy LAN Interface

lan-images-proxyfonc

Proxy

Proxy

Yum update

Update yum repositories and packages by typing the below command:

[root@naz ~]# yum update

Install Squid

Install squid package and dependencies using the below command:

[root@naz ~]# yum install squid

squid configuration file

By default squid configuration file “/etc/squid/squid.confwill contains recommended minimum configuration  and squid caching feature will work without making any changes .

Now start squid service

[root@naz ~]# service squid start

and type this below command to start squid service automatically while booting.

[root@naz ~]# chkconfig –levels 235 squid on

Setup your web browser to access Internet through proxy server on port 3128

IE : Tools » Internet options »Connections » LAN settings » Choose “Use a proxy server for your LAN” » Type your Proxy server ip (192.168.1.11 ) and port no 3128

Firefox : Options / Preferences » Advanced » Network » Settings » Choose “Manual proxy configuration ” » Type your Proxy server ip (192.168.1.11 ) and port no 3128

Browse some sites and check the access log file on proxy server

[root@naz ~]# cat /var/log/squid/access.log

1343759484.331   1828 192.168.1.15 TCP_MISS/200 7005 GET http://www.krizna.com/ – DIRECT/216.172.163.231 text/html

1343759484.645    265 192.168.1.15 TCP_MISS/304 477 GET http://platform.twitter.com/widgets.js – DIRECT/23.64.79.144 application/javascript

1343759484.681    309 192.168.1.15 TCP_MISS/304 839 GET http://apis.google.com/js/plusone.js – DIRECT/173.194.36.36 –

Troubleshooting

If you not able to browse using proxy settings , Disable the firewall ( iptables ) and selinux service on your squid proxy server .

  1. Disable firewall ( Iptables ) »

[root@naz ~]# service iptables stop

[root@naz ~]# chkconfig iptables off

  1. Disable Selinux »

open the file /etc/selinux/config and find the line

SELINUX=enforcing

and replace with

SELINUX=disabled

now reboot the server

Configure squid proxy as web filter

You can restrict user access to particular websites or keywords using access control lists (ACLs) .

» Restricting Access to specific web sites :

For example , we can see how to block facebook.com and gmail.com .

Step 1 » create a file ( /etc/squid/blockedsites.squid ) and add the site names one per line.

[root@naz ~]# cat /etc/squid/blockedsites.squid

#blocked sites

http://www.facebook.com

http://www.gmail.com

Step 2 » Open the /etc/squid/squid.conf and create a new acl ” blocksites” and acl type “dstdomain” in the acl section like the below .

acl Safe_ports port 488         # gss-http

acl Safe_ports port 591         # filemaker

acl Safe_ports port 777         # multiling http

acl CONNECT method CONNECT

# ACL blocksites

acl blocksites dstdomain “/etc/squid/blockedsites.squid”

and add the following line “http_access deny blocksites” to http_section to deny the access to the acl “blocksites” .

# Recommended minimum Access Permission configuration:

# Only allow cachemgr access from localhost

http_access allow manager localhost

# Deny access to blocksites ACL

http_access deny blocksites

Now restart squid service

[root@naz ~]# service squid restart

Try to access facebook.com in your browser

Try to access facebook.com in your browser. and check the log file you can see the facebook request is denied .

[root@naz ~]# tail -f /var/log/squid/access.log

………………………………………………………………………

1343820985.542      1 192.168.1.15 TCP_DENIED/403 4255 GET http://www.facebook.com/ – NONE/- text/html

Restricting Access to specific keywords

create a file ( /etc/squid/blockkeywords.squid ) and add the keywords one per line.

[root@naz ~]# cat /etc/squid/blockkeywords.squid

#blocked keywords

sex

porn

xxx

Open the /etc/squid/squid.conf and create a new acl “blockkeywords” and acl type “url_regex” in the acl section

acl Safe_ports port 488         # gss-http

acl Safe_ports port 591         # filemaker

acl Safe_ports port 777         # multiling http

acl CONNECT method CONNECT

# ACL blocksites

acl blocksites dstdomain “/etc/squid/blockedsites.squid”

# ACL blockkeywords

acl blockkeywords url_regex -i “/etc/squid/blockkeywords.squid”

and add the following line “http_access deny blockkeywords” to http_section to deny the access to the acl “blockkeywords” .

# Recommended minimum Access Permission configuration:

#

# Only allow cachemgr access from localhost

http_access allow manager localhost

# Deny access to blocksites ACL

http_access deny blocksites

# Deny access to blockkeywords ACL

http_access deny blockkeywords

Restricting Access to specific Ipaddress

create a file ( /etc/squid/blockip.squid ) and add the ip adresses one per line.

[root@naz ~]# cat /etc/squid/blockip.squid

#blocked ips

192.168.1.20

192.168.1.21

Open the /etc/squid/squid.conf and create a new acl “blockip” and acl type “src” in the acl section

acl Safe_ports port 488         # gss-http

acl Safe_ports port 591         # filemaker

acl Safe_ports port 777         # multiling http

acl CONNECT method CONNECT

# ACL blocksites

acl blocksites dstdomain “/etc/squid/blockedsites.squid”

# ACL blockkeywords

acl blockkeywords url_regex -i “/etc/squid/blockkeywords.squid”

# ACL blockip

acl blockip src “/etc/squid/blockip.squid”

and add the following line “http_access deny blockip” to http_section to deny the access to the acl “blockip” .

# Recommended minimum Access Permission configuration:

#

# Only allow cachemgr access from localhost

http_access allow manager localhost

# Deny access to blockip ACL

http_access deny blockip

# Deny access to blocksites ACL

http_access deny blocksites

# Deny access to blockkeywords ACL

http_access deny blockkeywords

Allow Full access to specific Ipaddress

You can allow specific ip address to gain full access without blocking sites and keywords . just create a file “/etc/squid/allowip.squid ” and add the ip address one per line and create an acl “allowip”  and acl type “src” in the acl section

# ACL allowip

acl allowip src “/etc/squid/allowip.squid“

and add the “allowip” in the http_access as below

# Recommended minimum Access Permission configuration:

#

# Only allow cachemgr access from localhost

http_access allow manager localhost

# Deny access to blockip ACL

http_access deny blockip

# Deny access to blocksites ACL

http_access deny blocksites !allowip

# Deny access to blockkeywords ACL

http_access deny blockkeywords !allowip

Changing squid proxy port number

You can change squid proxy port number , by default it uses 3128 port .

Just find the below line in “/etc/squid/squid.conf”

http_port 3128

and replace with

http_port 8000 # whatever port number you want

Restricting Download size

You can restrict download file size using reply_body_max_size .

Add the below line at the bottom of the http_access section

#Restrict download size

reply_body_max_size 10 MB all

or

#Restrict download size

reply_body_max_size 10 MB !allowip

Configuring Squid as Transparent Proxy

You can configure squid as transparent proxy .

Step 1 » just find the below line

# Squid normally listens to port 3128

http_port 3128

and replace with

# Squid normally listens to port 3128

http_port 3128 intercept

just run the script

[root@naz ~]# sh /root/squidfw.sh

and add the below line to “/etc/rc.local” to run the script during startup

sh /root/squidfw.sh

Step 4 (Updated) » Change default gateway ip to squid server ip on the user machines .

Now users can access Internet without setting proxy in the browser settings.

That’s it , hope this article will help you to learn little things about configuring squid proxy on centos 6.

References

How to install squid proxy on centos 6

Follow

Get every new post delivered to your Inbox.

Join 83 other followers