I.T. Discussion Community!
-Collapse +Expand
C#
Search C# Group:

Advanced
-Collapse +Expand C# To/From
To/FromCODEGuides
-Collapse +Expand C# Study Test
PRESTWOODCERTIFIED
-Collapse +Expand C# Store
PRESTWOODSTORE

Prestwood eMagazine

August Edition
Subscribe now! It's Free!
Enter your email:

   ► KBC# Knowledge Base  Print This    All Groups  

C# Flashcards Library

These FlashCards are contributed by you (our online community members). They are organized by our knowledge base topics. Specifically, by the C# sub-topics.

Contribute a Flashcard

64 C# (Visual C# & VS.Net) FlashCards

Group: C# (Visual C# & VS.Net)


Topic: C#

C# Empty String Check (String.IsNullOrEmpty)

The .Net framework offers a static method in the string class: String.IsNullOrEmpty.

String s;
 
s = "";
//s = null; //Uncomment to test 2nd case.
 
if (String.IsNullOrEmpty(s))
{
  MessageBox.Show("empty string");
}
Posted By Mike Prestwood, Post #102042, KB Topic: C#
Q&A: Coding for Application Virtualization
Question: How do I take advantage of Application Virtualization in the application I'm coding?

Answer:

You don't have to do anything special in your application. However, you do have to give certain folders and files the correct rights in your installer.

Posted By Mike Prestwood, Post #100840, KB Topic: C#
Definition

Delegate

Definition: A delegate is a variable that references a method.  A delegate's signature (parameters and return value) must match the signature of the method that it references.  In some cases it is possible to use a method with parameters that are less derived than in the delegate or a method with a return type that is more derived than in the delegate
Posted By Daniel Fought, Post #100897, KB Topic: C#
Definition

Reference Data type variables

Definition:

Variables that only contain a reference to the values. Reference data type variables only contain a reference to it's constituent value.  Reference data types include objects and strings.  Assignment of one reference type variable to another copies the reference, thus changes to the values in one variable changes the values in the other.

Posted By Daniel Fought, Post #100896, KB Topic: C#
Definition

Struct

Definition:

A Struct encapsulates a small set of related data. Although it can contain many of the characteristics of a class such as methods, events etc., they are usually very limited in number. If several such members are used implementing this as a class should be considered.  A struct can implement an interface, but it cannot inherit from a class or another struct

Posted By Daniel Fought, Post #100867, KB Topic: C#
Definition

Value Data type variables

Definition: Value data type variables contains values.  They can be either struct or enumerations.  Since the value data type variables contain values assigning one variable to another copies the data into the second variable.  Any changes to either variable are independant of the other.
Posted By Daniel Fought, Post #100895, KB Topic: C#



Topic: Tool Basics

C# Assignment (=)

Languages Focus: Assignment

Common assignment operators for languages include =, ==, and :=. An assignment operator allows you to assign a value to a variable. The value can be a literal value like "Mike" or 42 or the value stored in another variable or returned by a function.

C# Assignment

C# uses = for it's assignment operator.

int Age;
string FullName;
  
Age = 42;
FullName = "Randy Spitz";
Posted By Mike Prestwood, Post #101377, KB Topic: Tool Basics
C# Case Sensitivity (Yes)

C# is case sensitive. The following does NOT:

messagebox.Show("hello");  //Does not work!

The first time you type any other case for commands or variables, VS.Net will change it to the accepted or defined case. For example, if you type messagebox.show it is converted to MessageBox.Show. Once corrected, you can break it again by editing MessageBox to messagebox and the compiler will give you an error.

The following code works:

MessageBox.Show("hello");
Posted By Mike Prestwood, Post #101336, KB Topic: Tool Basics
C# Comparison Operators (==, !=)

General Info: Round Floating Point Numbers

When comparing floating point numbers, make sure you round to an acceptable level of rounding for the type of application you are using.

Languages Focus: Comparison Operators

A comparison operator compares two values either literals as in "Hello" and 3 or variables as in X and Counter. Most languages use the same operators for comparing both numbers and strings. Perl, for example, uses separate sets of comparison operators for numbers and strings.

C# Comparison Operators

Common comparison operators:

== equal
!= not equal
< less than
> greater than
<= less than or equal
>= greater than or equal

//Does C# evaluate the math correctly? No!
if (.1 + .1 + .1 == .3)
MessageBox.Show("correct");
else
MessageBox.Show("not correct");
Posted By Mike Prestwood, Post #101586, KB Topic: Tool Basics
C# Constants (const)

In C#, you define constants with the const keyword.

All constants are part of a class (no global constants) but you can make a constant public and have access to it so long as you have added the class to the project (even without creating the class as if they were static, but you cannot use the static keyword).

Constants must be of an integral type (sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, or string), an enumeration, or a reference to null.

public class Convert : Object
{
  public const string kName = "Mike";
 
  //You can declare multiple of the same type too:
  const Double kFeetToMeter = 3.2808, kMeterToFeet = .3048;
}
Posted By Mike Prestwood, Post #101803, KB Topic: Tool Basics
C# Deployment Overview

C# projects require the .Net framework and any additional dependencies you've added such as Crystal Reports.

In Visual Studio.Net, you can create a Setup and Deployment project by using any of the templates available on the New Project dialog (Other Project Types).

In addition, C# projects also support ClickOnce which brings the ease of Web deployment to Windows Forms and console applications. To get started, right click on your solution in the Solution Explorer, click Properties then select the Security tab. 

In addition, you can use any of the many free and commercially available installation packages.

C# File Extensions

Common source code file extensions include:

  • .SLN - Solution File. Contains solution specific information such as links to the projects within this solution.
  • .CSPROJ - C# Project File. Contains project specific information.
  • .CS - C# source file.
  • .Designer.CS - C# form file (a text resource file).
//Sample code snippet from the .csproj project file:
<ItemGroup>
  <Compile Include="Cyborg.cs" />
  <Compile Include="Cyborg600.cs" />
  <Compile Include="Form1.cs">
    <SubType>Form</SubType>
  </Compile>
  //...
Posted By Mike Prestwood, Post #101350, KB Topic: Tool Basics
C# Multiple Line Comment (// or /* */)

Commenting Code
C# uses "//" for a single line comment and /* */ for a multiple line comment.

//Single line comment.

/*
Multiple line
comment.
*/
Posted By Mike Prestwood, Post #101501, KB Topic: Tool Basics
C# Overview and History

Language Overview: C# is an OOP language (no global functions or variables) and is type-safe. You code using a fully OOP approach (everything is in a class).

Target Platforms: C# is most suitable for creating any type of application that runs on the .Net platform. This includes desktop business applications using WinForms and websites using WebForms.

C# Report Tools Overview

For WebForm applications the client target is the browser (a document interfaced GUI), a common solution is to simply output an HTML formatted page with black text and a white background (not much control but it does work for some situations). For WinForm applications, Crystal Reports is still a popular choice with C# developers because it has been bundled with many Microsoft products, it's overall popularity, and compatibility with many different development tools.

C# String Concatenation (+)

C# String Concatenation

C# performs implicit casting of numbers to strings. To concatenate two strings, a string to an integer, or a string to a floating point number, use the + operator. For example, to convert a floating point number to a string just concatenate an empty string to the number as in "" + 3.2.

Alternatively, you can use the System.Text.StringBuilder class which frequently but not always provides faster code.

String FirstName;
String LastName;
Int16 Age;
FirstName = "Mike";
LastName = "Prestwood";
Age = 43;
Console.WriteLine(FirstName + " " + LastName + " is " + Age + ".");
  
//Implicit casting of numbers.
//
//This fails:
//MessageBox.Show(3.3);
//
//This works:
MessageBox.Show("" + 3.3); 
Posted By Mike Prestwood, Post #101590, KB Topic: Tool Basics
C# Variables (Int16 x=0;)

C++, Java, and C# all use C-like variable declaration.

C# has C-like variable declaration and although variables are case sensitive, VS.Net will auto-fix your variable names to the defined case.

C# offers many variable types. Some common types used include short, intlong, float, double, decimal, Int16, UInt16, Int32, Int64, string, and bool.

You can also specify the value when you declare a variable as in:

String FirstName = "Mike";
String LastName = "Prestwood";
Int16 Age = 42;
string FullName;
int16 Age;
double Weight;
 
FullName = "Mike Prestwood";
Age = 32;
Weight = 154.4;
Posted By Mike Prestwood, Post #101565, KB Topic: Tool Basics



Topic: Language Basics

Associative Arrays in C# (a Dictionary)

A Dictionary is a data type which maps a key to a value. The key and the value can be any type, the Dictionary shows the link between the two.

This example shows the relationship between the 3-letter airport code and their location. The code will produce a message box which says "Los Angeles."

using System.Collections.Generic;
using System.Text;

using System.Windows.Forms;

protected void Button1_Click(object sender, EventArgs e)
{
            Dictionary airports = new Dictionary();
            airports.Add("LAX", "Los Angeles");
            airports.Add("SFO", "San Francisco");
            airports.Add("SAN", "San Diego");
            MessageBox.Show(airports["LAX"]);
}

Posted By Stephen Berry, Post #101206, KB Topic: Language Basics
Definition

Attribute

Definition:

Attributes cause additional metadata to be included in your assembly and, utilized when reflected over by another class. For your convenience, many, many useful attributes are pre-defined.

In C#, attributes are designated by enclusure in square brackets. For example, the [DllImport] attribute allows .NET to utilize Win32 DLLs. Another example is the [Serializable] attribute, which causes your class to be persisted to disk.

Posted By Wes Peterson, Post #100652, KB Topic: Language Basics
C# Code Blocks ({ })

For C#, I prefer to put the opening { and the closing } on their own line (as opposed to C++, Java, and JavaScript where I put the opening bracket at the end of the first line.

int DoSomething()
{
 int a = 1;
 int b = 2;
 return a + b;
}
Posted By Mike Prestwood, Post #101415, KB Topic: Language Basics
C# Custom Routines
ReturnType RoutineName()

 

Note: C# requires () in both the function declaration, and when it's invoked.

void SayHello(String pName)
{
MessageBox.Show("Hello " + pName);
}
int Add(int a, int b) 
{
return a + b;
}
Posted By Mike Prestwood, Post #101598, KB Topic: Language Basics
C# Development Tools

Languages Focus: Development Tools

Primary development tool(s) used to develop and debug code.

C# Development Tools

Microsoft Visual C# and the full version of Microsoft Visual Studio.Net are the current primary tools. CodeGear does have C#Builder but it's not a primary tool currently and development on the tool has slowed in recent years.

C# End of Statement (;)

C# uses a semicolon ";" as an end of statement specifier and you can put multiple statements on a single line of code if you wish as well as split a single statement into two or more code lines.

Console.WriteLine("Hello1");
Console.WriteLine("Hello2");
Console.WriteLine("Hello3");

//Same line works too:
Console.WriteLine("Hello4"); Console.WriteLine("Hello5");
 
//Two or more lines works too: 
Console.
  WriteLine
("Hello6");

Posted By Mike Prestwood, Post #101541, KB Topic: Language Basics
C# Exception Trapping (try...catch...finally)

C# uses a try...catch...finally statement to trap for errors.

try {}
catch {}
finally {}
try
{
int y = 0;
y = 1 / y;
}
catch
{
MessageBox.Show("you cannot divide by zero");
}
Posted By Mike Prestwood, Post #101646, KB Topic: Language Basics
C# If Statement (if..else if..else)

Use () around evaluation with no "then".

Boolean x = true;


if (x)
{
MessageBox.Show("hello");
}
else if (x==false)
{
MessageBox.Show("goodbye");
}
else
{
  MessageBox.Show("what?");
}
Posted By Mike Prestwood, Post #101384, KB Topic: Language Basics
C# Inheritance (: ParentClass)

Simple syntax example of class inheritance.

In the following example, a terminator T-600 is-an android. 

public class Android
{
}
 
public class T-600 : Android
{
}
Posted By Mike Prestwood, Post #101390, KB Topic: Language Basics
C# Literals (quote)

Literals are quoted as in "Prestwood". If you need to embed a quote use a slash in front of the quote as in \"

Console.WriteLine("Hello");
Console.WriteLine("Hello \"Mike\".");
 
//Does C# evaluate this simple
//floating point math correctly? No! 
if ((0.1 + 0.1 + 0.1) == 0.3)
{
MessageBox.Show("Correct");
}
else
{
MessageBox.Show("Not correct");
}
Posted By Mike Prestwood, Post #101527, KB Topic: Language Basics
C# Logical Operators

Same as C++ and Java. C# logical operators:

& and, as in this and that No Short Circuit
&& and, as in this and that short circuits
| or, as in this or that No Short Circuit
|| or, as in this or that short circuits
! Not, as in Not This
^ either or, as in this or that but not both

//Given expressions a, b, c, and d:
if !((a && b) && (c || d)) 
{
  //Do something.
}
Posted By Mike Prestwood, Post #101918, KB Topic: Language Basics
Definition

C# Null-Coalescing Operator: ??

C# Overloading (implicit)

C# Overloading

  • Operator - Yes.
  • Method - Yes.
C# Parameters

Defining
In C# the data type of each parameter must be specified, even if adjacent parameters are of the same type.

integer Add(int a, int b)

Posted By Mike Prestwood, Post #101626, KB Topic: Language Basics
C# Substring

C# Substring

Above returns "abcd" on a string literal. You can, of course, use VarName.Substring(0, 4).

Console.WriteLine("abcdefgh".Substring(0, 4));
Posted By Mike Prestwood, Post #101371, KB Topic: Language Basics
C# Unary Operators

An operation with only one operand (a single input). The following are the C# unary operators: +, -, !, ~, ++, --, true, or false.

Definition

Nullable Type

Definition: Nullable types are instances of System.Nullable(T). A Nullable type can represent any of the normal values for its value type or it can be assigned the value null. This is useful when dealing with databases that may have types that do not have a value.
Posted By Stephen Berry, Post #101280, KB Topic: Language Basics



Topic: Language Details

C# Associative Array (Dictionary)

General Info: Associative Array

A set of unique keys linked to a set of values. Each unique key is associated with a value. Think of it as a two column table. MyArray['CA'] = 'California' MyArray['AR'] = 'Arizona'

Languages Focus: Associative Array

Associative arrays are also known as a dictionary or a hash table in other languages.

C# Associative Array

//using System.Collections.Generic;
 
Dictionary <String, String> airports = new Dictionary <String, String>();
airports.Add("LAX", "Los Angeles"); 
airports.Add("SFO", "San Francisco");
airports.Add("SAN", "San Diego");
MessageBox.Show(airports["LAX"]);
Posted By Mike Prestwood, Post #101513, KB Topic: Language Details
C# Inlining (Automatic)

In C#, inlining is automatically done for you by the JIT compiler for all languages and in general leads to faster code for all programmers whether they are aware of inlining or not.

C# Pointers

Although pointer data types in C# coding are less important than in other languages such as C++, C# does support developer defined pointers. Use the * operator to declare a pointer data type. Use the & operator to return the current address of a variable.

In .Net managed coding the use of pointers is not safe because the garbage collector may move memory around. To safely use pointers, use the unsafe keyword.

C++/CLI has more extensive support for pointers than C#. If you have needs that go beyond what C# offers, you can code in C++/CLI and add it to your project.

//Declare a pointer of type integer.
Integer *PCounter;
Posted By Mike Prestwood, Post #101940, KB Topic: Language Details



Topic: OOP

C# Abstraction (abstract, override)

C# supports abstract class members and abstract classes using the abstract modifier. An abstract class is a class with one or more abstract members and you cannot instantiate an abstract class. However, you can have additional implemented methods and properties. An abstract member is either a method (implicitly virtual), property, indexer, or event in an abstract class. You can add abstract members ONLY to abstract classes using the abstract keyword.

abstract public class Cyborg : System.Object
{
  abstract public void Speak(string pMessage);
}
public class Series600 : Cyborg
{
  public override void Speak(string pMessage)  
  {
    MessageBox.Show(pMessage);  
  }
}
Posted By Mike Prestwood, Post #101344, KB Topic: OOP
C# Access Modifiers

In C#, you specify each class and each class member's visibility with an access modifier. The C# access modifiers are the traditional public, protected, and private plus the two additional .Net modifiers internal and protected internal.

Internal indicates members are accessible from types in the same assembly. Protected internal indicates members are accessible from types in the same assembly as well as descendant classes. OO purist might object to internal and protected internal and I suggest you choose private, protected, or public over them until you both fully understand them and have a need that is best suited by them.

The default for class and class members is Internal (members are accessible from types in the same assembly). This is different than with interfaces where the default for an interface is Internal but an interface's members are always public -- which makes sense but is noteworthy.

With both classes and interfaces, if you make a class public, the members are public. This applies to the other access modifiers too. For example, if you make a class protected, the members default access modifiers are protected.

public class Cyborg
{
private String FName;
}
Posted By Mike Prestwood, Post #101736, KB Topic: OOP
C# Base Class (System.Object)

In C#, the Object keyword is an alias for the base System.Object class and is the single base class all classes ultimately inherit from.

//Specify both namespace and class:
public class Cyborg : System.Object 
{ }
  
//Use shortcut alias:
public class Cyborg : Object 
{ }
  
//None, default is System.Object
public class Cyborg
{ }
Posted By Mike Prestwood, Post #101408, KB Topic: OOP
C# Class..Object (class...new)

In C#, you use the class keyword to specify a class and you signify its parent with a colon and the name of the parent class. When you instantiate an object from a class, you use the new keyword.

Define class:

public class Cyborg : System.Object
{
public virtual void IntroduceYourself()
{
MessageBox.Show("Hi, I do not have a name yet.");
}
}

Create object from class:

Cyborg T1 = new Cyborg();
T1.IntroduceYourself();
//No need to clean up with managed classes.
//The garbage collector will take care of it.
Posted By Mike Prestwood, Post #101399, KB Topic: OOP
C# Constructors (Use class name)

In C#, a constructor is called whenever a class or struct is created. A constructor is a method with the same name as the class with no return value and you can overload the constructor. If you do not create a constructor, C# will create an implicit constructor that initializes all member fields to their default values.

Constructors can execute at two different times. Static constructors are executed by the CLR before any objects are instantiated. Regular constructors are executed when you create an object.

public class Cyborg
{
public string CyborgName;
  
  //Constructor.
  public Cyborg(string pName)
{
CyborgName = pName;
}
}
Posted By Mike Prestwood, Post #101819, KB Topic: OOP
C# Finalizer (~ClassName)

Use a destructor to free unmanaged resources. A destructor is a method with the same name as the class but preceded with a tilde (as in ~ClassName). The destructor implicity creates an Object.Finalize method (you cannot directly call nor override the Object.Finalize method).

In C# you cannot explicitly destroy an object. Instead, the .Net Frameworks garbage collector (GC) takes care of destroying all objects. The GC destroys the objects only when necessary. Some situations of necessity are when memory is exhausted or you explicitly call the System.GC.Collect method. In general, you never need to call  System.GC.Collect.

class Cyborg {
public:
//Destructor for class Cyborg.
~Cyborg();
  {
  //Free non-managed resources here.
  }
};
Posted By Mike Prestwood, Post #101834, KB Topic: OOP
C# Inheritance-Multiple (Not Supported)

C# does not support multiple implementation inheritance. Each class can have only one parent class (a single inheritance path). In C#, you can use multiple interface usage to design in a multiple class way horizontally in a class hierarchy.

C# Interfaces (interface)

Classes and structs can inherit from interfaces in a manner similar to how classes can inherit a base class or struct, but a class or struct can inherit more than one interface and it inherits only the method names and signatures, because the interface itself contains no implementations.

class MyClass: IMyInterface
{  
  public object Clone()
{
return null;
}

// IMyInterface implemented here...
}
interface IMyInterface
{
  bool IsValid();
}
Posted By Mike Prestwood, Post #101435, KB Topic: OOP
C# Member Field

In C# you can set the visibility of a member field to any visibility: private, protected, public, internal or protected internal.

You can intialize a member field with a default when declared. If you set the member field value in your constructor, it will override the default value.

Finally, you can use the static modifier (no instance required) and readonly modifier (similar to a constant).

public class Cyborg : System.Object
{
  private string serialNumber = "A100";
 
  public string cyborgName; 
  public int cyborgAge = 0;
  public static readonly int seriesID = 100;
}
Posted By Mike Prestwood, Post #101824, KB Topic: OOP
C# Member Method

In C# you can set the visibility of a member field to any visibility: private, protected, public, internal or protected internal. You can intialize a member field with a default when declared. If you set the member field value in your constructor, it will override the default value. Finally, you can use the static modifier (no instance required) and readonly modifier (similar to a constant).

Define class:

public class Cyborg : System.Object
{
public virtual void IntroduceYourself()
{
MessageBox.Show("Hi, I do not have a name yet.");
}
}

Create object from class:

Cyborg T1 = new Cyborg();
T1.IntroduceYourself();
Posted By Mike Prestwood, Post #101744, KB Topic: OOP
C# Member Modifiers

The method modifiers are abstract, extern, new, partial, sealed, virtual, and override. Specify C# member modifiers as follows:

abstract SomeMethod() {..}

The field modifiers are const, readonly, static, volatile. Specify field modifiers as follows:

readonly int MyAge;

C# Member Property (no (), get, set)

In C#, parens indicate a method and the lack of parens indicate a property. You use special get and set methods to both get and set the values of properties. For a read-only property, leave out the set method. The value keyword is used to refer to the member field. Properties can make use of any of the access modifiers (private, protected, etc). It is common to use a lowercase member names for member fields ("name" in our example) and uppercase properties to manage member fields ("Name" in our example).

public class Cyborg : System.Object
{
  private string cyborgName;
 
  public string CyborgName
  {
  get {return cyborgName;}
  set {cyborgName = value;}
  }

}
Posted By Mike Prestwood, Post #101738, KB Topic: OOP
C# Overriding (virtual, override)

Method overriding allows you to define or implement a virtual method in a parent class and then replace it in a descendant class. In C#, you specify a virtual method with the virtual keyword in a parent class and replace it in a descendant class using the override keyword.

class Robot
{
  public virtual void Speak()
  {
  }
}

class Cyborg:Robot
{
  public override void Speak()
  {
  }
}
Posted By Mike Prestwood, Post #101472, KB Topic: OOP
C# Partial Classes (partial)

C# uses the keyword partial to specify a partial class. All parts must be in the same namespace.

A partial class, or partial type, is a class that can be split into two or more source code files and/or two or more locations within the same source file. Each partial class is known as a class part or just a part. Logically, partial classes do not make any difference to the compiler. The compiler puts the class together at compile time and treats the final class or type as a single entity exactly the same as if all the source code was in a single location.

You can use them for many things including to separate code generator code, organize large classes, divice a class up so you can split ownwership among multiple developers, have different versions of the same class, and to utilize multiple languages with a single class.

class partial Cyborg: System.Object
{
}
Posted By Mike Prestwood, Post #101807, KB Topic: OOP
C# Polymorphism

C# supports the following types of polymorphism:

C# Prevent Derivation (sealed)

With C#, use the sealed keyword to prevent a class from being inherited from and to prevent a method from being overridden.

A method marked sealed must override an ancestor method. If you mark a class sealed, all members are implicitly not overridable so the sealed keyword on members is not legal.

public class Machine : System.Object
{
public virtual void Speak(String pSentence)
{
MessageBox.Show(pSentence);
}
}

public class Robot : Machine
{
public sealed override void Speak(String pSentence)
{
MessageBox.Show(pSentence);
}
}
  
public sealed class Cyborg : Robot
{
}
Posted By Mike Prestwood, Post #101423, KB Topic: OOP
C# Self Keyword (this)

To refer to the current instance of a class, use the this keyword. The this keyword provides a way to refer to the specific instance in which the code is currently executing. It is particularly useful for passing information about the currently executing instance.

The this keyword is also used as a modifier of the first parameter of an extension method.

You cannot use this with static method functions because static methods do not belong to an object instance. If you try, you'll get an error.

C# Static Members (static)

C# supports both static members and static classes using the static keyword. You can add a static method, field, property, or event to an existing class. Also, you can designate a class as static and the compiler will ensure all members in that class are static. You can add a constructor to a static class to initialize values.

The CLR automatically loads static classes with the program or namespace.

//Static Class Example
public static class MyStaticClass
{
  //Static Method Example
  public static void MyStaticMethod()
{
// static method code
}
}
Posted By Mike Prestwood, Post #101475, KB Topic: OOP
VB Classic Prevent Derivation (Not Supported)

VB Classic supports a form of single level inheritance where you, in essence, create an abstract class and then implement it in one or more classes that inherit from the abstract class. However, you cannot have any further descendant classes so "prevent derivation" is implemented by design of this simple inheritance model.




Topic: WinForms

[DllImport] attribute

This code allows you to use Win32 DLLs in your .NET applications.

public class Form1 : System.Windows.Forms.Form
{
[DllImport("GetMyCode.dll")]
public static extern string GenerateMyCode(string pProduct,
string pVersion, string pName);

// other form properties, etc...

Note that, below the [DllImport] attribute, you must declare the functions and procedures exported by the DLL you want to use.

Posted By Wes Peterson, Post #100650, KB Topic: WinForms
Q&A: Using Win32 DLLs in .NET
Question:

Can I use a Win32 DLL in my Visual Studio.Net application?

Answer:

Yes. The trick is to use the [DllImport] attribute, followed by declarations for each of the DLL's functions and procedures.

Posted By Wes Peterson, Post #100649, KB Topic: WinForms



Topic: WebForms Beginners Corner

Q&A: Get UserID using ASP.NET Built-in Membership
Question:

How do you resolve the UserID of a user when using ASP.NET 2.0's built in Membership utility?

Answer:

//GetUser() returns current user information
MembershipUser myUser = Membership.GetUser();
  

//Returns the UserID and converts to a string
string UserID = myUser.ProviderUserKey.ToString();
Posted By Stephen Berry, Post #101288, KB Topic: WebForms Beginners Corner



Topic: WebForms Coding Tasks

Consuming an RSS feed in ASP.NET

Using this quickie code snippet, you can attach an ASP:Gridview  to an external RSS Feed.

All you need to accomplish this is the URL of a usable feed.

Create a ASP AJAX webform, and drop in a GRIDVIEW control, and a button.  Double click the button control and add this code.  You'll need to add these two namespaces to your using section.

using System.Xml;
using System.Data;

This snippet will fill it with DICE ASP.NET open postings.

protected void Button1_Click(object sender, EventArgs e)
{
    XmlTextReader myReader = new
XmlTextReader("http://rss.dice.com//system/net-jobs.xml");
    DataSet myDataSet = new DataSet();
    myDataSet.ReadXml(myReader);
    GridView1.DataSource=myDataSet.Tables[3];
    GridView1.DataBind();
}
Posted By Bryan Valencia, Post #102107, KB Topic: WebForms Coding Tasks
FileUpload

Demonstrates the code required to retreive and store a file uploaded via an ASP FileUpload object.  Assumes you have a web form with a FileUpload, a button, and a label control.  Also, this example stores the file uploaded into a folder named "Uploads" which is assumed to pre-exist.

string path=Server.MapPath(@"~\Uploads");
string SaveAsName=path+@"\"+FileUpload1.FileName;
try
{
FileUpload1.SaveAs(SaveAsName);
Label1.Text = FileUpload1.FileName + " uploaded.";
}
catch(Exception err)
{
Label1.Text = err.Message;
}
Posted By Bryan Valencia, Post #100925, KB Topic: WebForms Coding Tasks
Get all components in an ASPX page recursively

Retrieves an array of all the components of any given type within a starter control (such as a page, table, panel, etc.)  This routine is recursive and will keep iterating down until all the embedded components are found.

This C# code can be invoked to produce an array as  follows:

CheckBox[] myCheckboxes = GetAllCheckboxes(Table1); 
public CheckBox[] GetAllCheckboxes(Control myControl)
{
  ArrayList myCheckboxes = new ArrayList();
 
  foreach (Control thisControl in myControl.Controls)
  {
    if (thisControl is CheckBox)
    {
      myCheckboxes.Add(thisControl);
    }
 
    if (thisControl.HasControls())
    {
      myCheckboxes.AddRange(GetAllCheckboxes(thisControl));
    }            
  }
 
  CheckBox[] result = (CheckBox[])myCheckboxes.ToArray(typeof(CheckBox));
  return result;
}
Posted By Bryan Valencia, Post #100929, KB Topic: WebForms Coding Tasks
Getting Website Root Directory in C# ASP.NET

This code shows how to ask the webserver where the site's root directory is, and how to convert a relative path (like /Uploads) to the full filesystem path.  This will work across environments (i.e. Development/QA/Production).

string ServerPath2 = Server.MapPath(@"~/");

This gives the full path to the webserver's root directory. 

Example:

"C:\\Documents and Settings\\All Users\\Documents\\Visual Studio 2008\\WebSites\\MySite\\"

string ServerPath2 = Server.MapPath(@"~/Uploads");

This gives the full path to the Uploads subdirectory - even if it is a virtual directory in another location! 

...even if it is not a browsable web directory (such as APP_CODE or APP_DATA).

Posted By Bryan Valencia, Post #101679, KB Topic: WebForms Coding Tasks
Sending email from C#.NET in 5 lines of code.

First, you must add the System.Net.Mail namespace to your project. There are 2 objects we use to send the email, a MailMessage, and an SMTPClient.

This code works from C# projects or from ASP.NET projects. Make sure your mail server is set to relay messages for whoever might be sending the message. In my case my webserver is sending through my exchange server so I had to tell exchange to relay for my webserver.

using System.Net.Mail;
--
MailMessage thisMessage = new MailMessage("from@here.com","to@there.com");
thisMessage.Subject = "Sending a quick email.";
thisMessage.Body = "A rolling stone gathers no moss.";

SmtpClient thisMailer = new SmtpClient("mailserver.com");
thisMailer.Send(thisMessage);
--
Posted By Bryan Valencia, Post #100848, KB Topic: WebForms Coding Tasks
Follow PrestwoodBoards on: 


©1995-2019 PrestwoodBoards  [Security & Privacy]
Professional IT Services: Coding | Websites | Computer Tech