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
Related
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();
//// }
}
}
I have a source HTML document generated from an ASPX.
I then convert the html to PDF using ABCPDF.
The html has a signature area, which is just a text box with a border.
I need a signature field inside the PDF with a name that I can pass on.
The PDF will be sent to a third-party who will correspond with the client and then digitally sign the PDF and send it back.
Given that I have an html document, or PDF, how do I programmatically add the blank PDF signature field around the original html signature area or somehow relate the two?
Here is a sample application to demonstrate some of the things I'm doing:
namespace ABCPDFHtmlSignatureTest
{
using System.Diagnostics;
using System.IO;
using System.Reflection;
using WebSupergoo.ABCpdf8;
using WebSupergoo.ABCpdf8.Objects;
/// <summary>
/// The program.
/// </summary>
public class Program
{
/// <summary>
/// The file name.
/// </summary>
private const string FileName = #"c:\temp\pdftest.pdf";
/// <summary>
/// The application entry point.
/// </summary>
/// <param name="args">
/// The args.
/// </param>
public static void Main(string[] args)
{
var html = GetHtml();
var pdf = GetPdf(html);
/* save the PDF to disk */
File.WriteAllBytes(FileName, pdf);
/* open the PDF */
Process.Start(FileName);
}
/// <summary>
/// The get PDF.
/// </summary>
/// <param name="html">
/// The html.
/// </param>
/// <returns>
/// The <see cref="byte"/>.
/// </returns>
public static byte[] GetPdf(string html)
{
var document = new Doc();
/* Yes, generate PDF fields for the html form inputs */
document.HtmlOptions.AddForms = true;
document.AddImageHtml(html);
/* We can determine the location of the field */
var signatureRect = document.Form["Signature"].Rect;
MakeFieldsReadOnly(document.Form.Fields);
return document.GetData();
}
/// <summary>
/// The get html.
/// </summary>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public static string GetHtml()
{
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ABCPDFHtmlSignatureTest.HTMLPage1.html"))
{
using (var streamReader = new StreamReader(stream))
{
return streamReader.ReadToEnd();
}
}
}
/// <summary>
/// The make fields read only.
/// </summary>
/// <param name="fields">
/// The fields.
/// </param>
private static void MakeFieldsReadOnly(Fields fields)
{
foreach (var field in fields)
{
if (field.Name == "Signature") continue;
field.Stamp();
}
}
}
}
Hopefully this can help someone else.
I ended up using both ABCPDF and iTextSharp.
I used ABCPDF to convert the HTML to PDF, and to tell me where the element is, and then I used iTextSharp to put the blank signature field over it.
There were a couple of "gotchas" in this project:
ABCPDF was better at converting HTML to PDF because it is more forgiving with non-standard html, and it was better at reading the physical paths when they contained small mistakes like "/" instead of "\".
When sending your html to the PDF converter (iTextSharp or ABCPDF), the relative paths need to be changed into physical paths because the converter won't know in which web-site you are running or in which virtual directories to find the images, scripts and stylesheets. (See a converter below that can help with that)
ABCPDF was better at interpreting the style sheets, and the end result looked much better with less code.
When trying to figure out where ABCPDF placed the fields or tagged elements, bear in mind that after you add the first page, you still have to go into a loop to "chain" or register the rest of the pages, then only will you be able to resolve the field or the tagged element.
Here is a sample project to demonstrate the solution.
The sample html: (notice the abcpdf-tag-visible: true part in the style of the signature field, this will help us to see where the element is placed in the PDF)
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Test Document</title>
</head>
<body>
<form method="POST">
Sample Report Data: <br />
<table style="border: solid 1px red; margin: 5px" cellpadding="5px">
<tr>
<td>Field 1:</td>
<td><input type="text" id="field1" name="field1" value="FIELD1VALUE" /></td>
</tr>
<tr>
<td>Field 2:</td>
<td><input type="text" id="Text2" value="FIELD2VALUE" /></td>
</tr>
<tr>
<td>Field 3:</td>
<td><input type="text" id="Text3" value="FIELD3VALUE" /></td>
</tr>
<tr>
<td>Field 4:</td>
<td><input type="text" id="Text4" value="FIELD4VALUE" /></td>
</tr>
<tr>
<td>Signature:</td>
<td><textarea id="ClientSignature" style="background-color:LightCyan;border-color:Gray;border-width:1px;border-style:Solid;height:50px;width:200px;abcpdf-tag-visible: true"
rows="2" cols="20"></textarea></td>
</tr>
</table>
</form>
</body>
</html>
Here is a screen shot of the PDF with a blank signature field, opened with Adobe afterwards.
A sample console application to help test out the PDF converters:
namespace ABCPDFHtmlSignatureTest
{
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using iTextSharp.text;
using iTextSharp.text.pdf;
using WebSupergoo.ABCpdf8;
/// <summary>
/// The program.
/// </summary>
public class Program
{
/// <summary>
/// The file name.
/// </summary>
private const string PdfFileName = #"c:\temp\pdftest.pdf";
/// <summary>
/// Adds a blank signature field at the specified location.
/// </summary>
/// <param name="pdf">The PDF.</param>
/// <param name="signatureRect">The signature location.</param>
/// <param name="signaturePage">the page on which the signature appears</param>
/// <returns>The new PDF.</returns>
private static byte[] AddBlankSignatureField(byte[] pdf, Rectangle signatureRect, int signaturePage)
{
var pdfReader = new PdfReader(pdf);
using (var ms = new MemoryStream())
{
var pdfStamper = new PdfStamper(pdfReader, ms);
var signatureField = PdfFormField.CreateSignature(pdfStamper.Writer);
signatureField.SetWidget(signatureRect, null);
signatureField.Flags = PdfAnnotation.FLAGS_PRINT;
signatureField.Put(PdfName.DA, new PdfString("/Helv 0 Tf 0 g"));
signatureField.FieldName = "ClientSignature";
signatureField.Page = signaturePage;
pdfStamper.AddAnnotation(signatureField, signaturePage);
pdfStamper.Close();
return ms.ToArray();
}
}
/// <summary>
/// The application entry point.
/// </summary>
/// <param name="args">
/// The args.
/// </param>
public static void Main(string[] args)
{
var html = GetHtml();
XRect signatureRect;
int signaturePage;
byte[] pdf;
GetPdfUsingAbc(html, out pdf, out signatureRect, out signaturePage);
/* convert to type that iTextSharp needs */
var signatureRect2 = new Rectangle(
Convert.ToSingle(signatureRect.Left),
Convert.ToSingle(signatureRect.Top),
Convert.ToSingle(signatureRect.Right),
Convert.ToSingle(signatureRect.Bottom));
pdf = AddBlankSignatureField(pdf, signatureRect2, signaturePage);
/* save the PDF to disk */
File.WriteAllBytes(PdfFileName, pdf);
/* open the PDF */
Process.Start(PdfFileName);
}
/// <summary>
/// Returns the PDF for the specified html. The conversion is done using ABCPDF.
/// </summary>
/// <param name="html">The html.</param>
/// <param name="pdf">the PDF</param>
/// <param name="signatureRect">the location of the signature field</param>
/// <param name="signaturePage">the page of the signature field</param>
public static void GetPdfUsingAbc(string html, out byte[] pdf, out XRect signatureRect, out int signaturePage)
{
var document = new Doc();
document.MediaBox.String = "A4";
document.Color.String = "255 255 255";
document.FontSize = 7;
/* tag elements marked with "abcpdf-tag-visible: true" */
document.HtmlOptions.AddTags = true;
int pageId = document.AddImageHtml(html, true, 950, true);
int pageNumber = 1;
signatureRect = null;
signaturePage = -1;
TryIdentifySignatureLocationOnCurrentPage(document, pageId, pageNumber, ref signatureRect, ref signaturePage);
while (document.Chainable(pageId))
{
document.Page = document.AddPage();
pageId = document.AddImageToChain(pageId);
pageNumber++;
TryIdentifySignatureLocationOnCurrentPage(document, pageId, pageNumber, ref signatureRect, ref signaturePage);
}
pdf = document.GetData();
}
/// <summary>
/// The try identify signature location on current page.
/// </summary>
/// <param name="document">The document.</param>
/// <param name="currentPageId">The current page id.</param>
/// <param name="currentPageNumber">The current page number.</param>
/// <param name="signatureRect">The signature location.</param>
/// <param name="signaturePage">The signature page.</param>
private static void TryIdentifySignatureLocationOnCurrentPage(Doc document, int currentPageId, int currentPageNumber, ref XRect signatureRect, ref int signaturePage)
{
if (null != signatureRect) return;
var tagIds = document.HtmlOptions.GetTagIDs(currentPageId);
if (tagIds.Length > 0)
{
int index = -1;
foreach (var tagId in tagIds)
{
index++;
if (tagId.Contains("ClientSignature"))
{
var rects = document.HtmlOptions.GetTagRects(currentPageId);
signatureRect = rects[index];
signaturePage = currentPageNumber;
break;
}
}
}
}
/// <summary>
/// The get html.
/// </summary>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public static string GetHtml()
{
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ABCPDFHtmlSignatureTest.HTMLPage1.html"))
{
if (null == stream)
{
throw new InvalidOperationException("Unable to resolve the html");
}
using (var streamReader = new StreamReader(stream))
{
return streamReader.ReadToEnd();
}
}
}
}
}
When running inside the web server and still generating the HTML, you can use this class to change the relative (virtual) paths to physical (UNC) paths:
namespace YourNameSpace
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
/// <summary>
/// Replaces all uris within in an html document to physical paths, making it valid
/// html outside the context of a web site. This is necessary because outside the
/// context of a web site root folder, the uris are meaningless, and the html cannot
/// be interpreted correctly by external components, like ABCPDF or iTextSharp.
/// Without this step, the images and other 'SRC' references cannot be resolved.
/// </summary>
public sealed class HtmlRelativeToPhysicalPathConverter
{
#region FIELDS
/// <summary>
/// The _server.
/// </summary>
private readonly HttpServerUtility _server;
/// <summary>
/// The _html.
/// </summary>
private readonly string _html;
#endregion
#region CONSTRUCTOR
/// <summary>
/// Initialises a new instance of the <see cref="HtmlRelativeToPhysicalPathConverter"/> class.
/// </summary>
/// <param name="server">
/// The server.
/// </param>
/// <param name="html">
/// The html.
/// </param>
/// <exception cref="ArgumentNullException">
/// when <paramref name="server"/> or <paramref name="html"/> is null or empty.
/// </exception>
public HtmlRelativeToPhysicalPathConverter(HttpServerUtility server, string html)
{
if (null == server) throw new ArgumentNullException("server");
if (string.IsNullOrWhiteSpace(html)) throw new ArgumentNullException("html");
_server = server;
_html = html;
}
#endregion
#region Convert Html
/// <summary>
/// Convert the html.
/// </summary>
/// <param name="leaveUrisIfFileCannotBeFound">an additional validation can be performed before changing the uri to a directory path</param>
/// <returns>The converted html with physical paths in all uris.</returns>
public string ConvertHtml(bool leaveUrisIfFileCannotBeFound = false)
{
var htmlBuilder = new StringBuilder(_html);
// Double quotes
foreach (var relativePath in this.GetRelativePaths(htmlBuilder, '"'))
{
this.ReplaceRelativePath(htmlBuilder, relativePath, leaveUrisIfFileCannotBeFound);
}
// Single quotes
foreach (var relativePath in this.GetRelativePaths(htmlBuilder, '\''))
{
this.ReplaceRelativePath(htmlBuilder, relativePath, leaveUrisIfFileCannotBeFound);
}
return htmlBuilder.ToString();
}
#endregion
#region Replace Relative Path
/// <summary>
/// Convert a uri to the physical path.
/// </summary>
/// <param name="htmlBuilder">The html builder.</param>
/// <param name="relativePath">The relative path or uri string.</param>
/// <param name="leaveUrisIfFileCannotBeFound">an additional validation can be performed before changing the uri to a directory path</param>
private void ReplaceRelativePath(StringBuilder htmlBuilder, string relativePath, bool leaveUrisIfFileCannotBeFound)
{
try
{
var parts = relativePath.Split('?');
var mappedPath = _server.MapPath(parts[0]);
if ((leaveUrisIfFileCannotBeFound && File.Exists(mappedPath)) || !leaveUrisIfFileCannotBeFound)
{
if (parts.Length > 1)
{
mappedPath += "?" + parts[1];
}
htmlBuilder.Replace(relativePath, mappedPath);
}
else
{
/* decide what you want to do with these */
}
}
catch (ArgumentException)
{
/* ignore these */
}
}
#endregion
#region Get Relative Paths
/// <summary>
/// They are NOT guaranteed to be valid uris, simply values between quote characters.
/// </summary>
/// <param name="html">the html builder</param>
/// <param name="quoteChar">the quote character to use, e.g. " or '</param>
/// <returns>each of the relative paths</returns>
private IEnumerable<string> GetRelativePaths(StringBuilder html, char quoteChar)
{
var position = 0;
var oldPosition = -1;
var htmlString = html.ToString();
var previousUriString = string.Empty;
while (oldPosition != position)
{
oldPosition = position;
position = htmlString.IndexOf(quoteChar, position + 1);
if (position == -1) break;
var uriString = htmlString.Substring(oldPosition + 1, (position - oldPosition) - 1);
if (Uri.IsWellFormedUriString(uriString, UriKind.Relative)
&& uriString != previousUriString
/* as far as I know we never reference a file without an extension, so avoid the IDs this way */
&& uriString.Contains(".") && !uriString.EndsWith("."))
{
yield return uriString;
/* refresh the html string, and reiterate again */
htmlString = html.ToString();
position = oldPosition;
oldPosition = position - 1; /* don't exit yet */
previousUriString = uriString;
}
}
}
#endregion
}
}
You can use the class like this:
var html = textWriter.ToString();
// change relative paths to be absolute
html = new HtmlRelativeToPhysicalPathConverter(server, html).ConvertHtml();
I would like to have a function returning the last revision / commit ID of the source from which the deployed application / library was built.
I have been using the __DATE__ and __TIME__ macros in C++ but this approach has obvious drawbacks.
What tools are available to achieve this in an automated manner?
I am using Eclipse-CDT for C++ (Linux, SVN) but it I am also interested in git solutions, and sources written in Java and C#.
By using Visual Studio and C# you could within a Pre-Built step calling the SubWCRev command with a template file, that will be copied to a file used within the solution.
The command within the Pre-Built step is:
<PreBuildEvent>SubWCRev "$(ProjectDir)\" "$(ProjectDir)VersionProvider.template.cs" "$(ProjectDir)VersionProvider.cs"</PreBuildEvent>
Within the project add the following two files:
<Compile Include="VersionProvider.cs">
<DependentUpon>VersionProvider.template.cs</DependentUpon>
</Compile>
<None Include="VersionProvider.template.cs" />
With this content:
internal static class VersionProvider
{
/// <summary>
/// Provides the current subversion revision number
/// </summary>
internal const string CurrentSVNRevision = "$WCREV$";
}
Last but not least within AssemblyInfo.cs add the following line:
[assembly: AssemblyInformationalVersion(VersionProvider.CurrentSVNRevision)]
The project will by this way automatically get the current subversion revision number of this project folder baked into version info of the application which can be seen on the details page of the file properties.
You can also retrieve this information through code at runtime:
private string GetAdditionalVersionInfo()
{
var assembly = Assembly.GetEntryAssembly();
var attributesFound = assembly.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), true);
var version = attributesFound.OfType<AssemblyInformationalVersionAttribute>().FirstOrDefault();
return version != null ? version.InformationalVersion : String.Empty;
}
/// <summary>
/// Gets the SVN date.
/// </summary>
/// <value>The SVN date. value</value>
// ReSharper disable UnusedMember.Global
public static new string SvnDate{
// ReSharper restore UnusedMember.Global
get {
const string S = "$Date$";
return S.Substring(7, 19);
}
}
/// <summary>
/// Gets the SVN ID.
/// </summary>
/// <value>The SVN ID. value</value>
// ReSharper disable UnusedMember.Global
public static new string SvnID{
// ReSharper restore UnusedMember.Global
get{
const string S = "$Id$";
const string D = "$";
return S.Replace(D + "Id: ", string.Empty).Replace(" " + D, string.Empty);
}
}
/// <summary>
/// Gets the SVN rev.
/// </summary>
/// <value>The SVN rev. value</value>
// ReSharper disable UnusedMember.Global
// ReSharper disable MemberCanBePrivate.Global
public static new string SvnRev{
// ReSharper restore MemberCanBePrivate.Global
// ReSharper restore UnusedMember.Global
get {
const string S = "$Rev$";
return S.Item(1);
}
}
/// <summary>
/// Gets the SVN author.
/// </summary>
/// <value>The SVN author. value</value>
// ReSharper disable UnusedMember.Global
public static new string SvnAuthor{
// ReSharper restore UnusedMember.Global
get {
const string S = "$Author$";
return S.Item(1);
}
}
Note S.Item(n) returns a space delimited zero based item. Replace with your own code. Also, new is only necessary to deal with inheritance. Props must be set in svn. I dont have a snippet showing the expansions since I am on Mercurial now.
If you were working with a Makefile and SVN, you could do something like this for C or C++:
REVISION=$(shell svnversion)
CFLAGS=... -D__REVISION__=\"$REVISION\"
I'm not that familiar with CDT, but I understand it's able to use a Makefile-based build system.
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?
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