Exemplo n.º 1
0
        public ActionResult EditNode(EditNodePageModel model)
        {
            if (model is null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (model.Page is null)
            {
                throw new NullReferenceException(NULL_PAGE_MESSAGE);
            }

            using (IWriteContext writeContext = this.PageRepository.WriteContext())
            {
                Page thisPage = this.PageRepository.Find(model.Page._Id);

                thisPage.Content = model.Page.Content;

                thisPage.Type = model.Page.Type;

                thisPage.Url = model.Page.Url;

                thisPage.Cascade = model.Page.Cascade;

                thisPage.Layout = model.Page.Layout;

                thisPage.Parameters = model.Page.Parameters;

                this.PageRepository.AddOrUpdate(thisPage);
            }

            return(this.Redirect("/Admin/Page/Index"));
        }
Exemplo n.º 2
0
        public ActionResult AddPage(EditNodePageModel model)
        {
            if (model is null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (model.BaseUrl is null)
            {
                throw new NullReferenceException(NULL_BASE_URL_MESSAGE);
            }

            if (model.Page?.Url is null)
            {
                throw new NullReferenceException(NULL_PAGE_URL_MESSAGE);
            }

            using (IWriteContext writeContext = this.PageRepository.WriteContext())
            {
                model.Page.Url = Path.Combine(model.BaseUrl, model.Page.Url ?? "").Replace("\\", "/", StringComparison.OrdinalIgnoreCase);

                this.PageRepository.AddOrUpdate(model.Page);
            }

            return(this.Redirect("/Admin/Page/Index"));
        }
Exemplo n.º 3
0
        public ActionResult AddFolder(EditNodePageModel model)
        {
            if (model is null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (model.BaseUrl is null)
            {
                throw new NullReferenceException(NULL_BASE_URL_MESSAGE);
            }

            if (model.Page?.Url is null)
            {
                throw new NullReferenceException(NULL_PAGE_URL_MESSAGE);
            }

            using (IWriteContext writeContext = this.PageRepository.WriteContext())
            {
                Page thisPage = new Page
                {
                    Url = Path.Combine(model.BaseUrl, model.Page.Url).Replace('\\', '/')
                };

                this.PageRepository.AddOrUpdate(thisPage);
            }

            return(this.Redirect("/Admin/Page/Index"));
        }
        /// <summary>
        /// Opens a new writecontext, attempts to add an error, and closes the write context.
        /// If the context was already open, it may not persist until it closes.
        /// Can be called on a null repository. This will be treated as an error and caught/rethrown as
        /// instructed by the "rethrow" parameter
        /// </summary>
        /// <param name="errorRepository">The Error repository to attempt to use as a source</param>
        /// <param name="ex">The exception</param>
        /// <param name="rethrow">If theres an error writing the error, should the error be rethrown?</param>
        /// <param name="url">If relevant, any URL associated with the error</param>
        /// <param name="UserId">If relevant, the ID of the user that generated the error</param>
        /// <returns>False if an error occurs, regardless of whether or not it was rethrown</returns>
        public static bool TryAdd(this IRepository <AuditableError> errorRepository, Exception ex, bool rethrow = false, string url = null, Guid?UserId = null)
        {
            try
            {
                using (IWriteContext context = errorRepository?.WriteContext())
                {
                    AuditableError thisError = new AuditableError(ex)
                    {
                        RequestUrl = url,
                        UserId     = UserId ?? Guid.Empty
                    };

                    errorRepository.Add(thisError);
                }

                return(true);
            }
            catch (Exception)
            {
                if (rethrow)
                {
                    throw;
                }

                return(false);
            }
        }
Exemplo n.º 5
0
        public ActionResult Register(RegistrationPageModel model)
        {
            if (model is null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            System.Threading.Thread.Sleep(1000);

            if (!this.ModelState.IsValid)
            {
                return(this.View(model));
            }

            if (this.UserRepository.GetByLogin(model.Login) != null)
            {
                this.ModelState.AddModelError(string.Empty, "Username is already taken");
                return(this.View(model));
            }

            if (!this.ConfigurationService.GetBool(ConfigurationNames.ALLOW_DUPLICATE_EMAIL) && this.UserRepository.GetByEmail(model.Email) != null)
            {
                this.ModelState.AddModelError(string.Empty, "Email is already taken");
                return(this.View(model));
            }

            bool EmailValidationRequired = this.ConfigurationService.GetBool(ConfigurationNames.REQUIRE_EMAIL_VALIDATION);
            User newUser;

            using (IWriteContext context = this.UserRepository.WriteContext())
            {
                newUser = new User()
                {
                    Login    = model.Login,
                    Password = model.Password,
                    Email    = model.Email
                };

                this.UserRepository.AddOrUpdate(newUser);

                if (EmailValidationRequired)
                {
                    this.EmailValidationRepository.GenerateToken(newUser.Guid, this.GetEmailValidationLink());
                }
            }

            if (!EmailValidationRequired)
            {
                this.ViewBag.Messages = new List <string>()
                {
                    "Registration successful. You can now log in with your new account"
                };

                return(this.View("Login"));
            }
            else
            {
                return(this.RedirectToAction(nameof(EmailValidationRequired), new { Id = newUser.Guid.ToString(), area = "" }));
            }
        }
Exemplo n.º 6
0
        public static bool SetValue(this IRepository <CmsConfiguration> repository, string Name, string Value)
        {
            if (repository is null)
            {
                return(false);
            }
            else
            {
                using (IWriteContext context = repository.WriteContext())
                {
                    CmsConfiguration existing = repository.FirstOrDefault(c => c.Name == Name);

                    if (existing is null)
                    {
                        repository.Add(new CmsConfiguration()
                        {
                            Name  = Name,
                            Value = Value
                        });
                    }
                    else if (existing.Value != Value)
                    {
                        existing.Value = Value;
                        repository.Update(existing);
                    }
                }

                return(true);
            }
        }
        /// <summary>
        /// Updates all entities with guids in the JObject.Guids property using the provided Json
        /// </summary>
        /// <param name="json">Json string containing the new property values to use when updating the objects</param>
        /// <returns>A success state representation, or a redirect</returns>
        public virtual ActionResult BatchSave(string json) //Smashing the guids into the object is bad. Fix this
        {
            Type?commonType = null;

            try
            {
                using IWriteContext context = this.ServiceProvider.GetService <IPersistenceContext>().WriteContext();
                List <object> Entities = this.GetEntitiesByGuids(JsonConvert.DeserializeObject <BatchEditModelPageModel>(json).Guids.Select(g => Guid.Parse(g)).ToList());

                commonType = Entities.GetCommonType();

                JObject obj  = JObject.Parse(json);
                JToken? jtok = obj[nameof(BatchEditModelPageModel.Template)];

                if (jtok is null)
                {
                    throw new Exception("No template object found on posted json");
                }

                foreach (Entity entity in Entities)
                {
                    this.SaveJsonObject(jtok.ToString(), entity, new DynamicSaveCache());
                }
            }
            catch (Exception ex)
            {
                this.ErrorRepository.TryAdd(ex);
                return(this.Json(new { Response = new { Error = ex.Message } }));
            }

            return(this.Json(new { Response = new { Redirect = $"/Admin/List/{commonType?.FullName}" } }));
        }
 public virtual void Write(IWriteContext context, object obj)
 {
     _writeCalls++;
     TranslatorToTypehandlerMigrationTestCase.Item item = (TranslatorToTypehandlerMigrationTestCase.Item
                                                           )obj;
     context.WriteInt(item._id + 42);
 }
Exemplo n.º 9
0
        public void Write(IWriteContext context, object obj)
        {
            var classId = ClassMetadataIdFor(context, obj);

            context.WriteInt(classId);
            context.WriteLong(Convert.ToInt64(obj));
        }
Exemplo n.º 10
0
        public MarkupExtension Convert(IWriteContext context, object value)
        {
            var parameter = (RotatedSliderEdgeLabelModel.RotatedSliderParameter)InnerParameter;
            var side      = labelModel.Distance == ((RotatedSliderEdgeLabelModel)parameter.Model).Distance
        ? SliderParameterLocation.Right
        : SliderParameterLocation.Left;

            if (parameter.Segment < 0)
            {
                return(new RotatedSideSliderLabelModelParameterExtension
                {
                    Location = SliderParameterLocation.FromTarget | side,
                    SegmentIndex = -1 - parameter.Segment,
                    SegmentRatio = 1 - parameter.Ratio,
                    Model = Model
                });
            }
            else
            {
                return(new RotatedSideSliderLabelModelParameterExtension
                {
                    Location = SliderParameterLocation.FromSource | side,
                    SegmentIndex = parameter.Segment,
                    SegmentRatio = parameter.Ratio,
                    Model = Model
                });
            }
        }
 public void Write(IWriteContext context, object obj)
 {
     CustomTypeHandlerTestCase.ItemGrandChild item = (CustomTypeHandlerTestCase.ItemGrandChild
                                                      )obj;
     context.WriteInt(item.age);
     context.WriteInt(100);
 }
Exemplo n.º 12
0
 protected virtual void WriteElements(IWriteContext context, object obj, ArrayInfo
                                      info)
 {
     if (HandleAsByteArray(obj))
     {
         context.WriteBytes((byte[])obj);
     }
     else
     {
         // byte[] performance optimisation
         if (HasNullBitmap(info))
         {
             BitMap4 nullItems = NullItemsMap(ArrayReflector(Container(context)), obj);
             WriteNullBitmap(context, nullItems);
             for (int i = 0; i < info.ElementCount(); i++)
             {
                 if (!nullItems.IsTrue(i))
                 {
                     context.WriteObject(_handler, ArrayReflector(Container(context)).Get(obj, i));
                 }
             }
         }
         else
         {
             for (int i = 0; i < info.ElementCount(); i++)
             {
                 context.WriteObject(_handler, ArrayReflector(Container(context)).Get(obj, i));
             }
         }
     }
 }
 public Task ExistingEntityDeleted(IEventStreamIdentity deletedEntity,
                                   string commentary     = "",
                                   IWriteContext context = null)
 {
     // do nothing
     return(Task.CompletedTask);
 }
Exemplo n.º 14
0
        public EventStream(EventStreamAttribute attribute,
                           string connectionStringName = "",
                           IWriteContext context       = null)
        {
            _domainName           = attribute.DomainName;
            _aggregateTypeName    = attribute.AggregateTypeName;
            _aggregateInstanceKey = attribute.InstanceKey;

            if (string.IsNullOrWhiteSpace(connectionStringName))
            {
                _connectionStringName = ConnectionStringNameAttribute.DefaultConnectionStringName(attribute);
            }
            else
            {
                _connectionStringName = connectionStringName;
            }

            // wire up the event stream writer
            // TODO : Cater for different backing technologies... currently just AppendBlob
            _writer = new CQRSAzure.EventSourcing.Azure.Blob.Untyped.BlobEventStreamWriterUntyped(attribute,
                                                                                                  connectionStringName = _connectionStringName);

            if (null != context)
            {
                _context = context;
                if (null != _writer)
                {
                    _writer.SetContext(_context);
                }
            }
        }
        /// <summary>
        /// Create a new query instance
        /// </summary>
        /// <param name="domainName">
        /// The domain in which the query is to run
        /// </param>
        /// <param name="queryName">
        /// The name of the type of query to be run
        /// </param>
        /// <param name="queryUniqueIdentifier">
        /// The unique identifier of the query instance
        /// </param>
        /// <param name="context">
        /// Additional context information to use when writing events for the query
        /// </param>
        public Query(string domainName,
                     string queryName,
                     string queryUniqueIdentifier,
                     WriteContext context = null)
        {
            _domainName       = domainName;
            _queryName        = queryName;
            _uniqueIdentifier = queryUniqueIdentifier;
            // Make a query
            if (context == null)
            {
                // Use a default write context for this query
                _queryContext = new WriteContext()
                {
                    Source = _queryName,
                    CausationIdentifier = _uniqueIdentifier,
                    Commentary          = _queryName
                };
            }
            else
            {
                _queryContext = context;
            }

            StartListener();
        }
        public static async Task RequestProjection(Guid queryGuid,
                                                   string queryName,
                                                   string projectionName,
                                                   string domainName,
                                                   string aggregateTypeName,
                                                   string aggregateInstanceKey,
                                                   Nullable <DateTime> asOfDate,
                                                   IWriteContext writeContext = null)
        {
            EventStream qryEvents = new EventStream(Constants.Domain_Query,
                                                    queryName,
                                                    queryGuid.ToString());

            if (null != qryEvents)
            {
                if (null != writeContext)
                {
                    qryEvents.SetContext(writeContext);
                }
                await qryEvents.AppendEvent(new TheLongRun.Common.Events.Query.ProjectionRequested(domainName,
                                                                                                   aggregateTypeName,
                                                                                                   WebUtility.UrlDecode(aggregateInstanceKey),
                                                                                                   WebUtility.UrlDecode(projectionName),
                                                                                                   asOfDate));
            }
        }
 public virtual void Write(IWriteContext context, object obj)
 {
     _writeCalls++;
     FieldsToTypeHandlerMigrationTestCase.Item item = (FieldsToTypeHandlerMigrationTestCase.Item
                                                       )obj;
     context.WriteInt(item._id + 42);
 }
        public ActionResult CreateFolder(string FilePath, string FolderName)
        {
            DatabaseFile thisFile;

            using (IWriteContext context = this.DatabaseFileRepository.WriteContext())
            {
                thisFile = this.DatabaseFileRepository.GetByFullName(Path.Combine(FilePath, FolderName));

                if (thisFile != null && !thisFile.IsDeleted)
                {
                    throw new UnauthorizedAccessException();
                }
                else
                {
                    thisFile = new DatabaseFile
                    {
                        IsDirectory = true,
                        FileName    = FolderName,
                        FilePath    = FilePath
                    };
                }

                this.DatabaseFileRepository.AddOrUpdate(thisFile);
            }

            return(this.RedirectToAction(nameof(Index), new { Id = thisFile.FullName.Remove(this.FileService.GetUserFilesRoot()).Replace("\\", "/", StringComparison.OrdinalIgnoreCase) }));
        }
        public static async Task LogProjectionResult(Guid queryGuid,
                                                     string queryName,
                                                     string projectionTypeName,
                                                     string domainName,
                                                     string aggregateTypeName,
                                                     string aggregateInstanceKey,
                                                     Nullable <DateTime> asOfDate,
                                                     object projectionValues,
                                                     uint sequenceNumber,
                                                     IWriteContext writeContext = null)
        {
            EventStream qryEvents = new EventStream(Constants.Domain_Query,
                                                    queryName,
                                                    queryGuid.ToString());

            if (null != qryEvents)
            {
                if (null != writeContext)
                {
                    qryEvents.SetContext(writeContext);
                }

                await qryEvents.AppendEvent(new TheLongRun.Common.Events.Query.ProjectionValueReturned(domainName,
                                                                                                       aggregateTypeName,
                                                                                                       WebUtility.UrlDecode(aggregateInstanceKey),
                                                                                                       WebUtility.UrlDecode(projectionTypeName),
                                                                                                       asOfDate.GetValueOrDefault(DateTime.UtcNow),
                                                                                                       projectionValues,
                                                                                                       sequenceNumber));
            }
        }
Exemplo n.º 20
0
	    public override void Write(IWriteContext context, object obj)
		{
	        DateTime dateTime = (DateTime)obj;
	        long ticks = dateTime.Ticks;
			context.WriteLong(ticks);
	        WriteKind(context, dateTime);
		}
Exemplo n.º 21
0
        public static void Record(this IRepository <PageView> repository, HttpContext httpContext, IUserSession userSession = null)
        {
            if (repository is null)
            {
                throw new ArgumentNullException(nameof(repository));
            }

            if (httpContext is null)
            {
                throw new ArgumentNullException(nameof(httpContext));
            }

            PageView pageView = new PageView(httpContext.Request);

            if (userSession?.IsLoggedIn ?? false)
            {
                pageView.Creator = userSession.LoggedInUser.Guid;
            }

            pageView.DateCreated = DateTime.Now;

            using (IWriteContext context = repository.WriteContext())
            {
                repository.Add(pageView);
            }
        }
        public ActionResult SaveForm([FromBody] FormPost formBody)
        {
            if (formBody is null)
            {
                throw new ArgumentNullException(nameof(formBody));
            }

            JsonForm toSave;

            using (IWriteContext context = this.FormRepository.WriteContext())
            {
                if (formBody.Id != 0)
                {
                    toSave = this.FormRepository.Find(formBody.Id) ?? throw new NullReferenceException($"Can not find form with Id {formBody.Id}");
                }
                else
                {
                    toSave = new JsonForm();
                }

                toSave.FormData = formBody.Formhtml;

                this.FormRepository.AddOrUpdate(toSave);
            }

            JsonForm SavedForm = this.FormRepository.Find(toSave.Guid);

            return(new JsonResult(new { Id = SavedForm._Id }));
        }
 public Task NewEntityCreated(IEventStreamIdentity newEntity,
                              string commentary     = @"",
                              IWriteContext context = null)
 {
     // do nothing
     return(Task.CompletedTask);
 }
Exemplo n.º 24
0
 public virtual void Write(IWriteContext context, object obj)
 {
     Array collection = (Array) obj;
     ClassMetadata elementType = DetectElementTypeHandler(Container(context), collection);
     WriteElementTypeId(context, elementType);
     new ArrayHandler(elementType.TypeHandler(), false).Write(context, obj);
 }
        string IWriteContext.ToString()
        {
            IWriteContext ins = this;

            ins.Append("sign", sbSign.ToString());
            return("{" + sb.ToString() + "}");
        }
Exemplo n.º 26
0
        public override void Write(IWriteContext context, object obj)
        {
            char charValue = ((char)obj);

            context.WriteBytes(new byte[] { (byte)(charValue & unchecked ((int)(0xff))), (byte
                                                                                          )(charValue >> 8) });
        }
        /// <summary>
        /// Generates an email using the template(s) assigned to the given handler name
        /// </summary>
        /// <param name="parameters">Binding Parameters. First is property name, second is value. Value can be string.</param>
        /// <param name="SendDate">The date the email should be queued to send on</param>
        /// <param name="HandlerName">The name of the handler generating this email. If null, an attempt is made to retrieve this value using the stack</param>
        /// <param name="skipCallerValidation">For when anything other than an action is calling the method</param>
        /// <param name="Overrides">An email message whos non-default values override the generated template values, useful for debugging by altering the output</param>
        public void GenerateEmailFromTemplate(List <TemplateParameter> parameters, DateTime?SendDate = null, string HandlerName = null, bool skipCallerValidation = false, IEmailMessage Overrides = null)
        {
            if (parameters is null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            if (SendDate == null)
            {
                SendDate = DateTime.Now;
            }

            if (HandlerName is null || !skipCallerValidation)
            {
                StackInformation stackInformation = new StackInformation(new StackTrace(), HandlerName);
                HandlerName = stackInformation.HandlerName;

                if (!skipCallerValidation)
                {
                    stackInformation.ValidateMethodParameters(parameters);
                }
            }

            List <EmailTemplate> templates = this.GetEnabledTemplates(HandlerName);

            foreach (EmailTemplate thisTemplate in templates.Select(t => JsonConvert.DeserializeObject <EmailTemplate>(JsonConvert.SerializeObject(t)))) //Detatch the templates (Without losing child properties) so we can overwrite with post-transform values
            {
                EmailMessage thisMessage = new EmailMessage();

                foreach (PropertyInfo templateProperty in thisTemplate.GetType().GetProperties().Where(p => p.PropertyType == typeof(string)))
                {
                    string value = this.EmailRenderer.RenderEmail(parameters, thisTemplate, templateProperty);

                    templateProperty.SetValue(thisTemplate, value);
                }

                JsonConvert.PopulateObject(JsonConvert.SerializeObject(thisTemplate), thisMessage);

                //Check for an override object. Created so that the recipient of a template can be overridden
                //Null fields arent serialized and so values that arent set in the override should be ignored
                if (Overrides != null)
                {
                    JsonConvert.PopulateObject(JsonConvert.SerializeObject(Overrides, new JsonSerializerSettings()
                    {
                        DefaultValueHandling = DefaultValueHandling.Ignore
                    }), thisMessage);
                }

                //Make sure we create a new entity
                thisMessage._Id        = 0;
                thisMessage.Guid       = Guid.NewGuid();
                thisMessage.ExternalId = thisMessage.Guid.ToString();
                thisMessage.Label      = HandlerName;

                using (IWriteContext writeContext = this.WriteContext())
                {
                    this.EmailRepository.QueueOrSend(thisMessage);
                }
            }
        }
Exemplo n.º 28
0
        public static NewEntityEventGridPayload Create(IEventStreamIdentity newEntity,
                                                       string notificationId = @"",
                                                       string commentary     = @"",
                                                       IWriteContext context = null)
        {
            if (null == newEntity)
            {
                throw new ArgumentNullException(nameof(newEntity));
            }

            // Default the notification id if not are provided
            if (string.IsNullOrEmpty(notificationId))
            {
                notificationId = Guid.NewGuid().ToString("N");
            }

            return(new NewEntityEventGridPayload()
            {
                DomainName = newEntity.DomainName,
                EntityTypeName = newEntity.EntityTypeName,
                InstanceKey = newEntity.InstanceKey,
                NotificationId = notificationId,
                Commentary = commentary,
                Context = context
            });
        }
			public virtual void Write(IWriteContext context, object obj)
			{
				_writeCalls++;
				FieldsToTypeHandlerMigrationTestCase.Item item = (FieldsToTypeHandlerMigrationTestCase.Item
					)obj;
				context.WriteInt(item._id + 42);
			}
Exemplo n.º 30
0
        public virtual void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            coding       = CreateCoding(context);
            ReadContext  = CreateReadContext(context);
            WriteContext = CreateWriteContext(context);
            string type = context.Request.QueryString["t"];

            if (context.Request.RequestType.ToLower() == "post")
            {
                try
                {
                    Dictionary <string, object> kv = ReadContext.ToDictionary();
                    string str = ProcessRequestPostHandler(type, kv);
                    Write(context, str);
                }
                catch (Exception ex)
                {
                    Log.writeLog("ProcessRequest", ex.ToString(), type);
                }
            }
            else
            {
                string str = ProcessRequestGetHandler(type);
                Write(context, str);
            }
        }
 /// <summary>
 /// Converts this port location model parameter using <see cref="RotatablePortLocationModelDecoratorParameterExtension"/>.
 /// </summary>
 MarkupExtension IMarkupExtensionConverter.Convert(IWriteContext context, object value)
 {
     return(new RotatablePortLocationModelDecoratorParameterExtension {
         Model = model == Instance ? null : model,
         Wrapped = wrapped
     });
 }
Exemplo n.º 32
0
 public JsonRequest()
 {
     if (null == wc)
     {
         wc = new WriteContextByJson();
     }
 }
Exemplo n.º 33
0
    	public void Write(IWriteContext context, object obj)
        {
            int classId = ClassMetadataIdFor(context, obj);

            context.WriteInt(classId);
            context.WriteLong(Convert.ToInt64(obj));
        }
Exemplo n.º 34
0
        protected override void WriteElements(IWriteContext context, object obj, ArrayInfo
                                              info)
        {
            IEnumerator objects = AllElements(Container(context), obj);

            if (HasNullBitmap(info))
            {
                BitMap4         nullBitMap       = new BitMap4(info.ElementCount());
                IReservedBuffer nullBitMapBuffer = context.Reserve(nullBitMap.MarshalledLength());
                int             currentElement   = 0;
                while (objects.MoveNext())
                {
                    object current = objects.Current;
                    if (current == null)
                    {
                        nullBitMap.SetTrue(currentElement);
                    }
                    else
                    {
                        context.WriteObject(DelegateTypeHandler(), current);
                    }
                    currentElement++;
                }
                nullBitMapBuffer.WriteBytes(nullBitMap.Bytes());
            }
            else
            {
                while (objects.MoveNext())
                {
                    context.WriteObject(DelegateTypeHandler(), objects.Current);
                }
            }
        }
Exemplo n.º 35
0
		public virtual void WriteTypeInfo(IWriteContext context, ArrayInfo info)
		{
			BitMap4 typeInfoBitmap = new BitMap4(2);
			typeInfoBitmap.Set(0, info.Primitive());
			typeInfoBitmap.Set(1, info.Nullable());
			context.WriteByte(typeInfoBitmap.GetByte(0));
		}
Exemplo n.º 36
0
        // #end example

        // #example: Write the StringBuilder
        public void Write(IWriteContext writeContext, object o)
        {
            StringBuilder builder = (StringBuilder) o;
            string str = builder.ToString();
            byte[] bytes = Encoding.UTF8.GetBytes(str);
            writeContext.WriteInt(bytes.Length);
            writeContext.WriteBytes(bytes);
        }
Exemplo n.º 37
0
		public virtual void Write(IWriteContext context, object obj)
		{
			ICollection collection = (ICollection)obj;
			ITypeHandler4 elementHandler = DetectElementTypeHandler(Container(context), collection
				);
			WriteElementClassMetadataId(context, elementHandler);
			WriteElementCount(context, collection);
			WriteElements(context, collection, elementHandler);
		}
Exemplo n.º 38
0
		public virtual void Write(IWriteContext context, object obj)
		{
            ICollectionInitializer initializer = CollectionInitializer.For(obj);
            IEnumerable enumerable = (IEnumerable)obj;
			ClassMetadata elementType = DetectElementTypeErasingNullables(Container(context), enumerable);
			WriteElementTypeHandlerId(context, elementType);
			WriteElementCount(context, initializer);
			WriteElements(context, enumerable, elementType.TypeHandler());
		}
Exemplo n.º 39
0
		private void WriteElements(IWriteContext context, ICollection collection, ITypeHandler4
			 elementHandler)
		{
			IEnumerator elements = collection.GetEnumerator();
			while (elements.MoveNext())
			{
				context.WriteObject(elementHandler, elements.Current);
			}
		}
Exemplo n.º 40
0
 public override void Write(IWriteContext context, object obj)
 {
     var charValue = ((char) obj);
     context.WriteBytes(new[]
     {
         (byte) (charValue & unchecked(0xff)), (byte
             ) (charValue >> 8)
     });
 }
Exemplo n.º 41
0
		public virtual void Write(IWriteContext context, object obj)
		{
			IDictionary map = (IDictionary)obj;
			KeyValueHandlerPair handlers = DetectKeyValueTypeHandlers(Container(context), map
				);
			WriteClassMetadataIds(context, handlers);
			WriteElementCount(context, map);
			WriteElements(context, map, handlers);
		}
Exemplo n.º 42
0
 public override void Write(IWriteContext context, object obj)
 {
     ushort us = (ushort)obj;
     context.WriteBytes(
         new byte[] { 
             (byte)(us>>8),
             (byte)us,
         });
 }
Exemplo n.º 43
0
 public override void Write(IWriteContext context, object obj)
 {
     uint ui = (uint)obj;
     context.WriteBytes(
         new byte[] { 
             (byte)(ui>>24),
             (byte)(ui>>16),
             (byte)(ui>>8),
             (byte)ui,
         });
 }
Exemplo n.º 44
0
		private void WriteElements(IWriteContext context, IDictionary map, KeyValueHandlerPair
			 handlers)
		{
			IEnumerator elements = map.Keys.GetEnumerator();
			while (elements.MoveNext())
			{
				object key = elements.Current;
				context.WriteObject(handlers._keyHandler, key);
				context.WriteObject(handlers._valueHandler, map[key]);
			}
		}
Exemplo n.º 45
0
		private void WriteElements(IWriteContext context, IDictionary map, KeyValueHandlerPair
			 handlers)
		{
			IEnumerator elements = map.GetEnumerator();
			while (elements.MoveNext())
			{
				DictionaryEntry entry = (DictionaryEntry)elements.Current;
				context.WriteObject(handlers._keyHandler, entry.Key);
				context.WriteObject(handlers._valueHandler, entry.Value);
			}
		}
			public void Write(IWriteContext context, object obj)
			{
				CustomTypeHandlerTestCase.Item item = (CustomTypeHandlerTestCase.Item)obj;
				if (item.numbers == null)
				{
					context.WriteInt(-1);
					return;
				}
				context.WriteInt(item.numbers.Length);
				for (int i = 0; i < item.numbers.Length; i++)
				{
					context.WriteInt(item.numbers[i]);
				}
			}
Exemplo n.º 47
0
 public override void Write(IWriteContext context, object obj)
 {
     ulong ui = (ulong)obj;
     context.WriteBytes(
         new byte[] { 
             (byte)(ui>>56),
             (byte)(ui>>48),
             (byte)(ui>>40),
             (byte)(ui>>32),
             (byte)(ui>>24),
             (byte)(ui>>16),
             (byte)(ui>>8),
             (byte)ui,
         });
 }
Exemplo n.º 48
0
 public override void Write(IWriteContext context, object obj)
 {
     decimal dec = (decimal)obj;
     byte[] bytes = new byte[16];
     int offset = 4;
     int[] ints = Decimal.GetBits(dec);
     for (int i = 0; i < 4; i++)
     {
         bytes[--offset] = (byte)ints[i];
         bytes[--offset] = (byte)(ints[i] >>= 8);
         bytes[--offset] = (byte)(ints[i] >>= 8);
         bytes[--offset] = (byte)(ints[i] >>= 8);
         offset += 8;
     }
     context.WriteBytes(bytes);
 }
Exemplo n.º 49
0
 public override void Write(IWriteContext context, object obj)
 {
     var dec = (decimal) obj;
     var bytes = new byte[16];
     var offset = 4;
     var ints = decimal.GetBits(dec);
     for (var i = 0; i < 4; i++)
     {
         bytes[--offset] = (byte) ints[i];
         bytes[--offset] = (byte) (ints[i] >>= 8);
         bytes[--offset] = (byte) (ints[i] >>= 8);
         bytes[--offset] = (byte) (ints[i] >>= 8);
         offset += 8;
     }
     context.WriteBytes(bytes);
 }
Exemplo n.º 50
0
 public override void Write(IWriteContext context, object obj)
 {
     int shortValue = ((short) obj);
     context.WriteBytes(new[] {(byte) (shortValue >> 8), (byte) shortValue});
 }
Exemplo n.º 51
0
		public override void Write(IWriteContext context, object obj)
		{
			context.WriteLong(((long)obj));
		}
Exemplo n.º 52
0
		private void WriteObject(IWriteContext context, ITypeHandler4 typeHandler, object
			 obj)
		{
			if (IsPlainObject(obj))
			{
				context.WriteObject(new PlainObjectHandler(), obj);
				return;
			}
			if (Handlers4.UseDedicatedSlot(context, typeHandler))
			{
				context.WriteObject(obj);
			}
			else
			{
				typeHandler.Write(context, obj);
			}
		}
		public override void WriteTypeInfo(IWriteContext context, ArrayInfo info)
		{
		}
Exemplo n.º 54
0
		public static void Write(ITypeHandler4 handler, IWriteContext context, object obj
			)
		{
			handler.Write(context, obj);
		}
Exemplo n.º 55
0
		public virtual void Write(IWriteContext context, object obj)
		{
			if (obj == null)
			{
				context.WriteInt(0);
				return;
			}
			MarshallingContext marshallingContext = (MarshallingContext)context;
			ClassMetadata classMetadata = ClassMetadataFor(obj);
			if (classMetadata == null)
			{
				context.WriteInt(0);
				return;
			}
			MarshallingContextState state = marshallingContext.CurrentState();
			marshallingContext.CreateChildBuffer(false);
			context.WriteInt(classMetadata.GetID());
			WriteObject(context, classMetadata.TypeHandler(), obj);
			marshallingContext.RestoreState(state);
		}
Exemplo n.º 56
0
		public virtual void Write(IWriteContext context, object obj)
		{
		}
Exemplo n.º 57
0
		public override void Write(IWriteContext context, object obj)
		{
			context.WriteLong(Platform4.DoubleToLong(((double)obj)));
		}
Exemplo n.º 58
0
 public void Write(IWriteContext context, object obj)
 {
 	WriteGuid(obj, context);
 }
Exemplo n.º 59
0
	    protected virtual void WriteKind(IWriteContext context, DateTime dateTime)
	    {
	        context.WriteInt((int) dateTime.Kind);
	    }
Exemplo n.º 60
0
 public virtual void Write(IWriteContext context, object obj)
 {
     InternalWrite((IInternalObjectContainer) context.ObjectContainer(), context, (string
         ) obj);
 }