Sponsored Ad

Sunday, November 29, 2009

Working with Strings in JavaScript

What is a string?

A string is simply a number of characters (letters, numbers, spaces ) joined. For example, the following are all strings:

Hello

abc123

Wow!!!

A string with many words

 

Creating strings

Creating a string variable in JavaScript :

var myString = "This is mic number one";

Be sure to put quotes around the string. Use double quotes ( ") or single quotes ( '), but be sure to use the same contribution rate to the beginning and end!

The String object

JavaScript can really stores strings in two ways:

as a primitive string data type .

how you create the same string of an object.

var myString = new String ( "This is mic number one" );

Although JavaScript can store strings as primitive data types or objects, you rarely have to worry about this distinction. JavaScript will automatically convert to a string type of data to a String object as needed, and vice versa. As we shall see, which fortunately can be used in methods of the String object primitive strings, and JavaScript do not notice it.

Basic string operations


You can compare two strings to see if they match, as with the variables of number:





Code Snippet



  1. var stringOne = "This is mic number one";

  2. var stringTwo = "Isn't this a lot of fun";

  3.  

  4. if ( stringOne == stringTwo ) alert ( "Strings match" );

  5. if ( stringOne != stringTwo ) alert ( "Strings don't match" );






Of course, it shows an alert saying that "The strings do not match.

You can also join the chains, along with the + (concatenation) operator:




Code Snippet



  1. var stringOne = "This is mic number one";

  2. var stringTwo = "Isn't this a lot of fun";

  3.  

  4. var stringThree = stringOne + ". " + stringOne + ". " + stringTwo + "!";

  5. alert ( stringThree );





This shows an alert saying "This is the number one microphone. This is the number one microphone. Is not that a lot of fun!"

String properties

Strings in JavaScript only have one property that you need for everyday use: the length property. This tells how long the chain is in characters:


var myString = "These go to eleven."
alert ( myString.length );

String methods


There are many affairs you can do with strings in JavaScript. I nuniversal, do these things with the methods of the String object. Let's look at each of these methods in alphabetical order.




Code Snippet



  1. anchor()

  2. stringObject.anchor ( anchorName )

  3. big()

  4. stringObject.big ( )

  5. blink()

  6. stringObject.blink ( )

  7. bold()

  8. stringObject.bold ( )

  9. charAt()

  10. stringObject.charAt ( index )

  11. charCodeAt()

  12. stringObject.charCodeAt ( index )

  13. concat()

  14. stringObject.concat ( string1, string2, ... stringN )

  15. fixed()

  16. stringObject.fixed ( )

  17. fontcolor()

  18. stringObject.fontcolor ( color )

  19. fontsize()

  20. stringObject.fontsize ( size )

  21. fromCharCode()

  22. String.fromCharCode ( code1, code2, ... codeN )

  23. indexOf()

  24. stringObject.indexOf ( searchText [, index] )

  25. italics()

  26. stringObject.italics ( )

  27. lastIndexOf()

  28. stringObject.lastIndexOf ( searchText [, index] )

  29. link()

  30. stringObject.link ( targetURL )

  31. match()

  32. stringObject.match ( expression )

  33. replace()

  34. stringObject.replace ( expression [, replacementText|function] )

  35. search()

  36. stringObject.search ( expression )

  37. slice()

  38. stringObject.slice ( start [, end ] )

  39. small()

  40. stringObject.small ( )

  41. split()

  42. stringObject.split ( delimiter [, count] )

  43. strike()

  44. stringObject.strike ( )

  45. sub()

  46. stringObject.sub ( )

  47. substr()

  48. stringObject.substr ( start [, length] )

  49. substring()

  50. stringObject.substring ( start [, end] )

  51. sup()

  52. stringObject.sup ( )

  53. toLowerCase()

  54. stringObject.toLowerCase ( )

  55. toString()

  56. object.toString ( )

  57. toUpperCase()

  58. stringObject.toUpperCase ( )

  59. valueOf()

  60. stringObject.valueOf ( )

  61. Returns the value of stringObject as a primitive string. Equivalent to toString().




Friday, November 27, 2009

C# 2D Array

Trouble: You want to use a 2D array containing any type of value in your program in C #. Iterate through each element with a loop, find the proper bounds of the array. Solution. Two-dimensional arrays are more difficult to treat than the one-dimensional arrays. Here is some advice on how to use 2D arrays in your programs using the C # programming language.

2D Array Benchmark

Looping with GetUpperBound: 142 ms

Looping with Length/2: 47 ms

1. Using two-dimensional arrays

First of all here we can see some sample uses two-dimensional arrays in C #. The party then initializes a 2D matrix, then B, C and D, all iterate over it. The sample does not change the values of the matrix. Displays the syntax of indexing.

+++ Program that uses two-dimensional arrays (C#) +++

Code Snippet
  1. using System;
  2.  
  3. class Program
  4. {
  5.     static void Main()
  6.     {
  7.         // A. 2D array of strings.
  8.         string[,] a = new string[,]
  9.         {
  10.             {"ant", "aunt"},
  11.             {"Sam", "Samantha"},
  12.             {"clozapine", "quetiapine"},
  13.             {"flomax", "volmax"},
  14.             {"toradol", "tramadol"}
  15.         };

 

Code Snippet
  1. // B. Get the upper bound to loop.
  2.         for (int i = 0; i <= a.GetUpperBound(0); i++)
  3.         {
  4.             string s1 = a[i, 0]; // ant, Sam, clozapine...
  5.             string s2 = a[i, 1]; // aunt, Samantha, quetiapine...
  6.             Console.WriteLine("{0}, {1}", s1, s2);
  7.         }
  8.         Console.WriteLine();
  9.  
  10.         // C. Loop based on length.
  11.         // ... Assumes each subarray is two elements long.
  12.         for (int i = 0; i < a.Length / 2; i++)
  13.         {
  14.             string s1 = a[i, 0];
  15.             string s2 = a[i, 1];
  16.             Console.WriteLine("{0}, {1}", s1, s2);
  17.         }
  18.         Console.WriteLine();
  19.  
  20.         // D. Get both bounds.
  21.         int bound0 = a.GetUpperBound(0);
  22.         int bound1 = a.GetUpperBound(1);
  23.         for (int i = 0; i <= bound0; i++)
  24.         {
  25.             for (int x = 0; x <= bound1; x++)
  26.             {
  27.                 string s1 = a[i, x];
  28.                 Console.WriteLine(s1);
  29.             }
  30.             Console.WriteLine();
  31.         }
  32.     }
  33. }
  34.  
  35. +++ Output of the program +++
  36. ant, aunt
  37. Sam, Samantha
  38. clozapine, quetiapine
  39. flomax, volmax
  40. toradol, tramadol
  41.  
  42. ant, aunt
  43. Sam, Samantha
  44. clozapine, quetiapine
  45. flomax, volmax
  46. toradol, tramadol
  47. ant
  48. aunt
  49. Sam
  50. Samantha
  51. clozapine
  52. quetiapine
  53. flomax
  54. volmax
  55. toradol
  56. tramadol

1A. Example 2D array declared. This text describes the behavior of part A in the example code. We see how to declare 2D arrays. Note the syntax confusing, with braces and commas. Just memorize the syntax. This is what we see in the Visual Studio.

clip_image002

Description of the Visual Studio. What we see is that the compiler sees the string [,] array as a string [5, 2] matrix. It follows automatically resized. This means that it is necessary to specify the length of the array always at compile time.

1B. Use GetUpperBound. This paper describes the use of GetUpperBound in the sample code. Here GetUpperBound method is used in the matrix. Note however that this method is probably not the best basis for a simple 2D.

Code Snippet
  1. for (int i = 0; i <= a.GetUpperBound(0); i++)
  2. {
  3.     string s1 = a[i, 0];
  4.     string s2 = a[i, 1];
  5.     Console.WriteLine("{0}, {1}", s1, s2);
  6. }

1C. 2D array to iterate over Largo. This part of the code shows how you can use the loop length array more efficient. The quickest method for a wide 2D is to do a little arithmetic. In this example, there are 5 rows. GetUpperBound (0) return 4. Taking long, which is 10, and divide by 2, we get 5.

Code Snippet
  1.   for (int i = 0; i < a.Length / 2; i++)
  2. {
  3.     string s1 = a[i, 0];
  4.     string s2 = a[i, 1];
  5.     Console.WriteLine("{0}, {1}", s1, s2);
  6. }

1D. Ensure that both the boundaries and keep them. This text describes how bounds of the array can be cached in local variables for better performance and clarity. Part D above shows how you can get the two dimensions of the array at runtime, and then iterate through the ranks. This example also shows how to cache limits.

Code Snippet
  1. int bound0 = a.GetUpperBound(0);
  2. int bound1 = a.GetUpperBound(1);
  3. for (int i = 0; i <= bound0; i++)
  4. {
  5.     for (int x = 0; x <= bound1; x++)
  6.     {
  7.         string s1 = a[i, x];
  8.         Console.WriteLine(s1);
  9.     }
  10.     Console.WriteLine();
  11. }

1. How slow is GetUpperBound

It's slow and does not want to call frequently. It took me a benchmark comparison 1 million repetitions of B and C, with the sample matrix. This illustrates the decrease in performance with GetUpperBound. You can see the reference point at the top of this document.

2. Parameters

Here we note that you can specify that a method receives a parameter of type two dimensional matrix. Use the type with the syntax of coma. The 2D array will be passed as a reference which means that changes will affect you for the original version as well. You can find more detailed information about 2D arrays as parameters to methods on this site.

C# String Array

Trouble. You have a set of string values that you need to store in a string array using C # programming language. There are different ways of declaring arrays, and you want to view. Solution. Here we can see different ways to declare and use string arrays in C #.

1. Declaring string array

First, here we see that there are several ways to declare and instantiate a String [ ] array variable local. They are equivalent in the compiled code [see footnote], so choose the one you think is clearer to read.

Program that initializes string arrays (C#)

Code Snippet
  1. class Program
  2. {
  3.     static void Main()
  4.     {
  5.         // String arrays with 3 elements:
  6.         string[] arr1 = new string[] { "one", "two", "three" }; // A
  7.         string[] arr2 = { "one", "two", "three" };              // B
  8.         var arr3 = new string[] { "one", "two", "three" };      // C
  9.         string[] arr4 = new string[3]; // D
  10.         arr4[0] = "one";
  11.         arr4[1] = "two";
  12.         arr4[2] = "three";
  13.     }
  14. }

Description: The main function above shows four string [ ] arrays, each equivalent to the compiler. The biggest difference is that the first three sets are declared in a single line, while the fourth series is given in separate statements. The fourth matrix allows you to test each value or logic of integration as assigned.

1. String arrays at class level

How to use String [ ] arrays as properties in classes. it is useful for storing values, either static or in cases.it return arrays of strings with the methods. Elements of string can also be returned with an indexer.

Program that uses string array (C#)

Code Snippet
  1. class Program
  2. {
  3.     static void Main()
  4.     {
  5.         Test test = new Test(); // Create new instance with string array
  6.         foreach (string element in test.Elements) // Loop over elements with property
  7.         {
  8.             System.Console.WriteLine(element);
  9.         }
  10.         System.Console.WriteLine(test[0]); // Get first string element
  11.     }
  12. }
  13. public class Test
  14. {
  15.     /// <summary>
  16.     /// String array field instance.
  17.     /// </summary>
  18.     string[] _elements = { "one", "two", "three" };
  19.  
  20.     /// <summary>
  21.     /// String array property getter.
  22.     /// </summary>
  23.     public string[] Elements
  24.     {
  25.         get { return _elements; }
  26.     }
  27.  
  28.     /// <summary>
  29.     /// String array indexer.
  30.     /// </summary>
  31.     public string this[int index]
  32.     {
  33.         get { return _elements[index]; }
  34.     }
  35. }
  36.  
  37. === Output of the program ===
  38. one
  39. two
  40. three
  41. one

Description: The first part of the code is the main method, which is the entry point of the program. A new instance of test class is created. Internally, the class that contains an array of strings. The kind of test that in real life, change their internal strings.

Trial lesson.:The test class contains a String array field. The array elements are actually added in the constructor of the class, the C # compiler automatically generated.

The second part of the test class is access to the property. It provides a clean source of external access to internal array.This properties are not useful in many cases,

This int [ ] code. Final part of the class of test is called an indexer. This is basically a function that receives one parameter, an integer, and returns a value based on that parameter.

Jagged Arrays in C#.NET

Jagged Arrays (array-of-arrays)

A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called "matrix arrays".

A special type of matrix is presented in C #. A jagged array is an array of a matrix in which the length of each array index may be different

Example:

Code Snippet
  1. int[][] jagArray = new int[5][];
  2.   
  3. In the above declaration the rows are fixed in size. But columns are not specified as they can vary.
  4.   
  5. Declaring and initializing jagged array.
  6.   
  7. int[][] jaggedArray = new int[5][];
  8.   
  9. jaggedArray[0] = new int[3];
  10. jaggedArray[1] = new int[5];
  11. jaggedArray[2] = new int[2];
  12. jaggedArray[3] = new int[8];
  13. jaggedArray[4] = new int[10];
  14.   
  15. jaggedArray[0] = new int[] { 3, 5, 7, };
  16. jaggedArray[1] = new int[] { 1, 0, 2, 4, 6 };
  17. jaggedArray[2] = new int[] { 1, 6 };
  18. jaggedArray[3] = new int[] { 1, 0, 2, 4, 6, 45, 67, 78 };
  19. jaggedArray[4] = new int[] { 1, 0, 2, 4, 6, 34, 54, 67, 87, 78 };

 

You can also initialize the array upon declaration like this:

Code Snippet
  1. int[][] jaggedArray = new int[][]
  2. {
  3. new int[] { 3, 5, 7, },
  4. new int[] { 1, 0, 2, 4, 6 },
  5. new int[] { 1, 6 },
  6. new int[] { 1, 0, 2, 4, 6, 45, 67, 78 }
  7. };
  8.   
  9. You can use the following shorthand form:
  10.   
  11. int[][] jaggedArray =
  12. {
  13. new int[] { 3, 5, 7, },
  14. new int[] { 1, 0, 2, 4, 6 },
  15. new int[] {1, 2, 3, 4, 5, 6, 7, 8},
  16. new int[] {4, 5, 6, 7, 8}
  17. };

 

Note: Notice that you cannot omit the new operator from the elements initialization because there is no default initialization for the elements.

clip_image001
Jagged array real life example

You can consider jagged array as a movie ticket

counter where ticket selling counters are fixed (rows are fixed) but you don't know how many people will be standing in each counter in a queue (column numbers are not fixed can vary on different rows).

A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null.

It is possible to mix jagged and multidimensional arrays. The following is a declaration and initialization of a single-dimensional jagged array that contains two-dimensional array elements of different sizes:

Code Snippet
  1. int[][,] jaggedArray = new int[4][,]
  2. {
  3. new int[,] { {11,23}, {58,78} },
  4. new int[,] { {50,62}, {45,65}, {85,15} },
  5. new int[,] { {245,365}, {385,135} },
  6. new int[,] { {1,2}, {4,4}, {4,5} }
  7. };

We should be careful using methods like GetLowerBound(), GetUpperBound, GetLength, etc. with jagged arrays. Since jagged arrays are constructed out of single-dimensional arrays, they shouldn't be treated as having multiple dimensions in the same way that rectangular arrays do.

Practical demonstration of jagged array of integers

Code Snippet
  1. using System;
  2.   
  3. namespace jagged_array
  4. {
  5.     class Program
  6.     {
  7.         static void Main(string[] args)
  8.         {
  9.             // Declare the array of four elements:
  10.             int[][] jaggedArray = new int[4][];
  11.   
  12.             // Initialize the elements:
  13.             jaggedArray[0] = new int[2] { 7, 9 };
  14.             jaggedArray[1] = new int[4] { 12, 42, 26, 38 };
  15.             jaggedArray[2] = new int[6] { 3, 5, 7, 9, 11, 13 };
  16.             jaggedArray[3] = new int[3] { 4, 6, 8 };
  17.   
  18.             // Display the array elements:
  19.             for (int i = 0; i < jaggedArray.Length; i++)
  20.             {
  21.                 System.Console.Write("Element({0}): ", i + 1);
  22.   
  23.                 for (int j = 0; j < jaggedArray[i].Length; j++)
  24.                 {
  25.                     System.Console.Write(jaggedArray[i][j] + "\t");
  26.                 }
  27.                 System.Console.WriteLine();
  28.             }
  29.             Console.ReadLine();
  30.         }

Run the code to see the output.

clip_image001[6]

Practical demonstration of jagged array of string

Code Snippet
  1. using System;
  2.   
  3. namespace jagged_array
  4. {
  5.     class Program
  6.     {
  7.         static void Main(string[] args)
  8.         {
  9.             string[][] Members = new string[4][]{
  10.                new string[]{"Rocky", "Sam", "Alex"},
  11.                new string[]{"Peter", "Sonia", "Prety", "Ronnie", "Dino"},
  12.             new string[]{"Yomi", "John", "Sandra", "Alex", "Tim", "Shaun"},
  13.             new string[]{"Teena", "Mathew", "Arnold", "Stallone", "Goddy", "Samson", "Linda"},
  14.                 };
  15.   
  16.             for (int i = 0; i < Members.Length; i++)
  17.             {
  18.                 System.Console.Write("Name List ({0}): ", i + 1);
  19.   
  20.                 for (int j = 0; j < Members[i].Length; j++)
  21.                 {
  22.                     System.Console.Write(Members[i][j] + "\t");
  23.                 }
  24.                 System.Console.WriteLine();
  25.             }
  26.             Console.ReadKey();
  27.         }
  28.     }
  29. }

Run the code to see the output.

clip_image001[8]

C# First tutorial

First open a DOS command shell.

You should begin to work in an empty directory for this. let call it "C:\learncs". Type in the shell:

> md C:\learncs

> cd C:\learncs

> C:

Now you should create your first C# program, type "notepad hello.cs" and type (in the notepad)

Code Snippet
  1. using System;  
  2.     public class Hello
  3.     {
  4.         public static void Main()
  5.         {
  6.             Console.WriteLine("Hello C# World :-)");
  7.         }
  8.     }

the using keyword just let you write Console at line 7, instead of System.Console. It's very usefull shortcut when you use a lot of "class" define in System.

Save the file.

Now you could compile. Type in the DOS Shell again and type:

csc /nologo /out:hello.exe hello.cs

Second tutorial

Now you become to be pretty confident, I guess, so we could start using multiple file, and even a dll ? go into an other directory (or stay in this one, I won't mind) and create 2 file:

hello.cs

Code Snippet
  1.  
  2.     using System;    
  3.     public class Hello
  4.     {
  5.         public static void Main()
  6.         {
  7.             HelloUtil.Echo h = new HelloUtil.Echo("Hello my 1st C# object !");
  8.             h.Tell();
  9.         }
  10.     }   
  11. echo.cs
  12.     using System;    
  13.     namespace HelloUtil
  14.     {
  15.         public class Echo
  16.         {
  17.             string myString;            
  18.             public Echo(string aString)
  19.             {
  20.                 myString = aString;
  21.             }            
  22.             public void Tell()
  23.             {
  24.                 Console.WriteLine(myString);
  25.             }
  26.         }
  27.     }

Note in the syntax I used hello.cs "HelloUtil.Echo" is because it is in the Echo HelloUtil namespace, could have been written (in which the start of the file) using HelloUtil and avoid HelloUtil., This is the workspace thus.

Now you could compile both in one .exe with

> csc /nologo /out:hello.exe *.cs

But it's not my intention, no.

Well.

(Have you tried?)

Let's go building a DLL:

> csc /nologo /t:library /out:echo.dll echo.cs

that's it (dir will confirm).

Now we could use it ...

> csc /out:hello.exe /r:echo.dll hello.cs

if you typed "hello" it will worked as usual..., but if you delete "echo.dll" the program will now crash: it use the DLL. You could also change Echo.cs, rebuild the DLL and see... that's the advantage of DLL!

Alternatively, put the DLL in the global assembly cache (GAC), and any program would be able to access it, even if the DLL is not in your directory!

to put it in the GAC, I suggest you read doc of MS, but here are the step without explanation:

# Create a key Assembly to create once and use for each version. created by:

sn-k myKeyName.snk

the. snk must be in the build directory (in which the execution CSC)

# Make a title added in any asssembly strong. Cs source file the following directive at the highest level:

Code Snippet
  1. using System.Reflection;    
  2.     using System.Runtime.CompilerServices;
  3.     [assembly: AssemblyTitle("My Lib Title")]
  4.     [assembly: AssemblyVersion("1.2.3.4")]
  5.     [assembly: AssemblyKeyFile("myKeyName.snk")]
  6. # now add it to the GAC:
  7.   > gacutil.exe /if myLib.dll

when I referenced the hello.dll while compiling, remember? csc /out:hello.exe /r:echo.dll hello.cs, it could have been any assembly, even a .exe !!!

Fourth tutorial

Greeting soon to be able to hack CsGL but there is one last step you should understand: interoperability (with code C).

You will need a C compiler, I advise for Windows called MinGW gcc is free, is good is GCC?

We will create 3 files:

Code Snippet
  1. echo.c
  2.     #include <stdio.h>    
  3.     #define DLLOBJECT __declspec(dllexport)    
  4.     DLLOBJECT void writeln(char* s)
  5.     {
  6.         printf("%s\n", s);
  7.     }

 

 

Code Snippet
  1. echo.cs
  2.     using System;
  3.     using System.Runtime.InteropServices;    
  4.     namespace HelloUtil
  5.     {
  6.         public class Echo
  7.         {
  8.             [DllImport("echo.native.dll", CallingConvention=CallingConvention.Cdecl)]
  9.             static extern void writeln(string s);            
  10.             string myString;            
  11.             public Echo(string aString)
  12.             {
  13.                 myString = aString;
  14.             }
  15.             
  16.             public void Tell()
  17.             {
  18.                 writeln(myString);
  19.             }
  20.         }
  21.     }
  22.     hello.cs
  23.     using System;
  24.     using HelloUtil;
  25.     
  26.     public class Hello
  27.     {
  28.         public static void Main()
  29.         {
  30.             Echo h = new Echo("Hello my 1st interop code !");
  31.             h.Tell();
  32.         }
  33.     }

 

Here you find something completely new attributes.

[DllImport (.. "is an attribute.

You could label any method / field / class with any number of attributes.

Generate additional information that could be used by anyone who could understand.

The DllImport attribute is understood by the compiler and said that the function below is actually the name of a DLL, which is "echo.native.dll. I add a parameter of the calling convention as the default. NET calling convention is __stdcall that in C, is __cdecl.

By the way, if you look in documentation DllImport, DllImportAttribute search, because it removes the "attribute" of attribute class name to use, it does.

And now let's compile this!

 

Code Snippet
  1. > csc /nologo /t:library /out:echo.dll echo.cs
  2.     > csc /nologo /out:hello.exe /r:echo.dll hello.cs
  3.     >
  4.     > rem "if the following line don't work, read bellow.."
  5.     > gcc -shared -o echo.native.dll echo.c
  6.     > strip echo.native.dll

the 2 last line (the gcc & strip command) are for building the "C-DLL".

If they don't work maybe gcc is not in a directory listed in your path environment variable ? check with:

%lt; echo %PATH%

Well it's probably not,anyway, so type, assumin mingc is in C:\MinGW:

set PATH=C:\MinGW;%PATH%

And try again... you sure it's not a syntax error ?

If it compile test it now: hello Great isn't it ?

Now I must admit I did not tell the whole truth. echo.dll and echo.native.dll are not the same type of DLL. It's not just the language (C / C #), C is a single executable filled probably x86 instruction, while the C # one is what MS call a portable executable .. are different anyway.

If you install in the GAC is echo.dll wont work because it is not echo.native.dll except if put in the path (like C: \ Windows \ System32).

Likewise when you add the reference in VS.NET echo.native.dll overlooked and your program does not work .

C# Testing and Debugging

There are two possible methods

  • Tracepoints
  • Debug class usage

Using trace points cleanest way to test and debug code that work without adding to your code. It is simply appear in the part of own code very similar to a breakpoint.

Debug Class

The Debug class allows you to do what you can do follow-up points, but require actual line of code that is added. However, only add to your code in the development of the construction. The release versions will include no debugging by default.

Add using System.Diagnostics; to the namespaces. Then just reference Debug

Default - By default (C# Express 2005) Debug is disabled but Trace is enabled in the Release build.

Basic

Affirm - Is what I expect? (And the proof is not put in debug release builds)

  • Fail - Use the method Debug.Fail place when you are using the MessageBox.Show statement for 'quick / small experiments.
  • Write, WriteLine - Simple debugging
  • or sangria, sangria - Simple Format
  • WriteIf, WriteLineIf - debugging output depends on outcome

Advanced

When the output window is not enough to place next to turn to external files. There are many ways to write external files. However, many of these segments will leave behind unwanted code in Building launch.

The quickest and easiest way to write a debug file is to add an application configuration file for your project.

Once you have a. Config settings in the project just paste the following code inside the tags.

Code Snippet
  1. <system.diagnostics>
  2.     <trace autoflush="false">
  3.       <listeners>
  4.         <add name="debugListener"
  5.            type="System.Diagnostics.TextWriterTraceListener"
  6.            initializeData="debug.txt" />
  7.       </listeners>
  8.     </trace>
  9.   </system.diagnostics>

If autoflush = "false" must ensure that places a Debug.Flush (); statement before your application closes, otherwise there will be nothing in the file specified. The easiest place to add this is the end of Main () method.

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Windows.Forms;
  4. namespace debugTesting {
  5.   static class Program {
  6.     /// <summary>
  7.     /// The main entry point for the application.
  8.     /// </summary>
  9.     [STAThread]
  10.     static void Main() {
  11.       Application.EnableVisualStyles();
  12.       Application.SetCompatibleTextRenderingDefault(false);
  13.       Application.Run(new Form1());
  14.       System.Diagnostics.Debug.Flush();
  15.     }
  16.   }
  17. }

With autoflush = "false" the program must reach a Debug.Close (); or Debug.Flush (); statement to save debugging information in the file.

It is possible to set autoflush = "true", so if the program fails will have a track record so far. However, this can have a negative impact on the performance of your application, due to the file stream.

Saving debug to file

Save debugging information to a file lets you use your application outside the development environment and still maintain a debug log. To make this a program configuration XML file must be created.

Code Snippet
  1.   <?xml version="1.0" encoding="utf-8" ?>
  2. <configuration>
  3.   <system.diagnostics>
  4.     <trace autoflush="true">
  5.       <listeners>
  6.     <add name="debugListener"
  7.            type="System.Diagnostics.TextWriterTraceListener"
  8.            initializeData="debug.txt" />
  9.       </listeners>
  10.     </trace>
  11.   </system.diagnostics>
  12. </configuration>

Thursday, November 26, 2009

ASP.NET AJAX DropDownExtender - Tips and Tricks

The DropDownExtender is an ASP.NET AJAX control that can connect to almost any ASP.NET control to provide a dropdown menu. For example: If you have a TextBox and a Panel control

(with a CheckBoxList), and wants to give the text box drop-down menu, then it applies only to the DropDownExtender the text box and set the DropDownControlID the Group. In this article we will see some tips and tricks that can be applied to a control DropDownExtender.

I suppose you have some basic experience developing ASP.NET Ajax applications and has installed the ASP.NET AJAX Library and ASP.NET Control Toolkit. As of this writing, the version of the toolkit is version 1.0.20229 (if you are targeting Framework 2.0, ASP.NET AJAX 1.0 and Visual Studio 2005) and Version 3.0.20229 (if targeting. NET Framework 3.5 and Visual Studio 2008).

Tip 1: How to attach a DropDownExtender to a TextBox and show a Panel in the dropdown

Drag and drop a ScriptManager to the page. Then drag and drop a Panel (panelItems) to the page. Now add a BulletedList to it and add some ListItems.

Code Snippet
  1. <asp:ScriptManager ID="ScriptManager1" runat="server">
  2.  
  3. </asp:ScriptManager>
  4.  
  5. <asp:Panel ID="panelItems" runat="server" BorderColor="Aqua" BorderWidth="1">
  6.  
  7. <asp:BulletedList ID="BulletedList1" runat="server">
  8.  
  9. <asp:ListItem Text="Item 1"/>
  10.  
  11. <asp:ListItem Text="Item 2"/>
  12.  
  13. <asp:ListItem Text="Item 3"/>
  14.  
  15. </asp:BulletedList>
  16.  
  17. </asp:Panel>

Now drag and drop a TextBox control outside the Panel. If you want to attach a DropDownExtender to the TextBox, then in the design mode, click on the smart tag of the TextBox > Add Extender > Choose the ‘DropDownExtender’ > OK.

If you go back to the ‘Source’ view, you will find the newly created DropDownExtender. Set the DropDownControlId to panelItems.

Code Snippet
  1. <cc1:DropDownExtender ID="TextBox1_DropDownExtender" runat="server"
  2.  
  3. DynamicServicePath="" Enabled="True" DropDownControlID="panelItems" TargetControlID="TextBox1">
  4.  
  5. </cc1:DropDownExtender>

The entire code will look similar to the following.

Code Snippet
  1. <body>
  2.  
  3. <form id="form2" runat="server">
  4.  
  5. <div>
  6.  
  7. <asp:ScriptManager ID="ScriptManager1" runat="server">
  8.  
  9. </asp:ScriptManager>
  10.  
  11. <asp:Panel ID="panelItems" runat="server" BorderColor="Aqua" BorderWidth="1">
  12.  
  13. <asp:BulletedList ID="BulletedList1" runat="server">
  14.  
  15. <asp:ListItem Text="Item 1"/>
  16.  
  17. <asp:ListItem Text="Item 2"/>
  18.  
  19. <asp:ListItem Text="Item 3"/>
  20.  
  21. </asp:BulletedList>
  22.  
  23. </asp:Panel>
  24.  
  25. <br />
  26.  
  27. <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
  28.  
  29. <cc1:DropDownExtender ID="TextBox1_DropDownExtender" runat="server"
  30.  
  31. DynamicServicePath="" Enabled="True" DropDownControlID="panelItems" TargetControlID="TextBox1">
  32.  
  33. </cc1:DropDownExtender>
  34.  
  35. </div>
  36.  
  37. </form>
  38.  
  39. </body>
  40.  
  41. </html>

Run the code. When you hover over the TextBox, you will see a dropdown. Click on it to view the Panel with the BulletedList as shown below

clip_image001

Tip 2: How to keep the DropDownExtender always visible

The dropdownlist as demonstrated above is visible only when the user hovers over the textbox. If you want to override this behavior and keep it always visible, then here is a trick I got from this post  Add the following script tag in the <body> element as shown below:

Code Snippet
  1. <body>
  2.  
  3. <form id="form2" runat="server">
  4.  
  5. <script type="text/javascript">
  6.  
  7. function pageLoad()
  8.  
  9.     {
  10.  
  11.           $find('TextBox1_DropDownExtender')._dropWrapperHoverBehavior_onhover();
  12.  
  13.       $find('TextBox1_DropDownExtender').unhover = VisibleMe;
  14.  
  15.     }
  16.  
  17. function VisibleMe()
  18.  
  19.     {
  20.  
  21.         $find('TextBox1_DropDownExtender')._dropWrapperHoverBehavior_onhover();
  22.  
  23.     }
  24.  
  25. </script>
  26.  
  27. ... ScriptManager and other Controls come here
  28.  
  29. </body>
  30.  
  31. </html>

If you run the code, you will see that the dropdown is always visible.

Tip 3: How to keep the DropDown expanded and show the Panel when first loaded

The default behavior is that the panel is shown only once the user clicks on the textbox. If you want the Panel to be visible as a dropdown when the page is loaded, add the following script

Tip 4: How to align DropDownExtender panel to left instead of right

By default, the panel drops down to the right. However if you need to change this behavior, use the following script. The script uses the set_positioningMode() and sets it to 2 (left). The default value is 3 (right).

Code Snippet
  1. <body>
  2.  
  3. <form id="form3" runat="server">
  4.  
  5. <script type="text/javascript">
  6.  
  7. function pageLoad()
  8.  
  9.     {
  10.  
  11. var chngPosition = $find('TextBox1_DropDownExtender')._dropPopupPopupBehavior;
  12.  
  13.           chngPosition.set_positioningMode(2);
  14.  
  15.     }
  16.  
  17. </script>
  18.  
  19. ... ScriptManager and other Controls come here
  20.  
  21. </body>
  22.  
  23. </html>

clip_image002

Tip 5: How can I make the width of the DropDownExtender (panel) the same as that of the TextBox

The width of the panel that is visible during the drop-down is not the same as that of the targetcontrol of the DropDownExtender. It is displayed to the right by default and adjusts its width according to the contents of the panel as shown below:

clip_image001[1]

However, if you want to manually adjust the width of the drop down and make it the same as that of the textbox, use this code:

Code Snippet
  1. <body>
  2.  
  3. <form id="form3" runat="server">
  4.  
  5. <script type="text/javascript">
  6.  
  7. function pageLoad()
  8.  
  9.     {
  10.  
  11.         $get('panelItems').style.width = $get('TextBox1').clientWidth;
  12.  
  13.     }
  14.  
  15. ... ScriptManager and other Controls come here
  16.  
  17. </body>
  18.  
  19. </html>

clip_image003

Create data table in ASP.NET 2.0(C#)

Code Snippet
  1. private DataTable CreateDataTable()
  2. {
  3. DataTable myDataTable = new DataTable();
  4. DataColumn myDataColumn;
  5. myDataColumn = new DataColumn();
  6. myDataColumn.DataType = Type.GetType("System.String");
  7. myDataColumn.ColumnName = "id";
  8. myDataTable.Columns.Add(myDataColumn);
  9. myDataColumn = new DataColumn();
  10. myDataColumn.DataType = Type.GetType("System.String");
  11. myDataColumn.ColumnName = "username";
  12. myDataTable.Columns.Add(myDataColumn);
  13. myDataColumn = new DataColumn();
  14. myDataColumn.DataType = Type.GetType("System.String");
  15. myDataColumn.ColumnName = "firstname";
  16. myDataTable.Columns.Add(myDataColumn);
  17. myDataColumn = new DataColumn();
  18. myDataColumn.DataType = Type.GetType("System.String");
  19. myDataColumn.ColumnName = "lastname";
  20. myDataTable.Columns.Add(myDataColumn);
  21. return myDataTable;
  22. }

Yes, it is possible to find a good web host. Sometimes it takes a while. After trying several, we went with Server Intellect and have been very happy. They are the most professional, customer service friendly and technically knowledgeable host we've found so far.

Insert data into datatable.

private void AddDataToTable(string username,string firstname,string lastname,DataTable

Code Snippet
  1. myTable)
  2. {
  3. DataRow row;
  4. row = myTable.NewRow();
  5. row["id"] = Guid.NewGuid().ToString();
  6. row["username"] = username;
  7. row["firstname"] = firstname;
  8. row["lastname"] = lastname;
  9. myTable.Rows.Add(row);
  10. }

If you're ever in the market for some great  Windows web hosting, try Server Intellect. We have been very pleased with their services and most importantly, technical support.

Add data to datatable which we have created

Code Snippet
  1. protected void btnAdd_Click(object sender, EventArgs e)
  2. {
  3. if (txtUserName.Text.Trim() == "")
  4. {
  5. this.lblTips.Text = "You must fill a username.";
  6. return;
  7. }
  8. else
  9. {
  10. AddDataToTable(this.txtUserName.Text.Trim(), this.txtFirstName.Text.Trim(), this.txtLastName.Text.Trim(), (DataTable)Session["myDatatable"]);
  11. this.GridView1.DataSource = ((DataTable)Session["myDatatable"]).DefaultView;
  12. this.GridView1.DataBind();
  13. this.txtFirstName.Text = "";
  14. this.txtLastName.Text = "";
  15. this.txtUserName.Text = "";
  16. this.lblTips.Text = "";
  17. }
  18. }

We migrated our web sites to  Server Intellect over one weekend and the setup was so smooth that we were up and running right away. They assisted us with everything we needed to do for all of our applications. With Server Intellect's  help, we were able to avoid any headaches!

Be noted "Session["myDatatable"] = myDt;" is important to ensure we can add new data continually until the page be closed.

Code Snippet
  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3. if (!Page.IsPostBack)
  4. {
  5. myDt = new DataTable();
  6. myDt = CreateDataTable();
  7. Session["myDatatable"] = myDt;
  8. this.GridView1.DataSource = ((DataTable)Session["myDatatable"]).DefaultView;
  9. this.GridView1.DataBind();
  10. }
  11. }
Sponsored Ad

More Related Articles

Website Update

Followers