Wednesday, December 21, 2005

drop down (select) in HTML, DIV, and a little bit more about it.

to pimp my website with a suggestion text box can be very cool... the meaning behind it is to show suggestions based on user's input. As a AJAX.net fan, I downloaded Michales great suggestion box and have used it in combination with some other controls on my page... eh voila!

have you ever tried to make show a div over a drop-down? Microsoft's MSDN answer sounds like that:


Remarks
-The SELECT element is available in HTML and script, as of Internet Explorer 3.0.

-This element is a windowed control and does not support the z-index attribute or zIndex property.

-This element is an inline element.

-This element requires a closing tag.


so now i still have the same problem like before. but since i get used to display div's i did the following try:

My HTML part looks like that:
<div id="myDivStyle" class="divBoxing">some
more
information

<input id="text" maxlength="30" onfocus="myLoveleySelectBox(true);void(0);" onblur="myLoveleySelectBox(false);void(0);" />
<br/>
<select id="myDropDown" style="visibility:visible;">
<option value="a">A
<option value="b">B
</select>


the css for my suggestion can looks like that (div):
<style type="text/css">
.divBoxing
{
border-right: #000000 3px dashed;
border-top: #000000 3px dashed;
border-left: #000000 3px dashed;
border-bottom: #000000 3px dashed;
line-height: 100px;
line-width:140;
visibility:hidden;
position:absolute;
left:12px;
top:36px;
background-color:Teal;
color:White;
}
</style>


and here the last part, a little bit javascript
<script type="text/javascript" language="javascript">
function myLoveleySelectBox(b)
{
var l = document.getElementById("myDivStyle");
l.style.visibility = b ? "visible" : "hidden";

var l = document.getElementById("myDropDown");
l.style.visibility = !b ? "visible" : "hidden";
}
</script>


enjoy it!

Sample page available at: DivAndDropDown.htm

Sunday, December 11, 2005

Disabling a button for few seconds

I have founded today in my backups the following code:

<script type="text/javascript">
<!--
var secs = 20;
var wait = secs * 1000;
document.sform.submitbtn.disabled=true;

for(i=1;i<=secs;i++)
{
window.setTimeout("update(" + i + ")", i * 1000);
}

window.setTimeout("timer()", wait);

function update(num)
{
if(num == (wait/1000))
{
document.sform.submitbtn.value = "Akzeptieren";
}
else
{
printnr = (wait/1000)-num;
document.sform.submitbtn.value = "Akzeptieren (" + printnr + ")";
}
}

function timer() {
document.sform.submitbtn.disabled=false;
}
//-->
</script>

I don't have written the above code by myself... Anyway
thanks to the writer. Just tested it and its working very
good, in case you want that user reads a your lic. agreement
or anything else.

Wednesday, December 07, 2005

Mulitculiti with CurrentCulture and CurrentUICulture - Localization

to understand when exactly what is happening during the page life cycle is not very difficult but its also not very easy. Anyway, during some tests with the .net 2.0, CurrentCulture and CurrnetUICulture I got the following conclusions:

- CurrentUICulture is exclusively used by the Resource Manager
- CurrentCulture is used by the formatting methods like myDateTimeObject.ToString()

as I received a small example from a friend of mine which contained the following lines to understand this behavior.

System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-us");
Console.WriteLine(DateTime.Today.ToString());

System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("de-ch");
Console.WriteLine(DateTime.Today.ToString());

System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-us");
Console.WriteLine(DateTime.Today.ToString());

System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("pt-br");
Console.WriteLine(DateTime.Today.ToString());


well, I have to say; based on those lines i understand where the difference is! Thanks to "XiCoLoKo"

more information you can get at the following article: Localization Practices on TheServerSide.com


In my point of view the best approach will be using the Profile option which is provided by .net 2.0

the following is an extract from the article on theServerSide.com article I have pointed above:

Fortunately, with ASP.NET, a strongly-typed mechanism for storing profile data is available. For example, this web.config setting creates a profile that stores UICulture and Culture settings:

<profile>
<properties>
<add name="UICulture" allowAnonymous="true" />
<add name="Culture" allowAnonymous="true" />
</properties>
</profile>

These settings are accessible through the type-safe Profile object:

Profile.Culture = "it";
Profile.UICulture = "it";

Using profile, we are still faced with a similar challenge as with the Session object: when can we access the Profile for the user during request processing? Unfortunately the Profile is not initialized until the session is acquired, which means we cannot access it through the object model while the cache is inspected. In order to overcome this, the data store where user settings are persisted must be accessed using custom code.

Friday, December 02, 2005

Visual Studio Add-Ins Every Developer Should Download Now

today i found an article on 10 tools for visual studio...

great tools !


http://msdn.microsoft.com/msdnmag/issues/05/12/VisualStudioAddins/default.aspx

enjoy reading and installing of:


TestDriven.NET
GhostDoc
Smart Paster
CodeKeep
PInvoke.NET
VSWindowManager PowerToy
WSContractFirst
VSMouseBindings
CopySourceAsHTML
Cache Visualizer

on the right hand side of my blog you see my favorit tools.

Wednesday, November 30, 2005

What happens to the WebAdmin from the Visual Studio 2005?

Today I got a compiled solution from a friend in Asp.Net which is based on .Net 2.0.

Well great, this solution implements the Membership Model. This means first I have to register with a username, password, security question, etc.

But why the hack... I cannot login now. The answer is simple first i need to activate this user. That happens over the WebAdmin. But i dont have a solution i have just *.aspx and the releated *.dll's. How can I run now the WebAdmin for this web like I have it in the Visual Studio 2005?

There is a small trick you can do on your local machine. I don't know if its also works on a distributed environment but it works on my local machine well.


http://localhost/webadmin/default.aspx?applicationPhysicalPath=C:\Inetpub\wwwroot\cg\&applicationUrl=/cg

1) create a virtual directory at the root of your default website
2) name the virutal web "WebAdmin"
3) Set the Path of the virtual directory to
C:\WINDOWS\Microsoft.NET\Framework\%Your Framework Version%\ASP.NETWebAdminFiles
4) If you have already installed the release version your IIS is running with
the latest framework version otherwise change your running verison in the
ASP.Net tab in the Virtual Directory property.
[ i had also to set inside the Authentication Methods the
checkbox: Integrated Windows authentication. ]
5) now you have setup your environemnt set up to run it

http://localhost/webadmin/default.aspx?applicationPhysicalPath=C:\Inetpub\wwwroot\cg\&applicationUrl=/cg


translate it like that

- webadmin : name of your virtual directory
- applicationPhysicalPath: the path to your application on your pc
- applicationUrl: the virtual directory of your own application

Thanks to the author Jeff Widmer .

If you have a another option found inform me please.

UDPATE: in the meanwhile i developed my own webadmin. read more about it over here:
WebAdmin - Membership Management for ASP.NET MVC release 1.0

Tuesday, November 29, 2005

Real-Time Relevance Assessment Tool

Link:
http://www.webmasterbrain.com/seo-tools/seo-experiments/the-search-engine-experiment/

test results:
http://www.webmasterbrain.com/seo-tools/seo-experiments/the-search-engine-experiment/test-results/


Source: Internet Outsider: http://www.internetoutsider.com/2005/11/realtime_releva.html

this mate is more insider then a lot of people I know they just think they are!!!!

Thursday, November 24, 2005

I thought google supports Firefox - unfortunately not!

google comes out a few day's ago with a new service: base [Base.google.com].

Wow, an amazing service for content search. I'm always were impressed how Google comes out with solutions and people just effort thousands of work hours to optimize their environment for them.

The new service efforts a content search, or how others would say: deep search. In past I worked for a company which creates box-office solutions, so I went directly to the Event section of base service.

I liked the redefine options which Google provides and forwarded it to a friend of mine [myself is using IE and he is a Firefox fan]. Back to the redefine search, there are some options like date limitations, which appears as a calender control in IE. The Look & Feel of Google is always simple and friendly and I have pointed to my friend to have a look at the this option. His answer was simple to understand:

what control do you speak about
.

After that I installed Firefox and was surprise to see that Google doesn't makes the effort to provide the same functionality to all internet users. what a pity for Firefox users!

Saturday, November 19, 2005

Usage of Diagrams with SQL Server 2005 and compatibility level of: SQL Server 2000 (80)

Diagrams... yes I like them, to get a clear Idea of a DB I'm usually creating Diagrams. I got a DB from a friend which is working which works with SQL Server 2000 [80]. After I created an empty DB and restored the DB I tried to create an Diagram of its main tables. Every time I wanted to create a Diagram the following message appears:

Database diagram support objects cannot be installed because this database does not not have a valid owner. To continue, first use the Files page of the Database Properties dialog box or ALTER AUTHORIZATION statement to set the database owner to a valid login, then add the database diagram support objects.


at least to me that sounds interesting.... So, naturally I searched for the following store procedure:


USE MyFriendsDatabaseNameIHaveCreated
EXEC sp_changedbowner 'sa'


After I have executed this store procedure I clicked on my new DB and .... again the same message.

I have checked the configuration of this Database I have imported which has a compatibility level of: SQL Server 2000 (80). After playing around with all the different properties I have found out that the Sql Server Management Studio is not able to create Diagrams as long the database runs with the compatibility level of: SQL Server 2000 (80). once you change that to the compatibility level of: SQL Server 2005 (90) you can create as much as you want diagrams.

The Database Diagram tool in SQL Server 2005 uses supporting objects that require SQL Server 2005 functionality. So the readme txt file say's in the documentation of SQL Server 2005. Here is an extract from this text:

To install database diagram support in SQL Server Management Studio, databases must be in SQL Server 2005 database compatibility level. Database
compatibility level can be reset after diagram support is installed.


I just should read the manual ;-)

Thursday, November 17, 2005

XSLT Debugging in Visual Studio 2005

Last view day's I have concentrate myself on xml in new environment 2005

have a look at the follwing very intersting links i have found on MSDN:

XML Tools Introduction

This article is an introduction to the XML Editor and the XSLT Debugger in Visual Studio 2005 (formerly known by the codename "Whidbey").

and also this one:

Building an XPath Visualizer with Windows Forms:

Tuesday, November 15, 2005

.Net 2.0 is out, where we can download them

Microsoft .NET Framework Version 2.0 Redistributable Package (x86)

The Microsoft .NET Framework version 2.0 redistributable package installs the .NET Framework run-time and associated files required to run applications developed to target the .NET Framework v2.0.


.NET Framework 2.0 Software Development Kit (SDK) (x86)

The Microsoft .NET Framework Software Development Kit (SDK) v2.0 (x86) includes tools, documentation and samples developers need to write, build, test, and deploy .NET Framework applications.



Microsofts Subscription Members:
Visual Studio 2005


For those who don't have access to Microsoft's Subscription area they can use the "Visual Web Developer Express" environment to develop:

Visual Web Developer Express

Make DataTips Transparent, Visual Studio 2005

You can make the DataTip transparent by pressing the ctrl key or middle mouse button.

Checkout the following Link:
http://blogs.msdn.com/stevejs/archive/2005/11/12/492115.aspx

Source: Bug Babble

Monday, November 07, 2005

DNS Step-by-Step Guide

This document can help you implement Domain Name System (DNS) on Microsoft® Windows Server™ 2003 on a small network. DNS is the main way that Windows Server 2003 translates computer names to network addresses. An Active Directory®-based domain controller also can act as a DNS server that registers the names and addresses of computers in the domain and then provides the network address of a member computer when queried with the computer's name.
This guide explains how to set up DNS on a simple network consisting of a single domain.

Download Link: http://www.microsoft.com/downloads/details.aspx?familyid=15D276A5-4BF6-4ADD-9F67-56B38CCB576B&displaylang=en

Source: Microsoft

Download details: ASP.NET 2.0 Hosting Deployment Guide

The ASP.NET 2.0 Deployment Guide is a reference for web hosters who are interested in adding ASP.NET 2.0 to their existing Windows hosting service. Besides improving developer productivity, ASP.NET 2.0 also provides benefits for hosted environments, including support for shutting down inactive applications and locking down rogue applications. Enhanced health monitoring configuration can be used to set thresholds and severity levels for monitoring the health of ASP.NET.

Download details: ASP.NET 2.0 Hosting Deployment Guide

source: microsoft

LogDump: CLRProfiler Log analysis tool

I get wondering how-to analyse the CLR profiler output and I have found the following link:

http://blogs.msdn.com/ricom/archive/2005/08/08/449246.aspx


Update:

Microsoft CLR Overview

The .NET Framework from Microsoft provides services to application developers that are necessary to quickly create scalable solutions that meet stringent requirements for security, manageability and productivity. This whitepaper introduces the guiding principles and thoughts behind the .NET Framework, the core features of the Common Language Runtime and its supporting Framework Base Class Libraries and how it is evolving in the next major version.

The Microsoft Common Language Runtime (CLR) and the .NET Framework class libraries – collectively called the .NET Framework – were designed to enable developers to easily create scalable, secure, interoperable and manageable applications that can also leverage existing investments in other technologies and platforms. The .NET infrastructure works with non-Microsoft technologies through its built-in support for creating and consuming Web services, and it works with existing Microsoft technologies by providing native integration with COM components. These features help to extract further value from an organization’s existing investments in prior technologies and ensure interoperability with other platforms.

Since the earliest days of software development, organizations have sought to build applications quickly and with higher quality – that is fewer bugs. Applications should also interoperate with different environments and technologies and should be built with widely-accepted languages that are easy to learn and maintain, simultaneously boosting productivity. Many approaches have appeared to try to improve the development process, but often these efforts have been focused on the analysis and design phase. It is not until more recently that the underlying architecture of the development platform itself has achieved a prominent role in laying the groundwork for building enterprise applications.

Whether an enterprise is concerned with interoperability with Web services or COM applications, building solutions more quickly and with fewer bugs, or using a common programming model across application types and languages, the .NET Framework provides organizations the tools to meet all these goals and more.

Source: Microsoft

Wednesday, October 26, 2005

Login Control :: Password Recovery :: How-To send emails

that the emails issues are working fine, you will need to adapt the web.config with the following element:

≶blockquote>≶strong>≶system.net>
≶mailsettings>
≶smtp deliverymethod="Network">
≶network host="smtp.xyz.com" from="roni.schuetz@hotmail.com">
≶/smtp>
≶/mailsettings>
≶/SYSTEM.NET>≶/strong>≶/blockquote>

Asp.Net 2.0 Themes und URL-Rewriting

this is a well know problem with the relativ path's. Themes are using by default relativ Paths. the workaround is to use the follwoing method:

the reg-ex which is used here: ""

Notice: its just match css-links like in the sample!!!!

public override void Write(byte[] buffer, int offset, int count){string strBuffer = System.Text.UTF8Encoding.UTF8.GetString(buffer, offset, count);
// ---------------------------------// Wait for the closing tag// ---------------------------------Regex eof = new Regex("", RegexOptions.IgnoreCase);
if (!eof.IsMatch(strBuffer)){responseHtml.Append(strBuffer);}else{responseHtml.Append(strBuffer);
string finalHtml = responseHtml.ToString();Regex re = null;
// Css-Files auf die absolute Client-URL mappenre = new Regex("", RegexOptions.IgnoreCase);finalHtml = re.Replace (finalHtml, new MatchEvaluator (CssMatch));
// Write the formatted HTML backbyte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(finalHtml);
responseStream.Write(data, 0, data.Length);}
}
private string CssMatch(Match m){return m.ToString().Replace(m.Groups[1].Value, ConfigurationManager.AppSettings["ApplicationRoot"] + m.Groups[1].Value);}

Source: http://blogs.dotnetgerman.com/thomas/PermaLink,guid,f211331c-b175-4a25-8958-ece6bc6d364a.aspx

Workaround for ASP.NET 2.0 bug: LoadControl gives an exception in a TemplateControl

[since june CTP 2005 this bug is not available anymore]

http://blogs.infosupport.com/raimondb/archive/2005/04/29/203.aspx?Pending=true

ASP.NET - Relative Url's

ASPX:


HTML Client output:

somewhere else, not inside the control you can use the ResolveUrl("~/bilder/spacer.gif");

Masterpages per Browser

yes its possible to generate for each differnent browser its own MasterPage.

<%@ Page Language="C#"
AutoEventWireup="true"
CodeFile="Default.aspx.cs"
Inherits="_Default"
ie:MasterPageFile="~/MasterPage_IE.master"
mozilla:MasterPageFile="~/MasterPage_Firefox.master"
%>

ASP.NET 2.0 URLMappings

do we need a special url? as short as possible?

so make from:

http://www.xyz.ch/testApp/testApp1/Version51/thisIsASamplePageWhatEverItIs.aspx

http://www.xyz.ch/myPage.aspx


mappedUrl="~/testApp1/Version51/thisIsASamplePageWhatEverItIs.aspx"/>

MasterPage, How-To change it on the fly

surely you can also change your masterPage on the fly. the only thing which has to be done is the following thing:

NOTICE: think about the page cicle!!!!

protected override void OnPreInit(EventArgs e){object tpl = Request.QueryString["Template"];if (tpl == null tpl.ToString() == "Default"){this.MasterPageFile = "~/Templates/Category/Standard.master";}else{this.MasterPageFile = "~/Templates/Category/Sample.master";}}

JavaScript Debugging

Clear the "disable script debugging" checkbox in Internet Explorer's advanced properties. Add the keyword "debugger" somewhere within your JavaScript.When you run the web page from Visual Studio in debugging mode, viola--when it hits the "debugger" statement, the Visual Studio debugger window takes control, you can set your break points, and proceed as normal. You can even get very clever setting the "debugger" from within script created from you server-side code that's registered with one of the many "Register" client-side script block methods.

Tuesday, October 25, 2005

How-To handle RoleManagment features with my own Database

The role-based features in .net 2.0 are using some place to maintain the data. By default this will be the "SQL Server Express" instance which is automatically installed with the Visual Studio. If you dont make this wizard every try will end in the express version :-( - get sad from it but after several researches I have found the solution.

If you would like to use your own DB then go through the follwoing steps:

1 - Create DB
2 - Start -> Programs -> Microsoft Visual Studio 2005 ->
Visual Studio Tools -> Visual Studio 2005 Command
Prompt
3 - write "aspnet_regsql"
4 - Go through the Wizard
5 - Open your Web.Config file and add the following elements:



6 - Run now from your Visual Studio the WebSite / ASP.Net
Configuration [ WebAdmin Tool ]
7 - At the Security you should now choose the Authentication
type, adding your roles and user

thats the whole trick behind it.

Thursday, October 13, 2005

Javascript Control Helpers funcitons

Howto call:
setGroup(!this.checked, 'name1,name2,name3,etc')

radioPropertyChanged(this, 'name1,name2,etc')

getControls();

callOnclick('name');

//////////////////////////////////////
/**
* JavaScript functions for enabling / disabling controls
*/

function radioPropertyChanged(control, controlnamestring) {
if (event.propertyName == '' event.propertyName == 'checked') {
setGroup(control.checked, controlnamestring);
}
}

function setGroup(enabled, controlnamestring) {
// alert(controlnamestring + ': ' + enabled);
var controlnames = controlnamestring.split(',');
for (var i=0; i var control = document.getElementById(controlnames[i]);
if (control) {
if (!enabled && 'isvalid' in control)
ValidatorEnable(control, enabled)
else {
control.enabled = enabled;
control.disabled = !enabled;
}
if (!enabled) {
try {
var tagName=control.tagName.toLowerCase();
if(tagName=='input') {
//alert('Found checked in ' + control.id);
var type=control.type.toLowerCase();
if (type=='text') {
control.value='';
if (control.onchange) control.onchange();
}
else if (type=='radio' type=='checkbox'){
control.checked = false;
if (control.onclick) control.onclick();
if (control.onpropertychange) control.onpropertychange();
}
}
else if (tagName=='select') {
// alert('Found selectedIndex in ' + control.id);
control.selectedIndex = -1;
// control.onchange();
}
}
catch(ex){
//ignore
}
}
}
// else alert('control ' + controlname[i] + ' not found!');
}
}

function getControls(){
var ControlsArr = new Array();
ControlsArr = document.forms[0].getElementsByTagName('input');
for(var i=0; i {
if(ControlsArr[i].type == 'checkbox' ControlsArr[i].type == 'radio'){
//alert(ControlsArr[i].id);
callOnclick(ControlsArr[i].id);
}
}
}

function callOnclick(controlName) {
var control = document.all(controlName);
if (control && control.onclick) control.onclick();
else if (control && control.onchange) control.onchange();
else if (control && control.onpropertychange) control.onpropertychange();
}

Thursday, October 06, 2005

javascript "loop through all the options and test each one until"

You have to loop through all the options and test each one until you find
it, this example assumes you're testing against text value:

function setListbox(name, value, caseSensitive)
{
var oList = document.forms['abc'].elements[name];
var sTestValue = (caseSensitive ? value : value.toLowerCase());
var sListValue;
for (var i = 0; i < oList.options.length; i++)
{
sListValue = (caseSensitive ? oList.options[i].text :
oList.options[i].text.toLowerCase()); //change text to value if you wish to
compare by value of listbox.
if (sListValue == sTestValue)
{
oList.selectedIndex = i;
break;
}
}



}


setListbox("Country", "Canada", true);

untested code provided by joe, dont know how that is, but anyway thanks

Friday, September 30, 2005

.Net C# howto convert DataReader to Dataset

public DataSet ConvertDataReaderToDataSet(OleDbDataReader reader)
{
DataSet dataSet = new DataSet();
DataTable schemaTable = reader.GetSchemaTable();
DataTable dataTable = new DataTable();

for(int cntr = 0; cntr < schemaTable.Rows.Count; ++cntr )
{
DataRow dataRow = schemaTable.Rows[cntr];
string columnName = dataRow["ColumnName"].ToString();
DataColumn column = new DataColumn(columnName,dataRow.GetType());
dataTable.Columns.Add(column);
}

dataSet.Tables.Add(dataTable);

while (reader.Read())
{
DataRow dataRow = dataTable.NewRow();
for(int cntr = 0; cntr < reader.FieldCount; ++cntr)
{
dataRow[cntr] = reader.GetValue(cntr);
}
}

return dataSet;
}

Wednesday, September 28, 2005

The request failed with HTTP status 401: Unauthorized "System.Net.WebException: The request failed with HTTP status 401: Unauthorized".

The request failed with HTTP status 401: Unauthorized
"System.Net.WebException: The request failed with HTTP
status 401: Unauthorized".

If you use an authentication on your webservice like
Integrated Windows Authentication, you may have
to pre-authenticate before using your webservice:

WebService.webClass myWC= new WebService.webClass();

myWC.PreAuthenticate = true;

myWC.Credentials = System.Net.CredentialCache.DefaultCredentials;

posted on Friday, January 30, 2004 8:37 AM on "Heybo Blog"
http://heybo.com/weblog/posts/245.aspx

Tuesday, September 20, 2005

Convert ArrayList into Array

example:
ArrayList myArray = new ArrayList();
--- somewhere in your code you populate your array
--- then...
int[] myIntArray = (int[])myArray.ToArray(typeof(int));

provided by luiz ( thanks mate )

Thursday, September 15, 2005

Run IE trough batch job...

Dim wshShell
set wshShell = WScript.CreateObject("WScript.Shell")

wshShell.Run "cmd.exe /c ""title StartIE & runas.exe /user:virtual\bsz ""%ProgramFiles%\Internet Explorer\IEXPLORE.EXE"""""

wscript.Sleep(1000)
wshShell.AppActivate "StartIE"
wshShell.SendKeys "I'm2Happy" & "{ENTER}"

Monday, September 12, 2005

Regular Expression Email Check

Function ValidateEmail(Expression)
Dim objRegExp
Set objRegExp = New RegExp
objRegExp.Pattern = "^[\w\.-]+@[\w\.-]+\.[a-zA-Z]+$"
ValidateEmail = objRegExp.Test(Expression)
End Function

Wednesday, July 27, 2005

SQL Server 2005, SPROC

well i were wondering how to make sprocs in C# and i found the following page:

http://www.dotnetfun.com/articles/sql/sql2005/SQL2005CLRSProc.aspx

Thursday, July 21, 2005

Page directive

The page directive in the code behind version contains the attribute to corresponding source code file over attribute CompileWith="xxxx" and the class in the source code attribute="xxxx"

<@% Page CompileWith="YourPage.aspx.cs" ClassName="YourClassName"%>

Notice that the new class is a partial class which doesn't contains all information
you were used to it in version 1.x.

partial classes derives from System.Web.UI.Page.

Sample:

using System;
using System.Web;

.....


public partial class YourWebSite_aspx
{
void foo()
{
// your stuff goes here.....
}
}

the following link describes you this and some additional new features:

http://www.c-sharpcorner.com/Code/2004/July/WhidbeyFeatures.asp


If you wonder how the whole construct works you can do a research about
"Dynamic Page Compilation".

Code Inline vs. Code Behind

Microsofts IDE Visual Studio 2005 supports both models of writing code.

Code Inline - means that all your code is insise the *.aspx
Code Behind - means that all your code is separeted into two or MORE files.
*.aspx just contain markup data

by code behind selection you will generate a *.vb or *.cs file


Microsfts pronounced - is no performance difference between inline or behind option.

check Querystring parameters

today i found the following method inside the String class:

if(!String.IsNullOrEmtpy(this.Request["myQuerystringParameter"]) )
{
// here goes your code
}

Monday, July 11, 2005

Background of the Rational Unified Process

Background of the Rational Unified Process
The writers or developers of this software engineering process focused on diagnosing the characteristics of different software projects that failed; by doing this they tried to recognize what the common aspects were that made these software projects fail. They also looked at the existing software engineering processes and their solutions for these symptoms that caused the failure of these projects.

The symptoms are:

Ad hoc requirements management .
Ambiguous and imprecise communication
Brittle architecture
Overwhelming complexity
Undetected inconsistencies in requirements, designs, and implementations
Insufficient testing
Subjective assessment of project status
Failure to attack risks
Uncontrolled change propagation
Insufficient automation
Project failure is caused by a combination of several symptoms, though each project fails in a unique way. The outcome of their study was a system of software best practices they named the Rational Unified Process. Since knowing these problems will not guarantee a successful software product unless the solutions are also considered, they went on to create the Rational Unified Process Product (RUPP).

The Process was designed with the same techniques the team used to design software; it has an underlying object-oriented model, using Unified Modeling Language UML.

Refactoring Home

Refactoring Home

ONDotnet.com: Refactoring with Visual Studio Macros

ONDotnet.com: Refactoring with Visual Studio Macros

Wednesday, July 06, 2005

Make your life easier with "Shortcut keys"

To get things done, sometimes it's more efficient to use
keyboard shortcuts, instead of playing around with the
mouse. It's more quicker! Here are some useful shortcut
keys for most frequently used software packages like
Windows, Internet Explorer, Outlook etc.




Windows shortcut keys:
-------------------------------------------------------------------------
F2 Select a file and press F2 to rename the file
F3 In Windows Explorer and on Desktop, pressing F3 brings up the Find dialog box
Alt + Enter Select a file and press Alt + Enter to bring up its Properties dialog box
Alt + Space bar Inside a window, press Alt + Spacebar to bring up the system menu of that window
Ctrl + Escape Brings up the windows start menu
Alt + Tab Lets you switch between currently running applications
Shift + Delete Permanently deletes a file without moving it to Recycle Bin
Ctrl + A Selects all the files in Windows Explorer. Also selects all the text in text boxes
Alt + F4 Closes the current window
Double left click Double left click on the system icon of a window closes that window
Ctrl + Tab Changes the tabs in a tabbed dialog box in forward direction. Also switches windows in an MDI form
Ctrl + Shift + Tab Changes the tabs in a tabbed dialog box in backward direction
Ctrl + F6 Switches between the currently open child windows in an MDI form
Ctrl + Left click Deselects a specific item from a selected range. Works in Windows explorer
Crtl + Alt + Delete Brings up task manager in Windows 95/98. Brings up more options in NT/2000
Shift + F10 Brings up the context sensitive pop-up menu
Ctrl + W Closes the current window
Windows Key + m Minimizes all windows
Ctrl + (+) key from the right hand side of the keyboard Rearranges the widths of the list view's columns properly


Internet Explorer shortcut keys
-------------------------------------------------------------------------
Ctrl + F Brings up the Find dialog box
F5 Refreshes the page
Ctrl + N Opens a new browser window
Alt + Home Takes you to your homepage
Escape Stops loading the current page
Ctrl + A Selects the entire page
F11 Toggles between full-screen mode and normal mode
Backspace Takes you to the previously loded page
Alt + Right arrow Forwards you by one page in the available page stack
Alt + Left arrow Takes you to the previous page in the available page stack
Ctrl + Enter In the address bar, avoid typing http, ://www and .com by just typing the domain name and pressing Ctrl + Enter
Enter Not sure if the domain name ends with .com or .net? Type the domain name & press enter. IE will search for the domain
F4 In IE 5.0, F4 drops down the address bar combo box
Ctrl + P Prints the current page
Crtl + O Brings up the 'file open' dialog box
Ctrl + H Brings up the History window
Crtl + B Brings up the 'Organize Favorites' dialog box
Ctrl + R Reloads/refreshes the current page
Shift + Left click Opens the clicked link in new window

Outlook shortcut keys
-------------------------------------------------------------------------

Alt + S Sends the current mail
Ctrl + Enter Sends the current mail
Ctrl + K Resolves the email addresses from the address book
Alt + K Resolves the email addresses from the address book
F7 Starts spell check
Ctrl + D Deletes the current mail
Shift + Delete Permanently deletes the current mail
Ctrl + Z Undoes the last change
Ctrl + Y Redoes the last change
F4 Brings up the Find dialog box
Shift + F4 Finds the next occurence of the search string
Ctrl + R Brings up the reply window for the current mail
Ctrl + Shift + R Brings up the 'reply all' window for the current mail
Ctrl + P Prints the current mail
F5 Sends and receives mails

Thursday, June 02, 2005

do you need the Database ID to trace your DB?

Find it with the following sql statement on master db.

use master
select name, dbid
from sysdatabases
order by name

Wednesday, May 25, 2005

HowTo create Virtual Directiories in IIS with vbs

just take the following vbs code, adapt it and save it in a *.vbs file.


//////////////////////////////////////////////////////////////////

On error resume next
'
' Running as a VBS
'
Script = True
Source = GetPath
WebRoot = "c:\inetpub\wwwroot"

set fso = CreateObject("Scripting.FileSystemObject")
for each site in fso.GetFolder(Source).SubFolders
FolderName = fso.GetFileName(Site.Path)
if lcase(FolderName) <> "solution" then
ReinstallWebApplication FolderName
CheckError
end if
next

CheckError


Function Share(Path, Name)
Output "Sharing " & Path

'dim objServices As SWbemServices

Set objServices = GetObject _
("WinMgmts:{impersonationLevel=impersonate}!/root/cimv2")

'************************ Create the new share *********************

Set objShare = objServices.Get("Win32_Share")
Set objInParam = objShare.Methods_("Create").InParameters.SpawnInstance_()
objInParam.Properties_.Item("Description") = ""
objInParam.Properties_.Item("Name") = Name
objInParam.Properties_.Item("Path") = Path
objInParam.Properties_.Item("Type") = 0


'************************ Execute the method **********************
Set ObjOutParams = objShare.ExecMethod_("Create", objInParam)
If ObjOutParams.ReturnValue <> 0 And ObjOutParams.ReturnValue <> 22 Then
Beep
Output "***Unable to create share, return value was : " _
& "objOutParams.ReturnValue"
End If

End Function

'
' The following compatability functions allow this script to function in VB
' or as a VBS file.
'

Sub Output(s)
If Script Then
WScript.echo s
Else
Debug.Print s
End If
End Sub

Function GetPath()
If Script Then
GetPath = Left(WScript.scriptfullname, InStrRev(WScript.scriptfullname, "\") - 1)
Else
GetPath = App.Path
End If
End Function

Function Run(s)
If Script Then
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run s, ,true
Else
Shell s, vbNormalFocus
End If
End Function


Sub CheckError()
if Err.Number then
msgbox err.number & ":" & err.source & ":" & err.description
if script then
wscript.quit
else
stop
end if
end if
end sub

Sub StopService(ServiceName)
Set objServices = GetObject _
("WinMgmts:{impersonationLevel=impersonate}")

Set services = objServices.InstancesOf("Win32_Service")

For Each s In services
If s.DisplayName = ServiceName Then
s.ChangeStartMode ("Manual")
s.StopService
End If
Next
end sub

Sub DeleteGPO(nc, DisplayName)
'Dim Policies As IADsContainer
Set Policies = GetObject("LDAP://CN=Policies,CN=System," & nc)

'Dim Policy
For Each Policy In Policies
If Policy.DisplayName = DisplayName Then
'Dim c As IADsContainer
Set c = Policy
RecursiveDelete c
Policies.Delete Policy.Class, Policy.Name
Exit For
End If
Next
End Sub

Sub RecursiveDelete(c)
'Dim subc As IADsContainer

For Each subc In c
RecursiveDelete subc
Next

For Each subc In c
c.Delete subc.Class, "CN=" & subc.cn
Next
End Sub

Sub Uninstall(PartialName)
Set objServices = GetObject _
("WinMgmts:{impersonationLevel=impersonate}!/root/cimv2")


Set Products = objServices.InstancesOf("Win32_Product")

For Each product In Products
If instr(product.Name,PartialName) > 0 Then
output "Uninstalling " & product.name
product.uninstall
End If
Next
end sub



Sub ReinstallWebApplication(AppName)
UninstallWebApplication AppName
InstallWebApplication(AppName)
end Sub

sub UninstallWebApplication(AppName)
set fso = createobject("scripting.filesystemobject")

on error resume next
Set DirObj = GetObject("IIS://LocalHost/W3SVC/1/ROOT/" & AppName)
DirObj.AppDelete
on error goto 0

DeleteFolder WebRoot & "\" & AppName
end sub

sub InstallWebApplication (AppName)
set fso = createobject("scripting.filesystemobject")

output "Copying : " & Source & "\" & AppName & " to " & WebRoot & "\" & AppName
fso.CopyFolder Source & "\" & AppName, WebRoot & "\" & AppName
checkerror

Dim DirObj
Const INPROC = True
Const OUTPROC = False

output "Creating Web Application for IIS://LocalHost/W3SVC/1/ROOT/" & AppName

Set DirObj = GetObject("IIS://LocalHost/W3SVC/1/ROOT")
on error resume next
DirObj.delete "IIsWebVirtualDir", AppName
on error goto 0
set mywd = DirObj.Create ("IIsWebVirtualDir", AppName)
mywd.setinfo
mywd.AppCreate true
mywd.setinfo

run """c:\program files\common files\microsoft shared\web server extensions\40\bin\fpsrvadm.exe"" -o install -p 80 -w /" & AppName
run """c:\program files\common files\microsoft shared\web server extensions\40\bin\fpsrvadm.exe"" -o check -p 80 -w /" & AppName
end sub

function MyDocuments()
set shell = createobject("WScript.Shell")
MyDocuments = shell.SpecialFolders("MyDocuments")
end function

sub DeleteFile(FileName)
set fso = createobject("scripting.filesystemobject")
if fso.fileexists(filename) then
output "Deleting : " & filename
fso.deletefile filename, true
end if
end sub

sub DeleteFolder(FolderName)
set fso = createobject("scripting.filesystemobject")
if fso.FolderExists(Foldername) then
output "Deleting : " & Foldername
fso.deleteFolder Foldername, true
end if
end sub

Retriving Data from AssemblyInfo.cs

How to get data from the AssemblyInfo.cs can be made by a helper class inside the Assembly file:

Class1.cs

public class MyWinForm:System.Windows.Forms.Form
{
[STAThread]
static void Main()
{
Application.Run(new MyWinForm());
}

// its contains much more then the Main method but for this sample its enough.

}




AssemblyInfo.cs

// that part is generated auto. by visual studio
using System;
using System.Reflection;

[assembly: AssemblyTitle("Your Custom Assembly Title")]
[assembly: AssemblyDescription("Some information about your Assembly")]
[assembly: AssemblyCompany("Your Company Name")]
[assembly: AssemblyProduct("Your Product Name")]
[assembly: AssemblyCopyright("Who has the copyright")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyVersion("1.0.0.0")]

#region Helper class

// Your generated class does not contain the follwoing part.
public class AssemblyInfo
{
// Used by Helper Functions to access information from Assembly Attributes

private Type myType;
public AssemblyInfo()
{
myType = typeof(MyWinForm);
}
public string AsmName
{
get {return myType.Assembly.GetName().Name.ToString();}
}

public string AsmFQName
{
get {return myType.Assembly.GetName().FullName.ToString();}
}

public string CodeBase
{
get {return myType.Assembly.CodeBase;}
}

public string Copyright
{
get {
Type at = typeof(AssemblyCopyrightAttribute);
object[] r = myType.Assembly.GetCustomAttributes(at, false);
AssemblyCopyrightAttribute ct = (AssemblyCopyrightAttribute) r[0];
return ct.Copyright;
}
}

public string Company
{
get
{
Type at = typeof(AssemblyCompanyAttribute);
object[] r = myType.Assembly.GetCustomAttributes(at, false);
AssemblyCompanyAttribute ct = (AssemblyCompanyAttribute) r[0];
return ct.Company;
}
}


public string Description
{
get
{
Type at = typeof(AssemblyDescriptionAttribute);
object[] r = myType.Assembly.GetCustomAttributes(at, false);
AssemblyDescriptionAttribute da = (AssemblyDescriptionAttribute) r[0];
return da.Description;
}
}


public string Product
{
get
{
Type at = typeof(AssemblyProductAttribute);
object[] r = myType.Assembly.GetCustomAttributes(at, false);
AssemblyProductAttribute pt = (AssemblyProductAttribute) r[0];
return pt.Product;
}
}

public string Title
{
get
{
Type at = typeof(AssemblyTitleAttribute);
object[] r = myType.Assembly.GetCustomAttributes(at, false);
AssemblyTitleAttribute ta = (AssemblyTitleAttribute) r[0];
return ta.Title;
}
}

public string Version
{
get {return myType.Assembly.GetName().Version.ToString();}
}
}
#endregion


Now back to the "Class1.cs" where we see how to use it:

public class MyWinForm:System.Windows.Forms.Form
{



public void SetAnAssemblyInfoToControlOfYourChoice()
{
AssemblyInfo ainfo = new AssemblyInfo();
string title = ainfo.Title;
this.YourControlInstance.Text = string.Format("{0} ...", ainfo.Title);
}


}

Monday, May 23, 2005

QuickCode Forum

QuickCode Forum: "The QuickCode Forum"

Thursday, May 19, 2005

Howto implement collection, just ask msdn

the article shows how to implement a fully qualified collection based on the class collectionbase.

Monday, May 09, 2005

RSS in Outlook (Plugin)

on theire website (http://www.intravnews.com/) i have found the page with following header:

my answer to them

10 Best Reasons to Use intraVnews

Rich feature set
sometimes even to much ;-)
It simply works
thats the best thing, since i installed it i never had even one problem.
Save time
correct, instead of searching all the stuff again and again, i have now everything inside my outlook. Cool
Continuous improvements
never did an update, so i can not proof it.
Standards Support
dont know the standards, but never had a problem to add a new one.
Great customer service
never needed
Our customers are satisfied
at least myself
Great performance
great performance? well did i ever had a performance problem with it, i dont remember.
Outlook-based reader
thats a goodie, but well everything is inside.
Straight-forward installation process
thats sounds good, is it really something new?

all in all thanks to the crew for such a nice tool.

SpamBayes Outlook Plugin

During the last few months i had very good experience with this plugin. Its easy to handle and saves me many many many time to held my inbox (almoast totaly) clean :-)

thanks to developers of this tool.

Wednesday, March 30, 2005

What is EAI?

EAI refers to Enterprise Application Integration. EAI is the merging of applications and data from various new and legacy systems within a business. Various means are employed to accomplish EAI, including middleware, in order to unify IT resources, maximise new ERP investments, diminish errors and get everyone on the same page. EAI enables companies to link their existing software applications with each other and with portals. EAI provide the ability to get their applications to exchange critical data. EAI is usually close to the top of any CIO's list of concerns. There are different approaches to EAI. Some rely on linking specific applications with tailored code, but most rely on generic solutions, typically called middleware. XML, combined with SOAP and UDDI is a kind of middleware.

NOAA WebService Weather Forecase ASP.NET ServerControl

NOAA WebService Weather Forecase ASP.NET ServerControl

Very nice combination between control and webservice.

Sunday, March 06, 2005

script to copy create db backups, restore them, and call the web config adaption script

@cls
@echo offecho create network mappingnet

use I: \\DBServer\F$\SQLData\BackupForCopy /user:Administrator XXX >nul

echo run script to create backups
@isql -U sa -P XXXX -S DBServer -i "\\DBServer\F$\SQLData\BackupForCopy\RunScriptForDumpBackup.sql" >nul

echo Copy all DB's from the Server to localcopy \\DBServer\F$\SQLData\BackupForCopy\backup\*.*
E:\SQLServerBackups_DBServer\DBBackup
echo Delete all created backups on the server
del /Q \\DBServer\F$\SQLData\BackupForCopy\backup\*.*

echo run script to
restore db's@isql -U sa -P XXXXX -S localhost -i "E:\SQLServerBackups_DBServer\RestoreDB.sql" >nul

echo Delete all copied backups
del /Q E:\SQLServerBackups_DBServer\DBBackup\*.bak >nul

echo delete network mapping
net use I: /delete >nul

echo changing all web.config files to localhost db
cscript LocalDB.vbs >nul

vbscript to change several config files

My environment is using an separeted db server. So i created a scipt where i can just copy all db's and afterwards i'm using a vb script to modify all web.config

Const FilePath1 = "D:\DotNet\Indexus\WsAppAccount\"
Const FilePath2 = "D:\DotNet\Indexus\WsAppApplication\"
Const FilePath3 = "D:\DotNet\Indexus\WsAppBilling\"
Const FilePath4 = "D:\DotNet\Indexus\WsAppFailures\"
Const FilePath5 = "D:\DotNet\Indexus\WsAppLog\"
Const FilePath6 = "D:\DotNet\Indexus\WsAppNotification\"
Const FilePath7 = "D:\DotNet\Indexus\WsAppStatistic\"
Const FilePath8 = "D:\DotNet\Indexus\WsAppSupplier\"

Const ForReading = 1
Const ForWriting = 2

Dim strFrom, strTo

strFrom = "192.168.1.34"
strTo = "localhost"

ChangeDB strFrom, strTo, FilePath1 + "Web.config"
ChangeDB strFrom, strTo, FilePath2 + "Web.config"
ChangeDB strFrom, strTo, FilePath3 + "Web.config"
ChangeDB strFrom, strTo, FilePath4 + "Web.config"
ChangeDB strFrom, strTo, FilePath5 + "Web.config"
ChangeDB strFrom, strTo, FilePath6 + "Web.config"
ChangeDB strFrom, strTo, FilePath7 + "Web.config"
ChangeDB strFrom, strTo, FilePath8 + "Web.config"

'Msgbox "All config files changed to localhost", 0, "Localhost DB Script"

Sub ChangeDB(strFrom, strTo, FilePath)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(FilePath, ForReading)

strText = objFile.ReadAll objFile.Close
strNewText = Replace(strText, strFrom, strTo)

Set objFile = objFSO.OpenTextFile(FilePath, ForWriting)
objFile.WriteLine strNewText objFile.Close

set objFile = nothing
set objFSO = nothing

End Sub

Saturday, March 05, 2005

Article about restoring db's

http://www.devx.com/getHelpOn/10MinuteSolution/16503/1954?pf=true

coding guidelines

The following Code-Guidelines is an extract which I took form a german .Net magazine. My personal point of view of those guidelines makes really sense the develope such lines for coding.

coding collections:

describe genereal basic classes and how you should use them.

  • How do you use the Exeption Handling
  • How do you protokoll failers? Where do you handle failures and finally which data is going to be listed.
  • How do you make Database access. Capsulation of classes, DB mng. they're abstract or build in.
Naming Convensation
  • Namespaces, Structures
  • Filesystem, organisation of projectfolders and filenames
  • prepare lines for files, namespaces, assemblies, classes, methods, parameters, variables, properties, constants, forms, controls

Object Oriented

  • prepare lines what kind of properties, methods etc. can be public, protected, private ....
  • Factor (addition of code which can be used in same baseclasses)
  • usage of abstract classes
  • usage of interfaces
  • overloading
  • how deep its allowed to inherit

Qualityaspects

  • size of classes, methods, files, namespaces & assemblies (normaly we speak about LLOC - logical lines of code)
  • define complexity of classes and methods
  • dont allow constucts like typeof() - its usage is to use over polymorphism

Formating

  • size of files, classes, methods und lines
  • tabulator
  • comments
  • etc.

Legimitation of non allowed constructs

  • exeptions always happens in a any kind of project. if this case happens try to comment and explain why its happens and maybe give a sample or somehting simular
  • add links to articles (create a knowleage bases available with links from your code)

Friday, March 04, 2005

script to copy db backups between servers

@cls
@echo off

net use Z: \\ServerName\ShareFolderName /user:Administrator yourPass

@isql -U sa -P secuse12sql -S ServerName -i "
\\ServerName\AnyKindOfFolder\ScriptName.sql"

net use Y: \\ServerName1\FolderForDBDumps /user:Administrator yourPassnet
net use X: \\ServerName2\FolderForDBDumps /user:Administrator yourPass

copy \\ServerName1\FolderForDBDumps\*DemoDump.* \\ServerName2\FolderForDBDumps

net use Z: /delete net use Y: /delete net use X: /delete

pause

Tuesday, March 01, 2005

Clean .Net Environement

In my point of view, environments for Java and .Net has today all needed components to create a clean environment – most on it is free or comes built in with other components like VS.Net or the SQL Server Desktop Tools.

What do I mean with clean Environment; you should set your focus as much as possible on automation in generation and testing.

Which elements should I integrate when I create new environments? After several months, and I believe I spent quite high invest to make the researches I got finally my decision:

Microsoft Environment:

FxCop -> from Microsoft got from their Design Rules quite lot of new inputs.
Nant -> automatically compilation.
NUnit -> automatically testing
XmlUnit -> automatically testing
CLR Profiler -> CLR profiling
SQL Query Analyzer -> SQL profiling
MS Application Center Test -> installed with VS.Net
Cruise Control -> continuous build process

Java Environment:

CruiseControl
CheckStyle
JUnit
Jester
JCoverage
FindBugs
Ant
Maven

I'll concentrate myself on MS tools and not on Java. So dont search inside this blog about Java realted stuff.

Saturday, February 26, 2005

if a class contain just static methods as example i dont need to declare a CTOR, thats good.

extract from FxCop


Error, Certainty 90, for "StaticHolderTypesShouldNotHaveConstructors"
{
Target : "Indexus.AppCommon.TemporaryLogin" (IntrospectionTargetType)
Resolution : "Remove the public constructors from 'TemporaryLogin'.
"
Help : "http://www.gotdotnet.com/team/fxcop/docs/rules.aspx?version=1.312&&url=/Design/StaticHolderTypesShouldNotHaveConstructors.html" (String)
Category : "Microsoft.Design" (String)
CheckId : "CA1053" (String)
RuleFile : "Design Rules" (String)
Info : "Instances of types that define only static members
do not need to be created. Many compilers will automatically
add a public default constructor if no constructor
is specified. To prevent this, adding an empty private
constructor may be required."
Created : "2/26/2005 2:45:41 PM" (DateTime)
LastSeen : "2/26/2005 5:12:46 PM" (DateTime)
Status : Active (MessageStatus)
Fix Category : Breaking (FixCategories)
}

Friday, February 25, 2005

Logging Table

the follwing fields should be included in your Logging table structure.

ID
Datetime
Thread
Level (Info, Error, etc)
Logger
Message
Exception

NUnit: Suites & Categories

using NUnit.Framework;
using NUnit.Core; // requieres nunit.core.dll

[TestFixture]
public class TestClassSuite
{
[Suite]
public static TestSuite Suite
{
get{
TestSuite suite = new TestSuite(@"Give it a name");
suite.Add(new Test1());
suite.Add(new Test2());
// add more test cases
return suite;
}
}
}

The classes you add to the suite (Test1 , Test2 and so on), are marked as [TestFuxuture] classes. Within each of these classes you still have the [Test] attribute on individual mehtods, and the framework will run those automaitcally. The suite facility doesn't stop you running the individual fixtures when you want. But they also let you group those fixtures: by running the one Suite(), you can now run a whole bunch of test fuxtures at once.

suites are a useful machanism for composing tests hierachically, which can be handy for coordinating sets of tests especially for an unattended build.

But it's not that useful a mechanism for day-to-day testing. You would like to be able to cross-cut across all the tests and select or exclude certain kinds of tsests from the vast pool of existing test you have written.

NUnit forces also another mechanism you can use to categroize ansd classify individual test methods and fixtures.

Categories

For instance, suppose you have got a few methods that only take a few seconds to run, but one method that takes a long time to run. You can annotate them using the category attribute.


using NUnit.Framework;
using NUnit.Core;

[TestFixture]
public class SampleCategory()
{
[Test]
[Category("ShortTest")]
public void TestMethod1()
{
// suppose this takes 1 min.
}

[Test]
[Category("ShortTest")]
public void TestMethod1()
{
// suppose this takes 1 min.
}

[Test]
[Category("ShortIntensiv")]
public void TestMethod3()
{
// suppose this takes 3 hours.
}
}

isn't it great . . . . . .

Tuesday, February 22, 2005

NUnit: Restores a DataBase backup

#region Method: RestoreDatabaseBackup
///


/// Restores a DataBase backup
///

///
/// The Database restore operation will be done using a stored procedure called
/// dnx_unittest_restoredatabasebackup
/// That should have as code:
///
/// use Master
/// RESTORE DATABASE Northwind
/// FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL\BACKUP\NorthwindBk'
///

///

public virtual void RestoreDatabaseBackup(string database, string backupFilePath)
{
//Dnx.DnxDataLayer.DbBase dbBase = new Dnx.DnxDataLayer.DbBase(this.AuthenticationContext);
this.AuthenticationContext.TransactionManager.OpenConnection();

IDbCommand cmd = this.AuthenticationContext.TransactionManager.Connection.CreateCommand();

try
{
cmd.CommandTimeout = 180;
cmd.CommandText =
string.Format(@"USE MASTER;RESTORE DATABASE {0} FROM DISK = '{1}';", database, backupFilePath);
cmd.ExecuteNonQuery();
}
finally
{
this.AuthenticationContext.TransactionManager.CloseConnection();
}
}
#endregion

Friday, February 04, 2005


make it with clr profiling Part 3 Posted by Hello


make it with clr profiling Part 2 Posted by Hello


make it with clr profiling Part 1 Posted by Hello

Thursday, February 03, 2005


quit lot of snow Posted by Hello

Saturday, January 15, 2005

Do you have a problem to Debug WebSolutions after .Net 2.0?

Well, after a whole evening i found out the solution to this problem.

- Open Computer Managment
- Choose IIS-> Web Sites-> Default Web Sites
- Choose your Web and open the Properties

You can see the additional Tab: ASP.NET

Just change now from 1.1.XXXXX to 2.0.XXXXXX.

Enjoy to go on with .Net 1.1

Tuesday, January 11, 2005

Customised sorting of an ArrayList (C#)


A handy feature that was included in ArrayList's, is the ability to sort the list according to your own comparison criteria. Unfortunately the documentation is a bit scarce on exactly how to implement this, of which an example wouldn't have gone awry.

The first thing you need to start with is the object to store in your ArrayList, for this example I have put together a simple object call Person (Person.cs). This object one contains two member variables, Name and Age.

using System;

namespace SortArrayListCS {

public class Person {
public string Name;
public int Age;

public Person() {
}

public Person(string name, int age) {
this.Name = name;
this.Age = age;
}
}
}

Now we need to implement the infamous IComparer interface to define how we want to sort this. Whilst I have made this a little more elaborate than it need be, I wanted to show how you can further define how you want to sort this collection.

Our comparer is called PersonComparer (PersonComparer.cs), and we also have a enum called SortDirection which allows us to define whether we want to sort Ascending or Descending.

using System;
using System.Collections;

namespace SortArrayListCS {

public enum SortDirection {
Ascending,
Descending
}

public class PersonComparer : IComparer {

private SortDirection m_direction = SortDirection.Ascending;

public PersonComparer() : base() { }

public PersonComparer(SortDirection direction) {
this.m_direction = direction;
}

int IComparer.Compare(object x, object y) {

Person personX = (Person) x;
Person personY = (Person) y;

if (personX == null && personY == null) {
return 0;
} else if (personX == null && personY != null) {
return (this.m_direction == SortDirection.Ascending) ? -1 : 1;
} else if (personX != null && personY == null) {
return (this.m_direction == SortDirection.Ascending) ? 1 : -1;
} else {
return (this.m_direction == SortDirection.Ascending) ?
personX.Age.CompareTo(personY.Age) :
personY.Age.CompareTo(personX.Age);
}
}
}
}

If you wanted to sort an ArrayList of mismatched objects which have a common field, you would design an interface that each of those objects implement, then change the comparer to cast these objects as their interface.

Finally we need to test this to make sure everything is working as it seems. I knocked this together as a Console Project (C#) just to be quick and simple, so our test file is SortArrayList.cs.

using System;
using System.Collections;

namespace SortArrayListCS {

class SortArrayList {

[STAThread]
static void Main(string[] args) {

ArrayList list = new ArrayList();
list.Add(new Person("John", 50));
list.Add(new Person("Mary", 28));
list.Add(new Person("William", 12));
list.Add(new Person("Marcia", 17));
list.Add(new Person("Rodrick", 36));

list.Sort(new PersonComparer());

Console.WriteLine("Sort Ascending");
foreach (Person person in list) {
Console.WriteLine("Name: " + person.Name + ", Age: " + person.Age.ToString());
}

list.Sort(new PersonComparer(SortDirection.Descending));

Console.WriteLine("\n\rSort Descending");
foreach (Person person in list) {
Console.WriteLine("Name: " + person.Name + ", Age: " + person.Age.ToString());
}

Console.ReadLine();
}

}
}

If all of this worked as planned you should see the following output:

Sort Ascending
Name: William, Age: 12
Name: Marcia, Age: 17
Name: Mary, Age: 28
Name: Rodrick, Age: 36
Name: John, Age: 50

Sort Descending
Name: John, Age: 50
Name: Rodrick, Age: 36
Name: Mary, Age: 28
Name: Marcia, Age: 17
Name: William, Age: 12




===============================================================================
Maybe it wouldn't a better choice to avoid overhead/exceptions from trying to cast null's be:

int IComparer.Compare(object x, object y) {

if (x == null && y == null) return 0;
if (x == null && y != null)
return (this.m_direction == SortDirection.Ascending) ? -1 : 1;
if (x != null && y == null)
return (this.m_direction == SortDirection.Ascending) ? 1 : -1;

Person personX = (Person) x;
Person personY = (Person) y;

return (this.m_direction == SortDirection.Ascending) ?
personX.Age.CompareTo(personY.Age) :
personY.Age.CompareTo(personX.Age);
}
}
}
}

do you search a tip? please choose a category.

Tips

Loading assemblies by Reflection

MSD2D is a community site for Exchange, SharePoint, .NET and Security support.

Monday, January 10, 2005

Friday, January 07, 2005

Tekst

Das ist ja richtig interessant.

Tekst

Thursday, January 06, 2005

register dll; register ocx -> make it easy -> regsvr32.exe

just create copy the following text to a *.reg file and execute it. Right mouse click and choose Register or Un-Register. Enjoy it.

=========== START =============
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\.dll]@="dllfile"
[HKEY_CLASSES_ROOT\.ocx]@="ocxfile"
[HKEY_CLASSES_ROOT\dllfile]"EditFlags"=dword:00000000"BrowserFlags"=dword:00000008@="Programmbibliothek"
[HKEY_CLASSES_ROOT\dllfile\DefaultIcon]@="shell32.dll,72"
[HKEY_CLASSES_ROOT\dllfile\shell]@="Registrierung"
[HKEY_CLASSES_ROOT\dllfile\shell\Register DLL]
[HKEY_CLASSES_ROOT\dllfile\shell\Register DLL\command]@="c:\\windows\\system32\\regsvr32.exe \"%1\""
[HKEY_CLASSES_ROOT\dllfile\shell\Un-Register DLL]
[HKEY_CLASSES_ROOT\dllfile\shell\Un-Register DLL\command]@="c:\\windows\\system32\\regsvr32.exe \"%1\" /u"
[HKEY_CLASSES_ROOT\ocxfile]"EditFlags"=dword:00000000"BrowserFlags"=dword:00000008@="ActiveX-Control"
[HKEY_CLASSES_ROOT\ocxfile\DefaultIcon]@="shell32.dll,21"
[HKEY_CLASSES_ROOT\ocxfile\shell]@="Registrierung"
[HKEY_CLASSES_ROOT\ocxfile\shell\Register Active-X]
[HKEY_CLASSES_ROOT\ocxfile\shell\Register Active-X\command]@="c:\\windows\\system32\\regsvr32.exe \"%1\""
[HKEY_CLASSES_ROOT\ocxfile\shell\Un-Register Active-X]
[HKEY_CLASSES_ROOT\ocxfile\shell\Un-Register Active-X\command]@="c:\\windows\\system32\\regsvr32.exe \"%1\" /u"
=========== END ===============

Shared Cache - .Net Caching made easy

All information about Shared Cache is available here: http://www.sharedcache.com/. Its free and easy to use, we provide all sources at codeplex.

Facebook Badge