示例#1
0
        public bool Put(RmResourceChanges transaction, bool useAlternateEndpoint, out PutResponse response, SecurityToken token, ContextMessageProperty context)
        {
            response = null;
            if (transaction == null)
            {
                throw new ArgumentNullException("transaction");
            }

            if (!useAlternateEndpoint)
            {
                PutRequest resourceEPrequest = this.requestFactory.CreatePutRequest(transaction);
                try {
                    this.wsTransferClient.Put(resourceEPrequest, out response);
                }
                //catch AuthN Fault here so we have the original transaction so we can re-submit later
                catch (System.ServiceModel.FaultException <Microsoft.ResourceManagement.Client.Faults.AuthenticationRequiredFault> authNFault) {
                    String STSEndpoinAddresst = authNFault.Detail.SecurityTokenServiceAddress;
                    ContextMessageProperty responseContext;
                    //TODO: Add AuthNLogicHere. For now, only support QA gates on the Authernate Endpoint
                }

                if (response == null)
                {
                    return(false);
                }
                else
                {
                    return(true);
                }
            }
            else
            {
                //TODO:Verify that the ObjectID is in the form Domain\User.
                PutRequest alternateEPrequest = this.requestFactory.CreatePutRequest(transaction);
                response = null;

                try {
                    this.alternateClient.Put(alternateEPrequest, out response, token, context);
                } catch (System.ServiceModel.FaultException <Microsoft.ResourceManagement.Client.Faults.AuthenticationRequiredFault> authNFault) {
                    String STSEndpointAddress = authNFault.Detail.SecurityTokenServiceAddress;
                    ContextMessageProperty responseContext;

                    if (ContextMessageProperty.TryGet(response.Message, out responseContext))
                    {
                        ContextualSecurityToken userToken = HandleAuthNFault(STSEndpointAddress, responseContext);
                        Put(transaction, true, out response, userToken, responseContext);
                    }
                    else
                    {
                        throw new Exception("Could not get security context from Put.");
                    }
                }

                if (response == null)
                {
                    return(false);
                }
                else
                {
                    return(true);
                }
            }
        }
示例#2
0
        public IRequest Marshall(BatchWriteItemRequest batchWriteItemRequest)
        {
            IRequest request = new DefaultRequest(batchWriteItemRequest, "AmazonDynamoDB");
            string   target  = "DynamoDB_20111205.BatchWriteItem";

            request.Headers["X-Amz-Target"] = target;
            request.Headers["Content-Type"] = "application/x-amz-json-1.0";

            using (StringWriter stringWriter = new StringWriter())
            {
                JsonWriter writer = new JsonWriter(stringWriter);
                writer.WriteObjectStart();

                if (batchWriteItemRequest != null)
                {
                    if (batchWriteItemRequest.RequestItems != null)
                    {
                        writer.WritePropertyName("RequestItems");
                        writer.WriteObjectStart();
                        foreach (string batchWriteItemRequestRequestItemsKey in batchWriteItemRequest.RequestItems.Keys)
                        {
                            List <WriteRequest> requestItemsListValue;
                            bool requestItemsListValueHasValue = batchWriteItemRequest.RequestItems.TryGetValue(batchWriteItemRequestRequestItemsKey, out requestItemsListValue);
                            writer.WritePropertyName(batchWriteItemRequestRequestItemsKey);

                            writer.WriteArrayStart();
                            foreach (WriteRequest valueListValue in requestItemsListValue)
                            {
                                writer.WriteObjectStart();

                                if (valueListValue != null)
                                {
                                    PutRequest putRequest = valueListValue.PutRequest;
                                    if (putRequest != null)
                                    {
                                        writer.WritePropertyName("PutRequest");
                                        writer.WriteObjectStart();
                                        if (putRequest != null)
                                        {
                                            if (putRequest.Item != null)
                                            {
                                                writer.WritePropertyName("Item");
                                                writer.WriteObjectStart();
                                                foreach (string putRequestItemKey in putRequest.Item.Keys)
                                                {
                                                    AttributeValue itemListValue;
                                                    bool           itemListValueHasValue = putRequest.Item.TryGetValue(putRequestItemKey, out itemListValue);
                                                    writer.WritePropertyName(putRequestItemKey);

                                                    writer.WriteObjectStart();
                                                    if (itemListValue != null && itemListValue.IsSetS())
                                                    {
                                                        writer.WritePropertyName("S");
                                                        writer.Write(itemListValue.S);
                                                    }
                                                    if (itemListValue != null && itemListValue.IsSetN())
                                                    {
                                                        writer.WritePropertyName("N");
                                                        writer.Write(itemListValue.N);
                                                    }

                                                    if (itemListValue != null && itemListValue.SS != null && itemListValue.SS.Count > 0)
                                                    {
                                                        List <string> sSList = itemListValue.SS;
                                                        writer.WritePropertyName("SS");
                                                        writer.WriteArrayStart();

                                                        foreach (string sSListValue in sSList)
                                                        {
                                                            writer.Write(StringUtils.FromString(sSListValue));
                                                        }

                                                        writer.WriteArrayEnd();
                                                    }

                                                    if (itemListValue != null && itemListValue.NS != null && itemListValue.NS.Count > 0)
                                                    {
                                                        List <string> nSList = itemListValue.NS;
                                                        writer.WritePropertyName("NS");
                                                        writer.WriteArrayStart();

                                                        foreach (string nSListValue in nSList)
                                                        {
                                                            writer.Write(StringUtils.FromString(nSListValue));
                                                        }

                                                        writer.WriteArrayEnd();
                                                    }
                                                    writer.WriteObjectEnd();
                                                }
                                                writer.WriteObjectEnd();
                                            }
                                        }
                                        writer.WriteObjectEnd();
                                    }
                                }

                                if (valueListValue != null)
                                {
                                    DeleteRequest deleteRequest = valueListValue.DeleteRequest;
                                    if (deleteRequest != null)
                                    {
                                        writer.WritePropertyName("DeleteRequest");
                                        writer.WriteObjectStart();

                                        if (deleteRequest != null)
                                        {
                                            Key key = deleteRequest.Key;
                                            if (key != null)
                                            {
                                                writer.WritePropertyName("Key");
                                                writer.WriteObjectStart();

                                                if (key != null)
                                                {
                                                    AttributeValue hashKeyElement = key.HashKeyElement;
                                                    if (hashKeyElement != null)
                                                    {
                                                        writer.WritePropertyName("HashKeyElement");
                                                        writer.WriteObjectStart();
                                                        if (hashKeyElement != null && hashKeyElement.IsSetS())
                                                        {
                                                            writer.WritePropertyName("S");
                                                            writer.Write(hashKeyElement.S);
                                                        }
                                                        if (hashKeyElement != null && hashKeyElement.IsSetN())
                                                        {
                                                            writer.WritePropertyName("N");
                                                            writer.Write(hashKeyElement.N);
                                                        }

                                                        if (hashKeyElement != null && hashKeyElement.SS != null && hashKeyElement.SS.Count > 0)
                                                        {
                                                            List <string> sSList = hashKeyElement.SS;
                                                            writer.WritePropertyName("SS");
                                                            writer.WriteArrayStart();

                                                            foreach (string sSListValue in sSList)
                                                            {
                                                                writer.Write(StringUtils.FromString(sSListValue));
                                                            }

                                                            writer.WriteArrayEnd();
                                                        }

                                                        if (hashKeyElement != null && hashKeyElement.NS != null && hashKeyElement.NS.Count > 0)
                                                        {
                                                            List <string> nSList = hashKeyElement.NS;
                                                            writer.WritePropertyName("NS");
                                                            writer.WriteArrayStart();

                                                            foreach (string nSListValue in nSList)
                                                            {
                                                                writer.Write(StringUtils.FromString(nSListValue));
                                                            }

                                                            writer.WriteArrayEnd();
                                                        }
                                                        writer.WriteObjectEnd();
                                                    }
                                                }

                                                if (key != null)
                                                {
                                                    AttributeValue rangeKeyElement = key.RangeKeyElement;
                                                    if (rangeKeyElement != null)
                                                    {
                                                        writer.WritePropertyName("RangeKeyElement");
                                                        writer.WriteObjectStart();
                                                        if (rangeKeyElement != null && rangeKeyElement.IsSetS())
                                                        {
                                                            writer.WritePropertyName("S");
                                                            writer.Write(rangeKeyElement.S);
                                                        }
                                                        if (rangeKeyElement != null && rangeKeyElement.IsSetN())
                                                        {
                                                            writer.WritePropertyName("N");
                                                            writer.Write(rangeKeyElement.N);
                                                        }

                                                        if (rangeKeyElement != null && rangeKeyElement.SS != null && rangeKeyElement.SS.Count > 0)
                                                        {
                                                            List <string> sSList = rangeKeyElement.SS;
                                                            writer.WritePropertyName("SS");
                                                            writer.WriteArrayStart();

                                                            foreach (string sSListValue in sSList)
                                                            {
                                                                writer.Write(StringUtils.FromString(sSListValue));
                                                            }

                                                            writer.WriteArrayEnd();
                                                        }

                                                        if (rangeKeyElement != null && rangeKeyElement.NS != null && rangeKeyElement.NS.Count > 0)
                                                        {
                                                            List <string> nSList = rangeKeyElement.NS;
                                                            writer.WritePropertyName("NS");
                                                            writer.WriteArrayStart();

                                                            foreach (string nSListValue in nSList)
                                                            {
                                                                writer.Write(StringUtils.FromString(nSListValue));
                                                            }

                                                            writer.WriteArrayEnd();
                                                        }
                                                        writer.WriteObjectEnd();
                                                    }
                                                }
                                                writer.WriteObjectEnd();
                                            }
                                        }
                                        writer.WriteObjectEnd();
                                    }
                                }
                                writer.WriteObjectEnd();
                            }
                            writer.WriteArrayEnd();
                        }
                        writer.WriteObjectEnd();
                    }
                }

                writer.WriteObjectEnd();

                string snippet = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
                return(request);
            }
        }
示例#3
0
 /// <summary>
 /// Sets the key value in etcd
 /// </summary>
 /// <param name="request"></param>
 /// <returns></returns>
 public PutResponse Put(PutRequest request, Metadata headers = null)
 {
     return(_balancer.GetConnection().kvClient.Put(request, headers));
 }
示例#4
0
        public async Task <ActionResult <List <int> > > Edit([FromBody] PutRequest request)
        {
            if (!await _authManager.HasSitePermissionsAsync(request.SiteId,
                                                            MenuUtils.SitePermissions.Channels))
            {
                return(Unauthorized());
            }

            var site = await _siteRepository.GetAsync(request.SiteId);

            if (site == null)
            {
                return(NotFound());
            }

            if (string.IsNullOrEmpty(request.ChannelName))
            {
                return(this.Error("栏目修改失败,必须填写栏目名称!"));
            }

            var channel = await _channelRepository.GetAsync(request.Id);

            if (!StringUtils.Equals(channel.IndexName, request.IndexName) && !string.IsNullOrEmpty(request.IndexName))
            {
                if (await _channelRepository.IsIndexNameExistsAsync(request.SiteId, request.IndexName))
                {
                    return(this.Error("栏目修改失败,栏目索引已存在!"));
                }
            }

            if (!StringUtils.Equals(channel.FilePath, request.FilePath) && !string.IsNullOrEmpty(request.FilePath))
            {
                if (!DirectoryUtils.IsDirectoryNameCompliant(request.FilePath))
                {
                    return(this.Error("栏目页面路径不符合系统要求!"));
                }

                if (PathUtils.IsDirectoryPath(request.FilePath))
                {
                    request.FilePath = PageUtils.Combine(request.FilePath, "index.html");
                }

                if (await _channelRepository.IsFilePathExistsAsync(request.SiteId, request.FilePath))
                {
                    return(this.Error("栏目修改失败,栏目页面路径已存在!"));
                }
            }

            if (!string.IsNullOrEmpty(request.ChannelFilePathRule))
            {
                var filePathRule = request.ChannelFilePathRule.Replace("|", string.Empty);
                if (!DirectoryUtils.IsDirectoryNameCompliant(filePathRule))
                {
                    return(this.Error("栏目页面命名规则不符合系统要求!"));
                }
                if (PathUtils.IsDirectoryPath(filePathRule))
                {
                    return(this.Error("栏目页面命名规则必须包含生成文件的后缀!"));
                }
            }

            if (!string.IsNullOrEmpty(request.ContentFilePathRule))
            {
                var filePathRule = request.ContentFilePathRule.Replace("|", string.Empty);
                if (!DirectoryUtils.IsDirectoryNameCompliant(filePathRule))
                {
                    return(this.Error("内容页面命名规则不符合系统要求!"));
                }
                if (PathUtils.IsDirectoryPath(filePathRule))
                {
                    return(this.Error("内容页面命名规则必须包含生成文件的后缀!"));
                }
            }

            var styles = await GetStylesAsync(channel);

            foreach (var style in styles)
            {
                var inputType = style.InputType;
                if (inputType == InputType.TextEditor)
                {
                    var value = request.Get(style.AttributeName, string.Empty);
                    value = await _pathManager.EncodeTextEditorAsync(site, value);

                    value = UEditorUtils.TranslateToStlElement(value);
                    channel.Set(style.AttributeName, value);
                }
                else if (inputType == InputType.Image ||
                         inputType == InputType.Video ||
                         inputType == InputType.File)
                {
                    var count = request.Get(ColumnsManager.GetCountName(style.AttributeName), 0);
                    channel.Set(ColumnsManager.GetCountName(style.AttributeName), count);
                    for (var n = 0; n <= count; n++)
                    {
                        channel.Set(ColumnsManager.GetExtendName(style.AttributeName, n), request.Get(ColumnsManager.GetExtendName(style.AttributeName, n), string.Empty));
                    }
                }
                else if (inputType == InputType.CheckBox ||
                         style.InputType == InputType.SelectMultiple)
                {
                    var list = request.Get <List <object> >(style.AttributeName);
                    channel.Set(style.AttributeName, ListUtils.ToString(list));
                }
                else
                {
                    var value = request.Get(style.AttributeName, string.Empty);
                    channel.Set(style.AttributeName, value);
                }
            }

            channel.ChannelName = request.ChannelName;
            channel.IndexName   = request.IndexName;
            channel.GroupNames  = request.GroupNames;
            //channel.Content = request.Content;
            channel.ChannelTemplateId   = request.ChannelTemplateId;
            channel.ContentTemplateId   = request.ContentTemplateId;
            channel.LinkUrl             = request.LinkUrl;
            channel.LinkType            = request.LinkType;
            channel.DefaultTaxisType    = request.DefaultTaxisType;
            channel.FilePath            = request.FilePath;
            channel.ChannelFilePathRule = request.ChannelFilePathRule;
            channel.ContentFilePathRule = request.ContentFilePathRule;
            channel.Keywords            = request.Keywords;
            channel.Description         = request.Description;

            await _channelRepository.UpdateAsync(channel);

            var expendedChannelIds = new List <int>
            {
                request.SiteId
            };

            if (!expendedChannelIds.Contains(channel.ParentId))
            {
                expendedChannelIds.Add(channel.ParentId);
            }

            return(expendedChannelIds);
        }
示例#5
0
 public abstract void VisitPutDescription(PutRequest element);
 public class PutHandler { public object Execute_Put(PutRequest request)
                           {
                               return(null);
                           }
示例#7
0
        public void FeedMany <T>(IEnumerable <T> items, bool excludeFromEviction, int packetSize)
        {
            if (items == null)
            {
                throw new ArgumentNullException(nameof(items));
            }

            var itemType = typeof(T);

            ClientSideTypeDescription description = null;
            var    needPack = itemType != typeof(CachedObject);
            string typeName = null;

            var sessionId = Guid.NewGuid().ToString();

            if (needPack)
            {
                description = RegisterTypeIfNeeded(itemType);
                typeName    = description.FullTypeName;
            }


            using (var enumerator = items.GetEnumerator())
            {
                var endLoop = false;

                while (!endLoop)
                {
                    var packet = new CachedObject[packetSize];
                    var toPack = new T[packetSize];

                    var count = 0;
                    for (var i = 0; i < packetSize; i++)
                    {
                        if (enumerator.MoveNext())
                        {
                            var item = enumerator.Current;
                            toPack[i] = item;
                            count++;
                        }
                        else
                        {
                            endLoop = true;
                            break;
                        }
                    }


                    Parallel.For(0, count, new ParallelOptions {
                        MaxDegreeOfParallelism = 10
                    }, (i, loopState) =>
                    {
                        var item       = toPack[i];
                        var packedItem = needPack ? CachedObject.Pack(item, description) : item as CachedObject;

                        if (typeName == null)
                        {
                            typeName = packedItem?.FullTypeName;
                        }

                        packet[i] = packedItem;
                    }
                                 );


                    if (typeName != null) // null only for empty collection
                    {
                        var request = new PutRequest(typeName)
                        {
                            ExcludeFromEviction = excludeFromEviction,
                            SessionId           = sessionId,
                            EndOfSession        = endLoop
                        };

                        foreach (var cachedObject in packet)
                        {
                            if (cachedObject != null)
                            {
                                request.Items.Add(cachedObject);
                            }
                        }

                        var response = Channel.SendRequest(request);
                        if (response is ExceptionResponse exResponse)
                        {
                            throw new CacheException("Error while writing an object to the cache", exResponse.Message,
                                                     exResponse.CallStack);
                        }
                    }
                }
            }
        }
示例#8
0
        /// <summary>
        /// Constructs a put request based on the changes tracked in the transaction.
        /// </summary>
        /// <param name="transaction">The transaction object which tracked the changes made to an object.</param>
        /// <returns></returns>
        public virtual PutRequest CreatePutRequest(RmResourceChanges transaction)
        {
            if (transaction == null)
            {
                throw new ArgumentNullException("transaction");
            }

            RmResource rmObject = transaction.RmObject;

            if (rmObject == null)
            {
                throw new InvalidOperationException("transaction does not have rmObject");
            }
            if (rmObject.ObjectID == null)
            {
                throw new InvalidOperationException("The rmObject does not have an ObjectID.");
            }
            lock (rmObject)
            {
                PutRequest putRequest = new PutRequest();

                putRequest.ResourceReferenceProperty = new ResourceReferenceProperty(rmObject.ObjectID.ToString());
                if (string.IsNullOrEmpty(rmObject.Locale) == false)
                {
                    putRequest.ResourceLocaleProperty = new ResourceLocaleProperty(new System.Globalization.CultureInfo(rmObject.Locale));
                }

                putRequest.ModifyRequest = new ModifyRequest();

                IList <RmAttributeChange> changes = transaction.GetChanges();

                foreach (RmAttributeChange attributeChange in changes)
                {
                    if (this.ProhibitedAttributes.ContainsKey(attributeChange.Name.Name))
                    {
                        continue;
                    }

                    DirectoryAccessChange putReqChange = BuildDirectoryAccessChange(attributeChange);

                    if (base.IsMultiValued(attributeChange.Name))
                    {
                        putReqChange.Operation = attributeChange.Operation.ToString();
                    }
                    else
                    {
                        if (attributeChange.Operation == RmAttributeChangeOperation.Add)
                        {
                            putReqChange.Operation = RmAttributeChangeOperation.Replace.ToString();
                        }
                        else if (attributeChange.Operation == RmAttributeChangeOperation.Delete)
                        {
                            putReqChange.Operation      = RmAttributeChangeOperation.Replace.ToString();
                            putReqChange.AttributeValue = null;
                        }
                        else
                        {
                            putReqChange.Operation = attributeChange.Operation.ToString();
                        }
                    }
                    putRequest.ModifyRequest.Changes.Add(putReqChange);
                }
                return(putRequest);
            }
        }
示例#9
0
 /// <summary>
 ///  监控数据上报。
 /// </summary>
 /// <param name="request">请求参数信息</param>
 /// <returns>请求结果信息</returns>
 public PutResponse Put(PutRequest request)
 {
     return(new PutExecutor().Client(this).Execute <PutResponse, PutResult, PutRequest>(request));
 }
示例#10
0
 /// <summary>
 ///  监控数据上报。
 /// </summary>
 /// <param name="request">请求参数信息</param>
 /// <returns>请求结果信息</returns>
 public async Task <PutResponse> Put(PutRequest request)
 {
     return(await new PutExecutor().Client(this).Execute <PutResponse, PutResult, PutRequest>(request).ConfigureAwait(false));
 }
示例#11
0
 //--- Constructors ---
 public DynamoTableBatchWriteItemsPutItem(DynamoTableBatchWriteItems parent, PutRequest putRequest)
 {
     _parent     = parent ?? throw new ArgumentNullException(nameof(parent));
     _putRequest = putRequest ?? throw new ArgumentNullException(nameof(putRequest));
 }
示例#12
0
            // Auto-generating timestamp
            //public DateTime JobStartDate { get; set; }

            public static async Task <Dictionary <string, string> > Validation(PutRequest obj)
            {
                // Preparing
                var    errors = new Dictionary <string, string>();
                string fieldName;

                // Name
                fieldName = nameof(obj.Name).ToCamelCase();
                if (obj.Name == null || Regex.Matches(obj.Name, "^[a-zA-Z0-9-_]{1,50}$").Count == 0)
                {
                    errors.Add(fieldName, $"Incorrect \"{fieldName}\" field value");
                }
                // Surname
                fieldName = nameof(obj.Surname).ToCamelCase();
                if (obj.Surname == null || Regex.Matches(obj.Surname, "^[a-zA-Z0-9-_]{1,50}$").Count == 0)
                {
                    errors.Add(fieldName, $"Incorrect \"{fieldName}\" field value");
                }
                // Patronymic
                fieldName = nameof(obj.Patronymic).ToCamelCase();
                if (obj.Patronymic != null && Regex.Matches(obj.Patronymic, "^[a-zA-Z0-9-_]{1,50}$").Count == 0)
                {
                    errors.Add(fieldName, $"Incorrect \"{fieldName}\" field value");
                }
                // Department
                fieldName = nameof(obj.Department).ToCamelCase();
                if (obj.Department == null || Regex.Matches(obj.Department, "^[a-zA-Z0-9-_]{1,50}$").Count == 0)
                {
                    errors.Add(fieldName, $"Incorrect \"{fieldName}\" field value");
                }
                // Position
                fieldName = nameof(obj.Position).ToCamelCase();
                if (obj.Position == null || Regex.Matches(obj.Position, "^[a-zA-Z0-9-_]{1,50}$").Count == 0)
                {
                    errors.Add(fieldName, $"Incorrect \"{fieldName}\" field value");
                }
                // Supervisor
                fieldName = nameof(obj.Supervisor).ToCamelCase();
                if (obj.Supervisor != null)
                {
                    using (var connection = new SqlConnection(ConnectionStrings.Default))
                    {
                        // Opening connection
                        connection.Open();
                        // Configuring command
                        var command = new SqlCommand(@"
                            select count(*) from [Employees]
                                where [Id] = @Supervisor;
                        ", connection);
                        // Filling parameters
                        command.Parameters.AddWithValue("@Supervisor", (object)obj.Supervisor ?? DBNull.Value);
                        // Executing
                        var reader = await command.ExecuteReaderAsync();

                        // Reading query result
                        if (reader.Read() && reader.GetInt32(0) == 0)
                        {
                            errors.Add(fieldName, $"Specified \"{fieldName}\" not exists");
                        }
                        reader.Close();
                        // Closing connection
                        connection.Close();
                    }
                }
                // Result
                return(errors);
            }
示例#13
0
        public void FeedMany(string collectionName, IEnumerable <PackedObject> items, bool excludeFromEviction,
                             int packetSize = 50000)
        {
            if (items == null)
            {
                throw new ArgumentNullException(nameof(items));
            }


            var sessionId = Guid.NewGuid();


            using var enumerator = items.GetEnumerator();

            var endLoop = false;

            while (!endLoop)
            {
                var packet = new PackedObject[packetSize];


                for (var i = 0; i < packetSize; i++)
                {
                    if (enumerator.MoveNext())
                    {
                        var item = enumerator.Current;
                        packet[i] = item;
                    }
                    else
                    {
                        endLoop = true;
                        enumerator.Dispose();
                        break;
                    }
                }


                if (collectionName != null) // null only for empty collection
                {
                    var request = new PutRequest(collectionName)
                    {
                        ExcludeFromEviction = excludeFromEviction,
                        SessionId           = sessionId,
                        EndOfSession        = endLoop
                    };

                    foreach (var cachedObject in packet)
                    {
                        if (cachedObject != null)
                        {
                            request.Items.Add(cachedObject);
                        }
                    }



                    var split = request.SplitWithMaxSize();

                    foreach (var putRequest in split)
                    {
                        var response =
                            Channel.SendRequest(putRequest);

                        if (response is ExceptionResponse exResponse)
                        {
                            throw new CacheException(
                                      "Error while writing an object to the cache",
                                      exResponse.Message, exResponse.CallStack);
                        }
                    }
                }
            }
        }
示例#14
0
        private int ProcessPutRequest(PutRequest putRequest)
        {
            // a feed session may contain multiple requests
            if (putRequest.SessionId != default)
            {
                SessionManager.AddToSession(putRequest.SessionId, putRequest.Items);

                if (putRequest.EndOfSession)
                {
                    var all = SessionManager.EndSession(putRequest.SessionId);

                    _transactionLog?.NewTransaction(new PutDurableTransaction {
                        Items = all
                    });

                    _dataStore.InternalPutMany(all, putRequest.ExcludeFromEviction);

                    return(all.Count);
                }

                return(0);
            }

            if (putRequest.OnlyIfNew) // conditional insert
            {
                if (putRequest.Items.Count != 1)
                {
                    throw new NotSupportedException("TryAdd can be called only with exactly one item");
                }


                var item = putRequest.Items.First();
                if (!_dataStore.DataByPrimaryKey.ContainsKey(item.PrimaryKey))
                {
                    _transactionLog?.NewTransaction(new PutDurableTransaction {
                        Items = putRequest.Items
                    });

                    _dataStore.InternalAddNew(item, putRequest.ExcludeFromEviction);

                    return(1);
                }

                return(0);
            }

            if (putRequest.Predicate != null) // conditional update
            {
                if (putRequest.Items.Count != 1)
                {
                    throw new NotSupportedException("UpdateIf can be called only with exactly one item");
                }

                var newVersion = putRequest.Items.First();

                if (!_dataStore.DataByPrimaryKey.TryGetValue(newVersion.PrimaryKey, out var oldVersion))
                {
                    throw new NotSupportedException("Item not found. Conditional update failed");
                }

                if (putRequest.Predicate.Match(oldVersion))
                {
                    _transactionLog?.NewTransaction(new PutDurableTransaction {
                        Items = putRequest.Items
                    });

                    _dataStore.InternalUpdate(newVersion);

                    return(1);
                }

                throw new CacheException("Condition not satisfied.Item not updated");
            }

            _transactionLog?.NewTransaction(new PutDurableTransaction {
                Items = putRequest.Items
            });

            _dataStore.InternalPutMany(putRequest.Items, putRequest.ExcludeFromEviction);

            return(putRequest.Items.Count);
        }
示例#15
0
        /// <summary>
        /// Inserts the tuple passed as argument into the space.
        /// </summary>
        public void Put(params object[] tuple)
        {
            PutRequest request = new PutRequest(this.GetSource(), this.GetSessionId(), this.connectionString.Target, tuple);

            this.GetMode()?.PerformRequest <PutResponse>(request);
        }
示例#16
0
 private static void ModifyResource(RmResourceChanges changes)
 {
     PutRequest  putRequest  = requestFactory.CreatePutRequest(changes);
     PutResponse putResponse = transferClient.Put(putRequest);
 }
示例#17
0
    void PutBehaviorRPC(string requestJson)
    {
        PutRequest <Behavior> request = JsonUtility.FromJson <PutRequest <Behavior> >(requestJson);

        PutBehaviorLocal(request, false);
    }
        public void Split_transaction_request()
        {
            var schema = TypedSchemaFactory.FromType <Order>();

            var requests = new List <DataRequest>();

            // simple put requests
            for (int i = 0; i < 100; i++)
            {
                var order1 = new Order {
                    Id = Guid.NewGuid(), Category = "geek", ProductId = 123, Quantity = 1
                };

                var putRequest = new PutRequest("orders");
                var packed1    = PackedObject.Pack(order1, schema, "orders");
                putRequest.Items.Add(packed1);

                requests.Add(putRequest);
            }

            // conditional put requests
            for (int i = 0; i < 100; i++)
            {
                var order1 = new Order {
                    Id = Guid.NewGuid(), Category = "geek", ProductId = 123, Quantity = 1
                };

                var putRequest = new PutRequest("orders");
                var packed1    = PackedObject.Pack(order1, schema, "orders");
                putRequest.Items.Add(packed1);
                putRequest.Predicate = ExpressionTreeHelper.PredicateToQuery <Order>(o => o.IsDelivered, "orders");

                requests.Add(putRequest);
            }

            // simple delete requests
            for (int i = 0; i < 100; i++)
            {
                var order1 = new Order {
                    Id = Guid.NewGuid(), Category = "geek", ProductId = 123, Quantity = 1
                };
                var packed1       = PackedObject.Pack(order1, schema, "orders1");
                var deleteRequest = new RemoveRequest("orders1", packed1.PrimaryKey);

                requests.Add(deleteRequest);
            }

            // delete many request
            var deleteMany = new RemoveManyRequest(ExpressionTreeHelper.PredicateToQuery <Order>(o => o.IsDelivered, "orders"));

            requests.Add(deleteMany);


            var transactionRequest = new TransactionRequest(requests)
            {
                TransactionId = Guid.NewGuid()
            };

            var split = transactionRequest.SplitByServer(k => k.GetHashCode() % 5, 5);

            var total = split.Values.Sum(r => r.ChildRequests.Count);

            // 300 uniformly distributed + 5 (delete many) cloned on each server
            Assert.AreEqual(305, total);

            Assert.IsTrue(split.Values.All(s => s.TransactionId == transactionRequest.TransactionId));

            var tr0 = split[0];

            Assert.IsTrue(tr0.ConditionalRequests.All(r => r.HasCondition));
            Assert.IsTrue(tr0.ConditionalRequests.Any());

            var deleteManyCount = tr0.ChildRequests.Count(r => r is RemoveManyRequest);

            Assert.AreEqual(1, deleteManyCount);

            Assert.AreEqual(2, tr0.AllCollections.Length);// orders and orders1
        }
 /// <summary>
 /// .NET accesspointService Put function
 /// </summary>
 public PutResponse1 Put(PutRequest request)
 {
     throw new NotImplementedException();
 }
示例#20
0
        public static void OTPReset(string domain, string username, ContextualSecurityToken authNSecurityToken, ContextMessageProperty contextMessageProperty)
        {
            // Create Anonymouse RmPerson and set ObjectID to Domain\User
            // The ObjectID attribute will become ResourceReferenceProperty in the message header
            RmPerson    user = new RmPerson();
            RmReference domainAndUsernameReference = new RmReference();

            domainAndUsernameReference.DomainAndUserNameValue = domain + '\\' + username;
            user.ObjectID = domainAndUsernameReference;
            PutResponse putResponse;

            putResponse = new PutResponse();
            string STSEndpoint = String.Empty;
            bool   putSuccess  = false; //This should always stay false with these calls unless no password reset workflow or qa authn workflow is attached.

            var          alternateClient = new AlternateClient();
            var          mexClient       = new MexClient();
            XmlSchemaSet metadata        = mexClient.Get();
            var          requestFactory  = new RmRequestFactory(metadata);

            // Set ResetPassword to true
            // Need a transaction to watch changes to the user
            using (RmResourceChanges transaction = new RmResourceChanges(user))
            {
                transaction.BeginChanges();

                user.ResetPassword = "******";

                try
                {
                    if (transaction.RmObject.ObjectID.Value.Split('\\').Length != 2)
                    {
                        throw new ArgumentException("User Identity must be specified by netbios domain in this format: Domain name\\user name.");
                    }

                    PutRequest alternateEPrequest = requestFactory.CreatePutRequest(transaction);

                    try
                    {
                        alternateClient.Put(alternateEPrequest, out putResponse, authNSecurityToken, contextMessageProperty);
                        putSuccess = true;
                    }
                    catch (System.ServiceModel.FaultException <Microsoft.ResourceManagement.Client.Faults.AuthenticationRequiredFault> authNFault)
                    {
                        Microsoft.ResourceManagement.WebServices.WSResourceManagement.AuthenticationRequiredFault msAuthNFault =
                            new Microsoft.ResourceManagement.WebServices.WSResourceManagement.AuthenticationRequiredFault(authNFault.Detail.SecurityTokenServiceAddress,
                                                                                                                          authNFault.Detail.UserRegistered.GetValueOrDefault(),
                                                                                                                          authNFault.Detail.UserLockedOut.GetValueOrDefault());

                        ContextMessageProperty responseContext;

                        if (ContextMessageProperty.TryGet(putResponse.Message, out responseContext) == false)
                        {
                            throw new InvalidOperationException("Could not retrieve security context message property even though we received an AuthN Fault. Something is fundamentally broken. Ensure assembly versions are correct and upgrades did not change protocol.");
                        }

                        throw new AuthenticationRequiredException(authNFault.Reason.ToString(),
                                                                  msAuthNFault,
                                                                  responseContext);
                    }
                }
                finally
                {
                    if (putSuccess == true)
                    {
                        transaction.AcceptChanges();
                    }
                    else
                    {
                        transaction.DiscardChanges();
                    }
                }
            }
        }
示例#21
0
        /// <summary>
        ///     FeedMany is non transactional but it does not lock the cache. To be used for massive feeds
        ///     Can feed with business objects (they will be packed to CachedObject) or directly with CachedObject
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="items"></param>
        /// <param name="excludeFromEviction"></param>
        /// <param name="packetSize"></param>
        public void FeedMany <T>(IEnumerable <T> items, bool excludeFromEviction, int packetSize)
        {
            if (items == null)
            {
                throw new ArgumentNullException(nameof(items));
            }

            // Lazy type registration
            var itemType = typeof(T);

            ClientSideTypeDescription description = null;
            var    needPack = itemType != typeof(CachedObject);
            string typeName = null;

            var sessionId = Guid.NewGuid().ToString();

            if (needPack)
            {
                description = RegisterTypeIfNeeded(itemType);
                typeName    = description.FullTypeName;
            }

            // initialize one request per node
            var requests = new PutRequest[CacheClients.Count];


            // Parallelize both nodes and requests (multiple requests for the same node are executed in parallel if multiple connections are available in the pool)
            var tasks = new List <Task>();

            foreach (var item in items)
            {
                if (typeName == null)
                {
                    typeName = (item as CachedObject)?.FullTypeName;
                }

                var packedItem = needPack ? CachedObject.Pack(item, description) : item as CachedObject;

                var node = WhichNode(packedItem);

                if (requests[node] == null)
                {
                    requests[node] = new PutRequest(typeName)
                    {
                        ExcludeFromEviction = excludeFromEviction,
                        SessionId           = sessionId
                    }
                }
                ;

                var request = requests[node];


                request.Items.Add(packedItem);

                if (request.Items.Count == packetSize)
                {
                    var task = Task.Factory.StartNew(re =>
                    {
                        var response =
                            CacheClients[node].Channel.SendRequest((PutRequest)re);
                        if (response is ExceptionResponse exResponse)
                        {
                            throw new CacheException(
                                "Error while writing an object to the cache",
                                exResponse.Message, exResponse.CallStack);
                        }
                    }, request);


                    tasks.Add(task);
                    requests[node] = new PutRequest(typeName)
                    {
                        ExcludeFromEviction = excludeFromEviction,
                        SessionId           = sessionId
                    };
                }
            }


            //send the last packet left for each node
            for (var node = 0; node < CacheClients.Count; node++)
            {
                var request = requests[node];


                if (request != null)
                {
                    request.EndOfSession = true;

                    var n    = node;
                    var task = Task.Factory.StartNew(re =>
                    {
                        var response = CacheClients[n].Channel.SendRequest((PutRequest)re);
                        if (response is ExceptionResponse exResponse)
                        {
                            throw new CacheException(
                                "Error while writing an object to the cache",
                                exResponse.Message, exResponse.CallStack);
                        }
                    }, request);

                    tasks.Add(task);
                }
            }

            try
            {
                Task.WaitAll(tasks.ToArray());
                Dbg.Trace($"{tasks.Count} tasks finished");
            }
            catch (AggregateException e)
            {
                if (e.InnerException != null)
                {
                    throw e.InnerException;
                }
            }
        }
        public async Task <ActionResult <ApiResponse> > PutAccount([FromBody] PutRequest putRequest)
        {
            var id      = putRequest.Id;
            var account = new Account();

            try
            {
                account = await _context.Accounts.FindAsync(id);

                if (account == null)
                {
                    return(NotFound(new ApiResponse(false, "Account not found.", new List <Object>())));
                }

                if (putRequest.FirstName != null)
                {
                    if (!Validation.ValidateString(putRequest.FirstName))
                    {
                        return(BadRequest(new ApiResponse(false, "Validation Error.", new List <Object>())));
                    }

                    account.FirstName = putRequest.FirstName;
                }

                if (putRequest.LastName != null)
                {
                    if (!Validation.ValidateString(putRequest.LastName))
                    {
                        return(BadRequest(new ApiResponse(false, "Validation Error.", new List <Object>())));
                    }

                    account.LastName = putRequest.LastName;
                }

                account.CurrentBalance = putRequest.CurrentBalance ?? account.CurrentBalance;

                _context.Entry(account).State = EntityState.Modified;
            }
            catch (Exception ex)
            {
                this.HttpContext.Response.StatusCode = 500;
                return(new ApiResponse(false, ex.Message, new List <Object>()));
            }


            try
            {
                await _context.SaveChangesAsync();

                return(Ok(new ApiResponse(true, "Account details updated.", account)));
            }
            catch (Exception ex)
            {
                if (!AccountExists(putRequest.Id))
                {
                    return(NotFound(new ApiResponse(false, "Account not found.", new List <Object>())));
                }
                else
                {
                    this.HttpContext.Response.StatusCode = 500;
                    return(new ApiResponse(false, ex.Message, new List <Object>()));
                }
            }
        }
        public IRequest Marshall(BatchWriteItemRequest batchWriteItemRequest)
        {
            IRequest request = new DefaultRequest(batchWriteItemRequest, "AmazonDynamoDBv2");
            string   target  = "DynamoDB_20120810.BatchWriteItem";

            request.Headers["X-Amz-Target"] = target;

            request.Headers["Content-Type"] = "application/x-amz-json-1.0";


            string uriResourcePath = "";

            if (uriResourcePath.Contains("?"))
            {
                int    queryPosition = uriResourcePath.IndexOf("?", StringComparison.OrdinalIgnoreCase);
                string queryString   = uriResourcePath.Substring(queryPosition + 1);
                uriResourcePath = uriResourcePath.Substring(0, queryPosition);

                foreach (string s in queryString.Split('&', ';'))
                {
                    string[] nameValuePair = s.Split('=');
                    if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0)
                    {
                        request.Parameters.Add(nameValuePair[0], nameValuePair[1]);
                    }
                    else
                    {
                        request.Parameters.Add(nameValuePair[0], null);
                    }
                }
            }

            request.ResourcePath = uriResourcePath;


            using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
            {
                JsonWriter writer = new JsonWriter(stringWriter);
                writer.WriteObjectStart();

                if (batchWriteItemRequest != null)
                {
                    if (batchWriteItemRequest.RequestItems != null && batchWriteItemRequest.RequestItems.Count > 0)
                    {
                        writer.WritePropertyName("RequestItems");
                        writer.WriteObjectStart();
                        foreach (string batchWriteItemRequestRequestItemsKey in batchWriteItemRequest.RequestItems.Keys)
                        {
                            List <WriteRequest> requestItemsListValue;
                            bool requestItemsListValueHasValue = batchWriteItemRequest.RequestItems.TryGetValue(batchWriteItemRequestRequestItemsKey, out requestItemsListValue);
                            writer.WritePropertyName(batchWriteItemRequestRequestItemsKey);

                            writer.WriteArrayStart();
                            if (requestItemsListValue != null)
                            {
                                foreach (WriteRequest valueListValue in requestItemsListValue)
                                {
                                    writer.WriteObjectStart();

                                    if (valueListValue != null)
                                    {
                                        PutRequest putRequest = valueListValue.PutRequest;
                                        if (putRequest != null)
                                        {
                                            writer.WritePropertyName("PutRequest");
                                            writer.WriteObjectStart();
                                            if (putRequest != null)
                                            {
                                                if (putRequest.Item != null && putRequest.Item.Count > 0)
                                                {
                                                    writer.WritePropertyName("Item");
                                                    writer.WriteObjectStart();
                                                    foreach (string putRequestItemKey in putRequest.Item.Keys)
                                                    {
                                                        AttributeValue itemListValue;
                                                        bool           itemListValueHasValue = putRequest.Item.TryGetValue(putRequestItemKey, out itemListValue);
                                                        writer.WritePropertyName(putRequestItemKey);

                                                        writer.WriteObjectStart();
                                                        if (itemListValue != null && itemListValue.IsSetS())
                                                        {
                                                            writer.WritePropertyName("S");
                                                            writer.Write(itemListValue.S);
                                                        }
                                                        if (itemListValue != null && itemListValue.IsSetN())
                                                        {
                                                            writer.WritePropertyName("N");
                                                            writer.Write(itemListValue.N);
                                                        }
                                                        if (itemListValue != null && itemListValue.IsSetB())
                                                        {
                                                            writer.WritePropertyName("B");
                                                            writer.Write(StringUtils.FromMemoryStream(itemListValue.B));
                                                        }

                                                        if (itemListValue != null && itemListValue.SS != null && itemListValue.SS.Count > 0)
                                                        {
                                                            List <string> sSList = itemListValue.SS;
                                                            writer.WritePropertyName("SS");
                                                            writer.WriteArrayStart();

                                                            foreach (string sSListValue in sSList)
                                                            {
                                                                writer.Write(StringUtils.FromString(sSListValue));
                                                            }

                                                            writer.WriteArrayEnd();
                                                        }

                                                        if (itemListValue != null && itemListValue.NS != null && itemListValue.NS.Count > 0)
                                                        {
                                                            List <string> nSList = itemListValue.NS;
                                                            writer.WritePropertyName("NS");
                                                            writer.WriteArrayStart();

                                                            foreach (string nSListValue in nSList)
                                                            {
                                                                writer.Write(StringUtils.FromString(nSListValue));
                                                            }

                                                            writer.WriteArrayEnd();
                                                        }

                                                        if (itemListValue != null && itemListValue.BS != null && itemListValue.BS.Count > 0)
                                                        {
                                                            List <MemoryStream> bSList = itemListValue.BS;
                                                            writer.WritePropertyName("BS");
                                                            writer.WriteArrayStart();

                                                            foreach (MemoryStream bSListValue in bSList)
                                                            {
                                                                writer.Write(StringUtils.FromMemoryStream(bSListValue));
                                                            }

                                                            writer.WriteArrayEnd();
                                                        }
                                                        writer.WriteObjectEnd();
                                                    }
                                                    writer.WriteObjectEnd();
                                                }
                                            }
                                            writer.WriteObjectEnd();
                                        }
                                    }

                                    if (valueListValue != null)
                                    {
                                        DeleteRequest deleteRequest = valueListValue.DeleteRequest;
                                        if (deleteRequest != null)
                                        {
                                            writer.WritePropertyName("DeleteRequest");
                                            writer.WriteObjectStart();
                                            if (deleteRequest != null)
                                            {
                                                if (deleteRequest.Key != null && deleteRequest.Key.Count > 0)
                                                {
                                                    writer.WritePropertyName("Key");
                                                    writer.WriteObjectStart();
                                                    foreach (string deleteRequestKeyKey in deleteRequest.Key.Keys)
                                                    {
                                                        AttributeValue keyListValue;
                                                        bool           keyListValueHasValue = deleteRequest.Key.TryGetValue(deleteRequestKeyKey, out keyListValue);
                                                        writer.WritePropertyName(deleteRequestKeyKey);

                                                        writer.WriteObjectStart();
                                                        if (keyListValue != null && keyListValue.IsSetS())
                                                        {
                                                            writer.WritePropertyName("S");
                                                            writer.Write(keyListValue.S);
                                                        }
                                                        if (keyListValue != null && keyListValue.IsSetN())
                                                        {
                                                            writer.WritePropertyName("N");
                                                            writer.Write(keyListValue.N);
                                                        }
                                                        if (keyListValue != null && keyListValue.IsSetB())
                                                        {
                                                            writer.WritePropertyName("B");
                                                            writer.Write(StringUtils.FromMemoryStream(keyListValue.B));
                                                        }

                                                        if (keyListValue != null && keyListValue.SS != null && keyListValue.SS.Count > 0)
                                                        {
                                                            List <string> sSList = keyListValue.SS;
                                                            writer.WritePropertyName("SS");
                                                            writer.WriteArrayStart();

                                                            foreach (string sSListValue in sSList)
                                                            {
                                                                writer.Write(StringUtils.FromString(sSListValue));
                                                            }

                                                            writer.WriteArrayEnd();
                                                        }

                                                        if (keyListValue != null && keyListValue.NS != null && keyListValue.NS.Count > 0)
                                                        {
                                                            List <string> nSList = keyListValue.NS;
                                                            writer.WritePropertyName("NS");
                                                            writer.WriteArrayStart();

                                                            foreach (string nSListValue in nSList)
                                                            {
                                                                writer.Write(StringUtils.FromString(nSListValue));
                                                            }

                                                            writer.WriteArrayEnd();
                                                        }

                                                        if (keyListValue != null && keyListValue.BS != null && keyListValue.BS.Count > 0)
                                                        {
                                                            List <MemoryStream> bSList = keyListValue.BS;
                                                            writer.WritePropertyName("BS");
                                                            writer.WriteArrayStart();

                                                            foreach (MemoryStream bSListValue in bSList)
                                                            {
                                                                writer.Write(StringUtils.FromMemoryStream(bSListValue));
                                                            }

                                                            writer.WriteArrayEnd();
                                                        }
                                                        writer.WriteObjectEnd();
                                                    }
                                                    writer.WriteObjectEnd();
                                                }
                                            }
                                            writer.WriteObjectEnd();
                                        }
                                    }
                                    writer.WriteObjectEnd();
                                }
                            }
                            writer.WriteArrayEnd();
                        }
                        writer.WriteObjectEnd();
                    }
                }
                if (batchWriteItemRequest != null && batchWriteItemRequest.IsSetReturnConsumedCapacity())
                {
                    writer.WritePropertyName("ReturnConsumedCapacity");
                    writer.Write(batchWriteItemRequest.ReturnConsumedCapacity);
                }
                if (batchWriteItemRequest != null && batchWriteItemRequest.IsSetReturnItemCollectionMetrics())
                {
                    writer.WritePropertyName("ReturnItemCollectionMetrics");
                    writer.Write(batchWriteItemRequest.ReturnItemCollectionMetrics);
                }

                writer.WriteObjectEnd();

                string snippet = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
            }


            return(request);
        }
示例#24
0
 /// <summary>
 /// Sets the key value in etcd in async
 /// </summary>
 /// <param name="request"></param>
 /// <returns></returns>
 public async Task <PutResponse> PutAsync(PutRequest request, Metadata headers = null)
 {
     return(await _balancer.GetConnection().kvClient.PutAsync(request, headers));
 }
        public IRequest Marshall(BatchWriteItemRequest batchWriteItemRequest)
        {
            IRequest request = new DefaultRequest(batchWriteItemRequest, "AmazonDynamoDB");
            string   target  = "DynamoDB_20111205.BatchWriteItem";

            request.Headers["X-Amz-Target"] = target;
            request.Headers["Content-Type"] = "application/x-amz-json-1.0";



            string uriResourcePath = "";

            if (uriResourcePath.Contains("?"))
            {
                string queryString = uriResourcePath.Substring(uriResourcePath.IndexOf("?") + 1);
                uriResourcePath = uriResourcePath.Substring(0, uriResourcePath.IndexOf("?"));

                foreach (string s in queryString.Split('&', ';'))
                {
                    string[] nameValuePair = s.Split('=');
                    if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0)
                    {
                        request.Parameters.Add(nameValuePair[0], nameValuePair[1]);
                    }
                    else
                    {
                        request.Parameters.Add(nameValuePair[0], null);
                    }
                }
            }

            request.ResourcePath = uriResourcePath;


            using (StringWriter stringWriter = new StringWriter())
            {
                JsonWriter writer = new JsonWriter(stringWriter);
                writer.WriteObjectStart();

                if (batchWriteItemRequest != null)
                {
                    if (batchWriteItemRequest.RequestItems != null)
                    {
                        writer.WritePropertyName("RequestItems");
                        writer.WriteObjectStart();
                        foreach (string batchWriteItemRequestRequestItemsKey in batchWriteItemRequest.RequestItems.Keys)
                        {
                            List <WriteRequest> requestItemsListValue;
                            bool requestItemsListValueHasValue = batchWriteItemRequest.RequestItems.TryGetValue(batchWriteItemRequestRequestItemsKey, out requestItemsListValue);
                            writer.WritePropertyName(batchWriteItemRequestRequestItemsKey);

                            writer.WriteArrayStart();
                            if (requestItemsListValue != null)
                            {
                                foreach (WriteRequest valueListValue in requestItemsListValue)
                                {
                                    writer.WriteObjectStart();

                                    if (valueListValue != null)
                                    {
                                        PutRequest putRequest = valueListValue.PutRequest;
                                        if (putRequest != null)
                                        {
                                            writer.WritePropertyName("PutRequest");
                                            writer.WriteObjectStart();
                                            if (putRequest != null)
                                            {
                                                if (putRequest.Item != null)
                                                {
                                                    writer.WritePropertyName("Item");
                                                    writer.WriteObjectStart();
                                                    foreach (string putRequestItemKey in putRequest.Item.Keys)
                                                    {
                                                        AttributeValue itemListValue;
                                                        bool           itemListValueHasValue = putRequest.Item.TryGetValue(putRequestItemKey, out itemListValue);
                                                        writer.WritePropertyName(putRequestItemKey);

                                                        writer.WriteObjectStart();
                                                        if (itemListValue != null && itemListValue.IsSetS())
                                                        {
                                                            writer.WritePropertyName("S");
                                                            writer.Write(itemListValue.S);
                                                        }
                                                        if (itemListValue != null && itemListValue.IsSetN())
                                                        {
                                                            writer.WritePropertyName("N");
                                                            writer.Write(itemListValue.N);
                                                        }
                                                        if (itemListValue != null && itemListValue.IsSetB())
                                                        {
                                                            writer.WritePropertyName("B");
                                                            writer.Write(StringUtils.FromMemoryStream(itemListValue.B));
                                                        }

                                                        if (itemListValue != null && itemListValue.SS != null && itemListValue.SS.Count > 0)
                                                        {
                                                            List <string> sSList = itemListValue.SS;
                                                            writer.WritePropertyName("SS");
                                                            writer.WriteArrayStart();

                                                            foreach (string sSListValue in sSList)
                                                            {
                                                                writer.Write(StringUtils.FromString(sSListValue));
                                                            }

                                                            writer.WriteArrayEnd();
                                                        }

                                                        if (itemListValue != null && itemListValue.NS != null && itemListValue.NS.Count > 0)
                                                        {
                                                            List <string> nSList = itemListValue.NS;
                                                            writer.WritePropertyName("NS");
                                                            writer.WriteArrayStart();

                                                            foreach (string nSListValue in nSList)
                                                            {
                                                                writer.Write(StringUtils.FromString(nSListValue));
                                                            }

                                                            writer.WriteArrayEnd();
                                                        }

                                                        if (itemListValue != null && itemListValue.BS != null && itemListValue.BS.Count > 0)
                                                        {
                                                            List <MemoryStream> bSList = itemListValue.BS;
                                                            writer.WritePropertyName("BS");
                                                            writer.WriteArrayStart();

                                                            foreach (MemoryStream bSListValue in bSList)
                                                            {
                                                                writer.Write(StringUtils.FromMemoryStream(bSListValue));
                                                            }

                                                            writer.WriteArrayEnd();
                                                        }
                                                        writer.WriteObjectEnd();
                                                    }
                                                    writer.WriteObjectEnd();
                                                }
                                            }
                                            writer.WriteObjectEnd();
                                        }
                                    }

                                    if (valueListValue != null)
                                    {
                                        DeleteRequest deleteRequest = valueListValue.DeleteRequest;
                                        if (deleteRequest != null)
                                        {
                                            writer.WritePropertyName("DeleteRequest");
                                            writer.WriteObjectStart();

                                            if (deleteRequest != null)
                                            {
                                                Key key = deleteRequest.Key;
                                                if (key != null)
                                                {
                                                    writer.WritePropertyName("Key");
                                                    writer.WriteObjectStart();

                                                    if (key != null)
                                                    {
                                                        AttributeValue hashKeyElement = key.HashKeyElement;
                                                        if (hashKeyElement != null)
                                                        {
                                                            writer.WritePropertyName("HashKeyElement");
                                                            writer.WriteObjectStart();
                                                            if (hashKeyElement != null && hashKeyElement.IsSetS())
                                                            {
                                                                writer.WritePropertyName("S");
                                                                writer.Write(hashKeyElement.S);
                                                            }
                                                            if (hashKeyElement != null && hashKeyElement.IsSetN())
                                                            {
                                                                writer.WritePropertyName("N");
                                                                writer.Write(hashKeyElement.N);
                                                            }
                                                            if (hashKeyElement != null && hashKeyElement.IsSetB())
                                                            {
                                                                writer.WritePropertyName("B");
                                                                writer.Write(StringUtils.FromMemoryStream(hashKeyElement.B));
                                                            }

                                                            if (hashKeyElement != null && hashKeyElement.SS != null && hashKeyElement.SS.Count > 0)
                                                            {
                                                                List <string> sSList = hashKeyElement.SS;
                                                                writer.WritePropertyName("SS");
                                                                writer.WriteArrayStart();

                                                                foreach (string sSListValue in sSList)
                                                                {
                                                                    writer.Write(StringUtils.FromString(sSListValue));
                                                                }

                                                                writer.WriteArrayEnd();
                                                            }

                                                            if (hashKeyElement != null && hashKeyElement.NS != null && hashKeyElement.NS.Count > 0)
                                                            {
                                                                List <string> nSList = hashKeyElement.NS;
                                                                writer.WritePropertyName("NS");
                                                                writer.WriteArrayStart();

                                                                foreach (string nSListValue in nSList)
                                                                {
                                                                    writer.Write(StringUtils.FromString(nSListValue));
                                                                }

                                                                writer.WriteArrayEnd();
                                                            }

                                                            if (hashKeyElement != null && hashKeyElement.BS != null && hashKeyElement.BS.Count > 0)
                                                            {
                                                                List <MemoryStream> bSList = hashKeyElement.BS;
                                                                writer.WritePropertyName("BS");
                                                                writer.WriteArrayStart();

                                                                foreach (MemoryStream bSListValue in bSList)
                                                                {
                                                                    writer.Write(StringUtils.FromMemoryStream(bSListValue));
                                                                }

                                                                writer.WriteArrayEnd();
                                                            }
                                                            writer.WriteObjectEnd();
                                                        }
                                                    }

                                                    if (key != null)
                                                    {
                                                        AttributeValue rangeKeyElement = key.RangeKeyElement;
                                                        if (rangeKeyElement != null)
                                                        {
                                                            writer.WritePropertyName("RangeKeyElement");
                                                            writer.WriteObjectStart();
                                                            if (rangeKeyElement != null && rangeKeyElement.IsSetS())
                                                            {
                                                                writer.WritePropertyName("S");
                                                                writer.Write(rangeKeyElement.S);
                                                            }
                                                            if (rangeKeyElement != null && rangeKeyElement.IsSetN())
                                                            {
                                                                writer.WritePropertyName("N");
                                                                writer.Write(rangeKeyElement.N);
                                                            }
                                                            if (rangeKeyElement != null && rangeKeyElement.IsSetB())
                                                            {
                                                                writer.WritePropertyName("B");
                                                                writer.Write(StringUtils.FromMemoryStream(rangeKeyElement.B));
                                                            }

                                                            if (rangeKeyElement != null && rangeKeyElement.SS != null && rangeKeyElement.SS.Count > 0)
                                                            {
                                                                List <string> sSList = rangeKeyElement.SS;
                                                                writer.WritePropertyName("SS");
                                                                writer.WriteArrayStart();

                                                                foreach (string sSListValue in sSList)
                                                                {
                                                                    writer.Write(StringUtils.FromString(sSListValue));
                                                                }

                                                                writer.WriteArrayEnd();
                                                            }

                                                            if (rangeKeyElement != null && rangeKeyElement.NS != null && rangeKeyElement.NS.Count > 0)
                                                            {
                                                                List <string> nSList = rangeKeyElement.NS;
                                                                writer.WritePropertyName("NS");
                                                                writer.WriteArrayStart();

                                                                foreach (string nSListValue in nSList)
                                                                {
                                                                    writer.Write(StringUtils.FromString(nSListValue));
                                                                }

                                                                writer.WriteArrayEnd();
                                                            }

                                                            if (rangeKeyElement != null && rangeKeyElement.BS != null && rangeKeyElement.BS.Count > 0)
                                                            {
                                                                List <MemoryStream> bSList = rangeKeyElement.BS;
                                                                writer.WritePropertyName("BS");
                                                                writer.WriteArrayStart();

                                                                foreach (MemoryStream bSListValue in bSList)
                                                                {
                                                                    writer.Write(StringUtils.FromMemoryStream(bSListValue));
                                                                }

                                                                writer.WriteArrayEnd();
                                                            }
                                                            writer.WriteObjectEnd();
                                                        }
                                                    }
                                                    writer.WriteObjectEnd();
                                                }
                                            }
                                            writer.WriteObjectEnd();
                                        }
                                    }
                                    writer.WriteObjectEnd();
                                }
                            }
                            writer.WriteArrayEnd();
                        }
                        writer.WriteObjectEnd();
                    }
                }

                writer.WriteObjectEnd();

                string snippet = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
            }


            return(request);
        }
示例#26
0
 /// <summary>
 /// Sets the key value in etcd
 /// </summary>
 /// <param name="request">The request to send to the server.</param>
 /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
 /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
 /// <param name="cancellationToken">An optional token for canceling the call.</param>
 /// <returns>The response received from the server.</returns>
 public PutResponse Put(PutRequest request, Grpc.Core.Metadata headers = null, DateTime?deadline = null,
                        CancellationToken cancellationToken            = default)
 {
     return(CallEtcd((connection) => connection.kvClient.Put(request, headers, deadline, cancellationToken)));
 }
示例#27
0
 /// <summary>
 /// Sets the key value in etcd in async
 /// </summary>
 /// <param name="request">The request to send to the server.</param>
 /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
 /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
 /// <param name="cancellationToken">An optional token for canceling the call.</param>
 /// <returns>The response received from the server.</returns>
 public async Task <PutResponse> PutAsync(PutRequest request, Grpc.Core.Metadata headers = null,
                                          DateTime?deadline = null,
                                          CancellationToken cancellationToken = default) => await CallEtcdAsync(async (connection) => await connection._kvClient
                                                                                                                .PutAsync(request, headers, deadline, cancellationToken)).ConfigureAwait(false);
示例#28
0
 public Task <PutResponse> Put(int id, [FromBody] PutRequest request) => foo.Put(id, request);
示例#29
0
 // PUT api/<controller>/5
 public void Put(Guid id, PutRequest request)
 {
 }
示例#30
0
 public AsyncResult(Key key, object value, TimeSpan lifetime, SimpleDHT dht, AsyncCallback callback, object state)
 {
     _callback = callback;
     _state = state;
     _dht = dht;
     _key = key;
     _start = DateTime.Now;
     _getMethod = false;
     _putReq = new PutRequest (key, value, lifetime);
     _kbrAR = dht.KeyBasedRouter.BeginRoute (key, null, dht.NumberOfReplicas, dht.NumberOfSimultaneous, KBR_Callback, null);
 }
示例#31
0
        /// <summary>
        /// Inserts a record to Zoho
        /// </summary>
        /// <param name="schema"></param>
        /// <param name="record"></param>
        /// <returns></returns>
        private async Task <string> InsertRecord(Schema schema, Record record)
        {
            // get information from schema
            var moduleName = GetModuleName(schema);

            try
            {
                // build and send request
                var uri = String.Format("https://www.zohoapis.com/crm/v2/{0}", moduleName);

                var recObj  = JsonConvert.DeserializeObject <Dictionary <string, object> >(record.DataJson);
                var trigger = new List <string>();

                if (_server.Settings.WorkflowTrigger)
                {
                    trigger.Add("workflow");
                }

                var putObj = GetPutObject(recObj, schema);

                var putRequestObj = new PutRequest
                {
                    data    = new[] { putObj },
                    trigger = trigger
                };

                var json = new StringContent(JsonConvert.SerializeObject(putRequestObj), Encoding.UTF8,
                                             "application/json");

                var response = await _client.PostAsync(uri, json);

                response.EnsureSuccessStatusCode();

                Logger.Info(await response.Content.ReadAsStringAsync());

                var upsertResponse =
                    JsonConvert.DeserializeObject <UpsertResponse>(await response.Content.ReadAsStringAsync());
                var upsertObj = upsertResponse.Data.FirstOrDefault();


                if (upsertObj != null)
                {
                    if (upsertObj.Status == "error")
                    {
                        var error =
                            $"{upsertObj.Code}: {upsertObj.Message} {JsonConvert.SerializeObject(upsertObj.Details)}";
                        Logger.Error(null, error);
                        return(error);
                    }
                }

                Logger.Info("Created 1 record.");
                return("");
            }
            catch (Exception e)
            {
                Logger.Error(e, e.Message);
                // Logger.Error(null,record.DataJson);
                return(e.Message);
            }
        }