public void AddOption(string spec1, string spec2) { var option = new Option(); ParseOption(spec1, ref option); ParseOption(spec2, ref option); options.Add(option); }
public MongoDbStorage WithIdentityGenerator(Func<object> identityGenerator) { Requires.NotNull(identityGenerator, "identityGenerator"); _identityGenerator = identityGenerator; return this; }
public SubscribeCOVRequest(uint subscriberProcessIdentifier, ObjectId monitoredObjectIdentifier, Option<bool> issueConfirmedNotifications, Option<uint> lifetime) { this.SubscriberProcessIdentifier = subscriberProcessIdentifier; this.MonitoredObjectIdentifier = monitoredObjectIdentifier; this.IssueConfirmedNotifications = issueConfirmedNotifications; this.Lifetime = lifetime; }
public Catalog.OptionSelection ParseFromPlaceholder(Option baseOption, System.Web.UI.WebControls.PlaceHolder ph) { OptionSelection result = new OptionSelection(); result.OptionBvin = baseOption.Bvin; string val = string.Empty; foreach (OptionItem o in baseOption.Items) { if (!o.IsLabel) { string checkId = "opt" + o.Bvin.Replace("-", ""); System.Web.UI.HtmlControls.HtmlInputCheckBox cb = (System.Web.UI.HtmlControls.HtmlInputCheckBox)ph.FindControl(checkId); if (cb != null) { if (cb.Checked) { string temp = ""; if (val.Length > 0) { temp += ","; } temp += o.Bvin; val += temp; } } } } result.SelectionData = val; return result; }
public MongoDbStorage WithEnsuredIndexes(MongoDbIndexBuilder indexBuilder) { Requires.NotNull(indexBuilder, "indexBuilder"); _indexBuilder = indexBuilder; return this; }
public LifeSafetyOperationRequest(uint requestingProcessIdentifier, string requestingSource, LifeSafetyOperation request, Option<ObjectId> objectIdentifier) { this.RequestingProcessIdentifier = requestingProcessIdentifier; this.RequestingSource = requestingSource; this.Request = request; this.ObjectIdentifier = objectIdentifier; }
/// <summary> /// Converts the string representation of a number to its 64-bit signed integer equivalent. The return value indicates whether the conversion succeeded. /// </summary> /// <inheritdoc cref="ToInt32(Option{string})" source="param[name='value']"/> /// <returns> /// 64-bit signed integer value equivalent to the number contained in the <paramref name="value"/> if the conversion succeeded. /// <br/>-or-<br/>Null if the <paramref name="value"/> is None option. /// <br/>-or-<br/>Null if the conversion failed. /// </returns> public static long? ToInt64(Option<string> value) { // The TryParse() fails if the string parameter is null. // That means we don't need additional check if the value is None. long result; return long.TryParse(value.ValueOrNull, out result) ? result : (long?)null; }
public ReadRangeRequest(ObjectId objectIdentifier, PropertyIdentifier propertyIdentifier, Option<uint> propertyArrayIndex, Option<RangeType> range) { this.ObjectIdentifier = objectIdentifier; this.PropertyIdentifier = propertyIdentifier; this.PropertyArrayIndex = propertyArrayIndex; this.Range = range; }
protected override void LoadData() { if (Items.Count == 0) return; string maxId = Items[Items.Count - 1].Id; var option = new Option(); option.Add(Const.MAX_ID, maxId); tweetService.GetMentions(option, tweets => { if (!tweets.HasError) { #region no more tweets if (tweets.Count == 0) { toastMessageService.HandleMessage(languageHelper.GetString("Toast_Msg_NoMoreMentions")); } #endregion #region add else { #if !LOCAL if (maxId == tweets[0].Id) tweets.RemoveAt(0); #endif foreach (var tweet in tweets) { Items.Add(tweet); } } #endregion } base.LoadDataCompleted(); }); }
public static string FormatOption(Option<int> opt) { return Option.Match(opt, some => string.Format("Some {0}", some), () => "None" ); }
public static IList<Option> ToOptions(this string[] args) { var options = new List<Option>(); var parser = new Parser { OnShortOption = name => options.Add(new Option {ShortName = name}), OnLongOption = name => options.Add(new Option {LongName = name}), OnValue = value => { if (options.Count > 0) { var last = options[options.Count - 1]; last.AddValue(value); } else { var option = new Option(); option.AddValue(value); options.Add(option); } } }; parser.Parse(args); return options; }
public ProcessLogItem(ProcessLogItemType type, string message, Exception exception) { When = DateTime.UtcNow; Type = type; Message = message; Exception = exception; }
public MyOptions() { RunMe = new Action("runme"); RunMeToo = new Action("RunMeToo"); DoWalk = new Option("walk", OptionValueType.None); FilePath = new Option("file", OptionValueType.Single); Names = new Option("names", OptionValueType.List); // help text RunMe.HelpText("Run me"); RunMeToo.HelpText("Run me aswell"); DoWalk.HelpText("Walk, don't run"); FilePath.HelpText(""); Names.HelpText(""); // examples FilePath.ExampleText("C:\\Path\file.txt"); Names.ExampleText("John"); // ... or inline Sport = new Option("sport", OptionValueType.Single, SportDefault) .HelpText("") .ExampleText("Cricket"); }
private string GetTargetName( Option<BindingConfig> bindingConfig, TypePair typePair, MemberInfo sourceMember, Dictionary<string, string> targetBindings) { Option<string> targetName; List<BindAttribute> binds = sourceMember.GetAttributes<BindAttribute>(); BindAttribute bind = binds.FirstOrDefault(x => x.TargetType.IsNull()); if (bind.IsNull()) { bind = binds.FirstOrDefault(x => typePair.Target.IsAssignableFrom(x.TargetType)); } if (bind.IsNotNull()) { targetName = new Option<string>(bind.MemberName); } else { targetName = bindingConfig.Map(x => x.GetBindField(sourceMember.Name)); if (targetName.HasNoValue) { string targetMemberName; if (targetBindings.TryGetValue(sourceMember.Name, out targetMemberName)) { targetName = new Option<string>(targetMemberName); } else { targetName = new Option<string>(sourceMember.Name); } } } return targetName.Value; }
/// <summary> /// Initializes a new instance of the <see cref="GetOpt"/> class. /// </summary> /// <param name="options">Array of all possible options</param> public GetOpt(Option[] options) { int idCount = 1; this.shortOptions = new Dictionary<char, int>(); this.longOptions = new Dictionary<string, int>(); this.shortOptionMap = new Dictionary<int, char>(); this.Description = string.Empty; foreach (Option option in options) { if (option.HasArgument == false) { idCount = -idCount; } try { this.shortOptions.Add(option.ShortOption, idCount); this.longOptions.Add(option.LongOption, idCount); } catch (ArgumentException e) { throw new DuplicateOptionException("Duplicate option found", e); } this.shortOptionMap.Add(idCount, option.ShortOption); // FIXME make this a stringbuilder this.Description += "-" + option.ShortOption + ", --" + option.LongOption + "\t" + option.Description + "\n"; idCount = idCount < 0 ? -idCount : idCount; idCount++; } }
public void GettingOptionReturnsOption() { var optionService = TestOptionService.GetService(); var optionSet = optionService.GetOptions(); var option = new Option<bool>("Test Feature", "Test Name", false); Assert.Equal(false, optionSet.GetOption(option)); }
public UnconfirmedTextMessageRequest(ObjectId textMessageSourceDevice, Option<MessageClassType> messageClass, MessagePriorityType messagePriority, string message) { this.TextMessageSourceDevice = textMessageSourceDevice; this.MessageClass = messageClass; this.MessagePriority = messagePriority; this.Message = message; }
public Dialogue(int dialogueRef, SQLiteConnection conn) { SQLiteDataReader reader = new SQLiteCommand("Select * From Dialogue WHERE id = " + dialogueRef + ";", conn).ExecuteReader(); DataTable dialogueTable = new DataTable(); dialogueTable.Load(reader); DataView dialogueView = new DataView(dialogueTable); if (dialogueView.Count > 0) { mText = dialogueView[0]["text"].ToString(); mActor = new Actor(Convert.ToInt32(dialogueView[0]["actorId"]), conn); reader = new SQLiteCommand("Select * From Options WHERE dialogueId = " + dialogueRef + ";", conn).ExecuteReader(); DataTable optionTable = new DataTable(); optionTable.Load(reader); DataView optionView = new DataView(optionTable); mChoices = new Option[optionView.Count]; for(int i = 0; i < optionView.Count; i++) { string optionText = optionView[i]["actualtext"].ToString(); string optionDisplay = optionView[i]["displayText"].ToString(); int outcomeType = Convert.ToInt32(optionView[i]["outcomeType"]); int outcomeId = Convert.ToInt32(optionView[i]["outcomeId"]); mChoices[i] = new Option(optionText, optionDisplay, outcomeType, outcomeId); } } }
public void OptionWithNullOrWhitepace() { var optionService = TestOptionService.GetService(); var optionSet = optionService.GetOptions(); Assert.Throws<System.ArgumentException>(delegate { var option = new Option<bool>("Test Feature", "", false); }); Assert.Throws<System.ArgumentException>(delegate { var option2 = new Option<bool>("Test Feature", null, false); }); Assert.Throws<System.ArgumentNullException>(delegate { var option3 = new Option<bool>(" ", "Test Name", false); }); Assert.Throws<System.ArgumentNullException>(delegate { var option4 = new Option<bool>(null, "Test Name", false); }); }
public Response(Option type) { Id = IDUtils.NewGuid(); TypeCode = type.Code; MissingValues = new List<MissingValue>(); Layout = null; }
public DeviceObjectPropertyReference(ObjectId objectIdentifier, PropertyIdentifier propertyIdentifier, Option<uint> propertyArrayIndex, Option<ObjectId> deviceIdentifier) { this.ObjectIdentifier = objectIdentifier; this.PropertyIdentifier = propertyIdentifier; this.PropertyArrayIndex = propertyArrayIndex; this.DeviceIdentifier = deviceIdentifier; }
public void GetDefault([Values(OptionName.Controls, OptionName.Sound, OptionName.UnlockedLevel)] string option) { Option o = Option.GetDefault(option); Option expected; switch (option) { case OptionName.Controls: expected = new Option() { Name = OptionName.Controls, Value = ControlOption.Arrows }; break; case OptionName.Music: expected = new Option() { Name = OptionName.Music, Value = OnOffOption.On }; break; case OptionName.Sound: expected = new Option() { Name = OptionName.Sound, Value = OnOffOption.On }; break; case OptionName.UnlockedLevel: expected = new Option() { Name = OptionName.UnlockedLevel, Value = UnlockedLevelOption.Level_1 }; break; default: expected = null; break; } Assert.AreEqual(expected.Name, o.Name); Assert.AreEqual(expected.Value, o.Value); }
public void RenderAsControl(Option baseOption, System.Web.UI.WebControls.PlaceHolder ph) { System.Web.UI.WebControls.TextBox result = new System.Web.UI.WebControls.TextBox(); result.ID = "opt" + baseOption.Bvin.Replace("-", ""); result.ClientIDMode = System.Web.UI.ClientIDMode.Static; string c = this.GetColumns(baseOption); if (c == "") c = "20"; string r = this.GetRows(baseOption); if (r == "") r = "1"; int rint = 1; int.TryParse(r,out rint); int cint = 20; int.TryParse(c,out cint); int mint = 255; int.TryParse(this.GetMaxLength(baseOption),out mint); result.Rows = rint; result.Columns = cint; result.MaxLength = mint; if (r != "1") { result.TextMode = System.Web.UI.WebControls.TextBoxMode.MultiLine; } ph.Controls.Add(result); }
public ProcessLogItem(ProcessLogItemType type, string message, Exception exception) { When = DateTime.UtcNow; Type = type; Message = Optional(message); Exception = Optional(exception); }
StrategyContext( StrategyState global, Exception exception, object message, ProcessId sender, ProcessId failedProcess, ProcessId parentProcess, IEnumerable<ProcessId> siblings, IEnumerable<ProcessId> affects, Time pause, Option<Directive> directive, Option<MessageDirective> messageDirective ) { bool isStop = directive == LanguageExt.Directive.Stop; Global = isStop ? StrategyState.Empty : global; Exception = exception; Message = message; Sender = sender; Self = failedProcess; ParentProcess = parentProcess; Siblings = siblings ?? Siblings; Affects = affects ?? Affects; Pause = isStop ? 0 * s : pause; Directive = directive; MessageDirective = messageDirective; }
public virtual Message Deserialize(byte[] bytes) { var reader = new DatagramReader(bytes); var factory = new MessageFactory(); var version = reader.Read(Message.VersionBits); if (version != Message.Version) { throw new SerializationException("incorrect version"); } var type = (MessageType) reader.Read(Message.TypeBits); var optionCount = reader.Read(Message.OptionCountBits); var code = (CodeRegistry) reader.Read(Message.CodeBits); var id = reader.Read(Message.IdBits); var message = factory.Create(type, code, id); var currentOption = 0; for (var i = 0; i < optionCount; i++) { var delta = reader.Read(Message.OptionDeltaBits); var length = reader.Read(Message.OptionLengthBits); currentOption += delta; var option = new Option((OptionNumber) currentOption) { Value = reader.ReadBytes(length) }; message.AddOption(option); } message.Payload = reader.ReadAllBytes(); return message; }
public AddListElementRequest(ObjectId objectIdentifier, PropertyIdentifier propertyIdentifier, Option<uint> propertyArrayIndex, GenericValue listOfElements) { this.ObjectIdentifier = objectIdentifier; this.PropertyIdentifier = propertyIdentifier; this.PropertyArrayIndex = propertyArrayIndex; this.ListOfElements = listOfElements; }
/// <summary> /// Writes dump file with the specified options and exception info. /// </summary> /// <param name="options">The options.</param> /// <param name="exceptionInfo">The exception information.</param> /// <returns></returns> public static bool Write(Option options, ExceptionInfo exceptionInfo) { Process currentProcess = Process.GetCurrentProcess(); IntPtr currentProcessHandle = currentProcess.Handle; uint currentProcessId = (uint) currentProcess.Id; MiniDumpExceptionInformation exp; exp.ThreadId = GetCurrentThreadId(); exp.ClientPointers = false; exp.ExceptionPointers = IntPtr.Zero; if (exceptionInfo == ExceptionInfo.Present) { exp.ExceptionPointers = System.Runtime.InteropServices.Marshal.GetExceptionPointers(); } bool bRet = false; using (var fs = new FileStream(GenerateDumpFilename(), FileMode.Create, FileAccess.ReadWrite, FileShare.Write)) { if (exp.ExceptionPointers == IntPtr.Zero) { bRet = MiniDumpWriteDump(currentProcessHandle, currentProcessId, fs.SafeFileHandle, (uint) options, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); } else { bRet = MiniDumpWriteDump(currentProcessHandle, currentProcessId, fs.SafeFileHandle, (uint) options, ref exp, IntPtr.Zero, IntPtr.Zero); } } return bRet; }
int IOleCommandTarget.Exec(ref Guid commandGroup, uint commandId, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { try { KeyInput ki; if (TryConvert(commandGroup, commandId, pvaIn, out ki)) { // Swallow the input if it's been flagged by a previous QueryStatus if (SwallowIfNextExecMatches.IsSome && SwallowIfNextExecMatches.Value == ki) { return NativeMethods.S_OK; } if (_buffer.CanProcess(ki) && _buffer.Process(ki)) { return NativeMethods.S_OK; } } } finally { SwallowIfNextExecMatches = Option.None; } return _nextTarget.Exec(commandGroup, commandId, nCmdexecopt, pvaIn, pvaOut); }
/// <summary> /// If this node is part of a cluster then it updates a shared map of /// node-names to states. This also downloads the latest map so the /// cluster state is known locally. /// </summary> /// <param name="state">Current state</param> /// <returns>Latest state from the cluster, or a map with just one item 'root' /// in it that represents this node.</returns> static State Heartbeat(State state, Option<ICluster> cluster) => cluster.Map( c => { try { var cutOff = DateTime.UtcNow.Add(0 * seconds - OfflineCutoff); c.HashFieldAddOrUpdate(MembersKey, c.NodeName.Value, new ClusterNode(c.NodeName, DateTime.UtcNow, c.Role)); var newState = new State(c.GetHashFields<ProcessName, ClusterNode>(MembersKey, s => new ProcessName(s)) .Where(m => m.LastHeartbeat > cutOff)); var diffs = DiffState(state, newState); diffs.Item1.Iter(offline => publish(state.Members[offline])); diffs.Item2.Iter(online => publish(newState.Members[online])); return newState; } catch(Exception e) { logErr(e); return HeartbeatLocal(state); } }) .IfNone(HeartbeatLocal(state));
public static IEnumerable <object[]> GetLogsUploadRequestHandlerData() { string sasUrl = $"https://test1.blob.core.windows.net/cont2?st={Guid.NewGuid()}"; yield return(new object[] { @"{""schemaVersion"":""1.0"",""sasUrl"":""<sasurl>"",""items"":{""id"":""edgeAgent""}}".Replace("<sasurl>", sasUrl), "edgeAgent", sasUrl, LogsContentEncoding.None, LogsContentType.Json, ModuleLogFilter.Empty }); sasUrl = $"https://test1.blob.core.windows.net/cont2?st={Guid.NewGuid()}"; yield return(new object[] { @"{""schemaVersion"":""1.0"",""sasUrl"":""<sasurl>"",""items"":{""id"":""edgeAgent""},""encoding"":""gzip""}".Replace("<sasurl>", sasUrl), "edgeAgent", sasUrl, LogsContentEncoding.Gzip, LogsContentType.Json, ModuleLogFilter.Empty }); sasUrl = $"https://test1.blob.core.windows.net/cont2?st={Guid.NewGuid()}"; yield return(new object[] { @"{""schemaVersion"":""1.0"",""sasUrl"":""<sasurl>"",""items"":{""id"":""mod1""},""encoding"":""gzip"",""contentType"":""text""}".Replace("<sasurl>", sasUrl), "mod1", sasUrl, LogsContentEncoding.Gzip, LogsContentType.Text, ModuleLogFilter.Empty }); sasUrl = $"https://test1.blob.core.windows.net/cont2?st={Guid.NewGuid()}"; yield return(new object[] { @"{""schemaVersion"":""1.0"",""sasUrl"":""<sasurl>"",""items"":{""id"":""edgeHub""},""encoding"":""none"",""contentType"":""json""}".Replace("<sasurl>", sasUrl), "edgeHub", sasUrl, LogsContentEncoding.None, LogsContentType.Json, ModuleLogFilter.Empty }); sasUrl = $"https://test1.blob.core.windows.net/cont2?st={Guid.NewGuid()}"; var filter = new ModuleLogFilter(Option.Some(100), Option.Some("1501000"), Option.None <string>(), Option.Some(3), Option.Some("ERR")); yield return(new object[] { @"{""schemaVersion"":""1.0"",""sasUrl"":""<sasurl>"",""items"":{""id"":""edgeAgent"",""filter"":<filter>}}".Replace("<sasurl>", sasUrl).Replace("<filter>", filter.ToJson()), "edgeAgent", sasUrl, LogsContentEncoding.None, LogsContentType.Json, filter }); sasUrl = $"https://test1.blob.core.windows.net/cont2?st={Guid.NewGuid()}"; filter = new ModuleLogFilter(Option.None <int>(), Option.Some("1501000"), Option.None <string>(), Option.None <int>(), Option.Some("ERR")); yield return(new object[] { @"{""schemaVersion"":""1.5"",""sasUrl"":""<sasurl>"",""items"":{""id"":""edgeAgent"",""filter"":<filter>}}".Replace("<sasurl>", sasUrl).Replace("<filter>", filter.ToJson()), "edgeAgent", sasUrl, LogsContentEncoding.None, LogsContentType.Json, filter }); sasUrl = $"https://test1.blob.core.windows.net/cont2?st={Guid.NewGuid()}"; filter = new ModuleLogFilter(Option.Some(100), Option.None <string>(), Option.None <string>(), Option.Some(3), Option.None <string>()); yield return(new object[] { @"{""schemaVersion"":""1.2"",""sasUrl"":""<sasurl>"",""items"":{""id"":""edgeAgent"",""filter"":<filter>}}".Replace("<sasurl>", sasUrl).Replace("<filter>", filter.ToJson()), "edgeAgent", sasUrl, LogsContentEncoding.None, LogsContentType.Json, filter }); }
/// <summary> /// Delete navigation property relations for groups /// </summary> public Command BuildDeleteCommand() { var command = new Command("delete"); command.Description = "Delete navigation property relations for groups"; // Create options for all the parameters var groupIdOption = new Option <string>("--group-id", description: "key: id of group") { }; groupIdOption.IsRequired = true; command.AddOption(groupIdOption); var siteIdOption = new Option <string>("--site-id", description: "key: id of site") { }; siteIdOption.IsRequired = true; command.AddOption(siteIdOption); var storeIdOption = new Option <string>("--store-id", description: "key: id of store") { }; storeIdOption.IsRequired = true; command.AddOption(storeIdOption); var setIdOption = new Option <string>("--set-id", description: "key: id of set") { }; setIdOption.IsRequired = true; command.AddOption(setIdOption); var termIdOption = new Option <string>("--term-id", description: "key: id of term") { }; termIdOption.IsRequired = true; command.AddOption(termIdOption); var termId1Option = new Option <string>("--term-id1", description: "key: id of term") { }; termId1Option.IsRequired = true; command.AddOption(termId1Option); var relationIdOption = new Option <string>("--relation-id", description: "key: id of relation") { }; relationIdOption.IsRequired = true; command.AddOption(relationIdOption); var ifMatchOption = new Option <string>("--if-match", description: "ETag") { }; ifMatchOption.IsRequired = false; command.AddOption(ifMatchOption); command.SetHandler(async(object[] parameters) => { var groupId = (string)parameters[0]; var siteId = (string)parameters[1]; var storeId = (string)parameters[2]; var setId = (string)parameters[3]; var termId = (string)parameters[4]; var termId1 = (string)parameters[5]; var relationId = (string)parameters[6]; var ifMatch = (string)parameters[7]; var cancellationToken = (CancellationToken)parameters[8]; var requestInfo = CreateDeleteRequestInformation(q => { }); requestInfo.PathParameters.Add("group%2Did", groupId); requestInfo.PathParameters.Add("site%2Did", siteId); requestInfo.PathParameters.Add("store%2Did", storeId); requestInfo.PathParameters.Add("set%2Did", setId); requestInfo.PathParameters.Add("term%2Did", termId); requestInfo.PathParameters.Add("term%2Did1", termId1); requestInfo.PathParameters.Add("relation%2Did", relationId); requestInfo.Headers["If-Match"] = ifMatch; var errorMapping = new Dictionary <string, ParsableFactory <IParsable> > { { "4XX", ODataError.CreateFromDiscriminatorValue }, { "5XX", ODataError.CreateFromDiscriminatorValue }, }; await RequestAdapter.SendNoContentAsync(requestInfo, errorMapping: errorMapping, cancellationToken: cancellationToken); Console.WriteLine("Success"); }, new CollectionBinding(groupIdOption, siteIdOption, storeIdOption, setIdOption, termIdOption, termId1Option, relationIdOption, ifMatchOption, new TypeBinding(typeof(CancellationToken)))); return(command); }
/// <summary> /// Update the navigation property relations in groups /// </summary> public Command BuildPatchCommand() { var command = new Command("patch"); command.Description = "Update the navigation property relations in groups"; // Create options for all the parameters var groupIdOption = new Option <string>("--group-id", description: "key: id of group") { }; groupIdOption.IsRequired = true; command.AddOption(groupIdOption); var siteIdOption = new Option <string>("--site-id", description: "key: id of site") { }; siteIdOption.IsRequired = true; command.AddOption(siteIdOption); var storeIdOption = new Option <string>("--store-id", description: "key: id of store") { }; storeIdOption.IsRequired = true; command.AddOption(storeIdOption); var setIdOption = new Option <string>("--set-id", description: "key: id of set") { }; setIdOption.IsRequired = true; command.AddOption(setIdOption); var termIdOption = new Option <string>("--term-id", description: "key: id of term") { }; termIdOption.IsRequired = true; command.AddOption(termIdOption); var termId1Option = new Option <string>("--term-id1", description: "key: id of term") { }; termId1Option.IsRequired = true; command.AddOption(termId1Option); var relationIdOption = new Option <string>("--relation-id", description: "key: id of relation") { }; relationIdOption.IsRequired = true; command.AddOption(relationIdOption); var bodyOption = new Option <string>("--body") { }; bodyOption.IsRequired = true; command.AddOption(bodyOption); command.SetHandler(async(object[] parameters) => { var groupId = (string)parameters[0]; var siteId = (string)parameters[1]; var storeId = (string)parameters[2]; var setId = (string)parameters[3]; var termId = (string)parameters[4]; var termId1 = (string)parameters[5]; var relationId = (string)parameters[6]; var body = (string)parameters[7]; var cancellationToken = (CancellationToken)parameters[8]; using var stream = new MemoryStream(Encoding.UTF8.GetBytes(body)); var parseNode = ParseNodeFactoryRegistry.DefaultInstance.GetRootParseNode("application/json", stream); var model = parseNode.GetObjectValue <Relation>(Relation.CreateFromDiscriminatorValue); var requestInfo = CreatePatchRequestInformation(model, q => { }); requestInfo.PathParameters.Add("group%2Did", groupId); requestInfo.PathParameters.Add("site%2Did", siteId); requestInfo.PathParameters.Add("store%2Did", storeId); requestInfo.PathParameters.Add("set%2Did", setId); requestInfo.PathParameters.Add("term%2Did", termId); requestInfo.PathParameters.Add("term%2Did1", termId1); requestInfo.PathParameters.Add("relation%2Did", relationId); var errorMapping = new Dictionary <string, ParsableFactory <IParsable> > { { "4XX", ODataError.CreateFromDiscriminatorValue }, { "5XX", ODataError.CreateFromDiscriminatorValue }, }; await RequestAdapter.SendNoContentAsync(requestInfo, errorMapping: errorMapping, cancellationToken: cancellationToken); Console.WriteLine("Success"); }, new CollectionBinding(groupIdOption, siteIdOption, storeIdOption, setIdOption, termIdOption, termId1Option, relationIdOption, bodyOption, new TypeBinding(typeof(CancellationToken)))); return(command); }
/// <summary> /// To indicate which terms are related to the current term as either pinned or reused. /// </summary> public Command BuildGetCommand() { var command = new Command("get"); command.Description = "To indicate which terms are related to the current term as either pinned or reused."; // Create options for all the parameters var groupIdOption = new Option <string>("--group-id", description: "key: id of group") { }; groupIdOption.IsRequired = true; command.AddOption(groupIdOption); var siteIdOption = new Option <string>("--site-id", description: "key: id of site") { }; siteIdOption.IsRequired = true; command.AddOption(siteIdOption); var storeIdOption = new Option <string>("--store-id", description: "key: id of store") { }; storeIdOption.IsRequired = true; command.AddOption(storeIdOption); var setIdOption = new Option <string>("--set-id", description: "key: id of set") { }; setIdOption.IsRequired = true; command.AddOption(setIdOption); var termIdOption = new Option <string>("--term-id", description: "key: id of term") { }; termIdOption.IsRequired = true; command.AddOption(termIdOption); var termId1Option = new Option <string>("--term-id1", description: "key: id of term") { }; termId1Option.IsRequired = true; command.AddOption(termId1Option); var relationIdOption = new Option <string>("--relation-id", description: "key: id of relation") { }; relationIdOption.IsRequired = true; command.AddOption(relationIdOption); var selectOption = new Option <string[]>("--select", description: "Select properties to be returned") { Arity = ArgumentArity.ZeroOrMore }; selectOption.IsRequired = false; command.AddOption(selectOption); var expandOption = new Option <string[]>("--expand", description: "Expand related entities") { Arity = ArgumentArity.ZeroOrMore }; expandOption.IsRequired = false; command.AddOption(expandOption); var outputOption = new Option <FormatterType>("--output", () => FormatterType.JSON) { IsRequired = true }; command.AddOption(outputOption); var queryOption = new Option <string>("--query"); command.AddOption(queryOption); var jsonNoIndentOption = new Option <bool>("--json-no-indent", r => { if (bool.TryParse(r.Tokens.Select(t => t.Value).LastOrDefault(), out var value)) { return(value); } return(true); }, description: "Disable indentation for the JSON output formatter."); command.AddOption(jsonNoIndentOption); command.SetHandler(async(object[] parameters) => { var groupId = (string)parameters[0]; var siteId = (string)parameters[1]; var storeId = (string)parameters[2]; var setId = (string)parameters[3]; var termId = (string)parameters[4]; var termId1 = (string)parameters[5]; var relationId = (string)parameters[6]; var select = (string[])parameters[7]; var expand = (string[])parameters[8]; var output = (FormatterType)parameters[9]; var query = (string)parameters[10]; var jsonNoIndent = (bool)parameters[11]; var outputFilter = (IOutputFilter)parameters[12]; var outputFormatterFactory = (IOutputFormatterFactory)parameters[13]; var cancellationToken = (CancellationToken)parameters[14]; var requestInfo = CreateGetRequestInformation(q => { q.QueryParameters.Select = select; q.QueryParameters.Expand = expand; }); requestInfo.PathParameters.Add("group%2Did", groupId); requestInfo.PathParameters.Add("site%2Did", siteId); requestInfo.PathParameters.Add("store%2Did", storeId); requestInfo.PathParameters.Add("set%2Did", setId); requestInfo.PathParameters.Add("term%2Did", termId); requestInfo.PathParameters.Add("term%2Did1", termId1); requestInfo.PathParameters.Add("relation%2Did", relationId); var errorMapping = new Dictionary <string, ParsableFactory <IParsable> > { { "4XX", ODataError.CreateFromDiscriminatorValue }, { "5XX", ODataError.CreateFromDiscriminatorValue }, }; var response = await RequestAdapter.SendPrimitiveAsync <Stream>(requestInfo, errorMapping: errorMapping, cancellationToken: cancellationToken); response = await outputFilter?.FilterOutputAsync(response, query, cancellationToken) ?? response; var formatterOptions = output.GetOutputFormatterOptions(new FormatterOptionsModel(!jsonNoIndent)); var formatter = outputFormatterFactory.GetFormatter(output); await formatter.WriteOutputAsync(response, formatterOptions, cancellationToken); }, new CollectionBinding(groupIdOption, siteIdOption, storeIdOption, setIdOption, termIdOption, termId1Option, relationIdOption, selectOption, expandOption, outputOption, queryOption, jsonNoIndentOption, new TypeBinding(typeof(IOutputFilter)), new TypeBinding(typeof(IOutputFormatterFactory)), new TypeBinding(typeof(CancellationToken)))); return(command); }
public async Task TestLogsUploadAllTaskRequest() { // Arrange string sasUrl = $"https://test1.blob.core.windows.net/cont2?st={Guid.NewGuid()}"; var filter = new ModuleLogFilter(Option.Some(100), Option.Some("1501000"), Option.None <string>(), Option.Some(3), Option.Some("ERR")); LogsContentEncoding contentEncoding = LogsContentEncoding.None; LogsContentType contentType = LogsContentType.Json; string payload = @"{ ""schemaVersion"": ""1.0"", ""sasUrl"": ""<sasurl>"", ""items"": { ""id"": "".*"", ""filter"": <filter> }, ""encoding"": ""none"", ""contentType"": ""json"" }" .Replace("<sasurl>", sasUrl) .Replace("<filter>", filter.ToJson()); string mod1 = "m1"; string mod2 = "m2"; string mod3 = "m3"; var moduleRuntimeInfoList = new List <ModuleRuntimeInfo> { new ModuleRuntimeInfo(mod1, "docker", ModuleStatus.Running, string.Empty, 0, Option.None <DateTime>(), Option.None <DateTime>()), new ModuleRuntimeInfo(mod2, "docker", ModuleStatus.Running, string.Empty, 0, Option.None <DateTime>(), Option.None <DateTime>()), new ModuleRuntimeInfo(mod3, "docker", ModuleStatus.Running, string.Empty, 0, Option.None <DateTime>(), Option.None <DateTime>()) }; var runtimeInfoProvider = new Mock <IRuntimeInfoProvider>(); runtimeInfoProvider.Setup(r => r.GetModules(It.IsAny <CancellationToken>())) .ReturnsAsync(moduleRuntimeInfoList); var logsUploader = new Mock <IRequestsUploader>(); var logsProvider = new Mock <ILogsProvider>(); var module1LogOptions = new ModuleLogOptions(contentEncoding, contentType, filter, LogOutputFraming.None, Option.None <LogsOutputGroupingConfig>(), false); var mod1LogBytes = new byte[100]; logsProvider.Setup(l => l.GetLogs(mod1, module1LogOptions, It.IsAny <CancellationToken>())) .ReturnsAsync(mod1LogBytes); logsUploader.Setup(l => l.UploadLogs(sasUrl, mod1, mod1LogBytes, contentEncoding, contentType)) .Returns(Task.CompletedTask); var module2LogOptions = new ModuleLogOptions(contentEncoding, contentType, filter, LogOutputFraming.None, Option.None <LogsOutputGroupingConfig>(), false); var mod2LogBytes = new byte[80]; logsProvider.Setup(l => l.GetLogs(mod2, module2LogOptions, It.IsAny <CancellationToken>())) .ReturnsAsync(mod2LogBytes); logsUploader.Setup(l => l.UploadLogs(sasUrl, mod2, mod2LogBytes, contentEncoding, contentType)) .Returns(Task.CompletedTask); var module3LogOptions = new ModuleLogOptions(contentEncoding, contentType, filter, LogOutputFraming.None, Option.None <LogsOutputGroupingConfig>(), false); var mod3LogBytes = new byte[120]; logsProvider.Setup(l => l.GetLogs(mod3, module3LogOptions, It.IsAny <CancellationToken>())) .ReturnsAsync(mod3LogBytes); logsUploader.Setup(l => l.UploadLogs(sasUrl, mod3, mod3LogBytes, contentEncoding, contentType)) .Returns(Task.CompletedTask); // Act var logsUploadRequestHandler = new ModuleLogsUploadRequestHandler(logsUploader.Object, logsProvider.Object, runtimeInfoProvider.Object); Option <string> response = await logsUploadRequestHandler.HandleRequest(Option.Maybe(payload), CancellationToken.None); // Assert Assert.True(response.HasValue); var taskStatusResponse = response.OrDefault().FromJson <TaskStatusResponse>(); Assert.NotNull(taskStatusResponse); Assert.NotEmpty(taskStatusResponse.CorrelationId); Assert.Equal(string.Empty, taskStatusResponse.Message); await WaitForBackgroundTaskCompletion(taskStatusResponse.CorrelationId).TimeoutAfter(TimeSpan.FromSeconds(5)); logsProvider.VerifyAll(); logsUploader.VerifyAll(); runtimeInfoProvider.VerifyAll(); }
public async Task TestLogsUploadRequest(string payload, string id, string sasUrl, LogsContentEncoding contentEncoding, LogsContentType contentType, ModuleLogFilter filter) { // Arrange var logsUploader = new Mock <IRequestsUploader>(); var logsProvider = new Mock <ILogsProvider>(); var uploadBytes = new byte[100]; var moduleLogOptions = new ModuleLogOptions(contentEncoding, contentType, filter, LogOutputFraming.None, Option.None <LogsOutputGroupingConfig>(), false); if (contentType == LogsContentType.Text) { Func <ArraySegment <byte>, Task> getLogsCallback = bytes => Task.CompletedTask; logsUploader.Setup(l => l.GetLogsUploaderCallback(sasUrl, id, contentEncoding, contentType)) .ReturnsAsync(getLogsCallback); logsProvider.Setup(l => l.GetLogsStream(id, moduleLogOptions, getLogsCallback, It.IsAny <CancellationToken>())) .Returns(Task.CompletedTask); } else { logsProvider.Setup(l => l.GetLogs(id, moduleLogOptions, It.IsAny <CancellationToken>())) .ReturnsAsync(uploadBytes); logsUploader.Setup(l => l.UploadLogs(sasUrl, id, uploadBytes, contentEncoding, contentType)) .Returns(Task.CompletedTask); } IEnumerable <ModuleRuntimeInfo> moduleRuntimeInfoList = new List <ModuleRuntimeInfo> { new ModuleRuntimeInfo(id, "docker", ModuleStatus.Running, string.Empty, 0, Option.None <DateTime>(), Option.None <DateTime>()) }; var runtimeInfoProvider = Mock.Of <IRuntimeInfoProvider>(r => r.GetModules(It.IsAny <CancellationToken>()) == Task.FromResult(moduleRuntimeInfoList)); // Act var logsUploadRequestHandler = new ModuleLogsUploadRequestHandler(logsUploader.Object, logsProvider.Object, runtimeInfoProvider); Option <string> response = await logsUploadRequestHandler.HandleRequest(Option.Maybe(payload), CancellationToken.None); // Assert Assert.True(response.HasValue); var taskStatusResponse = response.OrDefault().FromJson <TaskStatusResponse>(); Assert.NotNull(taskStatusResponse); Assert.NotEmpty(taskStatusResponse.CorrelationId); Assert.Equal(string.Empty, taskStatusResponse.Message); await WaitForBackgroundTaskCompletion(taskStatusResponse.CorrelationId).TimeoutAfter(TimeSpan.FromSeconds(5)); logsProvider.VerifyAll(); logsUploader.VerifyAll(); Mock.Get(runtimeInfoProvider).VerifyAll(); }
public async Task TestLogsUploadRequestWithInvalidSchemaVersion(string payload, Type exception) { // Arrange var logsUploader = new Mock <IRequestsUploader>(); var logsProvider = new Mock <ILogsProvider>(); var runtimeInfoProvider = Mock.Of <IRuntimeInfoProvider>(); // Act var logsUploadRequestHandler = new ModuleLogsUploadRequestHandler(logsUploader.Object, logsProvider.Object, runtimeInfoProvider); await Assert.ThrowsAsync(exception, () => logsUploadRequestHandler.HandleRequest(Option.Maybe(payload), CancellationToken.None)); }
/// <summary> /// Create new navigation property to singleValueExtendedProperties for me /// </summary> public Command BuildCreateCommand() { var command = new Command("create"); command.Description = "Create new navigation property to singleValueExtendedProperties for me"; // Create options for all the parameters var contactIdOption = new Option <string>("--contact-id", description: "key: id of contact") { }; contactIdOption.IsRequired = true; command.AddOption(contactIdOption); var bodyOption = new Option <string>("--body") { }; bodyOption.IsRequired = true; command.AddOption(bodyOption); var outputOption = new Option <FormatterType>("--output", () => FormatterType.JSON) { IsRequired = true }; command.AddOption(outputOption); var queryOption = new Option <string>("--query"); command.AddOption(queryOption); var jsonNoIndentOption = new Option <bool>("--json-no-indent", r => { if (bool.TryParse(r.Tokens.Select(t => t.Value).LastOrDefault(), out var value)) { return(value); } return(true); }, description: "Disable indentation for the JSON output formatter."); command.AddOption(jsonNoIndentOption); command.SetHandler(async(object[] parameters) => { var contactId = (string)parameters[0]; var body = (string)parameters[1]; var output = (FormatterType)parameters[2]; var query = (string)parameters[3]; var jsonNoIndent = (bool)parameters[4]; var outputFilter = (IOutputFilter)parameters[5]; var outputFormatterFactory = (IOutputFormatterFactory)parameters[6]; var cancellationToken = (CancellationToken)parameters[7]; using var stream = new MemoryStream(Encoding.UTF8.GetBytes(body)); var parseNode = ParseNodeFactoryRegistry.DefaultInstance.GetRootParseNode("application/json", stream); var model = parseNode.GetObjectValue <SingleValueLegacyExtendedProperty>(SingleValueLegacyExtendedProperty.CreateFromDiscriminatorValue); var requestInfo = CreatePostRequestInformation(model, q => { }); requestInfo.PathParameters.Add("contact%2Did", contactId); var errorMapping = new Dictionary <string, ParsableFactory <IParsable> > { { "4XX", ODataError.CreateFromDiscriminatorValue }, { "5XX", ODataError.CreateFromDiscriminatorValue }, }; var response = await RequestAdapter.SendPrimitiveAsync <Stream>(requestInfo, errorMapping: errorMapping, cancellationToken: cancellationToken); response = await outputFilter?.FilterOutputAsync(response, query, cancellationToken) ?? response; var formatterOptions = output.GetOutputFormatterOptions(new FormatterOptionsModel(!jsonNoIndent)); var formatter = outputFormatterFactory.GetFormatter(output); await formatter.WriteOutputAsync(response, formatterOptions, cancellationToken); }, new CollectionBinding(contactIdOption, bodyOption, outputOption, queryOption, jsonNoIndentOption, new TypeBinding(typeof(IOutputFilter)), new TypeBinding(typeof(IOutputFormatterFactory)), new TypeBinding(typeof(CancellationToken)))); return(command); }
/// <summary> /// When set, enables users to easily find assignments of a given type. Read-only. Nullable. /// </summary> public Command BuildGetCommand() { var command = new Command("get"); command.Description = "When set, enables users to easily find assignments of a given type. Read-only. Nullable."; // Create options for all the parameters var educationAssignmentIdOption = new Option <string>("--education-assignment-id", description: "key: id of educationAssignment") { }; educationAssignmentIdOption.IsRequired = true; command.AddOption(educationAssignmentIdOption); var educationCategoryIdOption = new Option <string>("--education-category-id", description: "key: id of educationCategory") { }; educationCategoryIdOption.IsRequired = true; command.AddOption(educationCategoryIdOption); var selectOption = new Option <string[]>("--select", description: "Select properties to be returned") { Arity = ArgumentArity.ZeroOrMore }; selectOption.IsRequired = false; command.AddOption(selectOption); var expandOption = new Option <string[]>("--expand", description: "Expand related entities") { Arity = ArgumentArity.ZeroOrMore }; expandOption.IsRequired = false; command.AddOption(expandOption); var outputOption = new Option <FormatterType>("--output", () => FormatterType.JSON) { IsRequired = true }; command.AddOption(outputOption); var queryOption = new Option <string>("--query"); command.AddOption(queryOption); var jsonNoIndentOption = new Option <bool>("--json-no-indent", r => { if (bool.TryParse(r.Tokens.Select(t => t.Value).LastOrDefault(), out var value)) { return(value); } return(true); }, description: "Disable indentation for the JSON output formatter."); command.AddOption(jsonNoIndentOption); command.SetHandler(async(object[] parameters) => { var educationAssignmentId = (string)parameters[0]; var educationCategoryId = (string)parameters[1]; var select = (string[])parameters[2]; var expand = (string[])parameters[3]; var output = (FormatterType)parameters[4]; var query = (string)parameters[5]; var jsonNoIndent = (bool)parameters[6]; var outputFilter = (IOutputFilter)parameters[7]; var outputFormatterFactory = (IOutputFormatterFactory)parameters[8]; var cancellationToken = (CancellationToken)parameters[9]; var requestInfo = CreateGetRequestInformation(q => { q.QueryParameters.Select = select; q.QueryParameters.Expand = expand; }); requestInfo.PathParameters.Add("educationAssignment%2Did", educationAssignmentId); requestInfo.PathParameters.Add("educationCategory%2Did", educationCategoryId); var errorMapping = new Dictionary <string, ParsableFactory <IParsable> > { { "4XX", ODataError.CreateFromDiscriminatorValue }, { "5XX", ODataError.CreateFromDiscriminatorValue }, }; var response = await RequestAdapter.SendPrimitiveAsync <Stream>(requestInfo, errorMapping: errorMapping, cancellationToken: cancellationToken); response = await outputFilter?.FilterOutputAsync(response, query, cancellationToken) ?? response; var formatterOptions = output.GetOutputFormatterOptions(new FormatterOptionsModel(!jsonNoIndent)); var formatter = outputFormatterFactory.GetFormatter(output); await formatter.WriteOutputAsync(response, formatterOptions, cancellationToken); }, new CollectionBinding(educationAssignmentIdOption, educationCategoryIdOption, selectOption, expandOption, outputOption, queryOption, jsonNoIndentOption, new TypeBinding(typeof(IOutputFilter)), new TypeBinding(typeof(IOutputFormatterFactory)), new TypeBinding(typeof(CancellationToken)))); return(command); }
public abstract Option Eval(Scope <Option> scope, Option param);
public override ReturnCode Execute( Interpreter interpreter, IClientData clientData, ArgumentList arguments, ref Result result ) { ReturnCode code = ReturnCode.Ok; if (interpreter != null) { if (arguments != null) { if (arguments.Count >= 2) { OptionDictionary options = new OptionDictionary( new IOption[] { new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-nonewline", null) }); int argumentIndex = Index.Invalid; code = interpreter.GetOptions(options, arguments, 0, 1, Index.Invalid, false, ref argumentIndex, ref result); if (code == ReturnCode.Ok) { if ((argumentIndex != Index.Invalid) && ((argumentIndex + 2) >= arguments.Count)) { bool newLine = true; if (options.IsPresent("-nonewline")) { newLine = false; } string channelId = Channel.StdOut; if ((argumentIndex + 1) < arguments.Count) { channelId = arguments[argumentIndex]; } Channel channel = interpreter.GetChannel(channelId, ref result); if (channel != null) { Encoding encoding = null; if (interpreter.GetChannelEncoding(channel, ref encoding) == ReturnCode.Ok) { string output = arguments[arguments.Count - 1]; try { if (channel.IsVirtualOutput) { // // NOTE: The encoding is ignored, because this is directly // from the input string, which is already Unicode. // channel.AppendVirtualOutput(output); if (newLine) { channel.AppendVirtualOutput(Channel.NewLine); } result = String.Empty; } else { BinaryWriter binaryWriter = interpreter.GetChannelBinaryWriter(channel); if (binaryWriter != null) { byte[] bytes = null; code = StringOps.GetBytes( encoding, output, EncodingType.Binary, ref bytes, ref result); if (code == ReturnCode.Ok) { channel.CheckAppend(); #if CONSOLE if (channel.IsConsoleStream) { int offset = 0; int count = bytes.Length; while (count > 0) { int writeCount = Math.Min( count, _Hosts.Console.SafeWriteSize); binaryWriter.Write(bytes, offset, writeCount); offset += writeCount; count -= writeCount; } } else #endif { binaryWriter.Write(bytes); } if (newLine) { binaryWriter.Write(Channel.NewLine); } #if MONO || MONO_HACKS // // HACK: *MONO* As of Mono 2.8.0, it seems that Mono "loses" // output unless a flush is performed right after a // write. So far, this has only been observed for the // console channels; however, always using flush here // on Mono shouldn't cause too many problems, except a // slight loss in performance. // https://bugzilla.novell.com/show_bug.cgi?id=645193 // if (CommonOps.Runtime.IsMono()) { binaryWriter.Flush(); /* throw */ } else #endif { // // NOTE: Check if we should automatically flush the channel // after each "logical" write done by this command. // /* IGNORED */ channel.CheckAutoFlush(); } result = String.Empty; } } else { result = String.Format( "failed to get binary writer for channel \"{0}\"", channelId); code = ReturnCode.Error; } } } catch (Exception e) { Engine.SetExceptionErrorCode(interpreter, e); result = e; code = ReturnCode.Error; } } else { result = String.Format( "failed to get encoding for channel \"{0}\"", channelId); code = ReturnCode.Error; } } else { code = ReturnCode.Error; } } else { if ((argumentIndex != Index.Invalid) && Option.LooksLikeOption(arguments[argumentIndex])) { result = OptionDictionary.BadOption(options, arguments[argumentIndex]); } else { result = "wrong # args: should be \"puts ?-nonewline? ?channelId? string\""; } code = ReturnCode.Error; } } } else { result = "wrong # args: should be \"puts ?-nonewline? ?channelId? string\""; code = ReturnCode.Error; } } else { result = "invalid argument list"; code = ReturnCode.Error; } } else { result = "invalid interpreter"; code = ReturnCode.Error; } return(code); }
/// <summary> /// The collection of single-value extended properties defined for the contact. Read-only. Nullable. /// </summary> public Command BuildListCommand() { var command = new Command("list"); command.Description = "The collection of single-value extended properties defined for the contact. Read-only. Nullable."; // Create options for all the parameters var contactIdOption = new Option <string>("--contact-id", description: "key: id of contact") { }; contactIdOption.IsRequired = true; command.AddOption(contactIdOption); var topOption = new Option <int?>("--top", description: "Show only the first n items") { }; topOption.IsRequired = false; command.AddOption(topOption); var skipOption = new Option <int?>("--skip", description: "Skip the first n items") { }; skipOption.IsRequired = false; command.AddOption(skipOption); var searchOption = new Option <string>("--search", description: "Search items by search phrases") { }; searchOption.IsRequired = false; command.AddOption(searchOption); var filterOption = new Option <string>("--filter", description: "Filter items by property values") { }; filterOption.IsRequired = false; command.AddOption(filterOption); var countOption = new Option <bool?>("--count", description: "Include count of items") { }; countOption.IsRequired = false; command.AddOption(countOption); var orderbyOption = new Option <string[]>("--orderby", description: "Order items by property values") { Arity = ArgumentArity.ZeroOrMore }; orderbyOption.IsRequired = false; command.AddOption(orderbyOption); var selectOption = new Option <string[]>("--select", description: "Select properties to be returned") { Arity = ArgumentArity.ZeroOrMore }; selectOption.IsRequired = false; command.AddOption(selectOption); var expandOption = new Option <string[]>("--expand", description: "Expand related entities") { Arity = ArgumentArity.ZeroOrMore }; expandOption.IsRequired = false; command.AddOption(expandOption); var outputOption = new Option <FormatterType>("--output", () => FormatterType.JSON) { IsRequired = true }; command.AddOption(outputOption); var queryOption = new Option <string>("--query"); command.AddOption(queryOption); var jsonNoIndentOption = new Option <bool>("--json-no-indent", r => { if (bool.TryParse(r.Tokens.Select(t => t.Value).LastOrDefault(), out var value)) { return(value); } return(true); }, description: "Disable indentation for the JSON output formatter."); command.AddOption(jsonNoIndentOption); command.SetHandler(async(object[] parameters) => { var contactId = (string)parameters[0]; var top = (int?)parameters[1]; var skip = (int?)parameters[2]; var search = (string)parameters[3]; var filter = (string)parameters[4]; var count = (bool?)parameters[5]; var orderby = (string[])parameters[6]; var select = (string[])parameters[7]; var expand = (string[])parameters[8]; var output = (FormatterType)parameters[9]; var query = (string)parameters[10]; var jsonNoIndent = (bool)parameters[11]; var outputFilter = (IOutputFilter)parameters[12]; var outputFormatterFactory = (IOutputFormatterFactory)parameters[13]; var cancellationToken = (CancellationToken)parameters[14]; var requestInfo = CreateGetRequestInformation(q => { q.QueryParameters.Top = top; q.QueryParameters.Skip = skip; if (!String.IsNullOrEmpty(search)) { q.QueryParameters.Search = search; } if (!String.IsNullOrEmpty(filter)) { q.QueryParameters.Filter = filter; } q.QueryParameters.Count = count; q.QueryParameters.Orderby = orderby; q.QueryParameters.Select = select; q.QueryParameters.Expand = expand; }); requestInfo.PathParameters.Add("contact%2Did", contactId); var errorMapping = new Dictionary <string, ParsableFactory <IParsable> > { { "4XX", ODataError.CreateFromDiscriminatorValue }, { "5XX", ODataError.CreateFromDiscriminatorValue }, }; var response = await RequestAdapter.SendPrimitiveAsync <Stream>(requestInfo, errorMapping: errorMapping, cancellationToken: cancellationToken); response = await outputFilter?.FilterOutputAsync(response, query, cancellationToken) ?? response; var formatterOptions = output.GetOutputFormatterOptions(new FormatterOptionsModel(!jsonNoIndent)); var formatter = outputFormatterFactory.GetFormatter(output); await formatter.WriteOutputAsync(response, formatterOptions, cancellationToken); }, new CollectionBinding(contactIdOption, topOption, skipOption, searchOption, filterOption, new NullableBooleanBinding(countOption), orderbyOption, selectOption, expandOption, outputOption, queryOption, jsonNoIndentOption, new TypeBinding(typeof(IOutputFilter)), new TypeBinding(typeof(IOutputFormatterFactory)), new TypeBinding(typeof(CancellationToken)))); return(command); }
public static Correlation Correlation(string columnA, string columnB, Option <string> where) => new Correlation(columnA, columnB, where);
public async Task GetModuleLogsTest() { // Arrange string id = "mod1"; string dummyLogs = new string('*', 1000); Stream GetLogsStream() => new MemoryStream(Encoding.UTF8.GetBytes(dummyLogs)); var systemInfoResponse = new SystemInfoResponse { OSType = OperatingSystemType, Architecture = Architecture }; ContainerLogsParameters receivedContainerLogsParameters = null; var containerOperations = new Mock <IContainerOperations>(); containerOperations.Setup(co => co.GetContainerLogsAsync(id, It.IsAny <ContainerLogsParameters>(), It.IsAny <CancellationToken>())) .Callback <string, ContainerLogsParameters, CancellationToken>((m, c, t) => receivedContainerLogsParameters = c) .ReturnsAsync(GetLogsStream); var dockerClient = Mock.Of <IDockerClient>( dc => dc.Containers == containerOperations.Object && dc.System == Mock.Of <ISystemOperations>(so => so.GetSystemInfoAsync(default(CancellationToken)) == Task.FromResult(systemInfoResponse))); var runtimeInfoProvider = await RuntimeInfoProvider.CreateAsync(dockerClient); // Act Stream receivedLogsStream = await runtimeInfoProvider.GetModuleLogs(id, false, Option.None <int>(), Option.None <string>(), CancellationToken.None); // Assert Assert.NotNull(receivedContainerLogsParameters); Assert.False(receivedContainerLogsParameters.Follow); Assert.Null(receivedContainerLogsParameters.Tail); Assert.Null(receivedContainerLogsParameters.Since); Assert.True(receivedContainerLogsParameters.ShowStderr); Assert.True(receivedContainerLogsParameters.ShowStdout); var buffer = new byte[1024]; int readBytes = await receivedLogsStream.ReadAsync(buffer); Assert.Equal(1000, readBytes); string receivedLogs = Encoding.UTF8.GetString(buffer, 0, readBytes); Assert.Equal(dummyLogs, receivedLogs); // Act receivedLogsStream = await runtimeInfoProvider.GetModuleLogs(id, true, Option.Some(1000), Option.None <string>(), CancellationToken.None); // Assert Assert.NotNull(receivedContainerLogsParameters); Assert.True(receivedContainerLogsParameters.Follow); Assert.Equal("1000", receivedContainerLogsParameters.Tail); Assert.Null(receivedContainerLogsParameters.Since); Assert.True(receivedContainerLogsParameters.ShowStderr); Assert.True(receivedContainerLogsParameters.ShowStdout); buffer = new byte[1024]; readBytes = await receivedLogsStream.ReadAsync(buffer); Assert.Equal(1000, readBytes); receivedLogs = Encoding.UTF8.GetString(buffer, 0, readBytes); Assert.Equal(dummyLogs, receivedLogs); // Act receivedLogsStream = await runtimeInfoProvider.GetModuleLogs(id, true, Option.None <int>(), Option.Some("1552887267"), CancellationToken.None); // Assert Assert.NotNull(receivedContainerLogsParameters); Assert.True(receivedContainerLogsParameters.Follow); Assert.Null(receivedContainerLogsParameters.Tail); Assert.Equal("1552887267", receivedContainerLogsParameters.Since); Assert.True(receivedContainerLogsParameters.ShowStderr); Assert.True(receivedContainerLogsParameters.ShowStdout); buffer = new byte[1024]; readBytes = await receivedLogsStream.ReadAsync(buffer); Assert.Equal(1000, readBytes); receivedLogs = Encoding.UTF8.GetString(buffer, 0, readBytes); Assert.Equal(dummyLogs, receivedLogs); }
public static Sum Sum(string column, Option <string> where) => new Sum(column, where);
/// <summary> /// The image and other file resources in OneNote pages. Getting a resources collection is not supported, but you can get the binary content of a specific resource. Read-only. Nullable. /// </summary> public Command BuildGetCommand() { var command = new Command("get"); command.Description = "The image and other file resources in OneNote pages. Getting a resources collection is not supported, but you can get the binary content of a specific resource. Read-only. Nullable."; // Create options for all the parameters var groupIdOption = new Option <string>("--group-id", description: "key: id of group") { }; groupIdOption.IsRequired = true; command.AddOption(groupIdOption); var siteIdOption = new Option <string>("--site-id", description: "key: id of site") { }; siteIdOption.IsRequired = true; command.AddOption(siteIdOption); var onenoteResourceIdOption = new Option <string>("--onenote-resource-id", description: "key: id of onenoteResource") { }; onenoteResourceIdOption.IsRequired = true; command.AddOption(onenoteResourceIdOption); var selectOption = new Option <string[]>("--select", description: "Select properties to be returned") { Arity = ArgumentArity.ZeroOrMore }; selectOption.IsRequired = false; command.AddOption(selectOption); var expandOption = new Option <string[]>("--expand", description: "Expand related entities") { Arity = ArgumentArity.ZeroOrMore }; expandOption.IsRequired = false; command.AddOption(expandOption); var outputOption = new Option <FormatterType>("--output", () => FormatterType.JSON) { IsRequired = true }; command.AddOption(outputOption); var queryOption = new Option <string>("--query"); command.AddOption(queryOption); var jsonNoIndentOption = new Option <bool>("--json-no-indent", r => { if (bool.TryParse(r.Tokens.Select(t => t.Value).LastOrDefault(), out var value)) { return(value); } return(true); }, description: "Disable indentation for the JSON output formatter."); command.AddOption(jsonNoIndentOption); command.SetHandler(async(object[] parameters) => { var groupId = (string)parameters[0]; var siteId = (string)parameters[1]; var onenoteResourceId = (string)parameters[2]; var select = (string[])parameters[3]; var expand = (string[])parameters[4]; var output = (FormatterType)parameters[5]; var query = (string)parameters[6]; var jsonNoIndent = (bool)parameters[7]; var outputFilter = (IOutputFilter)parameters[8]; var outputFormatterFactory = (IOutputFormatterFactory)parameters[9]; var cancellationToken = (CancellationToken)parameters[10]; var requestInfo = CreateGetRequestInformation(q => { q.QueryParameters.Select = select; q.QueryParameters.Expand = expand; }); requestInfo.PathParameters.Add("group%2Did", groupId); requestInfo.PathParameters.Add("site%2Did", siteId); requestInfo.PathParameters.Add("onenoteResource%2Did", onenoteResourceId); var errorMapping = new Dictionary <string, ParsableFactory <IParsable> > { { "4XX", ODataError.CreateFromDiscriminatorValue }, { "5XX", ODataError.CreateFromDiscriminatorValue }, }; var response = await RequestAdapter.SendPrimitiveAsync <Stream>(requestInfo, errorMapping: errorMapping, cancellationToken: cancellationToken); response = await outputFilter?.FilterOutputAsync(response, query, cancellationToken) ?? response; var formatterOptions = output.GetOutputFormatterOptions(new FormatterOptionsModel(!jsonNoIndent)); var formatter = outputFormatterFactory.GetFormatter(output); await formatter.WriteOutputAsync(response, formatterOptions, cancellationToken); }, new CollectionBinding(groupIdOption, siteIdOption, onenoteResourceIdOption, selectOption, expandOption, outputOption, queryOption, jsonNoIndentOption, new TypeBinding(typeof(IOutputFilter)), new TypeBinding(typeof(IOutputFormatterFactory)), new TypeBinding(typeof(CancellationToken)))); return(command); }
public static Maximum Maximum(string column, Option <string> where) => new Maximum(column, where);
public static StandardDeviation StandardDeviation(string column, Option <string> where) => new StandardDeviation(column, where);
public static MutualInformation MutualInformation(Option <string> column, Option <string> where) => new MutualInformation(new[] { column.Value }, where);
public static Mean Mean(string column, Option <string> where) => new Mean(column, where);
public static Compliance Compliance(string instance, Column predicate, Option <string> where) => new Compliance(instance, predicate, where);
public static MinLength MinLength(string column, Option <string> where) => new MinLength(column, where);
public static Distinctness Distinctness(IEnumerable <string> columns, Option <string> where) => new Distinctness(columns, where);
public static MutualInformation MutualInformation(IEnumerable <string> columns, Option <string> where) => new MutualInformation(columns, where);
public static Uniqueness Uniqueness(IEnumerable <string> columns, Option <string> where) => new Uniqueness(columns, where);
public static UniqueValueRatio UniqueValueRatio(IEnumerable <string> columns, Option <string> where) => new UniqueValueRatio(columns, where);
public static Completeness Completeness(Option <string> column) => new Completeness(column);
public static Uniqueness Uniqueness(Option <string> column, Option <string> where) => new Uniqueness(new[] { column.Value }, where);
public static Histogram Histogram(string column, Option <string> where, int maxDetailBins) => new Histogram(column, where, Option <Func <Column, Column> > .None, maxDetailBins);
public static Completeness Completeness(Option <string> column, Option <string> where) => new Completeness(column, where);