Archive for January, 2012

How to profile asp.net web application with DotTrace

Written by Alex on . Posted in Uncategorized

If your application works slow and you can’t understand why, than have a look at dotTrac. It’s a very good tool from JetBrains. It helps you to profile both windows and web application written in c#.

Profile web application is very easy. After starting dotTrace you have to select “Profile Application”.

dot-trace-profiler

New window appears and you have to provide path to Web dev server. At my PC it’s here:

 C:\Program Files\Common Files\microsoft shared\DevServer\9.0\WebDev.WebServer.EXE

Arguments must be path to your web application, port number and virtual path. It must be something like this:

/path:”D:\SVN\aspnetprofiling\Web” /port:1234 /vpath:”/aspnetprofiling”

be careful about slashes at the end of the path. It must be no slash.

start-profiling-with-dottrace

After that, window “Control profiling” appears. And you have to run your application and press button “Start profiling”. Than after finishing profiling press “Get Snaphost” button.

get-snaphost-profiling

New window appears with information about application. And in the bottom of this window you can see your source code for called methods. If you need to edit some method in source file, press “Open in Visual Studio” button in source code window and you will navigate to Visual studio.

dot-trace-profiling-results

 

If it will be an error while starting profiler, you have to copy files WebDev.WebServer.EXE and WebDev.WebServer.EXE.manifest into your .NET framework folder. Usually it’s

 C:\Windows\Microsoft.NET\Framework\v2.0.50727\

MS SQL Server 2008 nvarchar(max) limit and NHibernate

Written by Alex on . Posted in Uncategorized

Today we faced the following problem with Atomic CMS (content management system): when creating page in admin section it was not possible to save text > 4000 characters. SQL Server had this limit in old versions, but SQL Server 2008 does not have this problem if you declare column as nvarchar(max), in this case the length of the data can be 2^31-1 bytes

We double checked if the column in database has correct type, and yes, it was nvarchar(max), but we still have 4000 limit.

The source of the problem was found in about an hour, it was wrong NHibernate configuration (Atomic CMS use NHibernate to access database). By default NHibernate does not allow write in database and read back strings with length greater than 4000.

The fix was quick, we have to set length attribute for the PageContent property

<property name="PageContent" column="PageContent" type="String" length="2147483647"/>

jQuery.log(), Logging plugin for jQuery

Written by Alex on . Posted in Uncategorized

For the people who working with JavaScript, logging is very important for debugging. Before I start using Firebug plug-in for Firefox I used alert function. It works in all browsers, and it’s quickly to use.

But for big application where you working with kilobytes of JavaScript code it’s not the best option, because you have to click on “OK” button every time when see this window, and if it one or two times it’s not a problem, but anyway it’s annoying.

But Firebug has a great number of methods for logging it’s
console.log
console.debug
console.info
console.warn
……

All this methods provide you with logging messages in Firebug console, but with different icons. But anyway in my opinion the most popular is console.log

If you want to test your application in browsers different from Firefox, your will have error message, because console.log is not define, so the best solution is create wrapper for JavaScript logging.
You can just create a method for this purpose, but I like jQuery and prefer to create plugin for jQuery.

Creating jQuery plug-in for logging. jQuery.log()

jQuery it’s a great library and allow a lot of stuffs, and one of the most important feature is creating plug-in.
All plug-in in jQuery have pattern it’s :
 

(function($) {
    // your plug-in code here
})(jQuery);

This patterns allow you to user $ for accessing jQuery inside of plug-in and help to hide some internal methods and properties because of closure.

I want to access my logging plug-in this way

$.log('my message');

The code for jQuery log plug-in is below

(function($) {
    $.log =
    {
        log: function(message) {
            //if('console' in window && 'log' in window.console)
            if (typeof window.console != 'undefined' && typeof window.console.log != 'undefined') {
                console.log(message);
            }
            else {
                // do nothing
                //alert('console is not supported: ' + message);
            }
        },
        info : function(message) {
            // todo
        }
    }
})(jQuery);

Inside of plug-in I check if the browser supports console, because if this is old version of Internet explorer, or if in Firefox you close Firebug plug-in console will be undefined. There is at least two types of checking if console is defined, the first is check if it inside of window, and the second, check if it is not undefined, I prefer second.

I put just console.log() method inside of my logging method, but if you need to support more browsers, for example Opera… you can add more code in this method.

And it’s all that you need. Now you can save this file as

and attach it to your project.

How to call WCF services from JavaScript jQuery and ASP.NET AJAX

Written by Alex on . Posted in Uncategorized

First we have to create a webapplication and add to it Ajax enabled WCF service.

Change default DoWork method to accept parameter

        [OperationContract]
        public string DoWork(string userName)
        {
            // Add your operation implementation here
            return "Hello " + userName;
        }

First add on the page input text control and two buttons.

        <input type="text" name="txtName" id="txtName" />
        <input type="button" value="jQuery call" onclick="cityClickJQuery();" />
        <input type="button" value="ASP.NET AJAX Call" onclick="cityClick();" />

First we will call this method with jQuery. So reference jQuery library and add this javascript function for calling WCF service

        function cityClickJQuery()
        {
            $.ajax({
                type: "POST",
                url: "http://localhost:65424/CityService.svc/DoWork",
                data: '{"userName":"'+$get("txtName").value+'"}',
                processData:false,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data)
                {
                    alert(data.d);
                }
            });
        }

It’s very easy, you have to pass url with method, parameter (value from textbox) specify data type and callback function.

Now you can run webapplication, put some text in input box and press button “jQuery call”

Calling WCF service with Microsoft Ajax is much more easy. You do not to provide most of the properties like jQuery call.

        function cityClick()
        {
            CityService.DoWork($get("txtName").value, onSuccess);
        }

        function onSuccess(data)
        {
            if (data)
                alert(data);
        }

After pressing button, you will have the same result.

All source code can bi found below. I did not change web.config, so you can use default data generated by VisualStudio.

ASPX page:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
    Inherits="WebApplication1._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script src="jquery-1.3.2.js" type="text/javascript"></script>
    <script src="jquery-1.3.2-vsdoc.js" type="text/javascript"></script>

    <script type="text/javascript">
        function cityClickJQuery()
        {
            $.ajax({
                type: "POST",
                url: "http://localhost:65424/CityService.svc/DoWork",
                data: '{"userName":"'+$get("txtName").value+'"}',
                processData:false,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data)
                {
                    alert(data.d);
                }
            });
        }
        function cityClick()
        {
            CityService.DoWork($get("txtName").value, onSuccess);
        }

        function onSuccess(data)
        {
            if (data)
                alert(data);
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager runat="server">
            <Services>
                <asp:ServiceReference Path="~/CityService.svc" />
            </Services>
        </asp:ScriptManager>

        <div style="background-color:#eee;">

        <input type="text" name="txtName" id="txtName" />
        <input type="button" value="jQuery call" onclick="cityClickJQuery();" />
        <input type="button" value="ASP.NET AJAX Call" onclick="cityClick();" />
        </div>

    </div>
    </form>
</body>
</html>

 

C# code:

namespace WebApplication1
{
    using System.ServiceModel;
    using System.ServiceModel.Activation;

    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class CityService
    {
        // Add [WebGet] attribute to use HTTP GET
        [OperationContract]
        public string DoWork(string userName)
        {
            // Add your operation implementation here
            return "Hello " + userName;
        }

        // Add more operations here and mark them with [OperationContract]
    }
}

How to make a reference to table in different database in Oracle

Written by Alex on . Posted in Uncategorized

It can be very often than data are located in different databases, for example, HR data can be provided in some view which was created HR team. But it’s not very useful to use different databases from one application. The solution is to create DB Link.

create database link "HR_DATA.WORLD"
connect to USER_NAME
identified by "Password"
using '(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(PORT=1234)(HOST=hr.data.domain.com)))(CONNECT_DATA=(SERVICE_NAME=HRDATAP1)))';

and now you can run this types of queries from your database to external database in Oracle

select * from hr_data.table_name@HR_DATA;

But it’s difficult to type this long DB Link name, so it’s better to create synonym

CREATE PUBLIC SYNONYM HR
   FOR hr_data.table_name@hr_data;

so now this select statement will work from your database

select * from HR;

JavaScript namespace best practice

Written by Alex on . Posted in Uncategorized

JavaScript does not have native namespace support unlike languages like C#, Java…

But if you work in a big JavaScript project, with a lot of methods it’s very difficult to work without namespaces, because avoiding namespaces in Javascript leads to name collisions. It can be collisions for functions, variables… and your code became difficult to support and extend.

But JavaScript is a very powerful programming language, and you can easy simulate namespace in Javascript with Object.

Defining namespace in JavaScript

var MyNamespace = {};
MyNamespace.sayHello = function(name)
{
   alert('Hello ' + name);
}

and you can call this code from your functions like this

function callMethod()
{
  MyNamespace.sayHello('Alexander');
}

But sometimes you require to use more than one namespace (namespace inside of namespace), it’s also very easy to do with JavaScript.

var LevelOne = {};
LevelOne.LevelTwo = {};
LevelOne.LevelTwo.sayGoodbuy = function(name)
{
   alert('goodbuy ' + name);
}

And the code to call this methods

function callMethod()
{
      MyNamespace.sayHello('Alexander');
      LevelOne.LevelTwo.sayGoodbuy('Alexander');
}

Alias for namespace in JavaScript

If you have very long namespace it can be difficult to type it and require more time. But you can use simple solution with aliases.

var ns = LevelOne.LevelTwo;
ns.sayGoodbuy('Alexander');

So as you can see JavaScript namespacing is very easy and powerful.

Firebug console is not defined

Written by Alex on . Posted in Uncategorized

Working with firebug console is very easy and increase productivity, because Firebug console provide you with easy to use logging methods. But when you close Firebug you can get error “console is not defined”. It’s because console object exists only when Firebug is open.

The solution of this problem can be very easy:

Firebug console.log for Internet Explorer

Internet explorer 8 also supports console object and all the methods from Firebug like console.log, console.error, console.info…. But unlike Firefox console object exists and defined in Internet explorer all the time. It does not depend on Developer toolbar open or closed.

How to check if console object exists

I believe the best option avoid error “console is not defined” is use some wrapper class. But for quick fixes you can use code to check if console object exists in browser. I know at least two solutions how to check if console defined:

  • The first is to check if console object belongs to window object
  • And the second is to check if console is ‘undefined

For the first approach I would recommend this code

if('console' in window && 'log' in window.console)
{
    // code using console.log here
}

For the second approach – this code:

if(typeof window.console != 'undefined'
    && typeof window.console.log != 'undefined')
{
    // code using console.log here
}

Both works fine in all types of browsers.