using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Windows;
using System;
using System.Net;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace NewDocumentWindow
{
// To check whether a page exists, we can use a HEAD request
// rather than a full GET. Derive a custom client to do that
class HeadClient : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
var req = base.GetWebRequest(address);
if (req.Method == "GET")
req.Method = "HEAD";
return req;
}
}
public class Commands
{
// Asynchronous helper that checks whether a URL exists
// (i.e. that the URL is valid and can be loaded)
private async static Task<bool> PageExists(string url)
{
// First check whether the URL is valid
Uri uriResult;
if (
!Uri.TryCreate(url, UriKind.Absolute, out uriResult) ||
uriResult.Scheme != Uri.UriSchemeHttp
)
return false;
// Then we try to peform a HEAD request on the page
// (a WebException will be fired if it doesn't exist)
try
{
using(var client = new HeadClient())
{
await client.DownloadStringTaskAsync(url);
}
return true;
}
catch (WebException)
{
return false;
}
}
[CommandMethod("BLOG")]
public async static void OpenBlog()
{
const string url =
"http://blogs.autodesk.com/through-the-interface";
// As we're calling an async function, we need to await
// (and mark the command itself as async)
if (await PageExists(url))
{
// Now that we've validated the URL, we can call the
// new API in AutoCAD 2015 to load our page
Application.DocumentWindowCollection.AddDocumentWindow(
"Kean's blog", new System.Uri(url)
);
}
else
{
// Print a helpful message if the URL wasn't loadable
var doc = Application.DocumentManager.MdiActiveDocument;
var ed = doc.Editor;
ed.WriteMessage(
"\nCould not load url: \"{0}\".", url
);
}
}
[CommandMethod("ADW")]
public static void AddDocumentWindow()
{
// Hardcode some XML data
var xdoc =
XElement.Parse(@"
<orders>
<order Customer=""ACME"" Item=""Widget"" Price=""100"" />
<order Customer=""ACME"" Item=""Tyre"" Price=""200"" />
<order Customer=""Amazon"" Item=""Pen"" Price=""50""/>
<order Customer=""Amazon"" Item=""Paper"" Price=""20""/>
<order Customer=""Autodesk"" Item=""CAD"" Price=""10""/>
<order Customer=""Autodesk"" Item=""File"" Price=""40""/>
<order Customer=""ABC"" Item=""Flowers"" Price=""503""/>
<order Customer=""ABC"" Item=""Sand"" Price=""706""/>
</orders>"
);
// Create our WindowContent WPF UserControl and set the
// XML data on our DataGrid object
var wc = new WindowContent();
wc.MyGrid.DataContext = xdoc;
// Create a WPFDocumentWindow for our content then open it
var dw = new WPFDocumentWindow(wc);
dw.Title = "WPF Document Window";
Application.DocumentWindowCollection.AddDocumentWindow(dw);
}
[CommandMethod("TV")]
public static void TileVertically()
{
Application.DocumentWindowCollection.TileVertically();
}
[CommandMethod("TH")]
public static void TileHorizontally()
{
Application.DocumentWindowCollection.TileHorizontally();
}
}
}