示例#1
0
        protected static void Serialize(DurableEntity durableEntity, ref JObject jObject)
        {
            MovingEntitySerializer.Serialize(durableEntity, ref jObject);

            SerializationUtils.AddToObject(jObject, durableEntity, durableEntityType, serializeableProperties);
        }
        protected static void Deserialize(ref JObject jObject, HitableObject hitableObject)
        {
            GameObjectSerializer.Deserialize(ref jObject, hitableObject);

            SerializationUtils.SetFromObject(jObject, hitableObject, hitableObjectType, serializeableProperties);
        }
示例#3
0
        private void OpenNewGame(byte[] data)
        {
            GInfo newG = (GInfo)SerializationUtils.DeSerialization(data);

            server.OpenGame(newG);
        }
示例#4
0
        private void SetField(byte[] data)
        {
            FieldInfo fInfo = (FieldInfo)SerializationUtils.DeSerialization(data);

            server.AddField(fInfo);
        }
示例#5
0
 /// <summary>
 /// Initializes the data pairs.
 ///
 /// </summary>
 /// <param name="root">The root path.</param><exception cref="T:System.Exception"><c>Exception</c>.</exception>
 protected virtual void InitializeDataPairs(string root)
 {
     if (!Directory.Exists(root))
     {
         dataPairs = new DataPair[0];
         Trace.TraceWarning("Directoty does not exist " + root);
     }
     else
     {
         List <DataPair> result = new List <DataPair>();
         try
         {
             var rootDirectory = new DirectoryInfo(root);
             var directories   = new List <DirectoryInfo>(rootDirectory.GetDirectories());
             directories.Sort(new FileSystemInfoComparer <DirectoryInfo>());
             var files = new List <FileInfo>(rootDirectory.GetFiles());
             files.Sort(new FileSystemInfoComparer <FileInfo>());
             foreach (var file in files.Where(file => file != null))
             {
                 if (SerializationUtils.IsItemSerialization(file.FullName))
                 {
                     DirectoryInfo itemDirectory = null;
                     var           dirName       = file.FullName.Substring(0, file.FullName.Length - ".item".Length);
                     foreach (var dir in  directories.Where(d => string.Compare(d.FullName, dirName, true) == 0))
                     {
                         itemDirectory = dir;
                         directories.Remove(dir);
                         break;
                     }
                     if (itemDirectory != null)
                     {
                         var dataItem = new QuickContentDataItem(this.root, this.root.Length == file.Directory.FullName.Length ? string.Empty : file.Directory.FullName.Substring(this.root.Length), file.Name);
                         if (IsAllowed(dataItem) && dataItem.HasItem)
                         {
                             result.Add(new DataPair(itemDirectory, dataItem));
                         }
                     }
                     else
                     {
                         var dataItem = new QuickContentDataItem(this.root, this.root.Length == file.Directory.FullName.Length ? string.Empty : file.Directory.FullName.Substring(this.root.Length), file.Name);
                         if (IsAllowed(dataItem) && dataItem.HasItem)
                         {
                             result.Add(new DataPair(file, dataItem));
                         }
                     }
                 }
                 else
                 {
                     var dataItem = ItemUtils.GetFileSystemDataItem(this.root, file);
                     if (IsAllowed(dataItem))
                     {
                         result.Add(new DataPair(file, dataItem));
                     }
                 }
             }
             result.AddRange(
                 from directory in directories
                 let dataItem = Update.Utils.ItemUtils.GetSystemFolderDataItem(this.root, directory)
                                where IsAllowed(dataItem)
                                select new DataPair(directory, dataItem));
         }
         catch (Exception ex)
         {
             Trace.TraceError("Can't initialize provider. Exception: " + ex);
             throw ex;
         }
         dataPairs = result.ToArray();
     }
 }
 /// <inheritdoc/>
 public override DistributedContext FromByteArray(byte[] bytes)
 {
     return(SerializationUtils.DeserializeBinary(bytes));
 }
示例#7
0
 /// <summary>
 /// By setting contact field backup instructions, Maileon is told to backup the values of indicated contact fields used in mailings and to map them to the mailings. This feature is expensive in terms of storage and should only be used for those contact fields that are expected to be frequently updated and that are relevant for reports.
 /// </summary>
 /// <param name="fbi"></param>
 public void CreateFieldBackupInstruction(FieldBackupInstruction fbi)
 {
     Post("contacts/backup", SerializationUtils <FieldBackupInstruction> .ToXmlString(fbi));
 }
        internal static ResourceElement Serialize(ImageListOptions opts)
        {
            var imgList = new ImageList();

            imgList.ColorDepth       = opts.ColorDepth;
            imgList.ImageSize        = opts.ImageSize;
            imgList.TransparentColor = opts.TransparentColor;

            foreach (var imageSource in opts.ImageSources)
            {
                var bitmapSource = imageSource as BitmapSource;
                if (bitmapSource == null)
                {
                    throw new InvalidOperationException("Only BitmapSources can be used");
                }
                var encoder = new BmpBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
                var outStream = new MemoryStream();
                encoder.Save(outStream);
                outStream.Position = 0;
                var wfBmp = new System.Drawing.Bitmap(outStream);
                imgList.Images.Add(wfBmp);
            }

            var obj = imgList.ImageStream;

            return(new ResourceElement {
                Name = opts.Name,
                ResourceData = new BinaryResourceData(new UserResourceType(obj.GetType().AssemblyQualifiedName, ResourceTypeCode.UserTypes), SerializationUtils.Serialize(obj)),
            });
        }
示例#9
0
        /// <summary>
        /// Gets the number of contacts
        /// </summary>
        /// <returns></returns>
        public int GetCountContacts()
        {
            ResponseWrapper response = Get("contacts/count");

            return(SerializationUtils <int> .FromXmlString(response.Body));
        }
示例#10
0
        /// <summary>
        /// Returns the contact field backup instruction that are available in the account.
        /// </summary>
        /// <returns></returns>
        public List <FieldBackupInstruction> GetFieldBackupInstructions()
        {
            ResponseWrapper response = Get("contacts/backup");

            return(SerializationUtils <FieldBackupInstructionCollection> .FromXmlString(response.Body));
        }
示例#11
0
 public static bool SetCredential <T>(string p_key, T p_value)
 {
     return(SetString(p_key, p_value != null ? SerializationUtils.ToJson(p_value) : null));
 }
示例#12
0
        // TODO: This is ugly af , maybe an Action<request,header> instead ?
        // <summary>
        // Create IRestRequest object with required headers for CheckoutFinland API
        // </summary>
        private IRestRequest CreateRequest(string url, Method method, object requestBody, IDictionary <string, string> extraHeader = null)
        {
            IRestRequest request = new RestRequest(url, method, DataFormat.Json);

            IDictionary <string, string> headerDictionary = new Dictionary <string, string>()
            {
                { CheckoutRequestHeaders.Method, method.ToString("g") },
                { CheckoutRequestHeaders.NOnce, Guid.NewGuid().ToString() },
                { CheckoutRequestHeaders.Timestamp, DateTimeOffset.UtcNow.ToIsoDateTimeString() }
            };

            // TODO: If extra header already there , wut wut ?
            if (extraHeader != null)
            {
                extraHeader.ToList().Each(kv => { headerDictionary.Add(kv.Key, kv.Value); });
            }

            headerDictionary.ToList().Each(kv => { request.AddHeader(kv.Key, kv.Value); });

            var toEncrypt = EncryptionUtils.ConvertCustomRequestHeaders(
                defaultHeaders.Concat(headerDictionary).ToDictionary(x => x.Key, x => x.Value)
                );

            var signature = EncryptionUtils.CalculateHmac(_secretKey, toEncrypt.ToList(), SerializationUtils.RequestBodyToString(requestBody));

            request.AddHeader(CheckoutRequestHeaders.Signature, signature);
            if (requestBody != null)
            {
                request.AddJsonBody(requestBody);
            }

            return(request);
        }
示例#13
0
        /// <summary>
        /// Resolves parameters for method call from NextApiCommand
        /// </summary>
        /// <param name="methodInfo">Information about method</param>
        /// <param name="command">Information about NextApi call</param>
        /// <returns>Array of parameters</returns>
        /// <exception cref="Exception">when parameter is not exist in command</exception>
        public static object[] ResolveMethodParameters(MethodInfo methodInfo, NextApiCommand command)
        {
            var paramValues = new List <object>();

            foreach (var parameter in methodInfo.GetParameters())
            {
                var paramName = parameter.Name;

                var arg = command.Args.Cast <INamedNextApiArgument>().FirstOrDefault(d => d.Name == paramName);

                switch (arg)
                {
                case null when !parameter.IsOptional:
                    throw new Exception($"Parameter with {paramName} is not exist in request");

                // adding placeholder for optional param.
                // See: https://stackoverflow.com/questions/9977719/invoke-a-method-with-optional-params-via-reflection
                case null:
                    paramValues.Add(Type.Missing);
                    continue;

                case NextApiJsonArgument nextApiJsonArgument:
                    var argType           = parameter.ParameterType;
                    var deserializedValue = nextApiJsonArgument.Value?.ToObject(argType,
                                                                                JsonSerializer.Create(SerializationUtils.GetJsonConfig()));
                    paramValues.Add(deserializedValue);
                    break;

                case NextApiArgument nextApiArgument:
                    paramValues.Add(nextApiArgument.Value);
                    break;
                }
            }

            return(paramValues.ToArray());
        }
        internal ResourceElement Serialize(ResourceElement resElem)
        {
            var  data   = (byte[])((BuiltInResourceData)resElem.ResourceData).Data;
            bool isIcon = BitConverter.ToUInt32(data, 0) == 0x00010000;

            object obj;

            if (isIcon)
            {
                obj = new System.Drawing.Icon(new MemoryStream(data));
            }
            else
            {
                obj = new System.Drawing.Bitmap(new MemoryStream(data));
            }

            return(new ResourceElement {
                Name = resElem.Name,
                ResourceData = new BinaryResourceData(new UserResourceType(obj.GetType().AssemblyQualifiedName, ResourceTypeCode.UserTypes), SerializationUtils.Serialize(obj)),
            });
        }
示例#15
0
        /// <summary>
        /// Gets the custom fields
        /// </summary>
        /// <returns>a list of custom fields</returns>
        public List <CustomFieldDefinition> GetCustomFields()
        {
            ResponseWrapper resp = Get("contacts/fields/custom");

            return(SerializationUtils <CustomFieldDefinitionCollection> .FromXmlString(resp.Body));
        }
        /// <summary>
        /// Serializes the given build to a xml string and returns that string.
        /// </summary>
        public string ExportBuildToString(PoEBuild build)
        {
            var xmlBuild = ToXmlBuild(build);

            return(SerializationUtils.XmlSerializeToString(xmlBuild));
        }
示例#17
0
 public override byte[] ToByteArray(ITagContext tags)
 {
     return(SerializationUtils.SerializeBinary(tags));
 }
示例#18
0
        /// <summary>
        /// Returns object reference for supplied metahandle
        /// </summary>
        public object HandleToReference(MetaHandle handle, TypeRegistry treg, SlimFormat format, SlimReader reader)
        {
            if (handle.IsInlinedString)
            {
                return(handle.Metadata);
            }
            if (handle.IsInlinedTypeValue)
            {
                var tref = treg.GetByHandle(handle.Metadata);//adding this type to registry if it is not there yet
                return(tref);
            }

            if (handle.IsInlinedRefType)
            {
                var tref = treg.GetByHandle(handle.Metadata);//adding this type to registry if it is not there yet
                var ra   = format.GetReadActionForRefType(tref);
                if (ra != null)
                {
                    var inst = ra(reader);
                    m_List.Add(inst);
                    m_Dict.Add(inst, m_List.Count - 1);
                    return(inst);
                }
                else
                {
                    throw new SlimDeserializationException("Internal error HandleToReference: no read action for ref type, but ref mhandle is inlined");
                }
            }


            int idx = (int)handle.Handle;

            if (idx < m_List.Count)
            {
                return(m_List[idx]);
            }

            if (string.IsNullOrEmpty(handle.Metadata))
            {
                throw new SlimDeserializationException(StringConsts.SLIM_HNDLTOREF_MISSING_TYPE_NAME_ERROR + handle.ToString());
            }

            var metadata = handle.Metadata;
            var ip       = metadata.IndexOf('|');
            //var segments = metadata.Split('|');
            var th = ip > 0 ? metadata.Substring(0, ip) : metadata;

            //20140701 DKh
            var type = treg[th];//segments[0]];

            object instance = null;

            if (type.IsArray)
            {
                //DKh 20130712 Removed repetitive code that was refactored into Arrays class
                instance = Arrays.DescriptorToArray(metadata, treg, type);
            }
            else
            {
                //20130715 DKh
                instance = SerializationUtils.MakeNewObjectInstance(type);
            }

            m_List.Add(instance);
            m_Dict.Add(instance, m_List.Count - 1);
            return(instance);
        }
 public void SerializationUtilsTrimToLengthTests(string original, int maxLength, string expectedTrimmed) =>
 SerializationUtils.TrimToLength(original, maxLength).Should().Be(expectedTrimmed);
 /// <inheritdoc/>
 public override byte[] ToByteArray(DistributedContext context)
 {
     return(SerializationUtils.SerializeBinary(context));
 }
 public void SerializationUtilsTrimToPropertyMaxLengthTests(string original, string expectedTrimmed)
 {
     Consts.PropertyMaxLength.Should().BeGreaterThan(3);
     SerializationUtils.TrimToPropertyMaxLength(original).Should().Be(expectedTrimmed);
 }
示例#22
0
        private void LeaveGame(byte[] data)
        {
            GInfo game = (GInfo)SerializationUtils.DeSerialization(data);

            server.InterruptGame(User, game);
        }
 public static ProductAdditionalInfoXML FromPayload(string payload)
 {
     return(SerializationUtils.ParseFromPayload <ProductAdditionalInfoXML>(payload));
 }
示例#24
0
        private void NewMove(byte[] data)
        {
            Move move = (Move)SerializationUtils.DeSerialization(data);

            server.PlayerMove(move, User);
        }
 public string ToPayload()
 {
     return(SerializationUtils.SerializeObject <ProductAdditionalInfoXML>(this));
 }
示例#26
0
        protected static void Deserialize(ref JObject jObject, DurableEntity durableEntity)
        {
            MovingEntitySerializer.Deserialize(ref jObject, durableEntity);

            SerializationUtils.SetFromObject(jObject, durableEntity, durableEntityType, serializeableProperties);
        }
示例#27
0
        private static void writeAny(TextWriter wri, object data, int level, JsonWritingOptions opt)
        {
            if (data == null)
            {
                wri.Write("null");                //do NOT LOCALIZE!
                return;
            }

            if (level > opt.MaxNestingLevel)
            {
                throw new JSONSerializationException(StringConsts.JSON_SERIALIZATION_MAX_NESTING_EXCEEDED_ERROR.Args(opt.MaxNestingLevel));
            }

            if (data is string)
            {
                EncodeString(wri, (string)data, opt);
                return;
            }

            if (data is bool)                               //the check is here for speed
            {
                wri.Write(((bool)data) ? "true" : "false"); //do NOT LOCALIZE!
                return;
            }

            if (data is int || data is long)                //the check is here for speed
            {
                wri.Write(((IConvertible)data).ToString(System.Globalization.CultureInfo.InvariantCulture));
                return;
            }

            if (data is double || data is float || data is decimal)                //the check is here for speed
            {
                wri.Write(((IConvertible)data).ToString(System.Globalization.CultureInfo.InvariantCulture));
                return;
            }

            if (data is DateTime)
            {
                EncodeDateTime(wri, (DateTime)data, opt);
                return;
            }

            if (data is TimeSpan)
            {
                var ts = (TimeSpan)data;
                wri.Write(ts.Ticks);
                return;
            }

            if (data is Guid)
            {
                var guid = (Guid)data;
                wri.Write('"');
                wri.Write(guid.ToString("D"));
                wri.Write('"');
                return;
            }

            if (data is IJsonWritable)                //these types know how to directly write themselves
            {
                ((IJsonWritable)data).WriteAsJson(wri, level, opt);
                return;
            }

            if (data is JsonDynamicObject)                //unwrap dynamic
            {
                writeAny(wri, ((JsonDynamicObject)data).Data, level, opt);
                return;
            }


            if (data is IDictionary)                //must be BEFORE IEnumerable
            {
                writeMap(wri, (IDictionary)data, level, opt);
                return;
            }

            if (data is IEnumerable)
            {
                writeArray(wri, (IEnumerable)data, level, opt);
                return;
            }

            var tdata = data.GetType();

            if (tdata.IsPrimitive || tdata.IsEnum)
            {
                string val;
                if (data is IConvertible)
                {
                    val = ((IConvertible)data).ToString(System.Globalization.CultureInfo.InvariantCulture);
                }
                else
                {
                    val = data.ToString();
                }

                EncodeString(wri, val, opt);
                return;
            }

            var fields = SerializationUtils.GetSerializableFields(tdata);

            var dict = fields.Select(
                f =>
            {
                var name = f.Name;
                var iop  = name.IndexOf('<');
                if (iop >= 0)            //handle anonymous type field name
                {
                    var icl = name.IndexOf('>');
                    if (icl > iop + 1)
                    {
                        name = name.Substring(iop + 1, icl - iop - 1);
                    }
                }

                return(new DictionaryEntry(name, f.GetValue(data)));
            });                //select


            writeMap(wri, dict, level, opt);
        }
示例#28
0
        }//setOneField

        //Returns non null on success; may return null for collection sub-element in which case null=null and does not indicate failure
        private static object cast(object v, Type toType, bool fromUI, DocReadOptions options, JsonHandlerAttribute fieldCustomHandler = null)
        {
            //See #264 - the collection inability to cast has no amorphous data so it MUST throw
            //used only for collections inner calls
            if (v == null)
            {
                return(null);
            }

            var customHandler = fieldCustomHandler ?? JsonHandlerAttribute.TryFind(toType);

            if (customHandler != null)
            {
                var castResult = customHandler.TypeCastOnRead(v, toType, fromUI, options);

                if (castResult.Outcome >= JsonHandlerAttribute.TypeCastOutcome.ChangedTargetType)
                {
                    toType = castResult.ToType;
                }

                if (castResult.Outcome == JsonHandlerAttribute.TypeCastOutcome.ChangedSourceValue)
                {
                    v = castResult.Value;
                }
                else if (castResult.Outcome == JsonHandlerAttribute.TypeCastOutcome.HandledCast)
                {
                    return(castResult.Value);
                }
            }

            //object goes as is
            if (toType == typeof(object))
            {
                return(v);
            }

            //IJSONDataObject
            if (toType == typeof(IJsonDataObject))
            {
                if (v is IJsonDataObject)
                {
                    return(v);     //goes as is
                }
                if (v is string s) //string containing embedded JSON
                {
                    var jo = s.JsonToDataObject();
                    return(jo);
                }
            }

            //IJSONDataMap
            if (toType == typeof(JsonDataMap))
            {
                if (v is JsonDataMap)
                {
                    return(v);     //goes as is
                }
                if (v is string s) //string containing embedded JSON
                {
                    var jo = s.JsonToDataObject() as JsonDataMap;
                    return(jo);
                }
            }

            //IJSONDataArray
            if (toType == typeof(JsonDataArray))
            {
                if (v is JsonDataArray)
                {
                    return(v);     //goes as is
                }
                if (v is string s) //string containing embedded JSON
                {
                    var jo = s.JsonToDataObject() as JsonDataArray;
                    return(jo);
                }
            }

            var nntp = toType;

            if (nntp.IsGenericType && nntp.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                nntp = toType.GetGenericArguments()[0];
            }

            //20191217 DKh
            if (nntp == typeof(DateTime))
            {
                if (options.LocalDates)
                {
                    var d = v.AsDateTime(System.Globalization.DateTimeStyles.AssumeLocal);
                    return(d);
                }
                else //UTC (the default)
                {
                    var d = v.AsDateTime(System.Globalization.DateTimeStyles.AssumeUniversal | System.Globalization.DateTimeStyles.AdjustToUniversal);
                    return(d);
                }
            }
            //20191217 DKh


            //Custom JSON Readable (including config)
            if (typeof(IJsonReadable).IsAssignableFrom(nntp) || typeof(IConfigSectionNode).IsAssignableFrom(nntp))
            {
                var toAllocate = nntp;

                //Configuration requires special handling because nodes do not exist as independent entities and there
                //is master/detail relationship between them
                if (toAllocate == typeof(Configuration) ||
                    toAllocate == typeof(ConfigSectionNode) ||
                    toAllocate == typeof(IConfigSectionNode))
                {
                    toAllocate = typeof(MemoryConfiguration);
                }

                if (toAllocate.IsAbstract)
                {
                    throw new JSONDeserializationException(StringConsts.JSON_DESERIALIZATION_ABSTRACT_TYPE_ERROR.Args(toAllocate.Name, nameof(JsonHandlerAttribute)));
                }

                var newval = SerializationUtils.MakeNewObjectInstance(toAllocate) as IJsonReadable;
                var got    = newval.ReadAsJson(v, fromUI, options);//this may re-allocate the result based of newval

                if (!got.match)
                {
                    return(null);
                }

                if (typeof(IConfigSectionNode).IsAssignableFrom(nntp))
                {
                    return((got.self as Configuration)?.Root);
                }

                return(got.self);
            }

            //byte[] direct assignment w/o copies
            if (nntp == typeof(byte[]))
            {
                if (v is byte[] passed)
                {
                    return(passed);
                }
                //20210717 - #514
                if (v is string str && str.IsNotNullOrWhiteSpace())
                {
                    var buff = str.TryFromWebSafeBase64();
                    if (buff != null)
                    {
                        return(buff);
                    }
                }
            }


            //field def = []
            if (toType.IsArray)
            {
                var fvseq = v as IEnumerable;
                if (fvseq == null)
                {
                    return(null);      //can not set non enumerable into array
                }
                var arr    = fvseq.Cast <object>().Select(e => cast(e, toType.GetElementType(), fromUI, options, fieldCustomHandler)).ToArray();
                var newval = Array.CreateInstance(toType.GetElementType(), arr.Length);
                for (var i = 0; i < newval.Length; i++)
                {
                    newval.SetValue(arr[i], i);
                }

                return(newval);
            }

            //field def = List<t>
            if (toType.IsGenericType && toType.GetGenericTypeDefinition() == typeof(List <>))
            {
                var fvseq = v as IEnumerable;
                if (fvseq == null)
                {
                    return(false);      //can not set non enumerable into List<t>
                }
                var arr    = fvseq.Cast <object>().Select(e => cast(e, toType.GetGenericArguments()[0], fromUI, options, fieldCustomHandler)).ToArray();
                var newval = SerializationUtils.MakeNewObjectInstance(toType) as IList;
                for (var i = 0; i < arr.Length; i++)
                {
                    newval.Add(arr[i]);
                }

                return(newval);
            }

            //last resort
            try
            {
                return(StringValueConversion.AsType(v.ToString(), toType, false));
            }
            catch
            {
                return(null);//the value could not be converted, and is going to go into amorphous bag if it is enabled
            }
        }
        /// <summary>
        /// Serializes the given build.
        /// </summary>
        /// <remarks>
        /// Folders have to be serialized right after being changed to update parent information in time.
        ///
        /// The folder builds are moved to has to be serialized before their old folder.
        /// </remarks>
        public void SerializeBuild(IBuild build)
        {
            string oldName;

            _names.TryGetValue(build, out oldName);
            var name = build.Name;

            _names[build] = name;

            var path    = PathFor(build, true);
            var oldPath = path.Remove(path.Length - SerializationUtils.EncodeFileName(name).Length)
                          + SerializationUtils.EncodeFileName(oldName);
            var poeBuild = build as PoEBuild;

            if (poeBuild != null)
            {
                SerializeBuild(path, poeBuild);
                if (oldName != null && oldName != name)
                {
                    File.Delete(oldPath + BuildFileExtension);
                }
            }
            else
            {
                if (oldName != null && oldName != name)
                {
                    Directory.Move(oldPath, path);
                }
                var folder = (BuildFolder)build;

                // Move builds that are in folder.Builds but have _parents set to another folder
                // from their old folder to this one.
                foreach (var b in folder.Builds)
                {
                    BuildFolder parent;
                    _parents.TryGetValue(b, out parent);
                    if (_markedForDeletion.ContainsKey(b) || (parent != null && parent != folder))
                    {
                        var    isBuild   = b is PoEBuild;
                        var    extension = isBuild ? BuildFileExtension : "";
                        string old;
                        if (_markedForDeletion.ContainsKey(b))
                        {
                            old = _markedForDeletion[b];
                            _markedForDeletion.Remove(b);
                        }
                        else
                        {
                            old = PathFor(b, true) + extension;
                        }

                        var newPath = Path.Combine(path,
                                                   SerializationUtils.EncodeFileName(_names[b]) + extension);
                        if (old == newPath)
                        {
                            continue;
                        }
                        if (isBuild)
                        {
                            File.Move(old, newPath);
                        }
                        else
                        {
                            Directory.Move(old, newPath);
                        }
                    }
                }

                // Mark builds that have folder as _parents entry but are no longer in folder.Builds.
                // These will either be moved when their new folder is saved or deleted when Delete is called.
                // Skip unsaved builds (those are not contained in _names)
                foreach (var parentsEntry in _parents)
                {
                    var b = parentsEntry.Key;
                    if (parentsEntry.Value != folder ||
                        !_names.ContainsKey(b) ||
                        folder.Builds.Contains(b))
                    {
                        continue;
                    }
                    var extension = b is PoEBuild ? BuildFileExtension : "";
                    _markedForDeletion[b] = PathFor(b, true) + extension;
                }

                SerializeFolder(path, folder);
            }

            // Just recreate these. Easier than handling all edge cases.
            InitParents();
        }
 public RunLengthIntegerWriter(PositionedOutputStream output, bool signed)
 {
     this.output = output;
     this.signed = signed;
     this.utils = new SerializationUtils();
 }
示例#31
0
        public T Read()
        {
            T      item         = null;
            string data         = null;
            bool   firstTimeout = true;

            _maxNumberOfPolls = MaxNumberOfPolls;
            while (_maxNumberOfPolls > 0)
            {
                // Read Message from the dataQueue
                BasicGetResult result = _dataQueue.Channel.BasicGet(_dataQueue.QueueName, true);
                if (result != null)
                {
                    try
                    {
                        // Deserialize message to business object
                        item = SerializationUtils.DeserializeObject <T>(result.Body.ToArray());
                        break;
                    }
                    catch (Exception ex)
                    {
                        _logger.Debug("Json Serialize failed. Reason: " + ex.StackTrace);
                        throw;
                    }
                }
                else
                {
                    // If there is no data to poll, wait for master step
                    _logger.Debug("Wait for {0} second for dataQueue, check for master part is completed or not", PollingTimeOut);
                    Thread.Sleep(TimeSpan.FromSeconds(PollingTimeOut));
                    _logger.Debug("Polling of number : {0}", _maxNumberOfPolls);
                    // For the first timeout , check master step is completed
                    if (!string.IsNullOrWhiteSpace(MasterName))
                    {
                        if (_masterqueue == null)
                        {
                            _masterqueue = new ControlQueue();
                            QueueConnectionProvider queueConnectionProvider = new QueueConnectionProvider();
                            queueConnectionProvider.UserName = _dataQueue.UserName;
                            queueConnectionProvider.PassWord = _dataQueue.PassWord;
                            queueConnectionProvider.HostName = _dataQueue.HostName;
                            _masterqueue.ConnectionProvider  = queueConnectionProvider;
                            _masterqueue.QueueName           = "master";
                            _masterqueue.CreateQueue();
                        }


                        string MasterCompletedMessage = "master" + dot + MasterName + dot + "COMPLETED";

                        if (firstTimeout)
                        {
                            _logger.Debug("First Timeout need to check the master process is completed. ");
                            firstTimeout = false;

                            if (_masterqueue.CheckMessageExistAndConsume(MasterCompletedMessage))
                            {
                                _logger.Debug("There is no more data to read for worker.");
                                break;
                            }
                            _logger.Debug("Need to wait for master to completed.");
                        }
                    }
                    _maxNumberOfPolls--;
                }
            }


            return(item);
        }