Esempio n. 1
0
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            object result;

            if (value is string)
            {
                string        serialization = value as string;
                Configuration configuration = new Configuration();
                if (!string.IsNullOrEmpty(serialization))
                {
                    using (StringReader stringReader = new StringReader((string)value))
                    {
                        using (XmlTextReader reader = new XmlTextReader(stringReader))
                        {
                            reader.Read();
                            SerializationServices.Deserialize(configuration.GetType(), reader, false);
                        }
                    }
                }
                result = configuration;
            }
            else
            {
                result = base.ConvertFrom(context, culture, value);
            }
            return(result);
        }
Esempio n. 2
0
        public override void SavePersonalizationState(PersonalizationState state)
        {
            if (this.IsEnabled)
            {
                DictionaryPersonalizationState dictionaryState = state as DictionaryPersonalizationState;
                if (null == dictionaryState)
                {
                    throw new ArgumentException("state is not a DictionaryPersonalizationState");
                }

                if (!dictionaryState.ReadOnly)
                {
                    StringBuilder personalizationBuilder = new StringBuilder();
                    using (StringWriter stringWriter = new StringWriter(personalizationBuilder))
                    {
                        using (XmlTextWriter writer = new XmlTextWriter(stringWriter))
                        {
                            writer.Formatting = Formatting.Indented;
                            writer.WriteStartDocument();
                            writer.WriteStartElement("personalization");
                            writer.WriteAttributeString("version", ReflectionServices.Version());
                            foreach (string id in dictionaryState.States.Keys)
                            {
                                if (dictionaryState.IsPartPresent(id))
                                {
                                    writer.WriteStartElement("part");
                                    writer.WriteAttributeString("id", id);
                                    foreach (string propertyName in dictionaryState.States[id].Keys)
                                    {
                                        writer.WriteStartElement("property");
                                        writer.WriteAttributeString("name", propertyName);
                                        writer.WriteStartAttribute("sensitive");
                                        writer.WriteValue(dictionaryState.States[id][propertyName].IsSensitive);
                                        writer.WriteEndAttribute();
                                        writer.WriteStartAttribute("scope");
                                        writer.WriteValue((int)dictionaryState.States[id][propertyName].Scope);
                                        writer.WriteEndAttribute();
                                        object value = dictionaryState.States[id][propertyName].Value;
                                        if (null != value)
                                        {
                                            writer.WriteStartElement("value");
                                            writer.WriteStartAttribute("type");
                                            writer.WriteValue(SerializationServices.ShortAssemblyQualifiedName(value.GetType().AssemblyQualifiedName));
                                            writer.WriteEndAttribute();
                                            SerializationServices.Serialize(value, writer);
                                            writer.WriteEndElement();
                                        }
                                        writer.WriteEndElement();
                                    }
                                    writer.WriteEndElement();
                                }
                            }
                            writer.WriteEndElement();
                            writer.WriteEndDocument();
                        }
                    }
                    PersonalizationStorage.Instance.Write(XmlPersonalizationProvider.StorageKey, personalizationBuilder.ToString());
                }
            }
        }
Esempio n. 3
0
        public T Get <T>(string requestUrl, Dictionary <string, string> headers = null)
            where T : class
        {
            T   f;
            var strResponse = string.Empty;
            HttpResponseMessage response = null;

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                }

                response    = client.GetAsync(requestUrl).Result;
                strResponse = response.Content.ReadAsStringAsync().Result;
                f           = SerializationServices.DeserializeJson <T>(strResponse);
            }

            return(f);
        }
Esempio n. 4
0
        /// <summary>
        /// Deserialization constructor
        /// </summary>
        protected BaseActionDefinition(IObjectGraphNode node, object contextData)
        {
            var actionTemplate = node["Action"].RebuildObject <Name>();
            var terms          = actionTemplate.GetTerms().ToArray();
            var name           = terms[0];

            if (!name.IsPrimitive)
            {
                throw new Exception("Invalid Action Template format");
            }
            for (int i = 1; i < terms.Length; i++)
            {
                if (terms[i].IsComposed)
                {
                    throw new Exception("Invalid Action Template format");
                }
            }

            var target = SerializationServices.GetFieldOrDefault(node, "Target", Name.NIL_SYMBOL);

            if (target.IsComposed)
            {
                throw new ArgumentException("Action Definition Target must be a symbol definition", nameof(target));
            }

            Id = Guid.NewGuid();
            m_actionTemplate     = actionTemplate;
            Target               = target;
            ActivationConditions = node["Conditions"].RebuildObject <ConditionSet>();
        }
 public static T ValidateAndGetAttachedRequest <T>(RpcGenericRequestInfo requestInfo, int majorVersion, int minorVersion) where T : class
 {
     if (requestInfo.CommandMajorVersion > majorVersion)
     {
         throw new ActiveManagerGenericRpcVersionNotSupportedException(requestInfo.ServerVersion, requestInfo.CommandId, requestInfo.CommandMajorVersion, requestInfo.CommandMinorVersion, ActiveManagerGenericRpcHelper.LocalServerVersion, majorVersion, minorVersion);
     }
     return(SerializationServices.Deserialize <T>(requestInfo.AttachedData));
 }
Esempio n. 6
0
        public void ClientRethrowIfFailed(string databaseName, string serverName, RpcErrorExceptionInfo errorInfo)
        {
            Exception ex   = null;
            string    text = HaRpcExceptionWrapperBase <TBaseException, TBaseTransientException> .SanitizeServerName(serverName);

            if (errorInfo.IsFailed())
            {
                if (errorInfo.ReconstitutedException != null)
                {
                    ex = this.ConstructClientExceptionFromServerException(text, errorInfo.ReconstitutedException);
                }
                else
                {
                    if (errorInfo.SerializedException != null && errorInfo.SerializedException.Length > 0)
                    {
                        try
                        {
                            errorInfo.ReconstitutedException = SerializationServices.Deserialize <Exception>(errorInfo.SerializedException);
                            ex = this.ConstructClientExceptionFromServerException(text, errorInfo.ReconstitutedException);
                            goto IL_109;
                        }
                        catch (SerializationException innerException)
                        {
                            ex = this.GetGenericOperationFailedException(errorInfo.ErrorMessage, innerException);
                            ((TBaseException)((object)ex)).OriginatingServer = text;
                            goto IL_109;
                        }
                        catch (TargetInvocationException innerException2)
                        {
                            ex = this.GetGenericOperationFailedException(errorInfo.ErrorMessage, innerException2);
                            ((TBaseException)((object)ex)).OriginatingServer = text;
                            goto IL_109;
                        }
                    }
                    if (!string.IsNullOrEmpty(errorInfo.ErrorMessage))
                    {
                        ex = this.GetGenericOperationFailedException(errorInfo.ErrorMessage);
                        ((TBaseException)((object)ex)).OriginatingServer = text;
                    }
                    else
                    {
                        ex = this.GetGenericOperationFailedWithEcException(errorInfo.ErrorCode);
                        ((TBaseException)((object)ex)).OriginatingServer = text;
                    }
                }
IL_109:
                IHaRpcServerBaseException ex2 = ex as IHaRpcServerBaseException;
                if (ex2 != null && string.IsNullOrEmpty(ex2.DatabaseName) && !string.IsNullOrEmpty(databaseName))
                {
                    ((IHaRpcServerBaseExceptionInternal)ex).DatabaseName = databaseName;
                }
            }
            if (ex != null)
            {
                throw ex;
            }
        }
Esempio n. 7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var _httpHelper = new HttpHelper();

            var url         = $"{appConfig.apiBaseUrl}/api/client?companyid=1";
            var strResponse = _httpHelper.GetString(url);
            var oClientList = SerializationServices.DeserializeJson <List <ClientVM> >(strResponse);

            gdvClientList.DataSource = oClientList;
            gdvClientList.DataBind();
        }
        public static T RunRpcAndGetReply <T>(RpcGenericRequestInfo requestInfo, string serverName, int timeoutInMSec) where T : class
        {
            RpcGenericReplyInfo replyInfo = null;

            AmRpcClientHelper.RunRpcOperation(AmRpcOperationHint.GenericRpc, serverName, new int?(timeoutInMSec), delegate(AmRpcClient rpcClient, string rpcServerName)
            {
                ExTraceGlobals.ActiveMonitoringRpcTracer.TraceDebug <string>(0L, "GenericRequest(): Now making GenericRequest RPC to server {0}.", serverName);
                return(rpcClient.GenericRequest(requestInfo, out replyInfo));
            });
            return(SerializationServices.Deserialize <T>(replyInfo.AttachedData));
        }
Esempio n. 9
0
        protected void Page_Load(object sender, EventArgs e)
        {
            currentUser = (StaffVM)Session["CurrentUser"];
            var _httpHelper = new HttpHelper();

            var url         = $"{appConfig.apiBaseUrl}/api/case?companyid={currentUser.CompanyId}";
            var strResponse = _httpHelper.GetString(url);
            var oCaseList   = SerializationServices.DeserializeJson <List <CaseVM> >(strResponse);

            gdvCasesList.DataSource = oCaseList;
            gdvCasesList.DataBind();
        }
Esempio n. 10
0
        public void SetObjectData(ISerializationData dataHolder, ISerializationContext context)
        {
            object o = this;

            SerializationServices.ExtractFromFieldData(dataHolder, ref o, true);
            var set = dataHolder.GetValue <Condition[]>("Set");

            if (set != null)
            {
                m_conditions = new List <Condition>(set);
            }
        }
Esempio n. 11
0
 public IHttpActionResult GetAllbook()
 {
     try
     {
         var response = _BookService.GetAllBooks();
         var log      = string.Format("Response: {0}", SerializationServices.SerializeJson(response));
         LogHelper.Info(log);
         return(Ok(response));
     }
     catch (Exception ex)
     {
         LogHelper.Debug(ex);
         return(InternalServerError(ex));
     }
 }
Esempio n. 12
0
 protected void Dump()
 {
     if (!_isDisabled && this.Records.Count > 0)
     {
         StringBuilder dump = new StringBuilder();
         using (XmlWriter writer = XmlWriter.Create(dump, new XmlWriterSettings
         {
             Indent = true
         }))
         {
             SerializationServices.Serialize(this, writer);
         }
         string timestamp = DateTime.Now.ToString("yyyyMMddHHmmssff");
         this.Entries[timestamp] = dump.ToString();
     }
 }
Esempio n. 13
0
 public override void WriteXml(XmlWriter writer)
 {
     if (null == writer)
     {
         throw new ArgumentNullException("writer");
     }
     writer.WriteStartElement("attribute");
     base.WriteXml(writer);
     if (null == this._value)
     {
         this._value = string.Empty;
     }
     writer.WriteAttributeString("value", this._value.ToString());
     writer.WriteAttributeString("type", SerializationServices.ShortAssemblyQualifiedName(this._value.GetType().AssemblyQualifiedName));
     writer.WriteEndElement();
 }
Esempio n. 14
0
        public IHttpActionResult Returnbook(List <BookedHistory> request)
        {
            MyContext db = new MyContext();

            if (ModelState.IsValid)
            {
                var log = string.Format("Request: {0}, Response: {1}", SerializationServices.SerializeJson(request), BadRequest());
                LogHelper.Info(log);
                return(BadRequest());
            }

            try
            {
                //add unselected book to bookedhistory and add the quantity of unselected book
                foreach (var req in request)
                {
                    _BookedhistoryService.UpdateBookedHistory(req);
                    var qty = db.Books.Where(x => x.ID == req.BookID).ToList().FirstOrDefault();
                    //var cuntr = db.BookedHistories.Where(x => x.ID == req.BookID && x.Status == false).Count();

                    int qtynum  = qty.Quantity;
                    var updBook = qtynum + 1;

                    Book nm = new Book();
                    {
                        nm.Author_Name    = qty.Author_Name;
                        nm.CategoryID     = qty.CategoryID;
                        nm.ID             = qty.ID;
                        nm.ISBN           = qty.ISBN;
                        nm.Price          = qty.Price;
                        nm.Quantity       = updBook;
                        nm.Publisher_Date = qty.Publisher_Date;
                        nm.Title          = qty.Title;
                    }


                    _BookService.UpdateBook(nm);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Debug(ex);
                return(InternalServerError(ex));
            }

            return(Ok("successfully Returned"));
        }
            public override object ExtractObject(Type requestedType)
            {
                object buildObject;

                if (IsReferedMultipleTimes)
                {
                    if (ParentGraph.TryGetObjectForRefId(RefId, out buildObject))
                    {
                        return(buildObject);
                    }
                }

                Type typeToBuild = requestedType;

                if (ObjectType != null)
                {
                    Type myType = ObjectType.ClassType;
                    if (requestedType != null && !requestedType.IsAssignableFrom(myType))
                    {
                        throw new Exception("Unable to build object. Requested on type but data has another type");                             //TODO better exception
                    }
                    typeToBuild = myType;
                }

                if (typeToBuild == null)
                {
                    throw new Exception("Missing type information. Unable to build object");                            //TODO better exception
                }
                if (typeToBuild.IsAbstract || typeToBuild.IsInterface)
                {
                    throw new Exception("Cannot create a direct instance of a abstract or interface");                          //TODO better exception
                }
                if (typeToBuild.IsArray || typeToBuild.IsPrimitiveData())
                {
                    //Handle Boxed Value Types
                    IGraphNode boxedValue = m_fields[DEFAULT_BOXED_VALUE_FIELD_NAME];
                    return(boxedValue.RebuildObject(typeToBuild));
                }

                buildObject = SerializationServices.GetUninitializedObject(typeToBuild);
                ParentGraph.LinkObjectToNode(this, buildObject);

                var surrogate = SerializationServices.GetDefaultSerializationSurrogate(typeToBuild);

                surrogate.SetObjectData(ref buildObject, this);
                return(buildObject);
            }
Esempio n. 16
0
 public IHttpActionResult GetAllbooked(string isbn, string title, bool status)
 {
     try
     {
         //var log = string.Format("Request: {0}", SerializationServices.SerializeJson(request));
         //LogHelper.Info(log);
         var response = _BookedhistoryService.GetAllBookHistory(isbn, title, status);
         var log      = string.Format("Response: {0}", SerializationServices.SerializeJson(response));
         LogHelper.Info(log);
         return(Ok(response));
     }
     catch (Exception ex)
     {
         LogHelper.Debug(ex);
         return(InternalServerError(ex));
     }
 }
Esempio n. 17
0
        // Token: 0x06001142 RID: 4418 RVA: 0x000466F8 File Offset: 0x000448F8
        public EseDatabasePatchState ReadHeader()
        {
            this.AssertReadOperationValid();
            EseDatabasePatchState eseDatabasePatchState = null;

            this.SeekToStart();
            byte[] array = new byte[32768L];
            this.ReadFromFile(array, array.Length);
            int num  = 0;
            int num2 = BitConverter.ToInt32(array, num);

            num += 4;
            if (num2 > array.Length - 4 || num2 <= 0)
            {
                EseDatabasePatchFileIO.Tracer.TraceError <int, int>((long)this.GetHashCode(), "ReadHeader(): Serialized header state in bytes ({0}) is invalid. Must be >=0 and < pre-allocated fixed byte size of {1} bytes.", num2, array.Length);
                throw new PagePatchInvalidFileException(this.m_fileStream.Name);
            }
            byte[] array2 = new byte[num2];
            Array.Copy(array, num, array2, 0, num2);
            Exception ex = null;

            try
            {
                eseDatabasePatchState = SerializationServices.Deserialize <EseDatabasePatchState>(array2);
            }
            catch (SerializationException ex2)
            {
                ex = ex2;
            }
            catch (TargetInvocationException ex3)
            {
                ex = ex3;
            }
            catch (DecoderFallbackException ex4)
            {
                ex = ex4;
            }
            if (ex != null)
            {
                EseDatabasePatchFileIO.Tracer.TraceError <Exception>((long)this.GetHashCode(), "ReadHeader deserialize failed: {0}", ex);
                throw new PagePatchInvalidFileException(this.m_fileStream.Name, ex);
            }
            this.m_header = eseDatabasePatchState;
            return(eseDatabasePatchState);
        }
Esempio n. 18
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CurrentUser = (StaffVM)Session["CurrentUser"];
            }
            ;

            var url     = $"{appConfig.apiBaseUrl}/api/staff";
            var headers = new Dictionary <string, string>();

            headers.Add("companyId", CurrentUser.CompanyId.ToString());

            var strResponse = _httpHelper.GetString(url);
            var oStaffList  = SerializationServices.DeserializeJson <List <StaffVM> >(strResponse);

            gdvClientList.DataSource = oStaffList;
            gdvClientList.DataBind();
        }
Esempio n. 19
0
        private StaffVM AuthenticateUser(string emailaddress, string password)
        {
            StaffVM oStaffObj   = null;
            var     _httpHelper = new HttpHelper();
            string  url         = $"{appConfig.apiBaseUrl}/api/staff/authenticate";

            var headers = new Dictionary <string, string>();

            headers.Add("emailaddress", emailaddress);
            headers.Add("password", password);

            var httpResponse = _httpHelper.Get(url, headers);

            if (httpResponse.IsSuccessStatusCode)
            {
                var strResponse = httpResponse.Content.ReadAsStringAsync().Result;
                oStaffObj = SerializationServices.DeserializeJson <StaffVM>(strResponse);
            }
            return(oStaffObj);
        }
Esempio n. 20
0
        public void Open()
        {
            if (null == this._agent)
            {
                throw new InvalidOperationException("Agent not set");
            }

            // this._data = (HttpContext.Current.Cache[User.CurrentUser.Name] as Dictionary<string, object>);

            XDocument doc = null;

            if (_agent.HasKey(STORAGE_KEY))
            {
                doc = XDocument.Parse(_agent.Read(STORAGE_KEY));
            }

            if (null == this._data)
            {
                this._data = new Dictionary <string, object>();
                if (null != doc)
                {
                    foreach (string normalizedkey in this._agent.List())
                    {
                        XElement keyelement = doc.Element("keys")
                                              .Elements()
                                              .SingleOrDefault(x => x.Attribute("normalized").Value == normalizedkey);
                        if (null != keyelement)
                        {
                            string key           = keyelement.Attribute("full").Value;
                            string persisteddata = _agent.Read(normalizedkey);
                            if (!String.IsNullOrEmpty(persisteddata))
                            {
                                this._data.Add(key, SerializationServices.BinaryDeserialize(persisteddata));
                            }
                        }
                    }
                }
            }
        }
Esempio n. 21
0
        private static void TrySerializeException(Exception ex, RpcErrorExceptionInfo errorInfo)
        {
            Exception ex2 = null;

            try
            {
                errorInfo.SerializedException = SerializationServices.Serialize(ex);
            }
            catch (SerializationException ex3)
            {
                ex2 = ex3;
            }
            catch (TargetInvocationException ex4)
            {
                ex2 = ex4;
            }
            if (ex2 != null)
            {
                ExTraceGlobals.ReplayServiceRpcTracer.TraceError <Type, Exception>(0L, "ConvertExceptionToErrorExceptionInfo: Failed to serialize Exception of type '{0}'. Serialization Exception: {1}", ex.GetType(), ex2);
                errorInfo.ErrorMessage = ex.ToString();
            }
        }
Esempio n. 22
0
        public void Close()
        {
            if (null == this._agent)
            {
                throw new InvalidOperationException("Agent not set");
            }

            if (null != this._data)
            {
                if (this._data.Count > 0)
                {
                    XDocument doc = new XDocument(new XDeclaration("1.0", null, null),
                                                  new XElement("keys"));
                    // HttpContext.Current.Cache.Insert(User.CurrentUser.Name, this._data);
                    foreach (string key in this._data.Keys)
                    {
                        string sanitizedkey = key;
                        if (null != this._data[key])
                        {
                            sanitizedkey = _agent.Sanitize(key);
                            _agent.Write(sanitizedkey, SerializationServices.BinarySerialize(_data[key]));
                        }
                        doc.Element("keys").Add(new XElement("key",
                                                             new XAttribute("full", key),
                                                             new XAttribute("normalized", sanitizedkey)
                                                             ));
                    }
                    if (_agent.HasKey(STORAGE_KEY))
                    {
                        _agent.Erase(STORAGE_KEY);
                    }
                    _agent.Write(STORAGE_KEY, doc.ToString());
                    _data = null;
                }
            }

            _agent.CleanUp();
        }
Esempio n. 23
0
 public IHttpActionResult Addbook([FromBody] Book request)
 {
     if (ModelState.IsValid)
     {
         var log = string.Format("Request: {0}, Response: {1}", SerializationServices.SerializeJson(request), BadRequest());
         LogHelper.Info(log);
         return(BadRequest());
     }
     try
     {
         var log = string.Format("Request: {0}", SerializationServices.SerializeJson(request));
         LogHelper.Info(log);
         var response = _BookService.SaveBook(request);
         log = string.Format("Response: {0}", SerializationServices.SerializeJson(response));
         LogHelper.Info(log);
         return(Ok(response));
     }
     catch (Exception ex)
     {
         LogHelper.Debug(ex);
         return(InternalServerError(ex));
     }
 }
Esempio n. 24
0
        // Token: 0x06001143 RID: 4419 RVA: 0x00046808 File Offset: 0x00044A08
        public void WriteHeader()
        {
            this.AssertWriteOperationValid();
            if (this.m_header.NumPagesToPatch > 3276800)
            {
                throw new PagePatchTooManyPagesToPatchException(this.m_header.NumPagesToPatch, 3276800);
            }
            byte[] array  = new byte[32768L];
            byte[] array2 = SerializationServices.Serialize(this.m_header);
            DiagCore.RetailAssert(array2.Length <= array.Length - 4, "Serialized header state in bytes ({0}) is greater than pre-allocated fixed byte size of {1} bytes.", new object[]
            {
                array2.Length,
                array.Length
            });
            int num = 0;

            Array.Copy(BitConverter.GetBytes(array2.Length), 0, array, num, 4);
            num += 4;
            Array.Copy(array2, 0, array, num, array2.Length);
            this.SeekToStart();
            this.m_fileStream.Write(array, 0, array.Length);
            this.m_fileStream.Flush(true);
        }
Esempio n. 25
0
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            Configuration configuration = value as Configuration;
            object        result;

            if (null != configuration)
            {
                if (destinationType == typeof(string))
                {
                    StringBuilder serializationBuilder = new StringBuilder();
                    using (StringWriter stringWriter = new StringWriter(serializationBuilder))
                    {
                        using (XmlTextWriter writer = new XmlTextWriter(stringWriter))
                        {
                            SerializationServices.Serialize(configuration, writer);
                        }
                        result = serializationBuilder.ToString();
                        return(result);
                    }
                }
            }
            result = base.ConvertTo(context, culture, value, destinationType);
            return(result);
        }
Esempio n. 26
0
 public void GetObjectData(ISerializationData dataHolder, ISerializationContext context)
 {
     SerializationServices.PopulateWithFieldData(dataHolder, this, true, false);
     dataHolder.SetValue("Set", (m_conditions ?? Enumerable.Empty <Condition>()).ToArray());
 }
Esempio n. 27
0
        public IGraphNode BuildNode(object obj, Type fieldType)
        {
            if (obj == null)
            {
                return(null);
            }

            IGraphNode result;
            Type       objType = obj.GetType();

            if (typeof(Type).IsAssignableFrom(objType))
            {
                return(GetTypeEntry((Type)obj));
            }

            var formatter = GetFormatter(objType);

            if (formatter != null)
            {
                var node = formatter.ObjectToGraphNode(obj, this);
                var fieldTypeFormatter = fieldType != null?GetFormatter(fieldType) : null;

                if (formatter != fieldTypeFormatter)
                {
                    //Value needs to be boxed
                    ObjectGraphNode box = node as ObjectGraphNode;
                    if (box == null)
                    {
                        box = (ObjectGraphNode)CreateObjectData();
                        box[DEFAULT_BOXED_VALUE_FIELD_NAME] = node;
                    }

                    if (box.ObjectType == null)
                    {
                        box.ObjectType = GetTypeEntry(objType);
                    }
                    return(box);
                }
                return(node);
            }

            if (objType.IsArray || objType.IsPrimitiveData())
            {
                //Boxable Values (arrays, bools, numbers, strings)
                IGraphNode valueNode;
                if (objType.IsArray)
                {
                    Type elemType            = objType.GetElementType();
                    ISequenceGraphNode array = BuildSequenceNode();
                    IEnumerator        it    = ((IEnumerable)obj).GetEnumerator();
                    while (it.MoveNext())
                    {
                        IGraphNode elem = BuildNode(it.Current, elemType);
                        array.Add(elem);
                    }
                    valueNode = array;
                }
                else
                {
                    //Primitive data type
                    if (objType == typeof(string))
                    {
                        valueNode = BuildStringNode(obj as string);
                    }
                    else
                    {
                        if (objType.IsEnum)
                        {
                            obj = Convert.ChangeType(obj, ((Enum)obj).GetTypeCode());
                        }

                        valueNode = BuildPrimitiveNode(obj as ValueType);
                    }
                }

                if (objType != fieldType)
                {
                    //Value needs to be boxed
                    var boxNode = CreateObjectData();
                    boxNode.ObjectType = GetTypeEntry(objType);
                    boxNode[DEFAULT_BOXED_VALUE_FIELD_NAME] = valueNode;
                    valueNode = boxNode;
                }

                result = valueNode;
            }
            else
            {
                //Non-Boxable Values (structs and objects)
                IObjectGraphNode objReturnData;
                bool             extractData = true;
                if (objType.IsValueType)
                {
                    //Structure
                    objReturnData = CreateObjectData();
                }
                else
                {
                    //Classes
                    if (!GetObjectNode(obj, out objReturnData))
                    {
                        extractData = false;
                    }
                }

                if (extractData)
                {
                    var surrogate = SerializationServices.GetDefaultSerializationSurrogate(objType);
                    surrogate.GetObjectData(obj, objReturnData);
                }

                if ((objReturnData.ObjectType == null) && (objType != fieldType))
                {
                    objReturnData.ObjectType = GetTypeEntry(objType);
                }

                result = objReturnData;
            }
            return(result);
        }
Esempio n. 28
0
 private IGraphFormatter GetFormatter(Type type)
 {
     return(m_formatterSelector.GetFormatter(type) ?? SerializationServices.GetDefaultSerializationFormatter(type));
 }
 public static RpcGenericRequestInfo PrepareClientRequest(object attachedRequest, int commandId, int majorVersion, int minorVersion)
 {
     byte[] attachedData = SerializationServices.Serialize(attachedRequest);
     return(new RpcGenericRequestInfo(ActiveManagerGenericRpcHelper.LocalServerVersion, commandId, majorVersion, minorVersion, attachedData));
 }
 public static RpcGenericReplyInfo PrepareServerReply(RpcGenericRequestInfo request, object attachedReply, int majorVersion, int minorVersion)
 {
     byte[] attachedData = SerializationServices.Serialize(attachedReply);
     return(new RpcGenericReplyInfo(ActiveManagerGenericRpcHelper.LocalServerVersion, request.CommandId, majorVersion, minorVersion, attachedData));
 }