public void MutiTierTest() { CoapClient client = new CoapClient(new Uri($"coap://localhost:{_port}/ps")); Response resp = client.Get(); Assert.AreEqual(StatusCode.Content, resp.StatusCode); Assert.AreEqual(MediaType.ApplicationLinkFormat, resp.ContentType); List <WebLink> links = LinkFormat.Parse(resp.PayloadString).ToList(); Assert.AreEqual(0, links.Count); resp = client.Post($"<middle>;ct={MediaType.ApplicationLinkFormat}", MediaType.ApplicationLinkFormat); Assert.AreEqual(StatusCode.Created, resp.StatusCode); Assert.AreEqual("ps/middle", resp.LocationPath); client.UriPath = "/ps/middle"; resp = client.Post($"<topic1>;ct={MediaType.TextPlain}", MediaType.ApplicationLinkFormat); Assert.AreEqual(StatusCode.Created, resp.StatusCode); Assert.AreEqual("ps/middle/topic1", resp.LocationPath); resp = client.Post($"<topic2>;ct={MediaType.ApplicationCbor}", MediaType.ApplicationLinkFormat); Assert.AreEqual(StatusCode.Created, resp.StatusCode); Assert.AreEqual("ps/middle/topic2", resp.LocationPath); client.UriPath = ""; resp = client.Get(); Assert.AreEqual(StatusCode.Content, resp.StatusCode); Assert.AreEqual(MediaType.ApplicationLinkFormat, resp.ContentType); links = LinkFormat.Parse(resp.PayloadString).ToList(); Assert.AreEqual(3, links.Count); string[] linkStrings = resp.PayloadString.Split(','); Assert.Contains("</ps/middle/topic2>;ct=60;obs", linkStrings); Assert.Contains("</ps/middle/topic1>;ct=0;obs", linkStrings);; }
protected override void DoGet(CoapExchange exchange) { st.Start(); string path = exchange.Request.UriQuery; string[] tokens = path.Split('/'); string deviceName = tokens[0]; string requstdatasize = tokens[1]; // Devices di = new Devices(eviceName,requstdatasize,"GET",null); _content = GenerateResponseData(Int32.Parse(requstdatasize)); if (_content != null) { exchange.Respond(_content); } else { String subtree = LinkFormat.Serialize(this, null); exchange.Respond(StatusCode.Content, subtree, MediaType.ApplicationLinkFormat); } st.Stop(); int responseSize = exchange.getResponseSize(); st.WriteLogServer("GET", deviceName, requstdatasize); }
public void ConcreteTest() { String link = "</careless>;rt=\"SepararateResponseTester\";title=\"This resource will ACK anything, but never send a separate response\",</feedback>;rt=\"FeedbackMailSender\";title=\"POST feedback using mail\",</helloWorld>;rt=\"HelloWorldDisplayer\";title=\"GET a friendly greeting!\",</image>;ct=21;ct=22;ct=23;ct=24;rt=\"Image\";sz=18029;title=\"GET an image with different content-types\",</large>;rt=\"block\";title=\"Large resource\",</large_update>;rt=\"block\";rt=\"observe\";title=\"Large resource that can be updated using PUT method\",</mirror>;rt=\"RequestMirroring\";title=\"POST request to receive it back as echo\",</obs>;obs;rt=\"observe\";title=\"Observable resource which changes every 5 seconds\",</query>;title=\"Resource accepting query parameters\",</seg1/seg2/seg3>;title=\"Long path resource\",</separate>;title=\"Resource which cannot be served immediately and which cannot be acknowledged in a piggy-backed way\",</storage>;obs;rt=\"Storage\";title=\"PUT your data here or POST new resources!\",</test>;title=\"Default test resource\",</timeResource>;rt=\"CurrentTime\";title=\"GET the current time\",</toUpper>;rt=\"UppercaseConverter\";title=\"POST text here to convert it to uppercase\",</weatherResource>;rt=\"ZurichWeather\";title=\"GET the current weather in zurich\""; Resource res = RemoteResource.NewRoot(link); String result = LinkFormat.Serialize(res, null, true); Assert.IsEqualTo(link, result); }
public override void DoGet(Request request) { Response response = new Response(Code.Content); IEnumerable <Option> query = request.GetOptions(OptionType.UriQuery); response.SetPayload(LinkFormat.Serialize(_root, query, true), MediaType.ApplicationLinkFormat); request.Respond(response); }
public SnippetMarkdownHandling(string rootDirectory, LinkFormat linkFormat, string?urlPrefix = null) { this.linkFormat = linkFormat; this.urlPrefix = urlPrefix; Guard.AgainstNullAndEmpty(rootDirectory, nameof(rootDirectory)); rootDirectory = Path.GetFullPath(rootDirectory); this.rootDirectory = rootDirectory.Replace(@"\", "/"); }
public void ConversionTest() { String link1 = "</myUri/something>;ct=42;if=\"/someRef/path\";obs;rt=\"MyName\";sz=10"; String link2 = "</myUri>;rt=\"NonDefault\""; String link3 = "</a>"; String format = link1 + "," + link2 + "," + link3; Resource res = RemoteResource.NewRoot(format); String result = LinkFormat.Serialize(res, null, true); Assert.IsEqualTo(link3 + "," + link2 + "," + link1, result); }
protected override void DoGet(CoapExchange exchange) { if (_content != null) { exchange.Respond(_content); } else { String subtree = LinkFormat.Serialize(this, null); exchange.Respond(StatusCode.Content, subtree, MediaType.ApplicationLinkFormat); } }
public DirectoryMarkdownProcessor( string targetDirectory, bool scanForMdFiles = true, bool scanForSnippets = true, bool scanForIncludes = true, Action <string>?log = null, AppendSnippetGroupToMarkdown?appendSnippetGroup = null, bool writeHeader = true, string?header = null, DirectoryFilter?directoryFilter = null, bool readOnly = false, LinkFormat linkFormat = LinkFormat.GitHub, int tocLevel = 2, IEnumerable <string>?tocExcludes = null, bool treatMissingSnippetAsWarning = false, bool treatMissingIncludeAsWarning = false, int maxWidth = int.MaxValue, string?urlPrefix = null, bool validateContent = false) { this.writeHeader = writeHeader; this.validateContent = validateContent; this.header = header; this.urlPrefix = urlPrefix; this.directoryFilter = directoryFilter; this.readOnly = readOnly; this.tocLevel = tocLevel; this.tocExcludes = tocExcludes; this.maxWidth = maxWidth; this.treatMissingSnippetAsWarning = treatMissingSnippetAsWarning; this.treatMissingIncludeAsWarning = treatMissingIncludeAsWarning; this.appendSnippetGroup = appendSnippetGroup ?? new SnippetMarkdownHandling(targetDirectory, linkFormat, urlPrefix).AppendGroup; this.log = log ?? (s => { Trace.WriteLine(s); }); Guard.DirectoryExists(targetDirectory, nameof(targetDirectory)); this.targetDirectory = Path.GetFullPath(targetDirectory); if (scanForMdFiles) { AddMdFilesFrom(targetDirectory); } if (scanForSnippets) { AddSnippetsFrom(targetDirectory); } if (scanForIncludes) { AddIncludeFilesFrom(targetDirectory); } }
public static RemoteResource NewRoot(String linkFormat, int mediaType = MediaType.ApplicationLinkFormat) { switch (mediaType) { case MediaType.ApplicationLinkFormat: return(LinkFormat.Deserialize(linkFormat)); case MediaType.ApplicationJson: return(LinkFormat.DeserializeJson(linkFormat)); default: throw new ArgumentException("Unrecognized media type"); } }
public void MatchTest() { String link1 = "</myUri/something>;ct=42;if=\"/someRef/path\";obs;rt=\"MyName\";sz=10"; String link2 = "</myUri>;ct=50;rt=\"MyName\""; String link3 = "</a>;sz=10;rt=\"MyNope\""; String format = link1 + "," + link2 + "," + link3; Resource res = RemoteResource.NewRoot(format); List <Option> query = new List <Option>(); query.Add(Option.Create(OptionType.UriQuery, "rt=MyName")); String queried = LinkFormat.Serialize(res, query, true); Assert.IsEqualTo(link2 + "," + link1, queried); }
public static RemoteResource NewRoot(byte[] linkFormat, int mediaType = MediaType.ApplicationLinkFormat) { switch (mediaType) { case MediaType.ApplicationLinkFormat: return(LinkFormat.Deserialize(Encoding.UTF8.GetString(linkFormat))); case MediaType.ApplicationCbor: return(LinkFormat.DeserializeCbor(linkFormat)); case MediaType.ApplicationJson: return(LinkFormat.DeserializeJson(Encoding.UTF8.GetString(linkFormat))); default: throw new ArgumentException("Unrecognized media type"); } }
public SnippetMarkdownHandling(string targetDirectory, LinkFormat linkFormat, bool hashSnippetAnchors, string?urlPrefix = null) { this.linkFormat = linkFormat; this.urlPrefix = urlPrefix; Guard.AgainstNullAndEmpty(targetDirectory, nameof(targetDirectory)); targetDirectory = Path.GetFullPath(targetDirectory); this.targetDirectory = targetDirectory.Replace(@"\", "/"); if (hashSnippetAnchors) { getAnchorId = ComputeId; } else { getAnchorId = snippet => $"snippet-{snippet.Key}"; } }
/// <summary> /// A Get does the discovery thing on this node and it's children. /// </summary> /// <param name="exchange">information about current conversation</param> protected override void DoGet(CoapExchange exchange) { Request request = exchange.Request; if (!_doDiscovery) { exchange.Respond(StatusCode.MethodNotAllowed); return; } if (request.HasOption(OptionType.Accept)) { IEnumerable <Option> options = request.GetOptions(OptionType.Accept); foreach (Option opt in options) { switch (opt.IntValue) { case MediaType.ApplicationLinkFormat: exchange.Respond(StatusCode.Content, LinkFormat.Serialize(this, exchange.Request.UriQueries), MediaType.ApplicationLinkFormat); return; case 64: // application/link-format+cbor exchange.Respond(StatusCode.Content, LinkFormat.SerializeCbor(this, exchange.Request.UriQueries), 64); return; default: // Unsupported format break; } } // None of the requested formats that were asked for are supported. // Return the default format. } exchange.Respond(StatusCode.Content, LinkFormat.Serialize(this, exchange.Request.UriQueries), MediaType.ApplicationLinkFormat); }
public DirectoryMarkdownProcessor( string targetDirectory, DocumentConvention convention = DocumentConvention.SourceTransform, bool scanForMdFiles = true, bool scanForSnippets = true, bool scanForIncludes = true, Action <string>?log = null, bool?writeHeader = null, string?header = null, DirectoryFilter?directoryFilter = null, bool?readOnly = null, LinkFormat linkFormat = LinkFormat.GitHub, int tocLevel = 2, IEnumerable <string>?tocExcludes = null, IEnumerable <string>?documentExtensions = null, bool treatMissingAsWarning = false, int maxWidth = int.MaxValue, string?urlPrefix = null, bool validateContent = false, string?newLine = null, bool hashSnippetAnchors = false) : this( targetDirectory, new SnippetMarkdownHandling(targetDirectory, linkFormat, hashSnippetAnchors, urlPrefix).Append, convention, scanForMdFiles, scanForSnippets, scanForIncludes, log, writeHeader, header, directoryFilter, readOnly, tocLevel, tocExcludes, documentExtensions, treatMissingAsWarning, maxWidth, validateContent, newLine, hashSnippetAnchors) { }
/// <inheritdoc/> protected override void DoGet(CoapExchange exchange) { Request req = exchange.Request; if (req.HasOption(OptionType.Accept)) { byte[] payload; switch (req.Accept) { case MediaType.ApplicationLinkFormat: payload = Encoding.UTF8.GetBytes(LinkFormat.Serialize(_root, req.UriQueries)); break; #if false // Work is dead? case MediaType.ApplicationLinkFormatCbor: payload = LinkFormat.SerializeCbor(_root, req.UriQueries); break; case MediaType.ApplicationLinkFormatJson: payload = Encoding.UTF8.GetBytes(LinkFormat.SerializeJson(_root, req.UriQueries)); break; #endif case MediaType.ApplicationCoralReef: payload = LinkFormat.SerializeCoral(_root, req.UriQueries); break; default: exchange.Respond(StatusCode.BadOption); return; } exchange.Respond(StatusCode.Content, payload, req.Accept); } else { exchange.Respond(StatusCode.Content, LinkFormat.Serialize(_root, exchange.Request.UriQueries), MediaType.ApplicationLinkFormat); } }
public static string MakeLink(LinkFormat linkFormat, string host, SharesList shares, TokenizedLocalPath localPath, char systemSeparator) { if (linkFormat == LinkFormat.LocalFile || linkFormat == LinkFormat.LocalPath) { return(ComposeLink(linkFormat, host, null, localPath, systemSeparator)); } else { Share share = shares.FindParentShare(localPath); if (share != null) { TokenizedLocalPath relPath = TokenizedLocalPath.MakeRelative(share.LocalPath, localPath, shares.CaseSensitiveFileSystem); return(ComposeLink(linkFormat, host, share, relPath, systemSeparator)); } else { return(null); } } }
public void BitPivotShouldRepectLinkFormatClasses(Visual visual, LinkFormat linkFormat, LinkSize linkSize, OverflowBehavior overflowBehavior) { var component = RenderComponent <BitPivotTest>(parameters => { parameters.Add(p => p.Visual, visual); parameters.Add(p => p.LinkFormat, linkFormat); parameters.Add(p => p.LinkSize, linkSize); parameters.Add(p => p.OverflowBehavior, overflowBehavior); }); var visualClass = visual.ToString().ToLower(); var linkFormatClass = $"bit-pvt-{linkFormat.ToString().ToLower()}-{visualClass}"; var linkSizeClass = $"bit-pvt-{linkSize.ToString().ToLower()}-{visualClass}"; var overflowBehaviorClass = $"bit-pvt-{overflowBehavior.ToString().ToLower()}-{visualClass}"; var bitPivot = component.Find($".bit-pvt"); Assert.IsTrue(bitPivot.ClassList.Contains(linkFormatClass)); Assert.IsTrue(bitPivot.ClassList.Contains(linkSizeClass)); Assert.IsTrue(bitPivot.ClassList.Contains(overflowBehaviorClass)); }
private static byte[] EncodeResources(string sourceResouces, int mediaType) { RemoteResource rr = RemoteResource.NewRoot(sourceResouces, mediaType); switch (mediaType) { case MediaType.ApplicationLinkFormat: string x = LinkFormat.Serialize(rr); return(Encoding.UTF8.GetBytes(x)); #if false // Dead code? case MediaType.ApplicationLinkFormatCbor: return(LinkFormat.SerializeCbor(rr, null)); case MediaType.ApplicationLinkFormatJson: return(Encoding.UTF8.GetBytes(LinkFormat.SerializeJson(rr, null))); #endif case MediaType.ApplicationCoralReef: return(LinkFormat.SerializeCoral(rr, null)); default: return(null); } }
public void MementoLastTest() { Mementos mementos = new Mementos(LinkFormat.Parse(Test)); Assert.IsTrue(mementos.LastMemento == "http://archive.is/20170308191942/https://kernel.org/"); }
public Boolean SetAttribute(LinkAttribute attr) { // Adds depending on the Link Format rules return(LinkFormat.AddAttribute(Attributes, attr)); }
public static string ComposeLink(LinkFormat linkFormat, string host, Share share, TokenizedLocalPath shareRelativePath, char systemSeparator) { StringBuilder sb = new StringBuilder(); if (linkFormat == LinkFormat.Smb) { sb.Append("smb://"); sb.Append(Uri.EscapeUriString(host)); sb.Append('/'); sb.Append(share.NameEscaped); if (shareRelativePath != null && !shareRelativePath.IsEmpty()) { sb.Append('/'); shareRelativePath.Format(sb, true, '/'); } } else if (linkFormat == LinkFormat.Unc) { sb.Append("\\\\"); sb.Append(host); sb.Append('\\'); sb.Append(share.Name); if (shareRelativePath != null && !shareRelativePath.IsEmpty()) { sb.Append('\\'); shareRelativePath.Format(sb, false, '\\'); } } else if (linkFormat == LinkFormat.UncEscaped) { sb.Append("\\\\"); sb.Append(Uri.EscapeUriString(host)); sb.Append('\\'); sb.Append(share.NameEscaped); if (shareRelativePath != null && !shareRelativePath.IsEmpty()) { sb.Append('\\'); shareRelativePath.Format(sb, true, '\\'); } } else if (linkFormat == LinkFormat.File) { sb.Append("file://"); sb.Append(Uri.EscapeUriString(host)); sb.Append('/'); sb.Append(share.NameEscaped); if (shareRelativePath != null && !shareRelativePath.IsEmpty()) { sb.Append('/'); shareRelativePath.Format(sb, true, '/'); } } else if (linkFormat == LinkFormat.LocalFile) { sb.Append("file://"); if (share != null) { share.LocalPath.Format(sb, true, '/'); } if (shareRelativePath != null && !shareRelativePath.IsEmpty()) { if (share != null) { sb.Append('/'); } shareRelativePath.Format(sb, true, '/'); } } else if (linkFormat == LinkFormat.LocalPath) { if (share != null) { share.LocalPath.Format(sb, false, systemSeparator); } if (shareRelativePath != null && !shareRelativePath.IsEmpty()) { if (share != null) { sb.Append(systemSeparator); } shareRelativePath.Format(sb, false, systemSeparator); } } else { throw new Exception("unexpected link format: " + linkFormat); } string link = sb.ToString(); return(link); }
public static void Main(String[] args) { String method = null; Uri uri = null; String payload = null; Boolean loop = false; Boolean byEvent = false; OneKey authKey = null; SecurityContext oscoap = null; SecurityContextSet contextSet = null; if (args.Length == 0) { PrintUsage(); } Int32 index = 0; foreach (String arg in args) { if (arg[0] == '-') { if (arg.Equals("-l")) { loop = true; } else if (arg.Equals("-e")) { byEvent = true; } else if (arg.StartsWith("-psk=")) { if (authKey == null) { authKey = new OneKey(); authKey.Add(COSE.CoseKeyKeys.KeyType, COSE.GeneralValues.KeyType_Octet); } authKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes(arg.Substring(5)))); } else if (arg.StartsWith("-psk-id=")) { if (authKey == null) { authKey = new OneKey(); authKey.Add(COSE.CoseKeyKeys.KeyType, COSE.GeneralValues.KeyType_Octet); } authKey.Add(COSE.CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(Encoding.UTF8.GetBytes(arg.Substring(8)))); } else if (arg.StartsWith("-oscoap=")) { if (contextSet == null) { Console.WriteLine("Must have -oscoap-data before -oscoap"); Environment.Exit(1); } byte[] id = Encoding.UTF8.GetBytes(arg.Substring(8)); oscoap = contextSet.FindByGroupId(id).First(); } else if (arg.StartsWith("-oscoap-data=")) { contextSet = LoadContextSet(arg.Substring(13)); } else { Console.WriteLine("Unknown option: " + arg); } } else { switch (index) { case 0: method = arg.ToUpper(); break; case 1: try { uri = new Uri(arg); } catch (Exception ex) { Console.WriteLine("Failed parsing URI: " + ex.Message); Environment.Exit(1); } break; case 2: payload = arg; break; default: Console.WriteLine("Unexpected argument: " + arg); break; } index++; } } if (method == null || uri == null) { PrintUsage(); } Request request = NewRequest(method); if (request == null) { Console.WriteLine("Unknown method: " + method); Environment.Exit(1); } if ("OBSERVE".Equals(method)) { request.MarkObserve(); loop = true; } else if ("DISCOVER".Equals(method) && (String.IsNullOrEmpty(uri.AbsolutePath) || uri.AbsolutePath.Equals("/"))) { uri = new Uri(uri, "/.well-known/core"); } CoAPEndPoint ep = null; if (uri.Scheme == "coaps") { if (authKey == null) { Console.WriteLine("Must use the -psk option to provide an authentication key"); return; } ep = new DTLSClientEndPoint(authKey); ep.Start(); request.EndPoint = ep; } request.URI = uri; if (payload != null) { request.SetPayload(payload, MediaType.TextPlain); } if (oscoap != null) { request.OscoapContext = oscoap; } // uncomment the next line if you want to specify a draft to use // request.EndPoint = CoAP.Net.EndPointManager.Draft13; Console.WriteLine(Utils.ToString(request)); try { if (byEvent) { request.Respond += delegate(Object sender, ResponseEventArgs e) { Response response = e.Response; if (response == null) { Console.WriteLine("Request timeout"); } else { Console.WriteLine(Utils.ToString(response)); Console.WriteLine("Time (ms): " + response.RTT); } if (!loop) { if (ep != null) { ep.Stop(); } Environment.Exit(0); } }; request.Send(); while (true) { Console.ReadKey(); } } else { // uncomment the next line if you need retransmission disabled. // request.AckTimeout = -1; request.Send(); do { Console.WriteLine("Receiving response..."); Response response = null; response = request.WaitForResponse(); if (response == null) { Console.WriteLine("Request timeout"); break; } else { Console.WriteLine(Utils.ToString(response)); Console.WriteLine("Time elapsed (ms): " + response.RTT); if (response.ContentType == MediaType.ApplicationLinkFormat) { IEnumerable <WebLink> links = LinkFormat.Parse(response.PayloadString); if (links == null) { Console.WriteLine("Failed parsing link format"); Environment.Exit(1); } else { Console.WriteLine("Discovered resources:"); foreach (var link in links) { Console.WriteLine(link); } } } } } while (loop); } } catch (Exception ex) { Console.WriteLine("Failed executing request: " + ex.Message); Console.WriteLine(ex); if (ep != null) { ep.Stop(); } Environment.Exit(1); } }
/// <summary> /// Create a new node /// </summary> /// <param name="exchange">Information on current conversation</param> protected override void DoPost(CoapExchange exchange) { Request request = exchange.Request; WebLink linkInfo; // Parse the content based on the content type. // Assume content-type of =40 if (request.HasOption(OptionType.ContentFormat)) { switch (request.ContentFormat) { case MediaType.ApplicationLinkFormat: linkInfo = LinkFormat.Parse(request.PayloadString).First(); break; case 64: linkInfo = LinkFormat.Parse(request.PayloadString).First(); break; default: exchange.Respond(StatusCode.BadRequest); return; } } else { linkInfo = LinkFormat.Parse(request.PayloadString).First(); } // Is this a single level create? // Create the topic int maxAge = 0; if (request.HasOption(OptionType.MaxAge)) { maxAge = request.GetFirstOption(OptionType.MaxAge).IntValue; } IResource child; if (linkInfo.Attributes.GetContentTypes().Any(p => p.Equals("40") )) { child = new PubSubResource(linkInfo.Uri, false) { MaxAge = maxAge }; } else { child = new PubSubLeaf(linkInfo.Uri) { MaxAge = maxAge }; foreach (string key in linkInfo.Attributes.Keys) { bool f = true; foreach (string value in linkInfo.Attributes.GetValues(key)) { child.Attributes.Add(key, value); f = false; } if (f) { child.Attributes.Add(key); } } } this.Add(child); exchange.LocationPath = child.Uri; exchange.Respond(StatusCode.Created); }
public void TimeGateTest() { Mementos mementos = new Mementos(LinkFormat.Parse(Test)); Assert.IsTrue(mementos.TimeGate == "http://archive.is/timegate/http://kernel.org/"); }
/// <inheritdoc/> protected override void DoGet(CoapExchange exchange) { exchange.Respond(StatusCode.Content, LinkFormat.Serialize(_root, exchange.Request.UriQueries), MediaType.ApplicationLinkFormat); }
[STAThread] // for Windows.Forms, which is used by clipboard public static int Main(string[] args) { // Failed unless otherwise reached the right point. int exitCode = 1; string host = null; string sharesfile = null; bool showHelp = false; bool showVersion = false; LinkFormat linkFormat = LinkFormat.Unc; HostType hostType = HostType.Netbios; // Not implemented for now to keep things simple. The problem with the clipboard is that it's normally tied to a widget toolkit. // Other than that, easy peasy. bool copyToClipboard = false; bool readStdIn = false; bool noStdErr = false; // I don't really like changing local variables from lambdas, but it makes the code short. // If I get to know other command line parsing libs I may replace Mono.Options in the future.. maybe. var options = new OptionSet() { { "host=", "Custom hostname.", (string v) => host = v }, { "sharesfile=", "Provide a custom .ini file with share list. The format should correspond to outout of \"net usershare info\" command, which also matches smb.conf share list.", (string v) => sharesfile = v }, { "format=", "Link format. Either smb or unc. Default is " + linkFormat + ".", (LinkFormat v) => linkFormat = v }, { "hosttype=", "One of ip, ip6, netbios or hostname. Default is " + hostType + ". Ignored if custom host is specified.", (HostType v) => hostType = v }, { "help", "Show this message and exit.", v => showHelp = v != null }, { "stdin", "Read path list from strandard input.", v => readStdIn = v != null }, { "nostderr", "Write errors into stdout instead of stderr.", v => noStdErr = v != null }, { "copy", "Copy the result to clipboard instead of standard output.", v => copyToClipboard = v != null }, { "version", "Print version and exit.", v => showVersion = v != null }, }; try { List <string> localPaths = options.Parse(args); TextWriter output; StringWriter outputSW; if (copyToClipboard) { outputSW = new StringWriter(); output = outputSW; } else { outputSW = null; output = Console.Out; } if (noStdErr) { Console.SetError(output); } if (readStdIn) { string s; while ((s = Console.In.ReadLine()) != null) { localPaths.Add(s); } } if (showVersion) { Console.WriteLine(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()); exitCode = 0; } else if (showHelp) { exitCode = 0; } else { if (localPaths.Count < 1) { throw new InputError("local path not specified"); } // Make the path searches case insensitive on Windows and // case sensitive on anything else. // This is inexact as on the same machine it's possible to have multiple // file systems with different case sensitivity, but let's keep things // simple. In worst case the link won't be created. bool caseSensitiveFileSystem; switch (Environment.OSVersion.Platform) { case PlatformID.Win32NT: caseSensitiveFileSystem = false; break; case PlatformID.Win32Windows: caseSensitiveFileSystem = false; break; case PlatformID.WinCE: caseSensitiveFileSystem = false; break; default: caseSensitiveFileSystem = true; break; } SharesList shares = new SharesList(caseSensitiveFileSystem); if (sharesfile == null) { switch (Environment.OSVersion.Platform) { case PlatformID.Unix: // Load the samba shares. SambaShareLoader.LoadUserShares(shares); SambaShareLoader.LoadGlobalSambaShares(shares); break; // case PlatformID.MacOSX: case PlatformID.Win32NT: WindowsShareLoader.LoadGlobalShares(shares); break; case PlatformID.Win32Windows: // will it work? WindowsShareLoader.LoadGlobalShares(shares); break; case PlatformID.WinCE: // will it work? WindowsShareLoader.LoadGlobalShares(shares); break; default: throw new Exception(string.Format("Unknown platform {0}. Could not get LAN shares from the system.", Environment.OSVersion.Platform)); } } else { // For the custom share list we use the same format as the "net usershare info" command. string shareListIniContent = File.ReadAllText(sharesfile, Encoding.UTF8); SambaShareLoader.ParseNetUserShareList(shares, shareListIniContent); } if (host == null) { if (hostType == HostType.Ip || hostType == HostType.Ip6) { host = FindIPAddress(hostType == HostType.Ip6); } else if (hostType == HostType.Netbios) { host = System.Environment.MachineName; } else if (hostType == HostType.Hostname) { host = Dns.GetHostName(); } else { throw new InputError(String.Format("unexpected host-type option: {0}", hostType)); } } /* * Small note on complexity. For now the complexity is exponential. * As long as there aren't many shares AND many paths to convert it * shouldn't matter much. Otherwise a better solution is needed with * some data structure. For example searching in a sorted list of * shares using binary search. * * Could implement a binary search on SortedList<string,string> or * use a ready made class prefixdictionary/trie. */ bool first = true; bool foundAll = true; foreach (string localPath in localPaths) { if (first) { first = false; } else { output.WriteLine(); } string link = null; TokenizedLocalPath tokenizedLocalPath = null; try { // Do some sanity checks and make the path absolute. string localAbsolutePath; { // Uri uri = null; // if (Uri.TryCreate(localPath, UriKind.RelativeOrAbsolute, out uri)) { // if (!uri.IsFile) // throw new ArgumentException(string.Format("Could not resolve path {0} to URI. Only file/directory paths are supported.", localPath)); // // // Specific case for URIs like file://host/..., but I haven't seen them in the wild. // if (uri.Host != null && uri.Host != "") // throw new ArgumentException(string.Format("Could not resolve path {0} to URI. Only file/directory paths are supported.", localPath)); // // // replace the path with the absolute one taken from the URI // localAbsolutePath = uri.LocalPath; // } else { // use the passed path as-is localAbsolutePath = localPath; // } } tokenizedLocalPath = new TokenizedLocalPath(localAbsolutePath, Path.DirectorySeparatorChar); } catch (Exception ex) { Console.Error.WriteLine(ex.ToString()); } if (tokenizedLocalPath != null) { link = LinkMaker.MakeLink(linkFormat, host, shares, tokenizedLocalPath, Path.DirectorySeparatorChar); } else { link = localPath; } if (link != null) { output.Write(link); } else { Console.Error.WriteLine(string.Format("No share found containing local path \"{0}\"", localPath)); output.Write(localPath); foundAll = false; } } if (copyToClipboard) { string text = outputSW.ToString(); ClipboardHelper.CopyText(text); } if (foundAll) { // OK. If we reached this point then everything went O~K. exitCode = 0; } } } catch (InputError e) { Console.Error.WriteLine(e.Message); showHelp = true; } catch (OptionException e) { Console.Error.WriteLine(e.ToString()); showHelp = true; } catch (Exception ex) { Console.Error.WriteLine("Unexpected error: " + ex.ToString()); } if (showHelp) { Console.WriteLine("Usage:"); Console.WriteLine("\t" + Path.GetFileNameWithoutExtension(System.Environment.CommandLine) + " <local-path> [<local-path2>, ...]"); Console.WriteLine(); Console.WriteLine("Options:"); options.WriteOptionDescriptions(Console.Out); } return(exitCode); }
public void TimeMapUntilTest() { WebLink link = LinkFormat.Parse(Test).Where(a => a.Attributes.GetValues("rel").Contains("self")).First(); Assert.IsTrue(new TimeMap(link).Until == DateTime.Parse("Wed, 08 Mar 2017 19:19:42 GMT")); }
public void TimeMapFromTest() { WebLink link = LinkFormat.Parse(Test).Where(a => a.Attributes.GetValues("rel").Contains("self")).First(); Assert.IsTrue(new TimeMap(link).From == DateTime.Parse("Wed, 23 May 2012 21:04:12 GMT")); }
public void MementoOriginalTest() { Mementos mementos = new Mementos(LinkFormat.Parse(Test)); Assert.IsTrue(mementos.Original == "http://kernel.org/"); }
public void MementoFirstTest() { Mementos mementos = new Mementos(LinkFormat.Parse(Test)); Assert.IsTrue(mementos.FirstMemento == "http://archive.is/20120523210412/http://kernel.org/"); }