Thursday, November 29, 2007

How to capture the IP Address of the Oracle client making the data request

The key player is SYS_CONTEXT as in:

Select SYS_CONTEXT('USERENV','IP_ADDRESS') FROM dual


Here's a trigger that captures the ip addresses of clients deleting rows from a table:

CREATE OR REPLACE TRIGGER "MYSCHEMA"."SESSIONWATCHER" BEFORE

DELETE ON "MYSCHEMA"."CURRENTUSERSESSION" DECLARE

SInfo MYSCHEMA.SESSIONHISTORY.INFO%TYPE;
BEGIN
SELECT SYS_CONTEXT('USERENV','IP_ADDRESS') INTO SInfo FROM dual;
INSERT INTO MYSCHEMA.SESSIONHISTORY VALUES (SInfo);
END SessionWatcher;

Wednesday, February 21, 2007

NCover and NCover Console

For a free code coverage solution NCover is pretty darn nifty and NCover Explorer Rocks on top of it:

NCover
NCover Explorer

Tuesday, February 06, 2007

Unable to load DLL 'OraOps10.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)

That pesky problem has reared its ugly head again!
I remembered that its a permissions problem but forgot the wrinkle where you have to REMOVE THE PERMISSION AND THEN GIVE IT BACK.

See bold type below:

Solution Description:
Follow these steps to restore default access to Read and Execute access for Windows authenticated users:

1. Log on to Windows with administrator privileges.
2. Launch Windows Explorer from the Start Menu.
3. Navigate to the ORACLE_HOME directory and right click on the ORACLE_HOME folder icon.
4. Select the "Properties" option from the drop down list. A "Properties" window should appear.
5. Click on the "Security" tab on the "Properties" window.
6. Click on Autheticated Users in the "Name" list.
7. Uncheck the "Read and Execute" box in the "Permissions" list. This box will be under the "Allow" column.
8. Check the "Read and Execute" box. This is the box you just unchecked.

9. Click the "Apply" button.
10. Click the "OK" button.

Why I audah ......

Friday, January 26, 2007

Quiet BackgroundWorker Exceptions

The System.ComponentModel.BackgroundWorker catches all of its exceptions as well as those emanating from the delegate that you wired up as a DoWorkEventHandler. If you don't check the e.Error property of the RunWorkerCompletedEventArgs passed to the delegate you wired
up as a RunWorkerCompletedEventHandler then you've set yourself up with a real trooper of a BackgroundWorker. All hell could break loose during its processing but it won't make a peep!

Spinning off threads via:
 
Thread th = new Thread(new ThreadStart(myThreadStartMethod));
th.Start();

Is not nearly so tolerant.


private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {

// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// IF YOU DON'T CHECK e.Error != null THEN BAD THINGS CAN
// HAPPEN IN YOUR WORKER BUT NO ONE WILL EVER KNOW!!!!!!!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
if(e.Error != null) {
MessageBox.Show(e.Error.Message);
}
else if(e.Cancelled) {
// Next, handle the case where the user canceled
// the operation.
// Note that due to a race condition in
// the DoWork event handler, the Cancelled
// flag may not have been set, even though
// CancelAsync was called.
resultLabel.Text = "Canceled";
}
else {
// Finally, handle the case where the operation
// succeeded.
resultLabel.Text = e.Result.ToString();
}

// Enable the UpDown control.
this.numericUpDown1.Enabled = true;

// Enable the Start button.
startAsyncButton.Enabled = true;

// Disable the Cancel button.
cancelAsyncButton.Enabled = false;
}

Friday, January 12, 2007

Checking Status of Currently Open Cursors in ORACLE

Pesky too many open cursors error from ORACLE can be investigated with the help
of the following code:

--total cursors open, by username & machine
select sum(a.value) total_cur, avg(a.value) avg_cur, max(a.value) max_cur,
s.username, s.machine
from v$sesstat a, v$statname b, v$session s
where a.statistic# = b.statistic# and s.sid=a.sid
and b.name = 'opened cursors current'
and s.machine in ('MY Machine', 'His Machine', 'Her Machine')
group by s.username, s.machine
order by 1 desc;

Visit this nice link for more info

Friday, December 01, 2006

Adding Some Armor to Methods Using Passed Enums

In my previous post I demonstrated the fallibility of methods that take enumerations as parameters. As a defense you can use the Enum.IsDefined() method to check the validity of passed enum values:

static void SafeColorToString(EnumLegalColor color) {

if(!Enum.IsDefined(typeof(EnumLegalColor), color))
throw new Exception(string.Format("{0} is not a valid EnumLegalColor", (int) color));

Console.WriteLine(color.ToString());
}

Enumerations Aren't As Bullet Proof As I Thought

Pass an enumeration as a method parameter and its guaranteed to be valid right?
Wrong!

This code compiles and executes with no runtime error:
using System;

namespace Enumerating_Fun {

enum EnumLegalColor{red=1, white=2, blue=3};

class Program {

static void Main(string[] args) {

PrintColor(EnumLegalColor.red);
PrintColor(EnumLegalColor.white);
PrintColor(EnumLegalColor.blue);

PrintColor((EnumLegalColor) 1234);

while(!Console.KeyAvailable)
;
}


static void PrintColor(EnumLegalColor color) {

switch(color) {
case EnumLegalColor.red:
Console.WriteLine("Le Rouge");
break;

case EnumLegalColor.white:
Console.WriteLine("Le Blank");
break;

case EnumLegalColor.blue:
Console.WriteLine("Le Blu");
break;

default:
Console.WriteLine("WTF!");
break;
}
}
}
}

Wednesday, September 20, 2006

Disabling the ability to 'Set Web Reference' to a Web Service

You may wish to expose a 'private' web service such that in order for a new client to access it, the client must be furnished with a pre-built proxy class.

It seems there are two ways to accomplish this:

1. Implement the equivalent of the following in the WEB.CONFIG:


<webservices>
<wsdhelpgenerator href="DefaultWSDLHelpGenerator.aspx">
<!-- disable the web service test page -->
<wsdlhelpgenerator href="">
</wsdlhelpgenerator>
</webservices>


2. Implement the equivalent of the following in the WEB.CONFIG:


<webservices>
<protocols>
<remove name="Documentation">
</remove>
</protocols>
</webservices>


After implementing option #1, two things are very different:

1. Instead of help, you get a blank page in your browser.

Pointing your browser at the web service no longer yields the web service's Home /Help page. You know, the one with the big deep blue title banner with a 'invokable' (hyper-linked) list of all of the web methods below a line of text that reads "The following operations are supported. For a formal definition, please review the Service Description."



2. You cannot set a Web Reference to the service.

Trying to set a Web Reference to the Web Service from Visual Studio will ultimately result in an error. VS will be able to find and list the Web Service and it looks promising but selecting it and saying 'go' is an exercise in futility.

After implementing option #2, things are the same as implementing option #1 except that instead of getting a blank web page you get an error page saying:

Request format is unrecognized.


Presumably this is because a request for the main asmx page is interpereted as a documentation request and that protocol has been removed from the http handlers vocabulary. ... or something like that.

Wednesday, August 24, 2005

Friendly casting using 'as'

Running this code will NOT cause a runtime error if 'b' is not of type 'myclass'. 'a' will simply be assigned null :

myclass a;

a = b as myclass;

if(a == null)
Console.WriteLine("Oh well. b is not a myclass.");
else
Console.WriteLine("Hey, guess what! b is a myclass! Wow!");


This code will throw an invalid cast exception:


myclass a;
someotherclass b;

a = (myclass) b;


One might say "What's so cool about using 'as'? I can do this with roughly the same amount of code. Like this...":

myclass a;
someotherclass b;

try{
a = (myclass) b;
Console.WriteLine("Hey, guess what! b is a myclass! Wow!");
}
catch{
Console.WriteLine("Oh well. b is not a myclass.");
}


That's neat, but guess what? That's using the .Net framework's exception handling mechanism for flow control. In all the examples above the implication is that there is not just the possibility that 'b' is not a myclass but rather there is some likelihood that 'b' is not a myclass. Using the exception handling for flow control is very bad form and a bad habit to get into. Its very slow and can make the debugger stop for no good reason. Don't do it!

Friday, August 19, 2005

Using C#/.net Reflection to call Private and Protected methods

Today I learned that it is possible to call private and protected methods by using reflection.
This is a great technique for Unit Testing such critters for proper behavior when 'code that shuold never be reached' gets reached.

Example:


internal string GetAString(int stringId)
{
foreach(DataRow dr in _theDataSet.Tables["mySTringTable"].Rows)
{
if((int)dr["strID"] == stringId)
return((string)dr["theStringValue"]);
}

//Impossible or very difficult to create a test situation
// where this code would ever get executed. The methods
// that DO have access to this method ALWAYS pass a valid stringId.
throw new NotFoundException("String not found!");
}


Check out this link:

http://www.codeproject.com/csharp/TestNonPublicMembers.asp

Or google:

"reflection unit test private method"

Tuesday, August 09, 2005

Saving View State to a Place OTHER THAN a Hidden Field on the Page

If you want to keep the view state server-side or in some other place on the rendered page.
You might, for instance, determine that the wire cost exceeds the server-side memory cost and therefore want to keep View State on the server.

Override these two methods :


Saves any view-state information for the page.
Override this method if you want to save the Page view state in anything other than a hidden field. If you choose to do so, you must also override the Page.LoadPageStateFromPersistenceMedium method.

protected virtual void SavePageStateToPersistenceMedium(object viewState);



Loads any saved view-state information to the Page object. Override this method if you want to load the Page view-state information in anything other than a hidden field.

If you want to specify something other than hidden fields to save view state when using this method, you must also override the SaveStateToPersistenceMedium method.

protected virtual object LoadPageStateFromPersistenceMedium();

C# Sucks!

JK!! Seriously, though, somewhere around C#-3 we should have inculcated ourselves with the question: "Does 'CAN' == 'SHOULD...