Sei sulla pagina 1di 10

Tuneup Utilities

Avg PC Tuneup

w3mentor
Learning web technologies simplified!

CodeSmith Code Generator


codesmithtools.com
Template-driven. Easy to use. Your code. Your w ay. Faster!

Home
Search

8085/8086
Microprocessor Basics
C Sharp
.NET Silverlight
ASP.NET Ajax
C# ADO.NET
Access
ADO.NET Examples
C# Application Domains & Services
C# ASP.NET
C# ASP.NET LINQ
Cast
Concat
Distinct
GroupBy
Intersect
Join
OfType
OrderBy
Select
Skip/Take
Union
Where
C# ASP.NET Mail
C# ASP.NET MVC
Actions
Controller
Filters
HTML Helpers
Views
C# ASP.NET Reflection
C# Collections and Generics
C# Collections Examples
C# File Handling
C# Flow Control
C# Interoperability
C# Network Programming
C# Streams
C# Streams Examples
C# Threading
C# XML
Cryptography
Language Basics
Object Oriented Concepts C#
Csharp OOPS Examples
Windows phone 7
Input
Accelerometer
FM Radio
WPF .Net
Controls
C/C++
Arrays
Control Structures
Data Structures
File access & processing
Functions & Recursion
Interview Questions

Product Key

Serial

Pointers
User-Defined Data Types
CSS
CSS Basics
Flash
Actionscript Basics
HTML
HTML 5
HTML Basics
XHTML
Java Tutorials
Android Development
Android Http Services
Collections
Ext GWT (GXT)
Java Data Types
Java Language basics
Network Programming
Numbers & Dates
Javascript
ActiveX
Ajax
Extjs
Images and animations
Javascript & CSS
Javascript & DOM
Javascript Events
Jquery
Language basics
Object oriented Javascript
MYSQL
MYSQL Administration
MYSQL Basics
MySql Errors
MYSQL Functions
MYSQL Interview Questions
MYSQL Views
Perl
CGI
Modules
Perl Databases
Perl Email
Perl File Handling
Perl Functions
Perl Language Basics
Perl Networking
Perl string manipulation
Perl Web Services
Perl XML
PHP/MySQL Tutorials
CakePHP
Codeigniter
Language Basics
For statement
Functions
IF/ELSE Statement
Php Basics Examples
Switch statement
While statement
MongoDB
Object Oriented PHP
Classes/Objects
Constructor
Php OOPS Examples
PHP Arrays
Php Arrays Examples
PHP Cookies
PHP Date and Time
PHP Date Time Examples
PHP Design patterns
PHP File Handling
File read
PHP Flow Control

PHP Forms
Php Forms Examples
PHP Graphics
PHP Mail
PHP MYSQL
Php Mysql Examples
PHP Regular Expressions
PHP sessions
PHP Web Services
PHP XML
PHP XML Examples
Wordpress
Zend Framework
PL/SQL
PL/SQL Language Basics
PLSQL Basics Examples
PL/SQL String Manipulation
PL/SQL XML
PL/SQL Conversion
PLSQL Date Manipulation
Project Management
Cost Management
Procurement Management
Quality Management
Risk Management
Supply Chain Management
Python
Language Basics
MongoDB
Scientific computation
SAP
Introduction
Social Apps
Open Social
Social API References
Sql Server
MSSQL Basics
Transact-SQL
Video Tutorials
ASP.NET Videos
PHP Videos
Basics
Drupal Videos
Project Management Videos
Risk Management Videos
w3mentor > C Sharp

C Sharp
asp-dot-net-c-sharp

Check if a file is read only in C#


bool isReadOnly = ((File.GetAttributes(filePath) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly);

Display the call stack method names in C#


using System.Diagnostics;
[STAThread]
public static void Main()
{
//obtain call stack
StackTrace stackTrace = new StackTrace();
// obtain method calls (frames)
StackFrame[] stackFrames = stackTrace.GetFrames();
// display method names

foreach (StackFrame stackFrame in stackFrames)


{
Console.WriteLine(stackFrame.GetMethod().Name);
}

// output method name

Get Name of the calling method using Reflection in C#


using System.Diagnostics;
// get call stack
StackTrace stackTrace = new StackTrace();
// get calling method name
Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);

C# Enqueue and Dequeue queue operations


Queue<string> myQueue = new Queue<string>();
void AddQueueItem(string request)
{
myQueue.Enqueue(request) ;
}
string GetNextQueueItem()
{
return myQueue.Dequeue() ;
}

Stack push and pop in C#


Stack<string> myStack = new Stack<string>() ;
void addRecord(string move)
{
myStack.Push(move);
}
string GetLastRecord()
{
return myStack.Pop();
}

Arraylist properties and methods in C#


ArrayList alphaList = new ArrayList();
alphaList.Add("A");
alphaList.Add("D");
alphaList.Add("W");
Console.WriteLine("Original Capacity");
Console.WriteLine(alphaList.Capacity);
Console.WriteLine("Original Values");
foreach (object alpha in alphaList)
{
Console.WriteLine(alpha);
}
alphaList.Insert(alphaList.IndexOf("D") , "C");
alphaList.Insert(alphaList.IndexOf("W") , "J");
Console.WriteLine("New Capacity");
Console.WriteLine(alphaList. Capacity);
Console.WriteLine("New Values");
foreach (object alpha in alphaList)
{
Console.WriteLine(alpha);
}

Declare and fill a two-dimensional array in C#


int[, ] my2DArray = { { 1, 1 }, { 3, 5 }, { 5, 7 } };
for (int i = 0; i <= my2DArray. GetUpperBound(0) ; i++)
{
for (int x = 0; x <= my2DArray.GetUpperBound(1); x++)
{
Console.WriteLine("Index = [{0},{1}] Value = {2}", i, x, my2DArray[i, x] );
}
}

Foreach loop to iterate through the elements of the array in C#


int[] intArray = { 1, 2, 3, 4, 5 };

Console.WriteLine("Upper Bound");
Console.WriteLine(intArray. GetUpperBound(0) );
Console.WriteLine("Array elements") ;
foreach (int item in intArray)
{
Console.WriteLine(item) ;
}
Array.Reverse(intArray) ;
Console.WriteLine("Array reversed") ;
foreach (int item in intArray)
{
Console.WriteLine(item) ;
}
Array.Clear(intArray, 2, 2) ;
Console.WriteLine("Elements 2 and 3 cleared") ;
foreach (int item in intArray)
{
Console.WriteLine(item) ;
}
intArray[ 4] = 9;
Console.WriteLine("Element 4 reset");
foreach (int item in intArray)
{
Console.WriteLine(item) ;
}
Console.ReadLine();

Positioning elements on a Silverlight Canvas


The Canvas.Top and Canvas.Left attributes can be set within the children controls XAML to position within the Canvas relatively.
<UserControl x:Class='TestSilverlightApplication.MainPage'
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:d='http://schemas.microsoft.com/expression/blend/2008'
xmlns:mc='http://schemas.openxmlformats.org/markup-compatibility/2006'
mc:Ignorable='d'
d:DesignWidth='640'
d:DesignHeight='480'>
<StackPanel Orientation="Vertical" Background="Blue">
<Canvas x:Name="MyCanvas" HorizontalAlignment="Left" VerticalAlignment="Top"
Height="200" Width="400" Background="White" Margin="10">
<TextBlock Canvas.Top="10" Canvas.Left="15" FontSize="40" Foreground="Red" Text="Sample Canvas Text" />
<Rectangle Canvas.Top="40" Canvas.Left="50" Height="60" Width="100" Fill="Green" Canvas.ZIndex="-1" />
<TextBlock Canvas.Top="60" Canvas.Left="200" FontSize="20" Foreground="Gray" Text="Some More Example Text..." />
</Canvas>
</StackPanel>
</UserControl>

Set padding in silverlight code behind


Xaml:
<UserControl x:Class='TestSilverlightApplication.MainPage'
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:d='http://schemas.microsoft.com/expression/blend/2008'
xmlns:mc='http://schemas.openxmlformats.org/markup-compatibility/2006'
mc:Ignorable='d'
d:DesignWidth='640'
d:DesignHeight='480'>
<Canvas Name="canvas1">
</Canvas>
</UserControl>

Code behind:
namespace TestSilverlightApplication
{
public partial class MainPage : UserControl
{
Button mybutton = null;
public MainPage()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
mybutton = new Button { Content = "Hi and Welcome", Width = 150, Height = 25 };
mybutton.Padding = new Thickness(10, 12, 10, 12); //set the padding using thickness
Canvas.SetLeft(mybutton, 100);
Canvas.SetTop(mybutton, 124);
canvas1.Children.Add(mybutton);

}
}
}

Change canvas background in Silverlight .Net


<UserControl x:Class='TestSLApp.MainPage'
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:d='http://schemas.microsoft.com/expression/blend/2008'
xmlns:mc='http://schemas.openxmlformats.org/markup-compatibility/2006'
mc:Ignorable='d'
d:DesignWidth='640'
d:DesignHeight='480'>
<Canvas x:Name="LayoutRoot" Background="Red">
<Rectangle Canvas.Left="100"
Canvas.Top="10"
Width="40"
Height="20"
Fill="Yellow" />
</Canvas>
</UserControl>

Strip out all html tags in string using C#


The tags need not be correctly nested for the below implementation to work..
public static string RemoveHtmlTags(string pInput)
{
char[] array = new char[pInput.Length];
int arrayIndex = 0;
bool inside = false;
for (int i = 0; i < pInput.Length; i++)
{
char let = pInput[i];
if (let == '<')
{
inside = true;
continue;
}
if (let == '>')
{
inside = false;
continue;
}
if (!inside)
{
array[arrayIndex] = let;
arrayIndex++;
}
}
return new string(array, 0, arrayIndex);
}

Check if remote files exist using C#


public void CheckFile()
{
// The two different files as strings.
string urlfile1 = "http://remotehost.com/file1.zip";
string urlfile2 = "http://remotehost.com/file2.zip";
try
{
// Check to see if urlfile1 exists
HttpWebRequest myrequest = (HttpWebRequest)WebRequest.Create(urlfile1);
myrequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)myrequest.GetResponse();
Console.WriteLine(urlfile1 + "Found");
}
catch (Exception ex)
{
// Check to see if urlfile2 exists
HttpWebRequest myrequest2 = (HttpWebRequest)WebRequest.Create(urlfile2);
myrequest2.Credentials = System.Net.CredentialCache.DefaultCredentials;
HttpWebResponse response;
try
{
response = myrequest2.GetResponse() as HttpWebResponse;
}
catch (WebException exc)
{

response = exc.Response as HttpWebResponse;


}
// Check if response returns 404
if (response.StatusCode == HttpStatusCode.NotFound)
{
Console.WriteLine(urlfile1 + "Not Found");
}
else
{
if(response.StatusCode == HttpStatusCode.Ok)
{
Console.WriteLine(urlfile1 + "Found");
}
}
}

Ping a host machine to check uptime in C#


using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Text;

namespace ProgramSendPingtoHost
{
class ProgramSendPingtoHost
{
static void Main(string[] args)
{
try
{
string hostAddress = "127.0.0.1";
System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
System.Net.NetworkInformation.PingReply reply = ping.Send(hostAddress);
Console.WriteLine("The Host Address: {0}", reply.Address);
Console.WriteLine("Status of the ping: {0}", reply.Status);
Console.Read();
}
catch (Exception ex)
{
}
}
}
}

Output:

Convert Enum to Array dynamically in C#


using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Text;

namespace ProgramEmumtoArray
{
class ProgramEmumtoArray
{
static void Main(string[] args)
{
string[] people = Enum.GetNames(typeof(People));
foreach (var person in people)
{
Console.WriteLine(person);
}
Console.Read();
}
enum People
{
Gandhi, Anthony, Obama, Mani
}
}
}

Output:

Dynamic enumeration of Enum in C#

using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Text;

namespace w3mentorConsoleApp
{
class Program
{
static void Main(string[] args)
{
foreach (var car in Enum.GetValues(typeof(Cars)))
{
Console.WriteLine(Enum.GetName(typeof(Cars), car));
}
Console.Read();
}
enum Cars
{
Ferrari, Polo, GMC, FordExplorer
}
}
}

Output:

Sorting a hashtable in C#
Hashtable myHashTable = new Hashtable();
myHashTable.Add("1", "dotnet");
myHashTable.Add("2", "tutorials");
myHashTable.Add("3", "w3mentor");
List<int> myList = new List<int>();
foreach (var key in hash.Keys)
{
myList.Add(int.Parse(key.ToString()));
}
//sort the hashtable
myList.Sort();
foreach (var item in myList)
{
Console.WriteLine(string.Format("{0},{1}", item, hash[item.ToString()]));
}
Console.Read();

Cloning C# objects using MemberwiseClone


public CarClass GetCopy()
{
return MemberwiseClone() as CarClass;
}
CarClass beta = new CarClass();
CarClass newcar = beta.GetCopy();
bool areCarsEqual = ReferenceEquals(beta, newcar);
Console.WriteLine("Are cars Equal?: {0}",areCarsEqual);

Example of stringbuilder append operation in C#


void demoAppendSB()
{
StringBuilder sb;
sb = new StringBuilder("This is the existing text");
sb.Append("This will be appended");
Console.WriteLine("sb.Append(\"Appended\"): {0}",sb);
}

Delete newly created file from directory in C#


void deleteNewFile(string dirPath)
{
DirectoryInfo directInfo = new DirectoryInfo(dirPath); //read directory to enumerate files
FileInfo[] filelist = directInfo.GetFiles();
var fileList = from n in filelist select new { FileName = n.FullName, CreationDate = n.CreationTime.ToLongDateString() }; //get list of files by

var latestFile = (from m in fileList orderby m.CreationDate descending select m.FileName).First<string>(); //get the first file from the sorted l
Console.WriteLine(latestFile); //display filename before deleting

FileInfo file = new FileInfo(latestFile);


file.Delete();
Console.WriteLine(latestFile + " has been deleted");
Console.ReadKey();
}

Latest Tutorials & Code Snippets


Randomly select element from python list
Use append to merge two lists in python
Merge two lists in python
Display 5 posts in wordpress using wp_query
Display post title and content in wordpress theme
Common template tags in wordpress
Simple wordpress data loop
connect asynchronously to sql server
Test for websockets support in browser
websockets bufferedAmount example
Test if two matrices are equal in C#
Create identity matrix in C#
Parallel matrix multiplication in C# using task parallel library
Matrix multiplication in C#
Create matrix in C#
TreeMap in Java
HashMap in Java
Use TreeSet to parse sentences for word count in Java
HashSet in Java
PriorityQueue in Java
Reference Guides
C Library Functions
C# simple data types reference
Correlation between the UTF-8, UTF-16 and UTF-32
CSS 2 Reference Guide
Decimal, binary, octal and hexadecimal equivalents
HTML 5 Deprecated Attributes
HTML 5 Deprecated Tags
HTML 5 Tags Reference
HTML Character Encoding
HTML Deprecated Tags
HTML Entities
HTML Fonts Reference
HTML Quick Reference
HTML URL Encoding
HTML/XHTML Tags Reference
Javascript Events Reference
Javascript Functions Guide
jQuery Quick Reference
Media Kit
New types for input tag in HTML 5
PERL Functions Reference
Standard C string library functions
Tags introduced in HTML 5
Unicode Character Ranges Reference
Unix commands guide
Previous Page Next Page

Popular Tags

arrays assembly class command line computation contract database data types directory email error events example file file handling filestream form post form processing
functions Globals interview
query

questions logistics looping mail M VC numerical object object oriented quality read reference regex risk rpc serialization sessions social socket sql

string t ime variables views xml xml parsing

Home | Site Map | About W3mentor | Contact Us | FAQ | Link to W3mentor

Copyright 2012 Dotfluent Network.