UdpClient could not be found - c#

I am a newby programming in c# and have the following question. I want to make a program which receives Udp broadcast. In my program I want use UdpClient but got the message that the namespace could not be found. I have included System.Net.Sockets in my program. Could anybody help me to solve this?
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace Console
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
UdpClient udpClient = new UdpClient(11000);
public App()
{
Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(
Microsoft.ApplicationInsights.WindowsCollectors.Metadata |
Microsoft.ApplicationInsights.WindowsCollectors.Session);
this.InitializeComponent();
this.Suspending += OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
this.DebugSettings.EnableFrameRateCounter = true;
}
#endif
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
}
}

Good Afternoon Wamor:
I just created a class in my WPF Project and it compiled just fine:
What type of project are you working on? This is Visual Studio 2013 Targeting .Net Framework 4.5
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace HalliburtonCallouts.ViewModel
{
public class UPPClass
{
public UPPClass()
{
// This constructor arbitrarily assigns the local port number.
UdpClient udpClient = new UdpClient(11000);
try
{
udpClient.Connect("www.contoso.com", 11000);
// Sends a message to the host to which you have connected.
Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there?");
udpClient.Send(sendBytes, sendBytes.Length);
// Sends a message to a different host using optional hostname and port parameters.
UdpClient udpClientB = new UdpClient();
udpClientB.Send(sendBytes, sendBytes.Length, "AlternateHostMachineName", 11000);
//IPEndPoint object will allow us to read datagrams sent from any source.
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
// Uses the IPEndPoint object to determine which of these two hosts responded.
Console.WriteLine("This is the message you received " +
returnData.ToString());
Console.WriteLine("This message was sent from " +
RemoteIpEndPoint.Address.ToString() +
" on their port number " +
RemoteIpEndPoint.Port.ToString());
udpClient.Close();
udpClientB.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}

Hello Wamor: Your Code ahad alot of usings and things that my system was struggling to find: I think that this answer can help you I just compiled your code while commenting the other items out with four comment chars '////' The point is the UDPClient was found:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
////using System.Windows.ApplicationModel;
////using Windows.ApplicationModel.Activation;
////using Windows.Foundation;
////using Windows.Foundation.Collections;
////using Windows.UI.Xaml;
////using Windows.UI.Xaml.Controls;
////using Windows.UI.Xaml.Controls.Primitives;
////using Windows.UI.Xaml.Data;
////using Windows.UI.Xaml.Input;
////using Windows.UI.Xaml.Media;
////using Windows.UI.Xaml.Navigation;
namespace Console
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
UdpClient udpClient = new UdpClient(11000);
public App()
{
////Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(
//// Microsoft.ApplicationInsights.WindowsCollectors.Metadata |
//// Microsoft.ApplicationInsights.WindowsCollectors.Session);
////this.InitializeComponent();
////this.Suspending += OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
//// protected override void OnLaunched(LaunchActivatedEventArgs e)
//// {
////#if DEBUG
//// if (System.Diagnostics.Debugger.IsAttached)
//// {
//// this.DebugSettings.EnableFrameRateCounter = true;
//// }
////#endif
//// Frame rootFrame = Window.Current.Content as Frame;
//// // Do not repeat app initialization when the Window already has content,
//// // just ensure that the window is active
//// if (rootFrame == null)
//// {
//// // Create a Frame to act as the navigation context and navigate to the first page
//// rootFrame = new Frame();
//// rootFrame.NavigationFailed += OnNavigationFailed;
//// if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
//// {
//// //TODO: Load state from previously suspended application
//// }
//// // Place the frame in the current Window
//// Window.Current.Content = rootFrame;
//// }
//// if (rootFrame.Content == null)
//// {
//// // When the navigation stack isn't restored navigate to the first page,
//// // configuring the new page by passing required information as a navigation
//// // parameter
//// rootFrame.Navigate(typeof(MainPage), e.Arguments);
//// }
//// // Ensure the current window is active
//// Window.Current.Activate();
//// }
//// /// <summary>
//// /// Invoked when Navigation to a certain page fails
//// /// </summary>
//// /// <param name="sender">The Frame which failed navigation</param>
//// /// <param name="e">Details about the navigation failure</param>
//// void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
//// {
//// throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
//// }
//// /// <summary>
//// /// Invoked when application execution is being suspended. Application state is saved
//// /// without knowing whether the application will be terminated or resumed with the contents
//// /// of memory still intact.
//// /// </summary>
//// /// <param name="sender">The source of the suspend request.</param>
//// /// <param name="e">Details about the suspend request.</param>
//// private void OnSuspending(object sender, SuspendingEventArgs e)
//// {
//// var deferral = e.SuspendingOperation.GetDeferral();
//// //TODO: Save application state and stop any background activity
//// deferral.Complete();
//// }
}
}

Related

Delete Rows Start in CSV file In SSIS Controlflow Script Task

I have a .csv file that looks like this:
#Example Company
#(999) 999-9999
#http://yourwebsite.com
#Report Date Range: Dec 26, 2013 - Dec 26, 2013
#Exported: Dec 26, 2013
#Twitter : Profile Summary
#Screen Name,Name,Description,Location,Followers,Following,Listed
SctaSa,statisticalgraph,statistical Screen- The official account for your
organization,Saudi Arabia,6775,8,75
So, I need to take specific data from the .csv file to be readable to SSIS Transformation, start from column "Screen Name" and remove the garbage data which start with # , to be look like that
Screen Name,Name,Description,Location,Followers,Following,Listed,Exported,Report Date Range
SctaSa,statisticalgraph,statistical Screen- The official account for your organization,Saudi Arabia,6775,8,75,26-Dec-13,26-Dec-13
i tried to use this C# script but it does not wore file (I'm not an expert in C# so I don't know what the problem is) I tried to use the following script to delete any line start with # but the file dose not transfare to the out put path; could you give me any suggestions?!
#region Namespaces
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.IO;
using System.Collections.Generic;
#endregion
namespace ST_a7b941606e0b40aa920bfe13fc81dc81
{
/// <summary>
/// ScriptMain is the entry point class of the script. Do not change the name, attributes,
/// or parent of this class.
/// </summary>
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
protected void Page_Load(object sender, EventArgs e)
{
var lines = new List<string>();
string line;
using (var file = new System.IO.StreamReader("D:\\try.csv"))
{
while ((line = file.ReadLine()) != null)
{
if (line.Length != 0)
{
if (!line.StartsWith("#") )
{
lines.Add(line);
}
}
}
}
File.WriteAllLines("D:\\SCTA_ETL\\try.csv", lines);
}
/// <summary>
/// This method is called when this script task executes in the control flow.
/// Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
/// To open Help, press F1.
/// </summary>
public void Main()
{
// TODO: Add your code here
Dts.TaskResult = (int)ScriptResults.Success;
}
#region ScriptResults declaration
/// <summary>
/// This enum provides a convenient shorthand within the scope of this class for setting the
/// result of the script.
///
/// This code was generated automatically.
/// </summary>
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
}
}
Another way:
File.WriteAllLines(outputPath, File.ReadAllLines("c:\\mycsv.csv").Where(x => !x.StartsWith("#")).ToArray());
You might want to change your logic in the middle:
var lines = new List<string>();
string outputPath = // your output path here
using (var file = new System.IO.StreamReader("c:\\mycsv.csv"))
{
string line;
while ((line = file.ReadLine()) != null)
{
if (!line.StartsWith("#"))
{
lines.Add(line);
}
}
}
File.WriteAllLines(outputPath, lines);
You had been removing all lines that had "#" anywhere inside.
Instead, only add in lines that do not start with "#".
Also, be sure to close and dispose your StreamReader when you are done with it, or just put the whole thing in using section.

Client / Server multi threaded using TCP Listener and Streamreader / writer

I've been asked to write a Client / Server application in C#, and have been given half-completed code to get started.
It uses the ThreadPool, and TcpListener with StreamReader and StreamWriter classes for data transfer.The client has a working directory, which is fixed. The server has one too, but can change.
Basically, you type in an option on the client using a switch statement, and the server processes that option and sends it back to the client.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Security.Cryptography;
namespace Client
{
/// <summary>
/// Remote File Service client
/// </summary>
class Client
{
/// <summary>
/// Static entry point to client code
/// </summary>
/// <param name="args">unused</param>
static void Main(string[] args)
{
string dir = #"c:\st12_13d1_files";
try
{
Directory.SetCurrentDirectory(dir);
}
catch (DirectoryNotFoundException e)
{
Console.WriteLine("The specified directory does not exist. {0}", e);
}
try
{
using (TcpClient client = new TcpClient("localhost", 50012))
using (NetworkStream stream = client.GetStream())
using (StreamReader reader = new StreamReader(stream))
using (StreamWriter writer = new StreamWriter(stream))
{
writer.AutoFlush = true;
string option;
do
{
Console.WriteLine("-Menu-\n");
Console.WriteLine("1-Print out file names-\n");
Console.WriteLine("2-Current Working Directory-\n");
Console.WriteLine("3-Files Present on the Server-\n");
Console.WriteLine("4- List of Subdirectory Names-\n");
Console.WriteLine("5- Change Server Directory Location-\n");
Console.WriteLine("6-Copy the contents of a file specified-\n");
Console.WriteLine("7-Close-\n");
Console.WriteLine("Please enter your choice: ");
option = Console.ReadLine();
switch (option)
{
case "1":
case "one":
Console.WriteLine("You have selected Print out file names: ");
break;
}
using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
using System.Threading;
using System.Security.Cryptography;
namespace Server
{
/// <summary>
/// Remote File Service main functionality
/// </summary>
public class ServerMainline
{
public ServerMainline()
{
/*
* *** TO DO - your code goes here ***
* record initial current working directory value in a global variable
*/
string serv = (#"..\..");
try
{
//Set the current directory.
Directory.SetCurrentDirectory(serv);
}
catch (DirectoryNotFoundException e)
{
Console.WriteLine("The specified directory does not exist. {0}", e);
}
TcpListener server = null;
try
{
ThreadPool.SetMaxThreads(50, 50);
server = new TcpListener(IPAddress.Any, 50012);
server.Start();
while (true)
{
Console.WriteLine("Waiting for a new Client...");
TcpClient client = server.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(serviceClient, client);
}
}
catch (Exception e)
{
Console.WriteLine("Server mainline: SocketException: {0}", e);
}
finally
{
server.Stop();
server.Server.Close();
}
}
/// <summary>
/// method to run to handle each client on separate thread
/// </summary>
void serviceClient(object clientObject)
{
Thread currentThread = Thread.CurrentThread;
int threadID = currentThread.GetHashCode();
try
{
using (TcpClient client = (TcpClient)clientObject)
using (NetworkStream stream = client.GetStream())
using (StreamReader reader = new StreamReader(stream))
using (StreamWriter writer = new StreamWriter(stream))
{
writer.AutoFlush = true;
Console.WriteLine("Connected with a client, threadID: {0}", threadID);
string option = reader.ReadLine();
while (option != "7")
switch (option)
{
case "1":
case "one":
string[] myfiles = Directory.GetFiles(#"c:\st12_13d1_files");
Console.WriteLine("File Names {0}",Directory.GetFiles
(#"c:\st12_13d1_files"));
foreach (string file in myfiles)
{
//Console.WriteLine(file);
Console.WriteLine(Path.GetFileName(file));
writer.WriteLine(myfiles);
}
break;
}
With all due respect, I don't think it's appropriate to ask others to complete your homework assignments for you.
As a student, it should be your job to research (there are any number of TCP socket demos and tutorials on the web) and experiment with several solutions before resorting to asking others for help.
Software development is as much art as it is science and it requires that you spend time practicing your art. You cannot learn to be a great programmer by reading books and having others do your work for you.
Voting to close.
Update: Not wanting to be a complete curmudgeon, here are some links to some tutorials that should help you really get to grips with async TCP/socket programming:
Learn C# Socket Programming
What is a good tutorial/howto on .net / c# socket programming

Creating persistent RAS connection with opennetcf Ras in Windows CE 6.0

I'm in need to create an GPRS connection in an PDA that has windows ce 6. Now normally i would had to use the manufacturer's dll to create that, but they said that they use ras to accomplish this. The only problem of using that is that i program in .net c#, and the library is an unmanaged code one.
Fortunately i came by the opennetcf ras library that does already the necessary pInvokes for the windows ras library, the only problem being the poor documentation.
I created then an library that would call and set-up the necessary GPRS connection on windows. I'm using an Portuguese telecom operator that uses the following definitions:
Operator Name: Optimus P
Apn: umts
Password: *******
User: ******
Consulting the gsm module definition, i had the following modem settings:
Connection Name: GPRS
Device: Hayes Compatible on COM1:
Baund Rate:115200
Data Bits: 8
Parity:1
Stop Bits: 1
Flow Control: Hardware
and of course the extra settings (or how i call it the atCall)
+cgdcont=1, "ip", "umts"
This settings when i use the control panel and do an connect with that profile, it connects and i'm able to call all the webservices without an error. It also shows an extra profile for the modem that shows the settings for the device, incluid the ipaddress, subnet mask and even the default gateway.
The problem is that when i use the library that i created to create an gprs connection programatically, and then call the webservices at some point it throws me an web exception : The remote name could not be resolved. I also checked and the extra icon does not appear, but if i see the GPRS status it appears as it is connected.
The code that create, destroys and query if it exists an connection is as follows:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using OpenNETCF.Net;
using OpenNETCF.Diagnostics;
namespace gsmAdapterNet
{
/// <summary>
/// GPRS Connection class
/// </summary>
public class GPRS
{
private static string connectionName = "GPRS";
/// <summary>
/// Connects the GPRS.
/// </summary>
/// <returns></returns>
public static bool ConnectGPRS()
{
//precisamos de obter as connecoes e ligar
RasEntryCollection connecoesPossiveis = Ras.Entries;
RasEntry _currentEntry = connecoesPossiveis[connectionName];
_currentEntry.RasStatus += new RasNotificationHandler(RasStatusHandler);
RasError resultado = _currentEntry.Dial(false);
if (resultado == RasError.Success)
return true;
else
return false;
}
static void RasStatusHandler(int hConn, RasConnState State, RasError ErrorCode)
{
Logger.WriteLine("");
Logger.WriteLine("RAS STATUS: " + ErrorCode.ToString() + " , State: " + State.ToString());
}
/// <summary>
/// Disconnects the GPRS.
/// </summary>
/// <returns></returns>
public static void DisconnectGPRS()
{
RasEntryCollection entradas = Ras.Entries;
foreach (RasEntry possivelEntrada in entradas)
{
if (possivelEntrada.Name == connectionName)
{
possivelEntrada.Hangup();
}
}
}
/// <summary>
/// Determines whether this instance is connected.
/// </summary>
/// <returns>
/// <c>true</c> if this instance is connected; otherwise, <c>false</c>.
/// </returns>
public static bool isConnected()
{
RasConnection[] conecoes = Ras.ActiveConnections;
foreach (RasConnection conecao in conecoes)
{
if (conecao.Name == connectionName)
return true;
}
return false;
}
/// <summary>
/// Dumps the ras entries.
/// </summary>
public static void DumpRasEntries()
{
foreach (RasEntry entry in Ras.Entries)
{
Logger.DumpRasEntry(entry);
}
}
}
}
So resuming the question is how i can create an viable connection with the opennetcf ras library
Best Greetings
It seems as if the network interface for the GPRS connection that you get when dialing in is not configured with the correct DNS servers. Alternatively, the domain names needed for your service calls may be wrong.
To verify this:
Is it only a specific web service whose domain name cannot be resolved? Is it always the same? Do others work? Can you simply HTTP GET something like http://stackoverflow.com programmatically after the connection has been established?

stop cassiniDev after stop testing

i run cassiniDev from cmd
C:\CruiseControl.NET-1.5.0.6237\cassinidev.3.5.0.5.src-repack\CassiniDev\bin\Debug\CassiniDev.exe /a:D:_CCNET\proj /pm:Specific /p:3811
and then start debugging and testing. How can i stop cassiniDev from CMD after i finished testing. I try with cassiniDev_console but console not working so i am using cassiniDev from console.
First, glad to see someone is getting use out of CassiniDev, and to answer your question:
You can start it with the timeout param: /t:[ms till kill]
C:\CruiseControl.NET-1.5.0.6237\cassinidev.3.5.0.5.src-repack\CassiniDev\bin\Debug\CassiniDev.exe /a:D:_CCNET\proj /pm:Specific /p:3811 /t:20000
This will tell the app to shutdown after 20 seconds without a request.
Regarding the console app failing: The repack should have solved the issues with the console build. Can you add an issue and describe the problem.
Secondly, you may notice in the console project a type called Fixture that, if you follow the example NUnit tests, can be used to capably host the server in a test fixture and shut it down when the test completes.
Thirdly, CassiniDev was created to enable an easy to use ASP.Net server on an IP other than loopback.
Your command line indicates that you do not require this so you may have a better experience using a more native method, such as simply hosting the WebDevHost.
I plan to advertise this alternate possibility on the CassiniDev page soon. Looks like I should hurry up. ;-)
Try this:
Sample Test Fixture
using System.Net;
using NUnit.Framework;
namespace Salient.Excerpts
{
[TestFixture]
public class WebHostServerFixture : WebHostServer
{
[TestFixtureSetUp]
public void TestFixtureSetUp()
{
StartServer(#"..\..\..\..\TestSite");
// is the equivalent of
// StartServer(#"..\..\..\..\TestSite",
// GetAvailablePort(8000, 10000, IPAddress.Loopback, true), "/", "localhost");
}
[TestFixtureTearDown]
public void TestFixtureTearDown()
{
StopServer();
}
[Test]
public void Test()
{
// while a reference to the web app under test is not necessary,
// if you do add a reference to this test project you may F5 debug your tests.
// if you debug this test you will break in Default.aspx.cs
string html = new WebClient().DownloadString(NormalizeUri("Default.aspx"));
}
}
}
WebHostServer.cs
// Project: Salient
// http://salient.codeplex.com
// Date: April 16 2010
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Threading;
using Microsoft.VisualStudio.WebHost;
namespace Salient.Excerpts
{
/// <summary>
/// A general purpose Microsoft.VisualStudio.WebHost.Server test fixture.
/// WebHost.Server is the core of the Visual Studio Development Server (WebDev.WebServer).
///
/// This server is run in-process and may be used in F5 debugging.
/// </summary>
/// <remarks>
/// If you are adding this source code to a new project, You will need to
/// manually add a reference to WebDev.WebHost.dll to your project. It cannot
/// be added from within Visual Studio.
///
/// Please see the Readme.txt accompanying this code for details.
/// </remarks>
/// NOTE: code from various namespaces/classes in the Salient project have been merged into this
/// single class for this post in the interest of brevity
public class WebHostServer
{
private Server _server;
public string ApplicationPath { get; private set; }
public string HostName { get; private set; }
public int Port { get; private set; }
public string VirtualPath { get; private set; }
public string RootUrl
{
get { return string.Format(CultureInfo.InvariantCulture, "http://{0}:{1}{2}", HostName, Port, VirtualPath); }
}
/// <summary>
/// Combine the RootUrl of the running web application with the relative url specified.
/// </summary>
public virtual Uri NormalizeUri(string relativeUrl)
{
return new Uri(RootUrl + relativeUrl);
}
/// <summary>
/// Will start "localhost" on first available port in the range 8000-10000 with vpath "/"
/// </summary>
/// <param name="applicationPath"></param>
public void StartServer(string applicationPath)
{
StartServer(applicationPath, GetAvailablePort(8000, 10000, IPAddress.Loopback, true), "/", "localhost");
}
/// <summary>
/// </summary>
/// <param name="applicationPath">Physical path to application.</param>
/// <param name="port">Port to listen on.</param>
/// <param name="virtualPath">Optional. defaults to "/"</param>
/// <param name="hostName">Optional. Is used to construct RootUrl. Defaults to "localhost"</param>
public void StartServer(string applicationPath, int port, string virtualPath, string hostName)
{
if (_server != null)
{
throw new InvalidOperationException("Server already started");
}
// WebHost.Server will not run on any other IP
IPAddress ipAddress = IPAddress.Loopback;
if(!IsPortAvailable(ipAddress, port))
{
throw new Exception(string.Format("Port {0} is in use.", port));
}
applicationPath = Path.GetFullPath(applicationPath);
virtualPath = String.Format("/{0}/", (virtualPath ?? string.Empty).Trim('/')).Replace("//", "/");
_server = new Server(port, virtualPath, applicationPath, false, false);
_server.Start();
ApplicationPath = applicationPath;
Port = port;
VirtualPath = virtualPath;
HostName = string.IsNullOrEmpty(hostName) ? "localhost" : hostName;
}
/// <summary>
/// Stops the server.
/// </summary>
public void StopServer()
{
if (_server != null)
{
_server.Stop();
_server = null;
// allow some time to release the port
Thread.Sleep(100);
}
}
public void Dispose()
{
StopServer();
}
/// <summary>
/// Gently polls specified IP:Port to determine if it is available.
/// </summary>
/// <param name="ipAddress"></param>
/// <param name="port"></param>
public static bool IsPortAvailable(IPAddress ipAddress, int port)
{
bool portAvailable = false;
for (int i = 0; i < 5; i++)
{
portAvailable = GetAvailablePort(port, port, ipAddress, true) == port;
if (portAvailable)
{
break;
}
// be a little patient and wait for the port if necessary,
// the previous occupant may have just vacated
Thread.Sleep(100);
}
return portAvailable;
}
/// <summary>
/// Returns first available port on the specified IP address.
/// The port scan excludes ports that are open on ANY loopback adapter.
///
/// If the address upon which a port is requested is an 'ANY' address all
/// ports that are open on ANY IP are excluded.
/// </summary>
/// <param name="rangeStart"></param>
/// <param name="rangeEnd"></param>
/// <param name="ip">The IP address upon which to search for available port.</param>
/// <param name="includeIdlePorts">If true includes ports in TIME_WAIT state in results.
/// TIME_WAIT state is typically cool down period for recently released ports.</param>
/// <returns></returns>
public static int GetAvailablePort(int rangeStart, int rangeEnd, IPAddress ip, bool includeIdlePorts)
{
IPGlobalProperties ipProps = IPGlobalProperties.GetIPGlobalProperties();
// if the ip we want a port on is an 'any' or loopback port we need to exclude all ports that are active on any IP
Func<IPAddress, bool> isIpAnyOrLoopBack = i => IPAddress.Any.Equals(i) ||
IPAddress.IPv6Any.Equals(i) ||
IPAddress.Loopback.Equals(i) ||
IPAddress.IPv6Loopback.
Equals(i);
// get all active ports on specified IP.
List<ushort> excludedPorts = new List<ushort>();
// if a port is open on an 'any' or 'loopback' interface then include it in the excludedPorts
excludedPorts.AddRange(from n in ipProps.GetActiveTcpConnections()
where
n.LocalEndPoint.Port >= rangeStart &&
n.LocalEndPoint.Port <= rangeEnd && (
isIpAnyOrLoopBack(ip) || n.LocalEndPoint.Address.Equals(ip) ||
isIpAnyOrLoopBack(n.LocalEndPoint.Address)) &&
(!includeIdlePorts || n.State != TcpState.TimeWait)
select (ushort)n.LocalEndPoint.Port);
excludedPorts.AddRange(from n in ipProps.GetActiveTcpListeners()
where n.Port >= rangeStart && n.Port <= rangeEnd && (
isIpAnyOrLoopBack(ip) || n.Address.Equals(ip) || isIpAnyOrLoopBack(n.Address))
select (ushort)n.Port);
excludedPorts.AddRange(from n in ipProps.GetActiveUdpListeners()
where n.Port >= rangeStart && n.Port <= rangeEnd && (
isIpAnyOrLoopBack(ip) || n.Address.Equals(ip) || isIpAnyOrLoopBack(n.Address))
select (ushort)n.Port);
excludedPorts.Sort();
for (int port = rangeStart; port <= rangeEnd; port++)
{
if (!excludedPorts.Contains((ushort)port))
{
return port;
}
}
return 0;
}
}
}
NOTE:
The Microsoft.VisualStudio.WebHost namespace is contained in the file WebDev.WebHost.dll. This file is in the GAC but it is not possible to add a reference to this assembly from within Visual Studio.
To add a reference you will need to open your .csproj file in a text editor and add the reference manually.
Look for the ItemGroup that contains the project references and add the following element:
<Reference Include="WebDev.WebHost, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=x86">
<Private>False</Private>
</Reference>
Reference: the second example from http://www.codeproject.com/KB/aspnet/test-with-vs-devserver-2.aspx
http://www.microsoft.com/whdc/devtools/debugging/default.mspx
Debugging Tools for Windows ships with kill.exe. You can use it to kill any process that matches your wish.
For your case, simply execute,
kill CassiniDev.exe

NUnit with an ASP.NET web site

I'm currently trying to upgrade our build server at work, going from having no build server to having one!
I'm using JetBrains' TeamCity (having used ReSharper for a couple of years I trust their stuff), and intend to use NUnit and MSBuild.
However, I've come up with an issue: it appears that it is not possible to test an ASP.NET web site with NUnit. I had assumed it would be possible to configure it to test App_Code after a build, however it seems that the only way to do tests nicely is through converting the web site to a web application (which my boss does not like the idea of).
How could I go about this?
Please bear in mind that the testing needs to be able to be fired automatically from TeamCity.
If you want to smoke test your site, or bang on some endpoints - see the code below.
If, on the other hand, you want to test the untestable (detestable) ASP.NET website assembly (as opposed to a web app), you are, as they say in France, S.O.L.
The assembly is a randomly named dynamically compiled assembly deep in the bowels of the framework temporary ASP.NET files, making testing close to impossible.
You really do need to consider a couple of options:
place the logic that needs testing in a seperate assembly.
change to a web application project that delivers a testable assembly.
Sorry, I don't think that you will find what you are looking for, but I could be wrong. Let's see.
Good Luck
Download Visual Studio 2008 sample with site and applicatgion.
I wrote a wrapper for WebHost.WebServer.dll which is the core of the development server that works quite well in CI. I use it all the time.
Here is a scaled down version including a usage example.
Test.cs
using System.Net;
using NUnit.Framework;
namespace Salient.Excerpts
{
[TestFixture]
public class WebHostServerFixture : WebHostServer
{
[TestFixtureSetUp]
public void TestFixtureSetUp()
{
// debug/bin/testproject/solution/siteundertest - make sense?
StartServer(#"..\..\..\..\TestSite");
// is the equivalent of
// StartServer(#"..\..\..\..\TestSite",
// GetAvailablePort(8000, 10000, IPAddress.Loopback, true), "/", "localhost");
}
[TestFixtureTearDown]
public void TestFixtureTearDown()
{
StopServer();
}
[Test]
public void Test()
{
// while a reference to the web app under test is not necessary,
// if you do add a reference to this test project you may F5 debug your tests.
// if you debug this test you will break in Default.aspx.cs
string html = new WebClient().DownloadString(NormalizeUri("Default.aspx"));
}
}
}
WebHostServer.cs
// Project: Salient
// http://salient.codeplex.com
// Date: April 16 2010
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Threading;
using Microsoft.VisualStudio.WebHost;
namespace Salient.Excerpts
{
/// <summary>
/// A general purpose Microsoft.VisualStudio.WebHost.Server test fixture.
/// WebHost.Server is the core of the Visual Studio Development Server (WebDev.WebServer).
///
/// This server is run in-process and may be used in F5 debugging.
/// </summary>
/// <remarks>
/// If you are adding this source code to a new project, You will need to
/// manually add a reference to WebDev.WebHost.dll to your project. It cannot
/// be added from within Visual Studio.
///
/// Please see the Readme.txt accompanying this code for details.
/// </remarks>
/// NOTE: code from various namespaces/classes in the Salient project have been merged into this
/// single class for this post in the interest of brevity
public class WebHostServer
{
private Server _server;
public string ApplicationPath { get; private set; }
public string HostName { get; private set; }
public int Port { get; private set; }
public string VirtualPath { get; private set; }
public string RootUrl
{
get { return string.Format(CultureInfo.InvariantCulture, "http://{0}:{1}{2}", HostName, Port, VirtualPath); }
}
/// <summary>
/// Combine the RootUrl of the running web application with the relative url specified.
/// </summary>
public virtual Uri NormalizeUri(string relativeUrl)
{
return new Uri(RootUrl + relativeUrl);
}
/// <summary>
/// Will start "localhost" on first available port in the range 8000-10000 with vpath "/"
/// </summary>
/// <param name="applicationPath"></param>
public void StartServer(string applicationPath)
{
StartServer(applicationPath, GetAvailablePort(8000, 10000, IPAddress.Loopback, true), "/", "localhost");
}
/// <summary>
/// </summary>
/// <param name="applicationPath">Physical path to application.</param>
/// <param name="port">Port to listen on.</param>
/// <param name="virtualPath">Optional. defaults to "/"</param>
/// <param name="hostName">Optional. Is used to construct RootUrl. Defaults to "localhost"</param>
public void StartServer(string applicationPath, int port, string virtualPath, string hostName)
{
if (_server != null)
{
throw new InvalidOperationException("Server already started");
}
// WebHost.Server will not run on any other IP
IPAddress ipAddress = IPAddress.Loopback;
if(!IsPortAvailable(ipAddress, port))
{
throw new Exception(string.Format("Port {0} is in use.", port));
}
applicationPath = Path.GetFullPath(applicationPath);
virtualPath = String.Format("/{0}/", (virtualPath ?? string.Empty).Trim('/')).Replace("//", "/");
_server = new Server(port, virtualPath, applicationPath, false, false);
_server.Start();
ApplicationPath = applicationPath;
Port = port;
VirtualPath = virtualPath;
HostName = string.IsNullOrEmpty(hostName) ? "localhost" : hostName;
}
/// <summary>
/// Stops the server.
/// </summary>
public void StopServer()
{
if (_server != null)
{
_server.Stop();
_server = null;
// allow some time to release the port
Thread.Sleep(100);
}
}
public void Dispose()
{
StopServer();
}
/// <summary>
/// Gently polls specified IP:Port to determine if it is available.
/// </summary>
/// <param name="ipAddress"></param>
/// <param name="port"></param>
public static bool IsPortAvailable(IPAddress ipAddress, int port)
{
bool portAvailable = false;
for (int i = 0; i < 5; i++)
{
portAvailable = GetAvailablePort(port, port, ipAddress, true) == port;
if (portAvailable)
{
break;
}
// be a little patient and wait for the port if necessary,
// the previous occupant may have just vacated
Thread.Sleep(100);
}
return portAvailable;
}
/// <summary>
/// Returns first available port on the specified IP address.
/// The port scan excludes ports that are open on ANY loopback adapter.
///
/// If the address upon which a port is requested is an 'ANY' address all
/// ports that are open on ANY IP are excluded.
/// </summary>
/// <param name="rangeStart"></param>
/// <param name="rangeEnd"></param>
/// <param name="ip">The IP address upon which to search for available port.</param>
/// <param name="includeIdlePorts">If true includes ports in TIME_WAIT state in results.
/// TIME_WAIT state is typically cool down period for recently released ports.</param>
/// <returns></returns>
public static int GetAvailablePort(int rangeStart, int rangeEnd, IPAddress ip, bool includeIdlePorts)
{
IPGlobalProperties ipProps = IPGlobalProperties.GetIPGlobalProperties();
// if the ip we want a port on is an 'any' or loopback port we need to exclude all ports that are active on any IP
Func<IPAddress, bool> isIpAnyOrLoopBack = i => IPAddress.Any.Equals(i) ||
IPAddress.IPv6Any.Equals(i) ||
IPAddress.Loopback.Equals(i) ||
IPAddress.IPv6Loopback.
Equals(i);
// get all active ports on specified IP.
List<ushort> excludedPorts = new List<ushort>();
// if a port is open on an 'any' or 'loopback' interface then include it in the excludedPorts
excludedPorts.AddRange(from n in ipProps.GetActiveTcpConnections()
where
n.LocalEndPoint.Port >= rangeStart &&
n.LocalEndPoint.Port <= rangeEnd && (
isIpAnyOrLoopBack(ip) || n.LocalEndPoint.Address.Equals(ip) ||
isIpAnyOrLoopBack(n.LocalEndPoint.Address)) &&
(!includeIdlePorts || n.State != TcpState.TimeWait)
select (ushort)n.LocalEndPoint.Port);
excludedPorts.AddRange(from n in ipProps.GetActiveTcpListeners()
where n.Port >= rangeStart && n.Port <= rangeEnd && (
isIpAnyOrLoopBack(ip) || n.Address.Equals(ip) || isIpAnyOrLoopBack(n.Address))
select (ushort)n.Port);
excludedPorts.AddRange(from n in ipProps.GetActiveUdpListeners()
where n.Port >= rangeStart && n.Port <= rangeEnd && (
isIpAnyOrLoopBack(ip) || n.Address.Equals(ip) || isIpAnyOrLoopBack(n.Address))
select (ushort)n.Port);
excludedPorts.Sort();
for (int port = rangeStart; port <= rangeEnd; port++)
{
if (!excludedPorts.Contains((ushort)port))
{
return port;
}
}
return 0;
}
}
}
NOTE: The Microsoft.VisualStudio.WebHost namespace is contained in the file WebDev.WebHost.dll. This file is in the GAC, but it is not possible to add a reference to this assembly from within Visual Studio.
To add a reference you will need to open your .csproj file in a text editor and add the reference manually.
Look for the ItemGroup that contains the project references and add the following element:
<Reference Include="WebDev.WebHost, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=x86">
<Private>False</Private>
</Reference>
Reference: http://www.codeproject.com/KB/aspnet/test-with-vs-devserver-2.aspx

Categories

Resources