Wednesday, September 30, 2009
Double question mark operator in C#
(The following was taken from here)
For two nullable variables, a and b,
int? a = null;
int? b = 5;
If a is not null, return a.
If a is null, then return b only if b is not null.
If b is also null, then I want to return 10;
This logic is written as follows.
if(a != null)
return a;
if(b != null)
return b;
return 10;
Or it can be written as follows.
return (a != null ? a : (b != null ? b : 10));
Or it can also be written as follows.
return ((a ?? b) ?? 10);
Tuesday, September 15, 2009
VBScript Functions
VBScript Functions |
Type Checking | Typecasting | Formatting
|
|
Type Checking Functions |
|
Value |
Constant |
Data Type |
|
0 |
vbEmpty |
Empty [This is the type for a variable that has yet to be used, and
|
|
1 |
vbNull |
Null [no valid data] |
|
2 |
vbInteger |
Integer |
|
3 |
vbLong |
Long |
|
4 |
vbSingle |
Single |
|
5 |
vbDouble |
Double |
|
6 |
vbCurrency |
Currency |
|
7 |
vbDate |
Date |
|
8 |
vbString |
String |
|
9 |
vbObject |
Object |
|
10 |
vbError |
Error |
|
11 |
vbBoolean |
Boolean |
|
12 |
vbVariant |
Variant [used with vbArray] |
|
13 |
vbDataObject |
Data Access Object |
|
14 |
vbDecimal |
Decimal |
|
17 |
vbByte |
Byte |
|
8192 |
vbArray |
Array [VBScript uses 8192 as a base for arrays and adds the code for
|
|
TypeName(expression) returns astring with the name of the datatype rather than the code. |
||
|
IsNumeric(expression) returns aBoolean value of True if the expression is numeric, and False otherwise |
||
|
IsArray(expression) returns aBoolean value of True if the expression is an array, and False otherwise |
||
|
IsDate(expression) returns aBoolean value of True if the expression is date/time data, and False otherwise |
||
|
IsEmpty(expression) returns aBoolean value of True if the expression is an empty value (un-initialised variable), and False otherwise |
||
|
IsNull(expression) returns aBoolean value of True if the expression contains no valid data, and False otherwise |
||
|
IsObject(expression) returns aBoolean value of True if the expression is an object, and False otherwise |
|
Typecasting Functions |
|
Cint(expression) castsexpression to an integer. If expression is a floating-point value, it is rounded. If it is a string that looks like a number, it is turned into that number and then rounded if necessary. If it is a Boolean value of True, it becomes -1, False becomes 0. It must also be within the range that an integer can store. |
|
Cbyte(expression) castsexpression to a byte value provided that expression falls between 0 and 255, expression should be numeric or something that can be cast to a number. |
|
Cdbl(expression) castsexpression to a double. expression should be numeric or something that can be cast to a number. |
|
Csng(expression) castsexpression to a single. It works like Cdbl() but must fall within the range represented by a single. |
|
Cbool(expression) castsexpression to a Boolean value. If expression is zero, the result is False, otherwise the result is True. expression should be numeric or something that can be cast to a number. |
|
Ccur(expression) castsexpression to a Currency value. expression should be numeric or something that can be cast to a number. |
|
Cdate(expression) castsexpression to a Date value. expression should be numeric or something that can be cast to a number, or a string of a commonly used date format. DateValue(expression) or TimeValue(expression) can also be used for this. |
|
Cstr(expression) castsexpression to a string. expression can be any kind of data. |
|
Formatting Functions |
|
FormatDateTime(expression, format) is used to format the date/time data in expression. Format is an optional argument that should be one of the following: vbGeneralDate - Display date , if present, as short date. Display time, if present, as long time. Value is 0. This is the default setting if no format is specified. vbLongDate - Display the date using the server's long date format. Value is 1. vbShortDate - Display the date using the server's short date format. Value is 2. vbLongTime - Display the time using the server's long time format. Value is 3. vbShortTime - Display the time using the server's short time format. Value is 4. |
|
FormatCurrency(value, numdigits, leadingzero, negparen, delimiter) is used to format the monetary value specified by value. numdigits specifies the number of digits to display after the decimal place. -1 indicates to use the system default. Tristate options have three possible values. If the value is -2, it means use the system default. If it is -1, it means turn on the option. If it is 0, turn off the option. leadingzero is a Tristate option indicating whether to include leading zeroes on values less than 1. negparen is a Tristate option indicating whether to enclose negative values in parentheses. delimiter is a Tristate option indicating whether to use the delimiter specified in the computer's settings to group digits. |
|
FormatNumber is used to formatnumerical values. It is almost exactly like FormatCurrency, only it does not display a dollar sign. FormatPercent works the same as the two above, the options being the same except it turns the given value into a percentage. |
|
Math Functions |
|
Abs(number) returns the absolutevalue of number. |
|
Atn(number) returns thearctangent, in radians, of number. |
|
Cos(number) returns the cosine ofnumber. number should be in radians. |
|
Exp(number) returns e (approx.2.71828) raised to the power number. |
|
Fix(number) returns the integerportion of number. If number is negative, Fix returns the first integer greater than or equal to number. |
|
Hex(number) convertsnumber from base 10 to a hexadecimal string. |
|
Int(number) returns the integerportion of number. If number is negative, Int returns the first integer less than or equal to number. |
|
Log(number) returns the naturallogarithm of number. |
|
Oct(number) convertsnumber from base 10 to an octal string. |
|
Rnd number returns a random numberless than one and greater than or equal to number. If the argument number is less than 0, the same random number is always returned, using number as a seed. If number is greater than 0, or not provided, Rnd generates the next random number in the sequence. If number is 0, Rnd returns the most recently generated number. |
|
Randomize initialises the randomnumber generator. |
|
Round(number) returnsnumber rounded to an integer. |
|
Round(number, dec) returnsnumber rounded to dec decimal places. |
|
Sgn(number) returns 1 ifnumber is greater than zero, 0 if number equals zero, and -1 if number is less than zero. |
|
Sin(number) returns the sine ofnumber. number should be in radians. |
|
Sqr(number) returns the squareroot of number. number must be positive |
|
Tan(number) returns the tangent ofnumber. number should be in radians. |
|
Date Functions |
|
Date returns the current date onthe server. |
|
Time returns the current time onthe server. |
|
Now returns the current date andtime on the server. |
|
Year(date) returns the yearportion from date as a number. |
|
Month(date) returns the monthportion from date as a number. |
|
MonthName(date) returns the monthportion from date as a name. |
|
Day(date) returns the day portionfrom date as a number. |
|
Weekday(date) returns the day ofthe week of date as a number. |
|
Hour(time) returns the hourportion from time. |
|
Minute(time) returns the minuteportion from time. |
|
Second(time) returns the secondportion from time. |
|
DateAdd(interval, number, date) isused to add to the date specified by date. interval is a string that represents whether you want to add days, months, years and so on. number indicates the number of intervals you want to add; that is, the number of days, weeks, years etc. |
|
DateDiff(interval, date1, date2, firstDOW, firstWOY) is used to find the time between two dates. interval is one of the interval values from Table 1. DateDiff returns the number of intervals elapsed between date1 and date2. The optional integer firstDOW specifies what day of the week to treat as the first. Values for this can be found in Table 2. The optional integer firstWOY specifies which week of the year to treat as the first. Values for this can be found in Table 3. |
|
DateSerial(year, month, day) takesthe integers year, month, and day and puts them together into a date value. They may be negative. |
|
TimeSerial is similar toDateSerial. |
|
Timer returns the number ofseconds elapsed since midnight. |
|
DatePart(interval, datetime, firstDOW, firstWOY) allows you to retrieve the part of datetime specified by interval. The valid values for interval are listed in Table 1. The optional integer firstDOW specifies what day of the week to treat as first. The optional integer firstWOY specifies which week of the year to treat as first. These values are listed in Table 2 and Table 3. |
Table 1: Interval codes for the Date Functions |
|||
|
Value |
Meaning |
|
|
"yyyy" |
Year |
|
|
"q" |
Quarter |
|
|
"m" |
Month |
|
|
"y" |
Day of year |
|
|
"d" |
Day |
|
|
"w" |
Weekday |
|
|
"ww" |
Week of year |
|
|
"h" |
Hour |
|
|
"n" |
Minute |
|
|
"s" |
Second |
Table 2: Day of the Week Constants |
|||
|
Value |
Name |
Meaning |
|
0 |
vbUseSystem |
National Language Support API Setting |
|
1 |
vbSunday |
Sunday (default) |
|
2 |
vbMonday |
Monday |
|
3 |
vbTuesday |
Tuesday |
|
4 |
vbWednesday |
Wednesday |
|
5 |
vbThursday |
Thursday |
|
6 |
vbFriday |
Friday |
|
7 |
vbSaturday |
Saturday |
Table 3: First Week of the Year Constants |
|||
|
Value |
Name |
Meaning |
|
0 |
vbUseSystem |
National Language Support API Setting |
|
1 |
vbFirstJan1 |
Week of January 1 |
|
2 |
vbFirstFourDays |
First week with four days of the new year |
|
3 |
vbFirstFullWeek |
First full week |
|
String Functions |
|
UCase(string) returnsstring with all its lowercase letters converted to uppercase letters. |
|
LCase(string) returnsstring with all its uppercase letters converted to lowecase letters. |
|
LTrim(string) removes all thespaces from the left side of string. |
|
RTrim(string) removes all thespaces from the right side of string. |
|
Trim(string) removes spaces fromboth the left and right of string. |
|
Space(number) returns a stringconsisting of number spaces. |
|
String(number, character) returnsa string consisting of character repeated number times. |
|
Len(string) returns the number ofcharacters in string |
|
Len(variable) returns the numberof bytes required by variable. |
|
LenB(string) returns the number ofbytes required to store string. |
|
StrReverse(string) returnsstring with the characters in reverse. |
|
StrComp(string1, string2, comparetype) is used to perform string comparisons. If comparetype is zero or omitted, the two strings are compared as if uppercase letters come before lowercase letters. If comparetype is one, the two strings are compared as if upper- and lowercase letters are the same. StrComp returns -1 if string1 is less than string2. It returns 0 if they are the same, and 1 if string1 is greater than string2. |
|
Right(string, number) returns thenumber rightmost characters of string. |
|
RightB(string, number) works likeRight but number is taken to be the number of bytes rather than characters. |
|
Left(string, number) returns thenumber leftmost characters of string. |
|
LeftB(string, number) works likeLeft but number is taken to be the number of bytes rather than characters. |
|
Mid(string, start, length) returnslength characters from string, starting at position start. When length is greater than the number of characters left in the string, the rest of the string is returned. If length is not specified, the rest of the string starting at the specified starting position is returned. |
|
MidB(string, start, length) workslike Mid, but start and length are both taken to be byte numbers rather than character numbers. |
|
InStr(start, string1, string2, comparetype) is used to check if and where string2 ocurrs within string1. start is an optional argument that specifies where in string1 to start looking for string2. comparetype is an optional argument that specifies which type of comparison to perform. If comparetype is 0, a binary comparison is performed, and uppercase letters are distinct from lowercase letters. If comparetype is 1, a textual comparison is performed, and uppercase and lowercase letters are the same. InStr returns 0 if string1 is empty (" "), if string2 is not found in string1, or if start is greater than the length of string2. It returns Null if either string is Null. It returns start if string2 is empty. If string2 is successfully found in string1, it returns the starting position where it is first found. |
|
InStrB works likeInStr except that the start position and return value are byte positions, not character positions. |
|
InStrRev(string1, string2, start, comparetype) starts looking for a match at the right side of the string rather than the left side. start is by default -1, which means to start at the end of the string. |
|
Replace(string, find, replace, start, count, comparetype) is used to replace ocurrences of find with replace in string. start, count and comparetype are optional, but if you want to use one, you must use the ones that come before it. start indicates where the resulting string will start and where to start searching for find. It defaults to 1. count indicates how many times to perform the replacement. By default, count is -1, which means to replace every ocurrence. If comparetype is 1, a textual comparison is performed, and uppercase and lowercase letters are the same. |
|
Filter(arrStrings, SearchFor, include, comparetype) searches an array of strings, arrStrings, and returns a subset of the array. include is a Boolean value. if include is True, filter searches through all the strings in arrStrings and returns an array containing the strings that contain SearchFor. If include is False, filter returns an array of the strings that do not contain SearchFor. include is optional and defaults to True. comparetype works the same as in the other string functions. If you want to use comparetype, you must use include. |
|
Split(expression, delimiter, count, comparetype) takes a string and splits it into an array of strings. expression is the string to split up. If expression is zero length, Split returns an array of no elements. delimiter is a string that indicates what is used to separate the sub-strings in expression. This is optional; by default the delimiter is a space. If delimiter is zero length (" "), an array of one element consisting of the whole string is returned. count is used to specify a maximum number of sub-strings to be created. The default for count is -1, which means no limit. If comparetype is 0, a binary comparison is performed, and uppercase letters are distinct from lowercase letters. If comparetype is 1, a textual comparison is performed, and uppercase and lowercase letters are the same. comparetype is only useful when the delimiter you have chosen is a letter. |
|
Join(stringarray, delimiter) doesjust the opposite of Split. It takes an array of strings and joins them into one string, using delimiter to separate them. delimiter is optional; space being the default. |
|
Other Functions |
|
LBound(array) returns the smallestvalid index for array. |
|
UBound(array) returns the largestvalid index for array. |
|
Asc(string) returns the ANSIcharacter code for the first character of string. |
|
Chr(integer) returns a stringconsisting of the character that matches the ANSI character code specified by integer. |
|
Array(value1, value2, ..., valueN) returns an array containing the specified values. This is an alternative to assigning the values to array elements one at a time. |
Understanding C# Class and Member Modifiers
By Peter Aitken May 13, 2005
Access Modifiers
Some of the keywords you use with classes are access modifiers. In other words, they control the extent to which the class is available to code (similar to variable scope). For example, look at this code which creates, or attempts to create, an instance of the class MyClass:
MyClass cls = new MyClass();
If MyClass is accessible at the location where this code is located, there is no problem. If MyClass is not accessible, you get a compile error, to the effect that the type MyClass cannot be found.
Additional confusion comes from the fact that some of the access modifiers can be used with class members (methods, for example) as well as with the classes themselves. Let's take a look at these access modifier keywords, first as they apply to classes and then as they apply to class members.
Class Access Modifiers
The default class access modifier is internal. This makes the class accessible from other classes in the same assembly. By default, I mean that this is the access provided if you include no access modifier keyword. Thus, these two are equivalent:
class MyClass { ... }
internal class MyClass { ... }
The default internal access is appropriate for the vast majority of classes you will create.
Less restrictive access is provided by the public keyword. A public class is accessible without restriction. In practical terms, it means that a public class in one assembly is accessible from another assembly:
public class MyClass { ... }
The most restrictive class access is created with the private keyword. You can use private only with a nested class, one that is defined within another class. The result is that the private class is accessible only from within the containing class:
public class OuterClass
{
...
private class InnerClass
{
}
}
Member Access Modifiers
By default, class members are private, which means they are accessible only from code in the class. You can include the private keyword or omit it with the same effect:
SomeMethod() { ... }
private SomeMethod() { ... }
Slightly less restrictive is protected access, obtained with the (you guessed it) protected keyword. A protected member is accessible in the type in which it is defined and in types derived from that type:
protected SomeMethod() { ... }
Thus, if you create a protected member in class A and then create class B that inherits from A, the member will be available to code in class B.
Internal access means the member is accessible to other types that are defined in the same assembly:
internal SomeMethod() { ... }
You can combine the protected and internal keywords to provide member access that is a combination of the two:
protected internal SomeMethod() { ... }
The least restrictive access is obtained with the public keyword. Use the public keyword to make a class member freely accessible inside and outside of the class.
public internal SomeMethod() { ... }
Other Class Modifiers
Some class modifiers are not related to access at all but place limitations on inheritance and instantiation. By default, a class can be instantiated — in other words, you can create an object from it — and it can also be used as the base class for a new class. You can modify this with the abstract and sealed keywords.
A class defined using the abstract keyword cannot be instantiated. Thus if you have a class definition like this :
abstract class MyClass { ... }
you cannot do this:
MyClass cls = new MyClass(); // Causes compilation error.
Abstract classes are usually created to serve as base classes. The .Net Framework itself contains many base classes. For example, your program may need three classes that have many members in common, but differ in a few crucial details. A good programming strategy would be to create an abstract class that contains all the common elements, then create the three individual classes that each inherits from the abstract class. Abstract classes can also be used to provide functionality without data storage, such as the Math class in the .Net Framework.
A sealed class is sort of the opposite of abstract. It can be instantiated but cannot serve as a base class. The primary reason to seal a class is to prevent your users from fiddling around with it and breaking it (and of course blaming you, usually!). It's also the case that sealing a class permits certain compiler optimizations that are not possible with non-sealed classes. Obviously, a class cannot be both sealed and abstract.
The New ModifierThe New keyword is usually seen as an operator that is used to create new objects. It also plays a role as a modifier in class definitions and has a totally different meaning. It is used when you want a member of a derived class to hide a member of the same name in the base class. For example, here's a simple class:
public class A
{
public int total;
}
Suppose you want to derive a new class from A and give it a member called total that is type float. Here's where you need to use the new modifier:
public class B:A
{
new float total;
}
You don't see new used very often, for two reasons. First of all, omitting new does not prevent compilation; it just results in a warning. The class works as if you had included new — that is, the member in the derived class hides the same-name member in the base class. It can be included as an indication, perhaps to some maintenance programmer down the road, that you really did mean to include the member in the derived class even though the base class already had one of that name. Second, it is usually preferred to explicitly override the base class member using the override keyword.
I hope that this brief exposition has helped you to understand all these keywords and their uses. For convenience I have summarized this information in the following table and included the Visual Basic counterparts for each of the C# keywords.
C#
VB
Class cannot be inherited (cannot be a base class).
Sealed
NotInheritable
Class cannot be instantiated but only used as based class and/or with abstract methods.
Abstract
MustInherit
For class members: member is accessible only from the class in which it is declared. For classes: only allowed on nested classes to restrict access to the nested class to the containing class..
Private
Private
For class members: member is accessible only from types defined in the same assembly. For classes: class is accessible only from types in the same assembly.
Internal
Friend
For members: member is accessible from the class in which it is declared and from any class derived from that class.
Protected
Protected
Combines the access of Protected and Internal for a class member
Protected Internal
Protected Friend
Access is not restricted.
Public
Public
Hides a member inherited from a base class.
New
Shadows
Tuesday, September 1, 2009
Working with null values in the .NET Framework
Takeaway: Dealing with null or nonexistent data in application development can be tricky. Tony Patton takes a closer look at working with null values within the .NET Framework.
One of the trickier aspects of application development is dealing with null or nonexistent data. It gets complicated when the application expects a data value and gets nothing or unexpected values; that's when you must perform coding that properly handles these situations to avoid application failure. This requires a close examination of the data wherever and whenever it's needed. Let's take a closer look at working with null values within the .NET Framework.
http://articles.techrepublic.com.com/5100-10878_11-5764862.html
Wednesday, July 8, 2009
Home (Documentary in HD on YouTube)
Thanks Wayne!
Use PSCONFIG to set SharePoint's Config and AdminContent database names
In short, Kit Kai's article says the following.
Assuming the following,
{
Database Server Name = "myDatabaseServer"
AdminContent DB Name = "SP_AdminContent"
Config DB Name = "SP_Config"
Service Account = "myDomain\svcAccount"
}
1. Install SharePoint on the server. Do not run the Config Wizard just yet.
2. Go to the path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\bin".
3. Run psconfig.exe -cmd configdb -create -server "myDatabaseServer"
-database "SP_Config" -user "myDomain\svcAccount" -password "
-admincontentdatabase "SP_AdminContent"
(if you encounter an error at this point, I suggest that you assign local admin rights to the service account and use "runas" to run the psconfig under the service account's credential)
4. Make sure the collation of the newly created databases is "Latin1_General_CI_AS_KS_WS".
5. Run SharePoint Config Wizard. Choose "Do not disconnect from the server farm".
Thank you Kit Kai!
How to change database names for SharePoint's Config and Admin Content databases
To change SharePoint_AdminContent database name
{ assuming the following ...
- Central admin site = "http://mysharepoint:13311/"
- Service account = "myDomain\John Doe" - (allow dbcreator role temporarily while performing this name change task)
- Databse server name = "myDatabaseServer"
- New admin content database name = "SharePoint_AdminContent"
- Backup current admin content database and restore it to a new database with the desirable name (i.e. SharePoint_AdminContent)
- In central admin site, remove the content database of the Central Admin site. After this, the Central Admin site becomes non- functional.
- On the web server that runs SharePoint Central Admin site, give local admin rights to the impersonator account("myDomain\John Doe") that connects to the database server for SharePoint.
- On the web server that runs SharePoint Central Admin site, open the command console and run the following command, [runas /u:"myDomain\John Doe" cmd.exe]. Enter password of "myDomain\John Doe" when prompted. A new console window will open up.
- This will allow "myDomain\John Doe" to perform the following tasks as service account and relieve you of lots of permission-related conflict.
- On the new console window (running under "myDomain\John Doe"), go to the following path "C:\Progra~1\common files\Microsoft Shared\Web Server Extensions\12\bin\".
- Run "stsadm -o addcontentdb -url "http://mysharepoint:13311/" - databasename "SharePoint_AdminContent" -databaseserver "myDatabaseServer"
To change SharePoint_Config database name
{ assuming the following ...
- Central admin site = "http://mysharepoint:13311/"
- Service account = "myDomain\John Doe" - (allow dbcreator role temporarily for this example)
- Databse server name = "myDatabaseServer"
- New config database name = "SharePoint_Config"
::Method A
- Backup current config database. Create a new database with the desired name (i.e., SharePoint_Config) and restore from the database backup of the original config database.
- On the web server that runs SharePoint Central Admin site, give local admin rights to the impersonator account("myDomain\John Doe") that connects to the database server for SharePoint.
- On the web server that runs SharePoint Central Admin site, open the command console and run the following command, [ runas /u:"myDomain\John Doe" cmd.exe ]. Enter password of "myDomain\John Doe" when prompted. A new console window will open up.
- This will allow "myDomain\John Doe" to perform the following tasks as service account and relieve you of lots of permission-related conflicts.
- On the new console window (running under "myDomain\John Doe"), go to the following path "C:\Progra~1\common files\Microsoft Shared\Web Server Extensions\12\bin\".
- Run stsadm -o deleteconfigdb
- Run stsadm -o setconfigdb -connect -databaseserver "myDatabaseServer" -databasename "SharePoint_Config" -farmuser "myDomain\John Doe" -farmpassword "
" - Run stsadm -o setadminport 13311.
- Run Configuration Wizard to re-install the Central Admin site.
::Method B
- Backup current config database. Create a new database with the desired name (i.e., SharePoint_Config) and restore from the database backup of the original config database.
- Run the SharePoint Products and Technologies Configuration Wizard on the server that hosts Central Admin Site.
- Disjoin from the current config database (current farm).
- Run the Configuration Wizard again and join an existing farm by specifying the database server name ("myDatabaseServer") and the new config database name ("SharePoint_Config").
- Run the Configuration Wizard again. Choose the option that the machine (server) will continue to host the web site.
- On the next window, you will see the URL of the Central Admin Site listed as (http://mysharepoint:13311/). Click Next.
- After the Wizard completes, you should have the Central Admin site come up automatically(http://mysharepoint:13311/).