Thursday, August 5, 2010

Creating tablespace in Oracle

Permanent tablespace

create tablespace ts_something
  logging
  datafile '/dbf1/ts_sth.dbf' 
  size 32m 
  autoextend on 
  next 32m maxsize 2048m
  extent management local;
create tablespace data datafile '/home/oracle/databases/ora10/data.dbf'
size                                  10M
autoextend on maxsize                200M
extent management local uniform size  64K;

Tuesday, August 3, 2010

Killing Oracle Sessions

This is something I can never remember off the top of my head. So here we go:
Credit: http://www.oracle-base.com/articles/misc/KillingOracleSessions.php

Identify the Session to be Killed

Killing sessions can be very destructive if you kill the wrong session, so be very careful when identifying the session to be killed. If you kill a session belonging to a background process you will cause an instance crash.

Identify the offending session using the V$SESSION or GV$SESSION view as follows.

SET LINESIZE 100
COLUMN spid FORMAT A10
COLUMN username FORMAT A10
COLUMN program FORMAT A45

SELECT s.inst_id,
       s.sid,
       s.serial#,
       p.spid,
       s.username,
       s.program
FROM   gv$session s
       JOIN gv$process p ON p.addr = s.paddr AND p.inst_id = s.inst_id
WHERE  s.type != 'BACKGROUND';

   INST_ID        SID    SERIAL# SPID       USERNAME   PROGRAM
---------- ---------- ---------- ---------- ---------- ---------------------------------------------
         1         30         15 3859       TEST       sqlplus@oel5-11gr2.localdomain (TNS V1-V3)
         1         23        287 3834       SYS        sqlplus@oel5-11gr2.localdomain (TNS V1-V3)
         1         40        387 4663                  oracle@oel5-11gr2.localdomain (J000)
         1         38        125 4665                  oracle@oel5-11gr2.localdomain (J001)

SQL>
The SID and SERIAL# values of the relevant session can then be substituted into the commands in the following sections.

ALTER SYSTEM KILL SESSION

The basic syntax for killing a session is shown below.

SQL> ALTER SYSTEM KILL SESSION 'sid,serial#';
In a RAC environment, you optionally specify the INST_ID, shown when querying the GV$SESSION view. This allows you to kill a session on different RAC node.

SQL> ALTER SYSTEM KILL SESSION 'sid,serial#@inst_id';
The KILL SESSION command doesn't actually kill the session. It merely asks the session to kill itself. In some situations, like waiting for a reply from a remote database or rolling back transactions, the session will not kill itself immediately and will wait for the current operation to complete. In these cases the session will have a status of "marked for kill". It will then be killed as soon as possible.

In addition to the syntax described above, you can add the IMMEDIATE clause.

SQL> ALTER SYSTEM KILL SESSION 'sid,serial#' IMMEDIATE;
This does not affect the work performed by the command, but it returns control back to the current session immediately, rather than waiting for confirmation of the kill.

If the marked session persists for some time you may consider killing the process at the operating system level. Before doing this it's worth checking to see if it is performing a rollback. You can do this by running this script (session_undo.sql). If the USED_UREC value is decreasing for the session in question you should leave it to complete the rollback rather than killing the session at the operating system level.

Wednesday, April 28, 2010

Validation Summary, "Object doesn’t support this property or method" error

This is an issue that I could only came across to on IE7 and not any of the other browsers. Nonetheless, I spent almost a day trying to figure out why my asp.net validators threw "Object doesn’t support this property or method" javascript error everytime a validation failed or in other words, it wanted to show the ValidationSummary.
Here's how to reproduce the issue :

- Attach a validation control to a control, and put a validation summary in the page anywhere.
- Have any control…. any control with ids “pre”, “post”, “first”, “end”, "result", "headerSep" and you’ll get the   java script error when validation summary needs to be updated at the end of validation.


Solution? Just make sure you don't have any controls identified with with "pre", "post", "first", "end", "result", "headerSep". If you do, rename them

Here's more info on this:


http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=408628

Monday, March 1, 2010

How To Implement User Impersonation in ASP.NET

Below is a way to impersonate a certain user with your web app:


      
                    using System.DirectoryServices;
        using System.Runtime.InteropServices;     
  
        public const int LOGON32_LOGON_INTERACTIVE = 2;
        public const int LOGON32_PROVIDER_DEFAULT = 0;
        public const string password = "password";


        public string user = "userName";


        [DllImport("advapi32.dll")]
        public static extern int LogonUserA(String lpszUserName,
            String lpszDomain,
            String lpszPassword,
            int dwLogonType,
            int dwLogonProvider,
            ref IntPtr phToken);
        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int DuplicateToken(IntPtr hToken,
            int impersonationLevel,
            ref IntPtr hNewToken);


        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool RevertToSelf();


        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public static extern bool CloseHandle(IntPtr handle);



public Boolean ImpersonateUser(string domain, string userName, string password)
        {
            WindowsIdentity tempWindowsIdentity;
            WindowsImpersonationContext impersonationContext;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;


            if (RevertToSelf())
            {
                if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
                    LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                {
                    if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                    {


                        tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                        impersonationContext = tempWindowsIdentity.Impersonate();
                        if (impersonationContext != null)
                        {
                            CloseHandle(token);
                            CloseHandle(tokenDuplicate);
                            return true;
                        }
                    }
                }
            }
            if (token != IntPtr.Zero)
                CloseHandle(token);
            if (tokenDuplicate != IntPtr.Zero)
                CloseHandle(tokenDuplicate);
            return false;


        }

Wednesday, February 3, 2010

Missing Windows Authentication provider For IIS 7 on Windows Server 2008

This article is extremely helpful if you're to support IIS 7.0 for your IIS 6.0 application that uses Windows Authentication. Interestingly, IIS 7.0 on Windows 2008 does not come with Windows Authentication, so we have to install it before we deploy the product.

 This is from http://weblogs.asp.net/zroiy/archive/2008/08/17/missing-windows-authentication-provider-for-iis-7-on-windows-server-2008.aspx

In case your Windows Server 2008 machine doesn't include a windows authentication scheme (see image below), do the following
image
Open up Server Manager (one way to do this is by right clicking the computer node from within the start menu and choosing  Manage). Expend the Roles node. Right click the Web Server (IIS) and choose Add Role Services. You'll get the following wizard, just scroll down a bit and check Windows Authentication under the security node.
image
If you've done everything right , you should also get the following option in IIS authentication pane. If it doesn't, try running appcmd, or restarting. Here's the appcmd command you should run:
appcmd set config /section:windowsAuthentication /enabled:true

image

Monday, November 23, 2009

Very slow UpdatePanel refresh when containing big ListBoxes of DropDownLists

This is just a copy of this really nice entry here and hence not an original post: siderite

Update: this fix is now on CodePlex: CodePlex. Get the latest version from there.

The scenario is pretty straightforward: a ListBox or DropDownList or any control that renders as a Select html element with a few thousand entries or more causes an asynchronous UpdatePanel update to become incredibly slow on Internet Explorer and reasonably slow on FireFox, keeping the CPU to 100% during this time. Why is that?

Delving into the UpdatePanel inner workings one can see that the actual update is done through an _updatePanel Javascript function. It contains three major parts: it runs all dispose scripts for the update panel, then it executes _destroyTree(element) and then sets element.innerHTML to whatever content it contains. Amazingly enough, the slow part comes from the _destroyTree function. It recursively takes all html elements in an UpdatePanel div and tries to dispose them, their associated controls and their associated behaviours. I don't know why it takes so long with select elements, all I can tell you is that childNodes contains all the options of a select and thus the script tries to dispose every one of them, but it is mostly an IE DOM issue.

What is the solution? Enter the ScriptManager.RegisterDispose method. It registers dispose Javascript scripts for any control during UpdatePanel refresh or delete. Remember the first part of _updatePanel? So if you add a script that clears all the useless options of the select on dispose, you get instantaneous update!

First attempt: I used select.options.length=0;. I realized that on Internet Explorer it took just as much to clear the options as it took to dispose them in the _destroyTree function. The only way I could make it work instantly is with select.parentNode.removeChild(select). Of course, that means that the actual selection would be lost, so something more complicated was needed if I wanted to preserve the selection in the ListBox.

Second attempt: I would dynamically create another select, with the same id and name as the target select element, but then I would populate it only with the selected options from the target, then use replaceChild to make the switch. This worked fine, but I wanted something a little better, because I would have the same issue trying to dynamically create a select with a few thousand items.

Third attempt: I would dynamically create a hidden input with the same id and name as the target select, then I would set its value to the comma separated list of the values of the selected options in the target select element. That should have solved all problems, but somehow it didn't. When selecting 10000 items and updating the UpdatePanel, it took about 5 seconds to replace the select with the hidden field, but then it took minutes again to recreate the updatePanel!

Here is the piece of code that fixes most of the issues so far:
 /// 
    /// Use it in Page_Load.
    /// lbTest is a ListBox with 10000 items
    /// updMain is the UpdatePanel in which it resides
    /// 
    private void RegisterScript()
    {
        string script =
            string.Format(@"
var select=document.getElementById('{0}'); 
if (select) {{
    // first attempt
    //select.parentNode.removeChild(select);


    // second attempt
//    var stub=document.createElement('select');
//    stub.id=select.id;
//    for (var i=0; i
//        if (select.options[i].selected) {{
//            var op=new Option(select.options[i].text,select.options[i].value);
//            op.selected=true;
//            stub.options[stub.options.length]=op;
//        }}
//    select.parentNode.replaceChild(stub,select);


    // third attempt
    var stub=document.createElement('input');
    stub.type='hidden';
    stub.id=select.id;
    stub.name=select.name;
    stub._behaviors=select._behaviors;
    var val=new Array();
    for (var i=0; i
        if (select.options[i].selected) {{
            val[val.length]=select.options[i].value;
        }}
    stub.value=val.join(',');
    select.parentNode.replaceChild(stub,select);
    
}};",
                          lbTest.ClientID);
        ScriptManager sm = ScriptManager.GetCurrent(this);
        if (sm != null) sm.RegisterDispose(lbTest, script);
    }


What made the whole thing be still slow was the initialization of the page after the UpdatePanel updated. It goes all the way to the WebForms.js file embedded in the System.Web.dll (NOT System.Web.Extensions.dll), so part of the .NET framework. What it does it take all the elements of the html form (for selects it takes all selected options) and adds them to the list of postbacked controls within the WebForm_InitCallback javascript function.

The code looks like this:
if (tagName == "select") {
            var selectCount = element.options.length;
            for (var j = 0; j < selectCount; j++) {
                var selectChild = element.options[j];
                if (selectChild.selected == true) {
                    WebForm_InitCallbackAddField(element.name, element.value);
                }
            }
        }

function WebForm_InitCallbackAddField(name, value) {
    var nameValue = new Object();
    nameValue.name = name;
    nameValue.value = value;
    __theFormPostCollection[__theFormPostCollection.length] = nameValue;
    __theFormPostData += name + "=" + WebForm_EncodeCallback(value) + "&";
}


That is funny enough, because __theFormPostCollection is only used to simulate a postback by adding a hidden input for each of the collection's items to a xmlRequestFrame (just like my code above) in the function WebForm_DoCallback which in turn is called only in the GetCallbackEventReference(string target, string argument, string clientCallback, string context, string clientErrorCallback, bool useAsync) method of the ClientScriptManager which in turn is only used in rarely used scenarios with the own mechanism of javascript callbacks of GridViews, DetailViews and TreeViews.

And that is it!! The incredible delay in this javascript code comes from a useless piece of code! The whole WebForm_InitCallback function is useless most of the time!

So I added this little bit of code to the RegisterScript method and it all went marvelously fast: 10 seconds for 10000 selected items.
    string script = @"WebForm_InitCallback=function() {};";
        ScriptManager.RegisterStartupScript(this, GetType(), "removeWebForm_InitCallback", script, true);

ASP.NET 3.5 Page Life Cycle

original source:  msdn

Page request
The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.
Start
In the start step, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. Additionally, during the start step, the page's UICulture property is set.
Page initialization
During page initialization, controls on the page are available and each control's UniqueID property is set. Any themes are also applied to the page. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.
Load
During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.
Validation
During validation, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.
Postback event handling
If the request is a postback, any event handlers are called.
Rendering
Before rendering, view state is saved for the page and all controls. During the rendering phase, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream of the page's Response property.
Unload
Unload is called after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and any cleanup is performed.