public static Create ( Item1, Item2 ) : T2>.Tuple |
||
Результат | T2>.Tuple |
/// <summary> /// Calculate Fluctuation Index, which is defined as (Vmax-Vmin)/7, Vmax and Vmin are the maximum and minimum values in the past 7 days /// </summary> private void CalculateFluctuationIndex(List<AFAttribute> leafValueAttributes) { var timeRange = new AFTimeRange(_programStartTime.AddDays(-7), _programStartTime); var results = SummarizeAttributes(leafValueAttributes, attributeList => { try { return attributeList.Data.Summary( timeRange: timeRange, summaryTypes: AFSummaryTypes.Range, calculationBasis: AFCalculationBasis.EventWeighted, timeType: AFTimestampCalculation.Auto, pagingConfig: _pagingConfig).ToList(); } catch (OperationCanceledException) { Console.WriteLine("Exception reported at CalculateFluctuationIndex : {0}", _pagingConfig.Error); throw _pagingConfig.Error; } }); var orderedResults = results .Select(d => d[AFSummaryTypes.Range]) .Where(v => v.IsGood) .Select(v => Tuple.Create(v.Attribute.Element.Name, Convert.ToSingle(v.Value) / 7)) .OrderBy(t => t.Item1); using (StreamWriter writer = new StreamWriter(FluctuationIndexReportFile + _programStartTime.ToString("_MMddyyyy_HHmm") + @".csv", true)) { writer.WriteLine(@"Name, Fluctuation Index"); foreach (var elementNameAndValue in orderedResults) { writer.WriteLine(String.Format("{0}, {1}", elementNameAndValue.Item1, elementNameAndValue.Item2.ToString())); } } }
Tuple <Wrap, Wrap> GetWhereAndBeforeOf(Wrap what, Wrap anchor, MoveDestination dst) { if (dst == MoveDestination.Into) { if (what is VideoWrap && anchor is VideoWrap) { return(GetWhereAndBeforeOf(what, anchor, MoveDestination.After)); } return(new Tuple <Wrap, Wrap>(anchor, null)); } if (dst == MoveDestination.Before) { return(Tuple.Create(anchor.Parent, anchor)); } if (dst == MoveDestination.After) { if (anchor.Items.Count == 0) { if (anchor.Parent == null) { return(new Tuple <Wrap, Wrap>(null, null)); } var index = anchor.Parent.Items.IndexOf(anchor); if (index == anchor.Parent.Items.Count - 1) { return(new Tuple <Wrap, Wrap>(anchor.Parent, null)); } return (Tuple.Create(anchor.Parent, anchor.Parent.Items[index + 1])); } return(Tuple.Create(anchor, anchor.Items[0])); } throw new Exception("Cannot fall here"); }
public async Task <Dictionary <Tuple <Guid, string>, List <ContentEntry> > > GetContentWithCategory(string pCategoryName, int pageSize) { var categoryList = await ContentAccessor.All <Categories>() .Where(x => x.ParentCategory.Name == pCategoryName) .ToListAsync(); var dictContent = new Dictionary <Tuple <Guid, string>, List <ContentEntry> >(); foreach (var categoryItem in categoryList) { var contentList = await ContentAccessor.All <ContentEntry>().Where(x => x.Category.Id == categoryItem.Id).ToListAsync(); var tuple = Tuple.Create(categoryItem.Id, categoryItem.Name); dictContent.Add(tuple, contentList); } return(dictContent); //var contentList = await ContentAccessor.All<ContentEntry>() // .Where(x => x.Category.Name == pCategoryName) // .Select(x => new // { // Category = x.Category, // Content = x // }) // .GroupBy(x => x.Category.Name) // .ToDictionaryAsync(x => x.Key, c => c.Select(v => v.Content)); //var cateList = ContentAccessor.All<Categories>() // .Where(x => x.ParentCategory.Name == pCategoryName) // .Select(x => new // { // Category = x, // ContentList = x.ContentList.Take(pageSize).ToList() // }) // .GroupBy(x => x.Category.Name); //return await cateList.ToDictionaryAsync(x => x.Key, c => c.Select(v => v.ContentList)); }
public async Task <Tuple <bool> > CheckRenewalStatusByUserID(int UserID) { Tuple <bool> result = null; int status = -1; var parameters = new DynamicParameters(); try { using (SqlConnection con = new SqlConnection(_dvDb)) { con.Open(); parameters.Add("@UserID", UserID, DbType.Int32); status = await con.ExecuteScalarAsync <int>("[dbo].[Check_RenewalStatus]", parameters, commandType : CommandType.StoredProcedure, commandTimeout : 300); con.Close(); } if (status == 1) { result = Tuple.Create(true); } else if (status == 0) { result = Tuple.Create(false); } else { result = Tuple.Create(false); } } catch (Exception ex) { ErrorLog.Write(ex); result = Tuple.Create(false); } return(result); }
public IEnumerable <Tuple <Chromosome <string>, Chromosome <string> > > Select(IList <Chromosome <string> > chromosomes) { Contract.Requires <ArgumentNullException>(chromosomes != null); Contract.Requires <InvalidOperationException>(chromosomes.Count != 0); var list = new List <Chromosome <string> >(); while (list.Count < Count) { var number = Random.NextDouble(); var sum = 0.0; for (var i = 0; i < chromosomes.Count; i++) { sum += chromosomes[i].Fitness / Total; if (sum > number) { if (!list.Contains(chromosomes[i])) { list.Add(chromosomes[i]); } break; } } } var tupleList = new List <Tuple <Chromosome <string>, Chromosome <string> > >(); for (var i = 0; i < list.Count; i += 2) { tupleList.Add(Tuple.Create <Chromosome <string>, Chromosome <string> >(list[i], list[i + 1])); } return(tupleList.AsEnumerable()); }
public List<DateTime> PopularMonths(List<DateTime> dates) { var DateTimeWithCounterList = new List<Tuple<DateTime, int>>(); int PreviousYear = DateTime.Now.Year - 1; foreach (DateTime IterDate in dates) { if (IterDate.Year == PreviousYear) { // вычисляем начало месяца для текущей даты var DateMonthStart = new DateTime(IterDate.Year, IterDate.Month, 1, 0, 0, 0); // ищем эту дату во временном списке var index = DateTimeWithCounterList.FindIndex(item => item.Item1 == DateMonthStart); // кортежи можно создавать по-разному if (index == -1) { // такой даты нет - добавляю (используя конструктор) DateTimeWithCounterList. Add(new Tuple<DateTime, int>(DateMonthStart, 1)); } else { // дата есть - увеличиваем счетчик // свойства кортежа неизменяемые, поэтому перезаписываем текущий элемент новым кортежем, который создаем статическим методом DateTimeWithCounterList[index] = Tuple.Create(DateTimeWithCounterList[index].Item1, DateTimeWithCounterList[index].Item2 + 1); } } } return DateTimeWithCounterList .OrderByDescending(item => item.Item2) .ThenBy(item => item.Item1) .Select(item => item.Item1) .ToList(); }
/// <summary> /// Main method to run workflow. Loads a JSON file containing integer intervals with Start and Stop values. /// </summary> /// <param name="args">Expecting optional string arg[0] that is a path to a valid JSON file. /// If not provided, defaults to a project data file.</param> static void Main(string[] args) { string path = ((args.Length == 0) ? @".\SampleRanges3.json" : args[0]); // Default JSON files in $(OutDir) RangeCollection coll = new RangeCollection(); if (File.Exists(path)) { using (Stream stream = File.OpenRead(path)) { var serializer = new DataContractJsonSerializer(typeof(RangeCollection)); coll = (RangeCollection)serializer.ReadObject(stream); } List<Tuple<int, int>> tuples = new List<Tuple<int, int>>(); foreach (Range range in coll.Ranges) { bool startIsInt; bool stopIsInt; startIsInt = Int32.TryParse(range.Start, out int start); // Confirm each value is an integer stopIsInt = Int32.TryParse(range.Stop, out int stop); if (startIsInt && stopIsInt) { tuples.Add(Tuple.Create(start, stop)); } } RangeList rangeList = new RangeList(tuples); rangeList.PrintTuples("Unsorted"); rangeList.Sort(); rangeList.PrintTuples("Sorted"); rangeList.Merge(); rangeList.PrintTuples("Merged"); } }
void GetRemoteDescription() { string address = Path; if (!PathIsAppServer) { address = LocalServer.GetDescriptionUrl(Path); } using (var client = new System.Net.WebClient()) { string s = client.DownloadString(address); var responseSchema = JsonConvert.DeserializeObject <Resthopper.IO.IoResponseSchema>(s); _description = responseSchema.Description; _inputParams = new Dictionary <string, Tuple <InputParamSchema, IGH_Param> >(); _outputParams = new Dictionary <string, IGH_Param>(); foreach (var input in responseSchema.Inputs) { string inputParamName = input.Name; if (inputParamName.StartsWith("RH_IN:")) { var chunks = inputParamName.Split(new char[] { ':' }); inputParamName = chunks[chunks.Length - 1]; } _inputParams[inputParamName] = Tuple.Create(input, ParamFromIoResponseSchema(input)); } foreach (var output in responseSchema.Outputs) { string outputParamName = output.Name; if (outputParamName.StartsWith("RH_OUT:")) { var chunks = outputParamName.Split(new char[] { ':' }); outputParamName = chunks[chunks.Length - 1]; } _outputParams[outputParamName] = ParamFromIoResponseSchema(output); } } }
/// <summary> /// Extracts attributes from the skill tree nodes and fills _nodeAttributes /// and _areTravelNodes. /// </summary> private void ExtractNodeAttributes() { var skillNodes = SkillTree.Skillnodes; _nodeAttributes = new List <Tuple <int, float> > [ushort.MaxValue]; _areTravelNodes = new Dictionary <ushort, bool>(skillNodes.Count); foreach (var node in skillNodes) { var id = node.Key; var skillNode = node.Value; // Remove attributes that have no constraints. // Replace attributes that have constraints with a tuple of their number and the value. // For attributes with more than one value, the first one is selected, // that is reasonable for the attributes the skill tree currently has. // Attributes without value are not supported. If a constraint referencing an attribute // without value slips through, it will break. _nodeAttributes[id] = (from attr in SkillTree.ExpandHybridAttributes(skillNode.Attributes) where _attrNameLookup.ContainsKey(attr.Key) from constraint in _attrNameLookup[attr.Key] let value = attr.Value[0] * _attrConversionMultipliers[Tuple.Create(attr.Key, constraint)] select Tuple.Create(constraint, value)) .ToList(); // Set if the node is a travel node. if (skillNode.Attributes.Count == 1 && TravelNodeRegex.IsMatch(skillNode.Attributes.Keys.First()) && skillNode.Attributes.Values.First().Any(v => (int)v == 10)) { _areTravelNodes[id] = true; } else { _areTravelNodes[id] = false; } } }
public void DecodeImage(BtnEvent btnEvent) { try { IConfig config = _stegoUI.Config; Bitmap coverImage = _stegoUI.DisplayImage; string encryptionKey = string.Empty; _verifyUserInput.Image(coverImage); if (config.Encrypt) { encryptionKey = _stegoUI.GetEncryptionKey(); encryptionKey = _verifyUserInput.EncryptionKey(encryptionKey); } string stegoSeed = _stegoUI.GetStegoSeed(); stegoSeed = _verifyUserInput.StegoSeed(stegoSeed); _backgroundWorkerProgressBar.Text = "Decoding..."; _backgroundWorkerProgressBar.label1.Text = "Extracting message from image..."; _backgroundWorkerProgressBar.Show(); // Show that we're working on it! _stegoUI.Enable = false; // Disable the main-window, so the user click on anything they're not supposed to. var args = Tuple.Create <Bitmap, string, string, bool, bool>(coverImage, encryptionKey, stegoSeed, config.Encrypt, config.Compress); _decodeWorker.RunWorkerAsync(args); } catch (NotifyUserException exception) { ShowNotification(new DisplayNotificationEvent(exception.Message, exception.Title)); } catch (AbortActionException) { } }
public async Task <Tuple <bool, string> > CheckHomeLoanByUserID(int UserID) { Tuple <bool, string> result = null; int loanStatu = -1; var parameters = new DynamicParameters(); try { using (SqlConnection con = new SqlConnection(_dvDb)) { con.Open(); parameters.Add("@UserID", UserID, DbType.Int32); loanStatu = await con.ExecuteScalarAsync <int>("[dbo].[Check_HomeLoan]", parameters, commandType : CommandType.StoredProcedure, commandTimeout : 300); con.Close(); } if (loanStatu == 1) { result = Tuple.Create(true, ""); } else if (loanStatu == 0) { result = Tuple.Create(false, "Payment not done for previous applied loan"); } else { result = Tuple.Create(false, "Oops! Error while checking home loan"); } } catch (Exception ex) { ErrorLog.Write(ex); result = Tuple.Create(false, "Oops! Error while checking home loan"); } return(result); }
private async Task ProcessProgressChange( ExportJobConfiguration exportJobConfiguration, ExportJobProgress progress, List <Tuple <string, string> > queryParametersList, string continuationToken, bool forceCommit, CancellationToken cancellationToken) { // Update the continuation token in local cache and queryParams. // We will add or udpate the continuation token in the query parameters list. progress.UpdateContinuationToken(continuationToken); bool replacedContinuationToken = false; for (int index = 0; index < queryParametersList.Count; index++) { if (queryParametersList[index].Item1 == KnownQueryParameterNames.ContinuationToken) { queryParametersList[index] = Tuple.Create(KnownQueryParameterNames.ContinuationToken, progress.ContinuationToken); replacedContinuationToken = true; } } if (!replacedContinuationToken) { queryParametersList.Add(Tuple.Create(KnownQueryParameterNames.ContinuationToken, progress.ContinuationToken)); } if (progress.Page % _exportJobRecord.NumberOfPagesPerCommit == 0 || forceCommit) { // Commit the changes. await _exportDestinationClient.CommitAsync(exportJobConfiguration, cancellationToken); // Update the job record. await UpdateJobRecordAsync(cancellationToken); } }
public IHttpActionResult AddStudentToClass(int id, [FromBody] string SSN) { if (!_courses.Exists(c => c.ID == id)) { return(NotFound()); } if (!_student.Exists(s => s.SSN == SSN)) { return(NotFound()); } var newTuple = Tuple.Create(SSN, id); if (_studentInClass.Contains(newTuple)) { return(Conflict()); } _studentInClass.Add(newTuple); var location = Url.Link("StudentInCourse", new { id = id }); return(Created(location, SSN)); }
public static Tuple <string, string> ParseActorAndSoundNames(string actorAndSoundString) { var words = new List <string>(actorAndSoundString.Trim().Split(' ')); // ReSharper disable once ConvertIfStatementToSwitchStatement if (words.Count == 1 && words[0].IsNullOrWhiteSpace()) { words[0] = "#random"; words.Add("#random"); } else if (words.Count == 1) { words.Add("#random"); } else if (words.Count > 2) { for (var i = 2; i < words.Count; i++) { words[1] += " " + words[i]; } } return(Tuple.Create(words[0], words[1])); }
public static void Main() { Tuple<string, double, int>[] scores = { Tuple.Create("Jack", 78.8, 8), Tuple.Create("Abbey", 92.1, 9), Tuple.Create("Dave", 88.3, 9), Tuple.Create("Sam", 91.7, 8), Tuple.Create("Ed", 71.2, 5), Tuple.Create("Penelope", 82.9, 8), Tuple.Create("Linda", 99.0, 9), Tuple.Create("Judith", 84.3, 9) }; Console.WriteLine("The values in unsorted order:"); foreach (var score in scores) Console.WriteLine(score.ToString()); Console.WriteLine(); Array.Sort(scores); Console.WriteLine("The values in sorted order:"); foreach (var score in scores) Console.WriteLine(score.ToString()); }
static ExportDescriptorPromise[] GetExportFactoryDescriptors <TProduct>(CompositionContract exportFactoryContract, DependencyAccessor definitionAccessor) { var productContract = exportFactoryContract.ChangeType(typeof(TProduct)); var boundaries = new string[0]; IEnumerable <string> specifiedBoundaries; CompositionContract unwrapped; if (exportFactoryContract.TryUnwrapMetadataConstraint(Constants.SharingBoundaryImportMetadataConstraintName, out specifiedBoundaries, out unwrapped)) { productContract = unwrapped.ChangeType(typeof(TProduct)); boundaries = (specifiedBoundaries ?? new string[0]).ToArray(); } return(definitionAccessor.ResolveDependencies("product", productContract, false) .Select(d => new ExportDescriptorPromise( exportFactoryContract, Formatters.Format(typeof(ExportFactory <TProduct>)), false, () => new[] { d }, _ => { var dsc = d.Target.GetDescriptor(); var da = dsc.Activator; return ExportDescriptor.Create((c, o) => { return new ExportFactory <TProduct>(() => { var lifetimeContext = new LifetimeContext(c, boundaries); return Tuple.Create <TProduct, Action>((TProduct)CompositionOperation.Run(lifetimeContext, da), lifetimeContext.Dispose); }); }, dsc.Metadata); })) .ToArray()); }
/// <summary> /// Presses the specified virtual key to the window at a specified interval. /// </summary> /// <param name="key">The virtual key to press.</param> /// <param name="interval">The interval between the key activations.</param> public void Press(Keys key, TimeSpan interval) { // Create the tuple var tuple = Tuple.Create(Window.Handle, key); // If the key is already pressed if (PressedKeys.Contains(tuple)) return; // Add the key to the collection PressedKeys.Add(tuple); // Start a new task to press the key at the specified interval Task.Run(async () => { // While the key must be pressed while (PressedKeys.Contains(tuple)) { // Press the key Press(key); // Wait the interval await Task.Delay(interval); } }); }
public static Tuple <DateTime, float> RoznicaKursu(Dictionary <DateTime, Kurs> money) { float? roznica = null; DateTime data = DateTime.Now; foreach (var t in money) { if (roznica == null) { roznica = Math.Abs(t.Value.Kurs_Kupna - t.Value.Kurs_Sprzedarzy); data = t.Key; } else { if (roznica < Math.Abs(t.Value.Kurs_Kupna - t.Value.Kurs_Sprzedarzy)) { roznica = Math.Abs(t.Value.Kurs_Kupna - t.Value.Kurs_Sprzedarzy); Console.WriteLine(t.Key); data = t.Key; } } } return(Tuple.Create(data, (float)roznica)); }
private void RewriteMethod() { if (!this.Method.Equals("POST", StringComparison.OrdinalIgnoreCase)) { return; } var overrides = new List <Tuple <string, string> > { Tuple.Create("_method form input element", (string)this.Form["_method"]), Tuple.Create("X-HTTP-Method-Override form input element", (string)this.Form["X-HTTP-Method-Override"]), Tuple.Create("X-HTTP-Method-Override header", this.Headers["X-HTTP-Method-Override"].FirstOrDefault()) }; var providedOverride = overrides.Where(x => !string.IsNullOrEmpty(x.Item2)); if (!providedOverride.Any()) { return; } if (providedOverride.Count() > 1) { var overrideSources = string.Join(", ", providedOverride); var errorMessage = string.Format("More than one HTTP method override was provided. The provided values where: {0}", overrideSources); throw new InvalidOperationException(errorMessage); } this.Method = providedOverride.Single().Item2; }
public JsonResult Pay(int userId, float ammount, bool isCreditCard) { //We create a default Tuple to return the defaults data var result = Tuple.Create <bool, string>(false, "The ammount should be over 0."); //if the ammount is superior to 0 if (ammount > 0) { //we get the user by it's Id var user = _userService.GetUserById(userId); //if we find a User if (user != null) { //We call the service Method that let's the User Pay result = _userService.Pay(userId, ammount, isCreditCard); //We return the success and the message that we got from Pay() return(Json(new { success = result.Item1, message = result.Item2 })); } //else we return success false and User not found return(Json(new { success = result.Item1, message = "User not found." })); } //else we return success false and Ammount should be over 0 return(Json(new { success = result.Item1, message = result.Item2 })); }
public override Task <Tuple <Address, TaskCompletionSource <IAssociationEventListener> > > Listen() { var listenAddress = NodeBuilder.BuildNode().Host(Settings.Hostname).WithPort(Settings.Port); var newServerChannel = NewServer(listenAddress); newServerChannel.Open(); //Block reads until a handler actor is registered //TODO ConnectionGroup.TryAdd(newServerChannel); ServerChannel = newServerChannel; var addr = NodeToAddress(newServerChannel.Local, SchemeIdentifier, System.Name, Settings.Hostname); if (addr == null) { throw new HeliosNodeException("Unknown local address type {0}", newServerChannel.Local); } LocalAddress = addr; AssociationListenerPromise.Task.ContinueWith(result => ServerChannel.BeginReceive(), TaskContinuationOptions.AttachedToParent & TaskContinuationOptions.ExecuteSynchronously); return(Task.Run(() => Tuple.Create(addr, AssociationListenerPromise))); }
private void SetupPluginAggregator() { if (!LoadPlugins) { return; } var settings = System.Configuration.ConfigurationManager.AppSettings; var configs = settings .AllKeys .Where(k => k.Contains(':')) //Ignore keys that don't have a colon to indicate which plugin they go to .Select(k => Tuple.Create(k.Split(':'), settings[k])) //Get the data -- split the key to get the plugin name and setting name, look up the key to get the value .GroupBy(t => t.Item1[0]) //Group the settings based on which plugin they're for .ToDictionary( group => group.Key, //Index the outer dictionary based on plugin group => group.ToDictionary( t => t.Item1[1], //Index the inner dictionary based on setting name t => t.Item2 //The actual value of the setting ) ); PluginAggregator = new MEF.PluginAggregator(configs, new Utilities.PluginLogger(), PluginBlacklist); FirstChanceExceptionHandler.IgnoreModules(PluginAggregator.Select(p => p.PluginModule)); PluginAggregator.Init(); }
public void FileAskingForNumberAndCredit() { var steps = new FileStep(); steps.GivenIHaveThisFile("towel.txt" , "glob is I" , "prok is V" , "pish is X" , "tegj is L" , "glob glob Silver is 34 Credits" , "glob prok Gold is 57800 Credits" , "pish pish Iron is 3910 Credits" , "how much is pish tegj glob glob ?" , "how many Credits is glob prok Silver ?" ); steps.WhenICallTheInterpreterForFile(@"towel.txt"); steps.ThenIWillHaveTheseAnswers( "pish tegj glob glob is 42", "glob prok Silver is 68 Credits" ); steps.ThenIWillHaveTheseConversions( Tuple.Create("glob", "I"), Tuple.Create("prok", "V"), Tuple.Create("pish", "X"), Tuple.Create("tegj", "L") ); steps.ThenIWillHaveTheseThingValues( Tuple.Create("Silver", 17m), Tuple.Create("Gold", 14450m), Tuple.Create("Iron", 195.5m) ); }
public static Tuple <bool, string> SendRedBag(string openId, decimal money, string channel, string wishing, string actName, string remark, string productCategory, string paymentType, string payWay, string requestPlatformCode, string terminalType) { var result = false; var errorMsg = string.Empty; try { using (var client = new PayClient()) { var getResult = client.Wx_SendRedBag(new WxSendRedBagRequest() { OpenId = openId, ProductCategory = productCategory, PaymentType = paymentType, PayWay = payWay, RequestPlatformCode = requestPlatformCode, TerminalType = terminalType, Money = money, Channel = channel, Wishing = wishing, ActName = actName, Remark = remark }); getResult.ThrowIfException(true); result = getResult.Result; errorMsg = getResult.ErrorMessage; } } catch (Exception ex) { logger.Error(ex); } return(Tuple.Create(result, errorMsg)); }
public async Task<List<Tuple<ApplicationUser, string[]>>> GetUsersAndRolesAsync(int page, int pageSize) { IQueryable<ApplicationUser> usersQuery = _context.Users .Include(u => u.Roles) .OrderBy(u => u.UserName); if (page != -1) usersQuery = usersQuery.Skip((page - 1) * pageSize); if (pageSize != -1) usersQuery = usersQuery.Take(pageSize); var users = await usersQuery.ToListAsync(); var userRoleIds = users.SelectMany(u => u.Roles.Select(r => r.RoleId)).ToList(); var roles = await _context.Roles .Where(r => userRoleIds.Contains(r.Id)) .ToArrayAsync(); return users.Select(u => Tuple.Create(u, roles.Where(r => u.Roles.Select(ur => ur.RoleId).Contains(r.Id)).Select(r => r.Name).ToArray())) .ToList(); }
// Instance pattern: public void Initialize(AppFunc next, string arg1, string arg2), public Task Invoke(IDictionary<...> env) private static Tuple<Type, Delegate, object[]> ToInstanceMiddlewareFactory(object middlewareObject, object[] args) { MethodInfo[] methods = middlewareObject.GetType().GetMethods(); foreach (MethodInfo method in methods) { if (method.Name != Constants.Initialize) { continue; } ParameterInfo[] parameters = method.GetParameters(); Type[] parameterTypes = parameters.Select(p => p.ParameterType).ToArray(); if (parameterTypes.Length != args.Length + 1) { continue; } if (!parameterTypes .Skip(1) .Zip(args, TestArgForParameter) .All(x => x)) { continue; } // DynamicInvoke can't handle a middleware with multiple args, just push the args in via closure. Func<object, object> func = app => { object[] invokeParameters = new[] { app }.Concat(args).ToArray(); method.Invoke(middlewareObject, invokeParameters); return middlewareObject; }; return Tuple.Create<Type, Delegate, object[]>(parameters[0].ParameterType, func, new object[0]); } return null; }
/// <summary> /// 通过表单更新内容 /// </summary> /// <param name="url"></param> /// <param name="dictionary">字典数据</param> public static Tuple <bool, string> Post(string url, Dictionary <string, string> dictionary) { HttpClient client; if (ClientAuthContainer.CurrentHandler != null) { client = new HttpClient(ClientAuthContainer.CurrentHandler); } else { client = new HttpClient(); } var ms = new MemoryStream(); dictionary.FillFormDataStream(ms); //填充formData HttpContent hc = new StreamContent(ms); hc.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded"); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html")); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xhtml+xml")); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml", 0.9)); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("image/webp")); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*", 0.8)); hc.Headers.Add("UserAgent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36"); hc.Headers.Add("KeepAlive", "true"); var t = client.PostAsync($"{url}", hc); t.Wait(); var t2 = t.Result.Content.ReadAsByteArrayAsync(); var result = HttpUtility.HtmlDecode(Encoding.UTF8.GetString(t2.Result)); var status = t.Result.StatusCode == HttpStatusCode.OK; return(Tuple.Create(status, result)); }
public async Task <MembershipTableData> ReadRow(SiloAddress key) { var tx = _db.CreateTransaction(); var tableVersionRowTask = tx.HashGetAsync(_clusterKey, TableVersionKey); var entryRowTask = tx.HashGetAsync(_clusterKey, key.ToString()); if (!await tx.ExecuteAsync()) { throw new RedisClusteringException($"Unexpected transaction failure while reading key {key}"); } TableVersion tableVersion = GetTableVersionFromRow(await tableVersionRowTask); var entryRow = await entryRowTask; if (entryRow.HasValue) { var entry = Deserialize(entryRow); return(new MembershipTableData(Tuple.Create(entry, tableVersion.VersionEtag), tableVersion)); } else { return(new MembershipTableData(tableVersion)); } }
/// <summary> /// Real Video Request /// </summary> /// <param name="gbid"></param> /// <param name="mediaPort"></param> /// <param name="receiveIP"></param> /// <returns></returns> async public Task <Tuple <string, int, SIPHeader, ProtocolType> > RealVideoReq(string gbid, int[] mediaPort, string receiveIP) { Logger.Logger.Debug("Make video request started."); var target = GetTargetMonitorService(gbid); if (target == null) { return(null); } var taskResult = await Task.Factory.StartNew(() => { var cSeq = target.RealVideoReq(mediaPort, receiveIP, true); var result = target.WaitRequestResult(); return(result); }); var ipaddress = _sipCoreMessageService.GetReceiveIP(taskResult.Item2.Body); var port = _sipCoreMessageService.GetReceivePort(taskResult.Item2.Body, SDPMediaTypesEnum.video); var header = taskResult.Item1.Header; return(Tuple.Create(ipaddress, port, header, ProtocolType.Udp)); }
public async Task <Tuple <string, IEnumerable <ForumPost> > > GetAllBelongsToUser(string url, string token) { var request = new HttpRequestMessage(HttpMethod.Get, url + "getforumpostsforuser"); var client = _clientFactory.CreateClient(); if (token != null && token.Length > 0) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); } HttpResponseMessage response = await client.SendAsync(request); if (response.StatusCode == HttpStatusCode.OK) { string obj = await response.Content.ReadAsStringAsync(); return(Tuple.Create("", JsonConvert.DeserializeObject <IEnumerable <ForumPost> >(obj))); } string errorObj = await response.Content.ReadAsStringAsync(); return(Tuple.Create(ModelStateDeserializer.DeserializeModelState(errorObj), Enumerable.Empty <ForumPost>())); }