Example #1
0
 /// <summary>
 /// Value equality for two IKey's
 /// </summary>
 /// <returns>true if all parts of of the keys are the same</returns>
 public static bool EqualTo(this IKey key, IKey other)
 {
     return (key.Base == other.Base)
         && (key.TypeName == other.TypeName)
         && (key.ResourceId == other.ResourceId)
         && (key.VersionId == other.VersionId);
 }
Example #2
0
		public BTree(uint topSid, SegmentManager sm, IKey keyFactory)
		{
			this.m_top_sid = topSid;
			this.m_sgManager = sm;
			this.m_keyFactory = keyFactory;
			this.m_nodeFactory = new BNode();
		}
Example #3
0
 public void AddKey(IKey key)
 {
     lock (this)
     {
         _keys.AddLast(key.Key);
     }
 }
Example #4
0
 public bool TryGet(IKey key, out IEntry entry)
 {
     Entry tempEntry;
     var result = _entries.TryGetValue(key, out tempEntry) && !tempEntry.IsReserved;
     entry = result ? tempEntry : null;
     return result;
 }
Example #5
0
        public bool deletePair(IKey key, bool firstCall = false)
        {
            bool canRemoveKey = true;
            if(firstCall)
                canRemoveKey = m_rkm.removeKey(key);

            if (!canRemoveKey)
                return false;

            bool retVal = m_pairsManager.removePair(key);
            //the key is in the local server
            if (retVal)
            {
                m_pairsManager.saveToDisk();
                return retVal;
            }
            //if key doesn't exists on the server need ask the ring for it
            String serviceAddress = m_nextServer.Channel + "://" + m_nextServer.ServerAddress + ":" + m_nextServer.ServerPort + "/" + m_nextServer.ServiceName;

            //Creating server proxy
            IServer svc = (IServer)Activator.GetObject(
                                    typeof(IServer),
                                    serviceAddress);

            try
            {
                return svc.deletePair(key);
            }
            catch (Exception)
            {
                m_rkm.removeServerFromRKM(m_nextServer);
                return false;
            }
        }
Example #6
0
        public void DeletePair(IKey key)
        {
            if (_manager.Trykey(key))
                {
                    if (_hashtable.ContainsKey(key.Key))
                    {

                        _manager.RemoveKey(key);
                        _hashtable.Remove(key.Key);
                    }
                    else
                    {
                        bool b = true;
                        while (b)
                        {
                            try
                            {

                                if (_nextserverUri == null) return;
                                _mysuccessorServer.DeletePair(key);
                                b = false;
                            }
                            catch (Exception ex)
                            {
                                if (ex is WebException || ex is RemotingException)
                                {

                                    _manager.RemakeRing(_nextserverUri);
                                }
                            }
                        }
                    }
                }
        }
        async Task<RegisterOperationResult?> TryOneRequest(IKey key, KeyRegisterRequest request,
            CancellationToken cancellationToken)
        {
            try
            {
                var result = await key.RegisterAsync(request, cancellationToken);

                log.Info(result.Status.ToString());
                switch (result.Status)
                {
                    case KeyResponseStatus.Success:
                        return RegisterOperationResult.Success(request, result.Data);
                }
            }
            catch (KeyGoneException)
            {
                // No sense in continuing with this signer, the key isn't physically present anymore
                log.DebugFormat("Key '{0}' is gone", keyId);
                throw;
            }
            catch (TaskCanceledException)
            {
                // Let cancellation bubble up
                throw;
            }
            catch (KeyBusyException)
            {
                // Maybe it won't be busy later
            }
            catch (Exception exception)
            {
                log.Error("Authenticate request failed", exception);
            }
            return null;
        }
Example #8
0
 public static void HasTypeName(IKey key)
 {
     if (string.IsNullOrEmpty(key.TypeName))
     {
         throw Error.BadRequest("Resource type is missing: {0}", key);
     }
 }
Example #9
0
 public void Setup()
 {
     var mappingSet = ModelSetup.SetupModel();
     database = mappingSet.Database;
     table = database.Tables[0];
     key = table.Keys[0];
 }
        public virtual EntityKeyFactory GetKeyFactory(IKey key)
            => _cache.GetOrAdd(
                key,
                k =>
                    {
                        if (k.Properties.Count == 1)
                        {
                            var keyProperty = k.Properties[0];
                            var keyType = keyProperty.ClrType;

                            // Use composite key for anything with structural (e.g. byte[]) properties even if they are
                            // not composite because it is setup to do structural comparisons and the generic typing
                            // advantages of the simple key don't really apply anyway.
                            if (!typeof(IStructuralEquatable).GetTypeInfo().IsAssignableFrom(keyType.GetTypeInfo()))
                            {
                                var sentinel = keyProperty.SentinelValue;

                                return (EntityKeyFactory)(sentinel == null
                                    ? Activator.CreateInstance(
                                        typeof(SimpleNullSentinelEntityKeyFactory<>).MakeGenericType(keyType.UnwrapNullableType()), k)
                                    : Activator.CreateInstance(
                                        typeof(SimpleEntityKeyFactory<>).MakeGenericType(keyType.UnwrapNullableType()), k, sentinel));
                            }
                        }

                        return new CompositeEntityKeyFactory(k);
                    });
        public IEntry Get(IKey key)
        {
            IEntry entry;
            if (TryGet(key, out entry))
                return entry;

            throw new EntryNotFoundException(key);
        }
Example #12
0
        public bool TryRemove(IKey key)
        {
            var fragments = _fragments;
            foreach (var fragment in fragments)
                if (fragment.TableOfContent.Contains(key))
                    return fragment.TryRemove(key);

            return false;
        }
        public bool TryGet(IKey key, out IEntry entry)
        {
            foreach (var fragment in _fragments)
                if (fragment.TableOfContent.TryGet(key, out entry))
                    return true;

            entry = null;
            return false;
        }
 public KeyInteractionEventArgs( IKey k, IKeyProgram p, KeyInteractionEventType eventType )
     : base(k)
 {
     EventType = eventType;
     // Clone the commands: the emitted commands is a snapshot of the commands
     // at the time of the event.
     string[] copy = p.Commands.ToArray();
     Commands = new CKReadOnlyListOnIList<string>( copy );
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="Message" /> class.
        /// </summary>
        /// <param name="messageType">Type of the message.</param>
        /// <param name="classId">The class identifier.</param>
        /// <param name="commandId">The message identifier.</param>
        protected Message(MessageType messageType, ClassId classId, byte commandId)
        {
            _key = new Key(new Identifier(messageType, TechnologyType.Bluetooth_4_0_Single_Mode, classId, commandId));

            _header.MessageType = messageType;
            _header.TechnologyType = TechnologyType.Bluetooth_4_0_Single_Mode;
            _header.ClassId = classId;
            _header.CommandId = commandId;
        }
Example #16
0
        public override void Add(string name, IKey key)
        {
            string keyPath = Path.Combine (this.path, name);

            if (File.Exists (keyPath + privateSuffix) || File.Exists (keyPath + publicSuffix))
                throw new ArgumentException ("Key with that name already exists");

            WriteKey (key, name);
        }
 public override IEnumerable<IAnnotation> For(IKey key)
 {
     if (key.SqlServer().IsClustered.HasValue)
     {
         yield return new Annotation(
              SqlServerAnnotationNames.Prefix + SqlServerAnnotationNames.Clustered,
              key.SqlServer().IsClustered.Value);
     }
 }
Example #18
0
 protected void Set(IKey key)
 {
     Id = key.Id;
     OwnerUserId = key.OwnerUserId;
     BlobId = key.BlobId;
     Secure = key.Secure;
     if (key.KeyData != null)
         KeyData = (byte[])key.KeyData.Clone();
 }
Example #19
0
 private void put(IKey key, int level, IEnumerable<Resource> resources)
 {
     if (resources == null) return;
     foreach (var resource in resources)
     {
         if (resource is DomainResource)
         put(key, level, resource as DomainResource);
     }
 }
Example #20
0
        public bool TryGet(IKey key, out byte[] content)
        {
            foreach (var fragment in _fragments)
                if (fragment.TryGet(key, out content))
                    return true;

            content = null;
            return false;
        }
        protected static Collection<Dictionary<string, string>> ValidateDtoData(IKey dto, EntityBase entity)
        {
            var retVal = new Collection<Dictionary<string, string>>();
            var fieldName = string.Empty;
            foreach (var inputField in dto.GetType().GetProperties().Where(x => x.Name != "Key" && x.GetValue(dto) != null)) {
                if (inputField.Name.StartsWith("Start_")) {
                    fieldName = inputField.Name.Substring(6);
                } else if(inputField.Name.StartsWith("End_")){
                    fieldName = inputField.Name.Substring(4);
                } else if(inputField.Name.Contains("__")) {
                    //  using field from a different table
                    //      not currently handling this case
                } else {
                    fieldName = inputField.Name;
                }
                //  insure the entity contains the field represented by fieldName
                var entityFieldName = entity.GetType().GetProperty(fieldName);
                if (entityFieldName == null || entityFieldName.Name.Length == 0) {
                    //  entity does not contain this field
                    continue;
                }
                if (entity.GetDataType(fieldName) == typeof(string)) {
                    //  should be ok
                    continue;
                }
                if (entity.GetDataType(fieldName) == typeof(int) || entity.GetDataType(fieldName) == typeof(int?)) {
                    var nbr = 0;
                    if (!int.TryParse(inputField.GetValue(dto).ToString(), out nbr)) {

                        var dic = new Dictionary<string, string> {{inputField.Name, "Invalid data type cast"}};
                        retVal.Add(dic);
                    }
                    if (entity.GetDataType(fieldName) == typeof(bool) || entity.GetDataType(fieldName) == typeof(bool?)) {
                        if (inputField.GetValue(dto).ToString().ToLower() != "true" && inputField.GetValue(dto).ToString().ToLower() != "false") {
                            var dic = new Dictionary<string, string> { { inputField.Name, "Invalid data type cast" } };
                            retVal.Add(dic);
                        }
                    }
                    if (entity.GetDataType(fieldName) == typeof(DateTime) || entity.GetDataType(fieldName) == typeof(DateTime?)) {
                        DateTime dt;
                        if (!DateTime.TryParse(inputField.GetValue(dto).ToString(), out dt)) {
                            var dic = new Dictionary<string, string> { { inputField.Name, "Invalid data type cast" } };
                            retVal.Add(dic);
                        }
                    }
                    if (entity.GetDataType(fieldName) == typeof(decimal) || entity.GetDataType(fieldName) == typeof(decimal?)) {
                        decimal d;
                        if (!decimal.TryParse(inputField.GetValue(dto).ToString(), out d)) {
                            var dic = new Dictionary<string, string> { { inputField.Name, "Invalid data type cast" } };
                            retVal.Add(dic);
                        }
                    }
                }
            }
            return retVal;
        }
 /// <summary>
 ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
 ///     directly from your code. This API may change or be removed in future releases.
 /// </summary>
 public override IEnumerable<IAnnotation> For(IKey key)
 {
     var isClustered = key.SqlServer().IsClustered;
     if (isClustered.HasValue)
     {
         yield return new Annotation(
             SqlServerFullAnnotationNames.Instance.Clustered,
             isClustered.Value);
     }
 }
Example #23
0
 private void put(IKey key, int level, Resource resource)
 {
     if (resource is DomainResource)
     {
         DomainResource d = resource as DomainResource;
         put(key, level, d);
         put(key, level + 1, d.Contained);
     }
     
 }
Example #24
0
 private static void Key150To160( IPluginConfigAccessor simpleSkinConfigAccessor, IKey k )
 {
     //Prior to SimpleSkin plugin v1.6.0 the images were stored in the plugin datas of the layoutkeymodes
     //Since this version, the images are on the keymodes
     foreach( var layoutKeyMode in k.CurrentLayout.LayoutKeyModes )
     {
         PropertyMigrationLayoutKeyModeToKeyMode( simpleSkinConfigAccessor, layoutKeyMode, "Image" );
         PropertyMigrationLayoutKeyModeToKeyMode( simpleSkinConfigAccessor, layoutKeyMode, "DisplayType" );
     }
 }
Example #25
0
 internal static void Key150To160( IKey k )
 {
     //Should be in CK.Keyboard
     foreach( var keyMode in k.KeyModes )
     {
         ProcessKeyProgram150To160( keyMode.OnKeyDownCommands );
         ProcessKeyProgram150To160( keyMode.OnKeyUpCommands );
         ProcessKeyProgram150To160( keyMode.OnKeyPressedCommands );
     }
 }
Example #26
0
        public IList<string> History(IKey key, DateTimeOffset? since = null)
        {
            var clauses = new List<IMongoQuery>();

            clauses.Add(MonQ.Query.EQ(Field.TYPENAME, key.TypeName));
            clauses.Add(MonQ.Query.EQ(Field.RESOURCEID, key.ResourceId));
            if (since != null)
                clauses.Add(MonQ.Query.GT(Field.WHEN, BsonDateTime.Create(since)));

            return FetchPrimaryKeys(clauses);
        }
Example #27
0
 public static SparkException NotFound(IKey key)
 {
     if (key.VersionId == null)
     {
         return NotFound("No {0} resource with id {1} was found.", key.TypeName, key.ResourceId);
     }
     else
     {
         return NotFound("There is no {0} resource with id {1}, or there is no version {2}", key.TypeName, key.ResourceId, key.VersionId);
     }
 }
Example #28
0
 public override void Add(string name, IKey key)
 {
     if (key is PrivateKey) {
         privateKeys.Add (name, (PrivateKey)key);
         if (DefaultKey == null)
             DefaultKey = (PrivateKey)key;
         publicKeys.Add (name, ((PrivateKey)key).PublicKey);
     } else {
         publicKeys.Add (name, (PublicKey)key);
     }
 }
Example #29
0
 public static void HasResourceId(IKey key)
 {
     if (key.HasResourceId())
     {
         Validate.ResourceId(key.ResourceId);
     }
     else
     {
         throw Error.BadRequest("The request should have a resource id.");
     }
 }
Example #30
0
        private static void TestValue(IKey key, string fkey)
        {
            var url = key.GetFileUrl(fkey);


            var inverseKey = key.GetFileKeyFromFileUrl(url);
            //Assert.AreEqual(fkey, inverseKey);
            Assert.AreEqual(fkey.Substring(1), inverseKey.Substring(1));

            Assert.AreEqual(key.GetFileUrl(fkey), key.GetFileUrl(inverseKey));
        }
Example #31
0
 /// <summary>
 ///  Creates a deleted entry
 /// </summary>
 public static Entry DELETE(IKey key, DateTimeOffset?when)
 {
     return(Entry.Create(Bundle.HTTPVerb.DELETE, key, DateTimeOffset.UtcNow));
 }
Example #32
0
 public static Entry PUT(IKey key, Resource resource)
 {
     return(Entry.Create(Bundle.HTTPVerb.PUT, key, resource));
 }
Example #33
0
 /// <summary>
 ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
 ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
 ///     any release. You should only use it directly in your code with extreme caution and knowing that
 ///     doing so can result in application failures when updating to a new Entity Framework Core release.
 /// </summary>
 public virtual IUpdateEntry TryGetEntry(IKey key, object[] keyValues)
 => _stateManager.TryGetEntry(key, keyValues);
Example #34
0
 public TypeReferanceFinalizeScope(IKey key, ISetUpTypeReference type)
 {
     this.key      = key ?? throw new ArgumentNullException(nameof(key));
     SetUpSideNode = type ?? throw new ArgumentNullException(nameof(type));
 }
Example #35
0
 public TypeReferanceResolveReference(IKey key)
 {
     this.key = key ?? throw new ArgumentNullException(nameof(key));
 }
 public bool BindingExists(IKey key)
 {
     return(_bindings.ContainsKey(key));
 }
Example #37
0
 public static Entry Create(Bundle.HTTPVerb method, IKey key, Resource resource)
 {
     return(new Entry(method, key, null, resource));
 }
Example #38
0
 public static RelationalKeyAnnotations MySQL(this IKey key)
 {
     ThrowIf.Argument.IsNull(key, "key");
     return(new RelationalKeyAnnotations(key, MySQLFullAnnotationNames.Instance));
 }
Example #39
0
 public CurrencyList(IKey key, IEnumerable <IEvent> events)
     : base(key, events)
 {
 }
Example #40
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TableEncryptionPolicy"/> class with the specified key and resolver.
 /// </summary>
 /// <param name="key">An object of type <see cref="IKey"/> that is used to wrap/unwrap the content encryption key.</param>
 /// <param name="keyResolver">The key resolver used to select the correct key for decrypting existing table entities.</param>
 /// <remarks>If the generated policy is to be used for encryption, users are expected to provide a key at the minimum.
 /// The absence of key will cause an exception to be thrown during encryption.<br/>
 /// If the generated policy is intended to be used for decryption, users can provide a key resolver. The client library will:<br/>
 /// 1. Invoke the key resolver, if specified, to get the key.<br/>
 /// 2. If resolver is not specified but a key is specified, the client library will match the key ID against the key and use the key.</remarks>
 public TableEncryptionPolicy(IKey key, IKeyResolver keyResolver)
 {
     this.Key         = key;
     this.KeyResolver = keyResolver;
 }
Example #41
0
        internal byte[] DecryptMetadataAndReturnCEK(string partitionKey, string rowKey, EntityProperty encryptionKeyProperty, EntityProperty propertyDetailsProperty, out EncryptionData encryptionData)
        {
            // Throw if neither the key nor the resolver are set.
            if (this.Key == null && this.KeyResolver == null)
            {
                throw new StorageException(SR.KeyAndResolverMissingError, null)
                      {
                          IsRetryable = false
                      };
            }

            try
            {
                encryptionData = JsonConvert.DeserializeObject <EncryptionData>(encryptionKeyProperty.StringValue);

                CommonUtility.AssertNotNull("ContentEncryptionIV", encryptionData.ContentEncryptionIV);
                CommonUtility.AssertNotNull("EncryptedKey", encryptionData.WrappedContentKey.EncryptedKey);

                // Throw if the encryption protocol on the entity doesn't match the version that this client library understands
                // and is able to decrypt.
                if (encryptionData.EncryptionAgent.Protocol != Constants.EncryptionConstants.EncryptionProtocolV1)
                {
                    throw new StorageException(SR.EncryptionProtocolVersionInvalid, null)
                          {
                              IsRetryable = false
                          };
                }

                byte[] contentEncryptionKey = null;

                // 1. Invoke the key resolver if specified to get the key. If the resolver is specified but does not have a
                // mapping for the key id, an error should be thrown. This is important for key rotation scenario.
                // 2. If resolver is not specified but a key is specified, match the key id on the key and and use it.
                // Calling UnwrapKeyAsync synchronously is fine because for the storage client scenario, unwrap happens
                // locally. No service call is made.
                if (this.KeyResolver != null)
                {
                    IKey keyEncryptionKey = this.KeyResolver.ResolveKeyAsync(encryptionData.WrappedContentKey.KeyId, CancellationToken.None).Result;

                    CommonUtility.AssertNotNull("keyEncryptionKey", keyEncryptionKey);
                    contentEncryptionKey = keyEncryptionKey.UnwrapKeyAsync(encryptionData.WrappedContentKey.EncryptedKey, encryptionData.WrappedContentKey.Algorithm, CancellationToken.None).Result;
                }
                else
                {
                    if (this.Key.Kid == encryptionData.WrappedContentKey.KeyId)
                    {
                        contentEncryptionKey = this.Key.UnwrapKeyAsync(encryptionData.WrappedContentKey.EncryptedKey, encryptionData.WrappedContentKey.Algorithm, CancellationToken.None).Result;
                    }
                    else
                    {
                        throw new StorageException(SR.KeyMismatch, null)
                              {
                                  IsRetryable = false
                              };
                    }
                }

                // Decrypt the property details set and add it to entity properties.
#if WINDOWS_DESKTOP && !WINDOWS_PHONE
                using (AesCryptoServiceProvider myAes = new AesCryptoServiceProvider())
                {
                    using (SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider())
#else
                using (AesManaged myAes = new AesManaged())
                {
                    using (SHA256Managed sha256 = new SHA256Managed())
#endif
                    {
                        byte[] metadataIV = sha256.ComputeHash(CommonUtility.BinaryAppend(encryptionData.ContentEncryptionIV, Encoding.UTF8.GetBytes(string.Join(partitionKey, rowKey, Constants.EncryptionConstants.TableEncryptionPropertyDetails))));
                        Array.Resize <byte>(ref metadataIV, 16);
                        myAes.IV  = metadataIV;
                        myAes.Key = contentEncryptionKey;

                        using (ICryptoTransform transform = myAes.CreateDecryptor())
                        {
                            byte[] src = propertyDetailsProperty.BinaryValue;
                            propertyDetailsProperty.BinaryValue = transform.TransformFinalBlock(src, 0, src.Length);
                        }
                    }
                }

                return(contentEncryptionKey);
            }
            catch (JsonException ex)
            {
                throw new StorageException(SR.EncryptionMetadataError, ex)
                      {
                          IsRetryable = false
                      };
            }
            catch (StorageException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new StorageException(SR.DecryptionLogicError, ex)
                      {
                          IsRetryable = false
                      };
            }
        }
        public string GetPredicate(IKey dto, EntityBase entity, string companyId)
        {
            var sb  = new StringBuilder();
            var fld = dto.GetType().GetProperty("CompanyID");

            if (fld != null)
            {
                var type = entity.GetDataType("CompanyID");
                if (type == typeof(string))
                {
                    sb.Append(string.Format("{0}{1}{2}", "CompanyID", "==", companyId));
                }
                if (type == typeof(int?))
                {
                    sb.Append(string.Format("{0}{1}{2}{3}", "CompanyID", ".Value", "==", companyId));
                }
            }
            foreach (var field in dto.GetType().GetProperties().Where(x => x.Name != "Key" && x.GetValue(dto) != null))
            {
                var value = field.GetValue(dto).ToString();
                if (!string.IsNullOrEmpty(value))
                {
                    if (sb.Length > 0)
                    {
                        sb.Append(" && ");
                    }
                    if (field.Name.Contains("__"))
                    {
                        //  embedded table.field reference
                        sb.Append(FormatEmbeddedReference(field, field.GetValue(dto).ToString()));
                    }
                    else
                    {
                        var fieldName = string.Empty;
                        if (field.Name.StartsWith("Start_"))
                        {
                            fieldName = field.Name.Substring(6);
                        }
                        else if (field.Name.StartsWith("End_"))
                        {
                            fieldName = field.Name.Substring(4);
                        }
                        else
                        {
                            fieldName = field.Name;
                        }
                        var type = entity.GetDataType(fieldName);
                        if (type == typeof(string))
                        {
                            sb.Append(fieldName + ".Contains('");
                            sb.Append(String.Format("{0}{1}", field.GetValue(dto), "')"));
                            //sb.Append(field.GetValue(dto) + ")");
                            continue;
                        }
                        if (type == typeof(int))
                        {
                            sb.Append(string.Format("{0}{1}{2}", fieldName, "==", int.Parse(field.GetValue(dto).ToString())));
                            continue;
                        }
                        if (type == typeof(int?))
                        {
                            sb.Append(string.Format("{0}{1}{2}{3}", fieldName, ".Value", "==", int.Parse(field.GetValue(dto).ToString())));
                            continue;
                        }
                        if (type == typeof(bool))
                        {
                            sb.Append(string.Format("{0}{1}{2}", fieldName, "==", bool.Parse(field.GetValue(dto).ToString())));
                            continue;
                        }
                        if (type == typeof(bool?))
                        {
                            sb.Append(string.Format("{0}{1}{2}{3}", fieldName, ".Value", "==", bool.Parse(field.GetValue(dto).ToString())));
                            continue;
                        }
                        if (type == typeof(DateTime?))
                        {
                            var comparer = string.Empty;
                            var date     = string.Empty;
                            if (field.Name.StartsWith("Start_"))
                            {
                                comparer = ">";
                                date     = DateTime.Parse(field.GetValue(dto).ToString()).AddDays(-1).ToShortDateString();
                            }
                            else
                            {
                                comparer = "<";
                                date     = DateTime.Parse(field.GetValue(dto).ToString()).AddDays(1).ToShortDateString();
                            }
                            fieldName = fieldName + ".Value";
                            sb.Append(String.Format("{0}{1}{2}{3}{2}", fieldName, comparer, "'", date));
                            continue;
                        }
                        if (type == typeof(DateTime))
                        {
                            var comparer = string.Empty;
                            var date     = string.Empty;
                            if (field.Name.StartsWith("Start_"))
                            {
                                comparer = ">";
                                date     = DateTime.Parse(field.GetValue(dto).ToString()).AddDays(-1).ToShortDateString();
                            }
                            else
                            {
                                comparer = "<";
                                date     = DateTime.Parse(field.GetValue(dto).ToString()).AddDays(1).ToShortDateString();
                            }
                            sb.Append(String.Format("{0}{1}{2}{3}{2}", fieldName, comparer, "'", date));
                            continue;
                        }
                        if (type == typeof(decimal))
                        {
                            sb.Append(string.Format("{0}{1}{2}", fieldName, "==", decimal.Parse(field.GetValue(dto).ToString())));
                        }
                        if (type == typeof(decimal?))
                        {
                            sb.Append(string.Format("{0}{1}{2}{3}", fieldName, ".Value", "==", decimal.Parse(field.GetValue(dto).ToString())));
                        }
                    }
                }
            }
            return(sb.ToString());
        }
Example #43
0
 public static Entry Create(Bundle.HTTPVerb method, IKey key, DateTimeOffset when)
 {
     return(new Entry(method, key, when, null));
 }
        /// <summary>
        /// Return a reference to a <see cref="CryptoStream"/> object, given a user stream. This method is used for decrypting blobs.
        /// </summary>
        /// <param name="userProvidedStream">The output stream provided by the user.</param>
        /// <param name="metadata">A reference to a dictionary containing blob metadata that includes the encryption data.</param>
        /// <param name="transform">The <see cref="ICryptoTransform"/> function for the request.</param>
        /// <param name="requireEncryption">A boolean value to indicate whether the data read from the server should be encrypted.</param>
        /// <param name="iv">The iv to use if pre-buffered. Used only for range reads.</param>
        /// <param name="noPadding">Value indicating if the padding mode should be set or not.</param>
        /// <returns>A reference to a <see cref="CryptoStream"/> that will be written to.</returns>
        internal Stream DecryptBlob(Stream userProvidedStream, IDictionary <string, string> metadata, out ICryptoTransform transform, bool?requireEncryption, byte[] iv = null, bool noPadding = false)
        {
            CommonUtility.AssertNotNull("metadata", metadata);

            string encryptionDataString = null;

            // If encryption policy is set but the encryption metadata is absent, throw an exception.
            bool encryptionMetadataAvailable = metadata.TryGetValue(Constants.EncryptionConstants.BlobEncryptionData, out encryptionDataString);

            if (requireEncryption.HasValue && requireEncryption.Value && !encryptionMetadataAvailable)
            {
                throw new StorageException(SR.EncryptionDataNotPresentError, null)
                      {
                          IsRetryable = false
                      };
            }

            try
            {
                if (encryptionDataString != null)
                {
                    BlobEncryptionData encryptionData = JsonConvert.DeserializeObject <BlobEncryptionData>(encryptionDataString);

                    CommonUtility.AssertNotNull("ContentEncryptionIV", encryptionData.ContentEncryptionIV);
                    CommonUtility.AssertNotNull("EncryptedKey", encryptionData.WrappedContentKey.EncryptedKey);

                    // Throw if the encryption protocol on the blob doesn't match the version that this client library understands
                    // and is able to decrypt.
                    if (encryptionData.EncryptionAgent.Protocol != Constants.EncryptionConstants.EncryptionProtocolV1)
                    {
                        throw new StorageException(SR.EncryptionProtocolVersionInvalid, null)
                              {
                                  IsRetryable = false
                              };
                    }

                    // Throw if neither the key nor the resolver are set.
                    if (this.Key == null && this.KeyResolver == null)
                    {
                        throw new StorageException(SR.KeyAndResolverMissingError, null)
                              {
                                  IsRetryable = false
                              };
                    }

                    byte[] contentEncryptionKey = null;

                    // 1. Invoke the key resolver if specified to get the key. If the resolver is specified but does not have a
                    // mapping for the key id, an error should be thrown. This is important for key rotation scenario.
                    // 2. If resolver is not specified but a key is specified, match the key id on the key and and use it.
                    // Calling UnwrapKeyAsync synchronously is fine because for the storage client scenario, unwrap happens
                    // locally. No service call is made.
                    if (this.KeyResolver != null)
                    {
                        IKey keyEncryptionKey = this.KeyResolver.ResolveKeyAsync(encryptionData.WrappedContentKey.KeyId, CancellationToken.None).Result;

                        CommonUtility.AssertNotNull("KeyEncryptionKey", keyEncryptionKey);
                        contentEncryptionKey = keyEncryptionKey.UnwrapKeyAsync(encryptionData.WrappedContentKey.EncryptedKey, encryptionData.WrappedContentKey.Algorithm, CancellationToken.None).Result;
                    }
                    else
                    {
                        if (this.Key.Kid == encryptionData.WrappedContentKey.KeyId)
                        {
                            contentEncryptionKey = this.Key.UnwrapKeyAsync(encryptionData.WrappedContentKey.EncryptedKey, encryptionData.WrappedContentKey.Algorithm, CancellationToken.None).Result;
                        }
                        else
                        {
                            throw new StorageException(SR.KeyMismatch, null)
                                  {
                                      IsRetryable = false
                                  };
                        }
                    }

                    switch (encryptionData.EncryptionAgent.EncryptionAlgorithm)
                    {
                    case EncryptionAlgorithm.AES_CBC_256:
#if WINDOWS_DESKTOP && !WINDOWS_PHONE
                        using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
#else
                        using (AesManaged aesProvider = new AesManaged())
#endif
                        {
                            aesProvider.IV  = iv != null ? iv : encryptionData.ContentEncryptionIV;
                            aesProvider.Key = contentEncryptionKey;

                            if (noPadding)
                            {
#if WINDOWS_DESKTOP && !WINDOWS_PHONE
                                aesProvider.Padding = PaddingMode.None;
#endif
                            }

                            transform = aesProvider.CreateDecryptor();
                            return(new CryptoStream(userProvidedStream, transform, CryptoStreamMode.Write));
                        }

                    default:
                        throw new StorageException(SR.InvalidEncryptionAlgorithm, null)
                              {
                                  IsRetryable = false
                              };
                    }
                }
                else
                {
                    transform = null;
                    return(userProvidedStream);
                }
            }
            catch (JsonException ex)
            {
                throw new StorageException(SR.EncryptionMetadataError, ex)
                      {
                          IsRetryable = false
                      };
            }
            catch (StorageException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new StorageException(SR.DecryptionLogicError, ex)
                      {
                          IsRetryable = false
                      };
            }
        }
Example #45
0
 public TypeReferancePopulateScope(IKey typeName)
 {
     key = typeName ?? throw new ArgumentNullException(nameof(typeName));
 }
 public OutcomeAlreadyHasCategoryException(IKey categoryKey)
     : base(string.Format("The outcome already has a category '{0}'.", categoryKey))
 {
     CategoryKey = categoryKey;
 }
Example #47
0
 private void SaveMovieKey(XElement element, XName attributeName, IKey key)
 {
     element.SetAttributeValue(attributeName, GetMovieId(key));
 }
Example #48
0
 public static IPopulateScope <WeakTypeReference, ISetUpTypeReference> PopulateScope(IKey typeName)
 {
     return(new TypeReferancePopulateScope(typeName));
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="BlobEncryptionPolicy"/> class with the specified key and resolver.
 /// </summary>
 /// <param name="key">An object of type <see cref="IKey"/> that is used to wrap/unwrap the content key during encryption.</param>
 /// <param name="keyResolver">The key resolver used to select the correct key for decrypting existing blobs.</param>
 /// <remarks>If the generated policy is to be used for encryption, users are expected to provide a key at the minimum.
 /// The absence of key will cause an exception to be thrown during encryption.<br/>
 /// If the generated policy is intended to be used for decryption, users can provide a key resolver. The client library will:<br/>
 /// 1. Invoke the key resolver, if specified, to get the key.<br/>
 /// 2. If resolver is not specified but a key is specified, the client library will match the key ID against the key and use the key.</remarks>
 public BlobEncryptionPolicy(IKey key, IKeyResolver keyResolver)
 {
     this.Key            = key;
     this.KeyResolver    = keyResolver;
     this.EncryptionMode = BlobEncryptionMode.FullBlob;
 }
Example #50
0
        private async void abbPin_Click(object sender, RoutedEventArgs e)
        {
            IKey   categoryKey  = ViewModel.SelectedCategories.FirstOrDefault() ?? KeyFactory.Empty(typeof(Category));
            Color? background   = null;
            string categoryName = null;

            // Select a category.
            CategoryPicker categoryPicker = new CategoryPicker();

            categoryPicker.SelectedKey = categoryKey;

            ContentDialogResult categoryResult = await categoryPicker.ShowAsync();

            if (categoryResult == ContentDialogResult.None)
            {
                return;
            }

            if (categoryResult == ContentDialogResult.Primary)
            {
                categoryKey = categoryPicker.SelectedKey;
            }
            else if (categoryResult == ContentDialogResult.Secondary)
            {
                categoryKey = KeyFactory.Empty(typeof(Category));
            }

            if (!categoryKey.IsEmpty)
            {
                CategoryModel category = ViewModel.Categories.FirstOrDefault(c => c.Key.Equals(categoryKey));
                if (category != null)
                {
                    categoryName = category.Name;
                    background   = category.Color;
                }
            }

            // Select a background color.
            ColorPicker backgroundPicker = new ColorPicker();

            backgroundPicker.Title             = "Pick a tile background color";
            backgroundPicker.PrimaryButtonText = "Create";

            if (background != null)
            {
                backgroundPicker.Value = background.Value;
            }

            ContentDialogResult backgroundResult = await backgroundPicker.ShowAsync();

            if (backgroundResult == ContentDialogResult.None)
            {
                return;
            }

            // Create a tile.
            await tileService.PinOutcomeCreate(categoryKey, categoryName, backgroundPicker.Value);

            string message = "Tile created";

            if (categoryName != null)
            {
                message += $" for category '{categoryName}'";
            }

            navigator
            .Message(message)
            .Show();
        }
Example #51
0
 internal CacheableKeyRing(CancellationToken expirationToken, DateTimeOffset expirationTime, IKey defaultKey, IEnumerable <IKey> allKeys)
     : this(expirationToken, expirationTime, keyRing : new KeyRing(defaultKey, allKeys))
 {
 }
Example #52
0
 public ISigner CreateSigner(IKey key) => new EllipticCurveSigner(key, signingAlgorithm, hashAlgorithm);
Example #53
0
 protected virtual void OpenOverview(T item, IKey categorykey)
 {
 }
Example #54
0
 /// <summary>
 ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
 ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
 ///     any release. You should only use it directly in your code with extreme caution and knowing that
 ///     doing so can result in application failures when updating to a new Entity Framework Core release.
 /// </summary>
 protected override MethodCallCodeFragment GenerateFluentApi(IKey key, IAnnotation annotation)
 => annotation.Name == SqlServerAnnotationNames.Clustered
         ? (bool)annotation.Value == false
             ? new MethodCallCodeFragment(nameof(SqlServerIndexBuilderExtensions.IsClustered), false)
             : new MethodCallCodeFragment(nameof(SqlServerIndexBuilderExtensions.IsClustered))
         : null;
Example #55
0
 /// <summary>
 ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
 ///     directly from your code. This API may change or be removed in future releases.
 /// </summary>
 public virtual Func <bool, IIdentityMap> Create([NotNull] IKey key)
 => (Func <bool, IIdentityMap>) typeof(IdentityMapFactoryFactory).GetTypeInfo()
 .GetDeclaredMethod(nameof(CreateFactory))
 .MakeGenericMethod(GetKeyType(key))
 .Invoke(null, new object[] { key });
Example #56
0
 public PrivateMember(IKey key)
 {
     this.key = key ?? throw new ArgumentNullException(nameof(key));
 }
 /// <summary>
 ///     Gets all foreign keys that target a given primary or alternate key.
 /// </summary>
 /// <param name="key"> The key to find the foreign keys for. </param>
 /// <returns> The foreign keys that reference the given key. </returns>
 public static IEnumerable <IForeignKey> GetReferencingForeignKeys([NotNull] this IKey key)
 => Check.NotNull(key, nameof(key)).AsKey().ReferencingForeignKeys ?? Enumerable.Empty <IForeignKey>();
 /// <summary>
 ///     Returns a value indicating whether the key is the primary key.
 /// </summary>
 /// <param name="key"> The key to find whether it is primary. </param>
 /// <returns> <c>true</c> if the key is the primary key. </returns>
 public static bool IsPrimaryKey([NotNull] this IKey key)
 => key == key.DeclaringEntityType.FindPrimaryKey();
Example #59
0
        public override IAccountStateDelta Execute(IActionContext context)
        {
            IActionContext ctx    = context;
            var            states = ctx.PreviousStates;

            if (ctx.Rehearsal)
            {
                states = states.SetState(ShopState.Address, MarkChanged);
                states = states.SetState(sellerAvatarAddress, MarkChanged);
                return(states.SetState(ctx.Signer, MarkChanged));
            }
            var sw = new Stopwatch();

            sw.Start();
            var started = DateTimeOffset.UtcNow;

            Log.Debug("Sell exec started.");


            if (price.Sign < 0)
            {
                throw new InvalidPriceException($"Aborted as the price is less than zero: {price}.");
            }

            if (!states.TryGetAgentAvatarStates(ctx.Signer, sellerAvatarAddress, out AgentState agentState, out AvatarState avatarState))
            {
                throw new FailedLoadStateException("Aborted as the avatar state of the signer was failed to load.");
            }
            sw.Stop();
            Log.Debug("Sell Get AgentAvatarStates: {Elapsed}", sw.Elapsed);
            sw.Restart();

            if (!avatarState.worldInformation.IsStageCleared(GameConfig.RequireClearedStageLevel.ActionsInShop))
            {
                avatarState.worldInformation.TryGetLastClearedStageId(out var current);
                throw new NotEnoughClearedStageLevelException(GameConfig.RequireClearedStageLevel.ActionsInShop, current);
            }

            Log.Debug("Sell IsStageCleared: {Elapsed}", sw.Elapsed);

            sw.Restart();

            if (!states.TryGetState(ShopState.Address, out Bencodex.Types.Dictionary shopStateDict))
            {
                throw new FailedLoadStateException("Aborted as the shop state was failed to load.");
            }

            Log.Debug("Sell Get ShopState: {Elapsed}", sw.Elapsed);
            sw.Restart();

            Log.Debug("Execute Sell; seller: {SellerAvatarAddress}", sellerAvatarAddress);

            var      productId = context.Random.GenerateRandomGuid();
            ShopItem shopItem;

            void CheckRequiredBlockIndex(ItemUsable itemUsable)
            {
                if (itemUsable.RequiredBlockIndex > context.BlockIndex)
                {
                    throw new RequiredBlockIndexException($"Aborted as the itemUsable to enhance ({itemId}) is not available yet; it will be available at the block #{itemUsable.RequiredBlockIndex}.");
                }
            }

            ShopItem PopShopItemFromInventory(ItemUsable itemUsable, Costume costume)
            {
                avatarState.inventory.RemoveNonFungibleItem(itemId);
                return(itemUsable is null
                    ? new ShopItem(ctx.Signer, sellerAvatarAddress, productId, price, costume)
                    : new ShopItem(ctx.Signer, sellerAvatarAddress, productId, price, itemUsable));
            }

            // Select an item to sell from the inventory and adjust the quantity.
            if (avatarState.inventory.TryGetNonFungibleItem <Equipment>(itemId, out var equipment))
            {
                CheckRequiredBlockIndex(equipment);
                // FIXME: Use `equipment.Unequip()`
                equipment.equipped = false;
                shopItem           = PopShopItemFromInventory(equipment, null);
            }
            else if (avatarState.inventory.TryGetNonFungibleItem <Consumable>(itemId, out var consumable))
            {
                CheckRequiredBlockIndex(consumable);
                avatarState.inventory.RemoveNonFungibleItem(itemId);
                shopItem = PopShopItemFromInventory(consumable, null);
            }
            else if (avatarState.inventory.TryGetNonFungibleItem <Costume>(itemId, out var costume))
            {
                // FIXME: Use `costume.Unequip()`
                costume.equipped = false;
                shopItem         = PopShopItemFromInventory(null, costume);
            }
            else
            {
                throw new ItemDoesNotExistException(
                          $"Aborted as the NonFungibleItem ({itemId}) was failed to load from avatar's inventory.");
            }

            IValue shopItemSerialized  = shopItem.Serialize();
            IKey   productIdSerialized = (IKey)productId.Serialize();

            Dictionary products = (Dictionary)shopStateDict["products"];

            products      = (Dictionary)products.Add(productIdSerialized, shopItemSerialized);
            shopStateDict = shopStateDict.SetItem("products", products);

            sw.Stop();
            Log.Debug("Sell Get Register Item: {Elapsed}", sw.Elapsed);
            sw.Restart();

            avatarState.updatedAt  = ctx.BlockIndex;
            avatarState.blockIndex = ctx.BlockIndex;

            states = states.SetState(sellerAvatarAddress, avatarState.Serialize());
            sw.Stop();
            Log.Debug("Sell Set AvatarState: {Elapsed}", sw.Elapsed);
            sw.Restart();

            states = states.SetState(ShopState.Address, shopStateDict);
            sw.Stop();
            var ended = DateTimeOffset.UtcNow;

            Log.Debug("Sell Set ShopState: {Elapsed}", sw.Elapsed);
            Log.Debug("Sell Total Executed Time: {Elapsed}", ended - started);

            return(states);
        }
Example #60
0
 public static IPopulateBoxes <WeakTypeReference> PopulateBoxes(IKey key)
 {
     return(new TypeReferanceResolveReference(key));
 }