using System; using System.Net; using System.DirectoryServices; using System.DirectoryServices.Protocols; public class MainClass { public static void Main() { using (DirectoryEntry de = new DirectoryEntry()) { de.Path = "LDAP://yourSite/rootDSE"; de.Username = @"explorerchris"; de.Password = "password"; PropertyCollection props = de.Properties; foreach (string prop in props.PropertyNames) { PropertyValueCollection values = props[prop]; foreach (string val in values) { Console.Write(prop + ": "); Console.WriteLine(val); } } } } }
Author: coder
Using DirectorySearcher
using System; using System.Net; using System.DirectoryServices; public class MainClass { public static void Main() { using (DirectoryEntry de = new DirectoryEntry("LDAP://yourV/OU=yourV, DC=explorer, DC=local")) using (DirectorySearcher searcher = new DirectorySearcher()) { de.Username = @"exploreryourName"; de.Password = "password"; searcher.SearchRoot = de; searcher.Filter = "(&(objectClass=user)(description=Auth*))"; searcher.SearchScope = System.DirectoryServices.SearchScope.Subtree; searcher.PropertiesToLoad.Add("name"); searcher.PropertiesToLoad.Add("description"); searcher.PropertiesToLoad.Add("givenName"); searcher.PropertiesToLoad.Add("wWWHomePage"); searcher.Sort = new SortOption("givenName", SortDirection.Ascending); SearchResultCollection results = searcher.FindAll(); foreach (SearchResult result in results) { ResultPropertyCollection props = result.Properties; foreach (string propName in props.PropertyNames) { Console.Write(propName + ": "); Console.WriteLine(props[propName][0]); } } } } }
Web server
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
class MainClass {
private static int maxRequestHandlers = 5;
private static int requestHandlerID = 0;
private static HttpListener listener;
private static void RequestHandler(IAsyncResult result) {
try {
HttpListenerContext context = listener.EndGetContext(result);
StreamWriter sw = new StreamWriter(context.Response.OutputStream, Encoding.UTF8);
sw.WriteLine(“
sw.WriteLine(“” + result.AsyncState);
sw.WriteLine(““);
sw.Flush();
context.Response.ContentType = “text/html”;
context.Response.ContentEncoding = Encoding.UTF8;
context.Response.Close();
} catch (ObjectDisposedException) {
Console.WriteLine(result.AsyncState);
} finally {
if (listener.IsListening) {
listener.BeginGetContext(RequestHandler, “RequestHandler_” + Interlocked.Increment(ref requestHandlerID));
}
}
}
public static void Main(string[] args) {
using (listener = new HttpListener()) {
listener.Prefixes.Add(“http://localhost:8080/”);
listener.Start();
for (int count = 0; count < maxRequestHandlers; count++) {
listener.BeginGetContext(RequestHandler, "RequestHandler_" +
Interlocked.Increment(ref requestHandlerID));
}
Console.WriteLine("Press Enter to stop the HTTP Server");
Console.ReadLine();
listener.Stop();
listener.Abort();
}
}
}
[/csharp]
Get HTTP Response headers
using System; using System.IO; using System.Net; public class TryHttpRequest { public static void Main(String [] args) { HttpWebRequest request =(HttpWebRequest)WebRequest.Create("http://www.kutayzorlu.com/java2s/com"); HttpWebResponse response =(HttpWebResponse)request.GetResponse(); request.Accept = "text/plain"; Console.WriteLine("Response headers"); Console.WriteLine(" Protocol version: {0}", response.ProtocolVersion); Console.WriteLine(" Status code: {0}",response.StatusCode); Console.WriteLine(" Status description: {0}",response.StatusDescription); Console.WriteLine(" Content encoding: {0}",response.ContentEncoding); Console.WriteLine(" Content length: {0}",response.ContentLength); Console.WriteLine(" Content type: {0}",response.ContentType); Console.WriteLine(" Last Modified: {0}",response.LastModified); Console.WriteLine(" Server: {0}", response.Server); Console.WriteLine(" Length using method: {0} ",response.GetResponseHeader("Content-Length")); } }
Get HTTP Request Headers
using System;
using System.IO;
using System.Net;
public class TryHttpRequest {
public static void Main(String [] args) {
HttpWebRequest request =(HttpWebRequest)WebRequest.Create(“http://www.kutayzorlu.com/java2s/com”);
HttpWebResponse response =(HttpWebResponse)request.GetResponse();
request.Accept = “text/plain”;
Console.WriteLine(“Request header count: {0}”,request.Headers.Count);
WebHeaderCollection header = request.Headers;
for (int i = 0; i < header.Count; i++)
Console.WriteLine(" {0} : {1}",header.GetKey(i), header[i]);
}
}
[/csharp]
Uses WebRequest and WebResponse. Tests use HTTP and the file protocol
using System;
using System.IO;
using System.Net;
public class TryWebRequest {
public static void Main(String [] args) {
WebRequest request = WebRequest.Create(“http://www.kutayzorlu.com/java2s/com”);
WebResponse response = request.GetResponse();
Console.WriteLine(“Content length: {0}”, response.ContentLength);
Console.WriteLine(“Content type: {0}
“, response.ContentType);
Console.WriteLine(“Request header count: {0}”, request.Headers.Count);
WebHeaderCollection header = request.Headers;
for (int i = 0; i < header.Count; i++)
Console.WriteLine("{0} : {1}", header.GetKey(i), header[i]);
Console.WriteLine();
StreamReader input = new StreamReader(response.GetResponseStream());
Console.WriteLine(input.ReadToEnd());
input.Close();
}
}
[/csharp]
Implements a multi-threaded Web proxy server
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// Proxy.cs — Implements a multi-threaded Web proxy server
//
// Compile this program with the following command line:
// C:>csc Proxy.cs
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.IO;
using System.Threading;
namespace nsProxyServer
{
public class ProxyServer
{
static public void Main (string [] args)
{
int Port = 3125;
if (args.Length > 0)
{
try
{
Port = Convert.ToInt32 (args[0]);
}
catch
{
Console.WriteLine (“Please enter a port number.”);
return;
}
}
try
{
// Create a listener for the proxy port
TcpListener sockServer = new TcpListener (Port);
sockServer.Start ();
while (true)
{
// Accept connections on the proxy port.
Socket socket = sockServer.AcceptSocket ();
// When AcceptSocket returns, it means there is a connection. Create
// an instance of the proxy server class and start a thread running.
clsProxyConnection proxy = new clsProxyConnection (socket);
Thread thrd = new Thread (new ThreadStart (proxy.Run));
thrd.Start ();
// While the thread is running, the main program thread will loop around
// and listen for the next connection request.
}
}
catch (IOException e)
{
Console.WriteLine (e.Message);
}
}
}
class clsProxyConnection
{
public clsProxyConnection (Socket sockClient)
{
m_sockClient = sockClient;
}
Socket m_sockClient; //, m_sockServer;
Byte [] readBuf = new Byte [1024];
Byte [] buffer = null;
Encoding ASCII = Encoding.ASCII;
public void Run ()
{
string strFromClient = “”;
try
{
// Read the incoming text on the socket/
int bytes = ReadMessage (m_sockClient,
readBuf, ref strFromClient);
// If it's empty, it's an error, so just return.
// This will termiate the thread.
if (bytes == 0)
return;
// Get the URL for the connection. The client browser sends a GET command
// followed by a space, then the URL, then and identifer for the HTTP version.
// Extract the URL as the string betweeen the spaces.
int index1 = strFromClient.IndexOf (' ');
int index2 = strFromClient.IndexOf (' ', index1 + 1);
string strClientConnection =
strFromClient.Substring (index1 + 1, index2 – index1);
if ((index1 < 0) || (index2 < 0)) { throw (new IOException ()); } // Write a messsage that we are connecting. Console.WriteLine ("Connecting to Site " + strClientConnection); Console.WriteLine ("Connection from " + m_sockClient.RemoteEndPoint); // Create a WebRequest object. WebRequest req = (WebRequest) WebRequest.Create (strClientConnection); // Get the response from the Web site. WebResponse response = req.GetResponse (); int BytesRead = 0; Byte [] Buffer = new Byte[32]; int BytesSent = 0; // Create a response stream object. Stream ResponseStream = response.GetResponseStream(); // Read the response into a buffer. BytesRead = ResponseStream.Read(Buffer,0,32); StringBuilder strResponse = new StringBuilder(""); while (BytesRead != 0) { // Pass the response back to the client strResponse.Append(Encoding.ASCII.GetString(Buffer, 0, BytesRead)); m_sockClient.Send(Buffer, BytesRead, 0); BytesSent += BytesRead; // Read the next part of the response BytesRead = ResponseStream.Read(Buffer, 0, 32); } } catch (FileNotFoundException e) { SendErrorPage (404, "File Not Found", e.Message); } catch (IOException e) { SendErrorPage (503, "Service not available", e.Message); } catch (Exception e) { SendErrorPage (404, "File Not Found", e.Message); Console.WriteLine (e.StackTrace); Console.WriteLine (e.Message); } finally { // Disconnect and close the socket. if (m_sockClient != null) { if (m_sockClient.Connected) { m_sockClient.Close (); } } } // Returning from this method will terminate the thread. } // Write an error response to the client. void SendErrorPage (int status, string strReason, string strText) { SendMessage (m_sockClient, "HTTP/1.0" + " " + status + " " + strReason + " "); SendMessage (m_sockClient, "Content-Type: text/plain" + " "); SendMessage (m_sockClient, "Proxy-Connection: close" + " "); SendMessage (m_sockClient, " "); SendMessage (m_sockClient, status + " " + strReason); SendMessage (m_sockClient, strText); } // Send a string to a socket. void SendMessage (Socket sock, string strMessage) { buffer = new Byte [strMessage.Length + 1]; int len = ASCII.GetBytes (strMessage.ToCharArray(), 0, strMessage.Length, buffer, 0); sock.Send (buffer, len, 0); } // Read a string from a socket. int ReadMessage (Socket sock, byte [] buf, ref string strMessage) { int iBytes = sock.Receive (buf, 1024, 0); strMessage = Encoding.ASCII.GetString (buf); return (iBytes); } } } [/csharp]