Example #1
0
 dynamic ISender.Send(string request)
 {
     HttpContext interaction = new HttpContext(request);
     string result = ConvertionHandler.ToGB2312(interaction.Post());
     IStringSerializer factory = new JsonSerializerFactory().GetStringSerializer();
     return factory.Deserialize<WebinarStateAccept>(DataFilterHandler.JsonFilter(result));
 }
Example #2
0
        private static void Serialise(OscMessage msg, JsonWriter writer)
        {
            writer.WritePropertyName("address");
            writer.WriteValue(msg.Address);
            writer.WritePropertyName("typeTag");
            writer.WriteValue(msg.TypeTag);
            writer.WritePropertyName("data");
            writer.WriteStartArray();
            for (var i = 0; i < msg.Data.Count; i++)
            {
                var part = msg.Data[i];

                if (part is Array &&
                    !(part is byte[]))    // NB: blobs are handled with a specific serialisator.)
                {
                    var collection = part as Array;
                    foreach (var component in collection)
                    {
                        var ser = JsonSerializerFactory.GetSerializer(component);
                        ser.Encode(writer, component);
                    }
                }
                else
                {
                    var ser = JsonSerializerFactory.GetSerializer(part);
                    ser.Encode(writer, part);
                }
            }
            writer.WriteEndArray();
        }
Example #3
0
        static void Main(string[] args)
        {
            Author author = new Author();
            author.FullName = "Gang of Four";
            author.Age = 22;

            Blog blog = new Blog();
            blog.Id = 1;
            blog.Name = "Design Patterns";
            blog.Comments.Add("Visitor pattern");
            blog.Comments.Add("Abstract factory pattern");
            blog.Comments.Add("Composite pattern");
            blog.Author = author;

            ISerializerFactory serializerFactory = new UnicodeXmlSerializerFactory();
            var service = new BlogDataExchangeService();
            service.SerializerFactory = serializerFactory;

            System.Console.WriteLine("{0}:\n{1}\n", "Full as Unicode XML Document", service.GetFull(blog));
            System.Console.WriteLine("{0}:\n{1}\n", "Header as Unicode XML Document", service.GetHeader(blog));
            System.Console.WriteLine("{0}:\n{1}\n", "Exchange as Unicode XML Document", service.GetFullForExchange(blog));

            System.Console.WriteLine();

            serializerFactory = new JsonSerializerFactory();
            service.SerializerFactory = serializerFactory;

            System.Console.WriteLine("{0}:\n{1}\n", "Full as JSON Document", service.GetFull(blog));
            System.Console.WriteLine("{0}:\n{1}\n", "Header as JSON Document", service.GetHeader(blog));
            System.Console.WriteLine("{0}:\n{1}\n", "Exchange as JSON Document", service.GetFullForExchange(blog));

            System.Console.WriteLine("Execution finished. Press a key to exit.");
            System.Console.ReadLine();
        }
Example #4
0
File: Bus.cs Project: jellebens/edt
        public void Publish <TCommand>(TCommand command) where TCommand : ICommand
        {
            if (command.Id == default(Guid))
            {
                throw new CommandMissingIdException();
            }

            string connectionString = CloudConfigurationManager.GetSetting(Settings.Bus.ConfigKey);

            NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

            if (!namespaceManager.QueueExists(Settings.Bus.Queue.SendCommand))
            {
                _Logger.InfoFormat("Queue does not exist creating queue {0}", Settings.Bus.Queue.SendCommand);
                QueueDescription queueDescription = namespaceManager.CreateQueue(Settings.Bus.Queue.SendCommand);
            }

            QueueClient Client = QueueClient.CreateFromConnectionString(connectionString, Settings.Bus.Queue.SendCommand);

            DataContractJsonSerializer serializer = JsonSerializerFactory.Create(command);

            BrokeredMessage message = new BrokeredMessage(command, serializer)
            {
                MessageId = command.Id.ToString()
            };

            _Logger.DebugFormat("Dispatching message with id {0}", message.MessageId);
            _JobService.New(command);

            Client.SendAsync(message);
        }
Example #5
0
        private void HandleMessage(BrokeredMessage receivedMessage)
        {
            try {
                _Logger.InfoFormat("Processing message: {0}. DeliveryCount: {1}", receivedMessage.MessageId,
                                   receivedMessage.DeliveryCount);

                DataContractJsonSerializer serializer = JsonSerializerFactory.Create <RegisterUser>();
                dynamic command = receivedMessage.GetBody <ICommand>(serializer);

                ICommandProcessor processor = _Container.Resolve <ICommandProcessor>();
                _jobservice.Start(command);
                try {
                    processor.Execute(command);

                    _Logger.InfoFormat("Handled message {0}", receivedMessage.MessageId);
                    receivedMessage.Complete();
                    _jobservice.Complete(command);
                } finally {
                    _Container.Release(processor);
                }
            } catch (InvalidCastException e) {
                _Logger.ErrorFormat(e, "An InvalidCastException has been caught moving message to deadletter");
                receivedMessage.DeadLetter("Unknown Message can not cast to ICommand", e.Message);
            } catch (SerializationException e) {
                _Logger.ErrorFormat(e, "An SerializationException has been caught moving message to deadletter {0}.", e.Message);
                receivedMessage.DeadLetter("Can not deserialize message", e.Message);
            } catch (Exception e) {
                _Logger.FatalFormat(e, "An Exception Has been caught: {0}", e.Message);
            }
        }
Example #6
0
        /// <summary>Infrastructure. Creates and configures an instance of the default service client.</summary>
        /// <returns>The <see cref="IServiceClient"/>.</returns>
        private IServiceClient CreateServiceClient()
        {
            Uri baseUri = this.GetRepositoryUri();
            JsonSerializerFactory jsonSerializerFactory = new JsonSerializerFactory();
            GzipInflator          gzipInflator          = new GzipInflator();

            return(new ServiceClient(baseUri, jsonSerializerFactory, jsonSerializerFactory, gzipInflator));
        }
Example #7
0
        /// <summary>Infrastructure. Creates and configures an instance of an authorized service client.</summary>
        /// <param name="apiKey">The api key grating access to the authorized area.</param>
        /// <returns>The <see cref="IServiceClient"/>.</returns>
        private IServiceClient CreateAuthorizedServiceClient(string apiKey)
        {
            Uri baseUri = this.GetRepositoryUri();
            JsonSerializerFactory jsonSerializerFactory = new JsonSerializerFactory();
            GzipInflator          gzipInflator          = new GzipInflator();

            return(new ServiceClientAuthorized(baseUri, apiKey, jsonSerializerFactory, jsonSerializerFactory, gzipInflator));
        }
Example #8
0
 public JsonConvertersBenchmarkContext()
 {
     SysSerializer     = JsonSerializerFactory.CreateJsonSerializer(true);
     JsonNetSerializer = JsonNetSerializerFactory.CreateJsonSerializer(true);
     Docflow           = SysSerializer.Deserialize <IDocflowWithDocuments>(json);
     utf8JsonBytes     = Encoding.UTF8.GetBytes(json);
     emptyJsonBytes    = new byte[json.Length * sizeof(char)];
 }
Example #9
0
        /// <summary>Infrastructure. Creates and configures an instance of the default service client.</summary>
        /// <returns>The <see cref="IServiceClient"/>.</returns>
        private IServiceClient CreateRenderingServiceClient()
        {
            Uri baseUri = this.GetRenderingUri();
            BinarySerializerFactory imageSerializerFactory = new BinarySerializerFactory();
            JsonSerializerFactory   jsonSerializerFactory  = new JsonSerializerFactory();
            GzipInflator            gzipInflator           = new GzipInflator();

            return(new ServiceClient(baseUri, imageSerializerFactory, jsonSerializerFactory, gzipInflator));
        }
Example #10
0
        public static IUkiyoBuilder AddWebApi(this IUkiyoBuilder builder, Action <IMvcCoreBuilder> configureMvc, IJsonSerializer jsonSerializer = null,
                                              string sectionName = SectionName)
        {
            if (string.IsNullOrWhiteSpace(sectionName))
            {
                sectionName = SectionName;
            }

            if (!builder.TryRegister(RegistryName))
            {
                return(builder);
            }

            if (jsonSerializer is null)
            {
                var factory = new JsonSerializerFactory(StandardResolver.AllowPrivateCamelCase);
                JsonSerializer.SetDefaultResolver(new UkiyoFormatterResolver());
                jsonSerializer = factory.GetSerializer();
            }

            builder.Services.AddSingleton(jsonSerializer);
            builder.Services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            builder.Services.AddSingleton(new WebApiEndpointDefinitions());
            var options = builder.GetOptions <WebApiOptions>(sectionName);

            builder.Services.AddSingleton(options);
            _bindRequestFromRoute = options.BindRequestFromRoute;

            var mvcCoreBuilder = builder.Services
                                 .AddLogging()
                                 .AddMvcCore();

            mvcCoreBuilder.AddMvcOptions(o =>
            {
                var resolver = CompositeResolver.Create(EnumResolver.Default, StandardResolver.AllowPrivateCamelCase);
                o.OutputFormatters.Clear();
                o.OutputFormatters.Add(new JsonOutputFormatter(resolver));
                o.InputFormatters.Clear();
                o.InputFormatters.Add(new JsonInputFormatter(resolver));
            })
            .AddDataAnnotations()
            .AddApiExplorer()
            .AddAuthorization();

            configureMvc?.Invoke(mvcCoreBuilder);

            builder.Services.Scan(s =>
                                  s.FromAssemblies(AppDomain.CurrentDomain.GetAssemblies())
                                  .AddClasses(c => c.AssignableTo(typeof(IRequestHandler <,>)))
                                  .AsImplementedInterfaces()
                                  .WithTransientLifetime());

            builder.Services.AddTransient <IRequestDispatcher, RequestDispatcher>();

            return(builder);
        }
        public void Serializer_ShouldBe_JsonSerializer()
        {
            // Arrange
            var factory = new JsonSerializerFactory();

            // Act
            var result = factory.Serializer <int>();

            // Assert
            result.Should().BeOfType <JsonSerializer <int> >();
        }
        public void Serializer_Should_NotBeNull()
        {
            // Arrange
            var factory = new JsonSerializerFactory();

            // Act
            var result = factory.Serializer <int>();

            // Assert
            result.Should().NotBeNull();
        }
        /// <summary>
        /// Reads the <paramref name="content"/> content as JSON and deserializes it into an object.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="content"></param>
        /// <param name="jsonSerializer"></param>
        /// <returns></returns>
        public static async Task <T> ReadAsJsonAsync <T>(this HttpContent content, JsonSerializer jsonSerializer)
        {
            var serializer = jsonSerializer ?? JsonSerializerFactory.GetDefaultSerializer();

            var stream = await content.ReadAsStreamAsync();

            using (var streamReader = new StreamReader(stream))
                using (var jsonReader = new JsonTextReader(streamReader))
                {
                    return(serializer.Deserialize <T>(jsonReader));
                }
        }
Example #14
0
        private static OscPacket DeserialiseMessage(JsonReader reader, string address)
        {
            reader.Read(); // read property tags
            var tags = reader.ReadAsString();
            var msg  = new OscMessage(address);

            reader.Read(); // data property name
            reader.Read(); // array start
            for (var index = 0; index < tags.Length; index++)
            {
                var tag = tags[index];

                if (tag == JsonSerializerFactory.ArrayOpen)
                {
                    // skip the '[' character.
                    index++;

                    // deserialise array of object
                    var ret = new List <object>();
                    while (tags[index] != JsonSerializerFactory.ArrayClose &&
                           index < tags.Length)
                    {
                        var des = JsonSerializerFactory.GetSerializer(tags[index]);
                        ret.Add(des.Decode(reader));

                        index++;
                    }

                    msg.Append(ret.ToArray());
                }
                else if (tag != JsonSerializerFactory.DefaultTag)
                {
                    if (tag != JsonSerializerFactory.EventTag)
                    {
                        var des = JsonSerializerFactory.GetSerializer(tag);
                        msg.Append(des.Decode(reader));
                    }
                    else
                    {
                        msg.IsEvent = true;
                    }
                }
            }
            reader.Read(); // array end

            return(msg);
        }
Example #15
0
        public static void BuildSerializer___Json___Gets_Json_serializer()
        {
            // Arrange
            var serializerRepresentation = new SerializerRepresentation(
                SerializationKind.Json,
                null,
                CompressionKind.None);

            // Act
            var serializer     = SerializerFactory.Instance.BuildSerializer(serializerRepresentation);
            var jsonSerializer = new JsonSerializerFactory(CompressorFactory.Instance).BuildSerializer(serializerRepresentation);

            // Assert
            serializer.Should().NotBeNull();
            serializer.Should().BeOfType <ObcJsonSerializer>();
            jsonSerializer.Should().NotBeNull();
            jsonSerializer.Should().BeOfType <ObcJsonSerializer>();
        }
Example #16
0
        static void Main(string[] args)
        {
            Author author = new Author();

            author.FullName = "Gang of Four";
            author.Age      = 22;

            Blog blog = new Blog();

            blog.Id   = 1;
            blog.Name = "Design Patterns";
            blog.Comments.Add("Visitor pattern");
            blog.Comments.Add("Abstract factory pattern");
            blog.Comments.Add("Composite pattern");
            blog.Author = author;

            ISerializerFactory serializerFactory = new UnicodeXmlSerializerFactory();
            var service = new BlogDataExchangeService();

            service.SerializerFactory = serializerFactory;

            System.Console.WriteLine("{0}:\n{1}\n", "Full as Unicode XML Document", service.GetFull(blog));
            System.Console.WriteLine("{0}:\n{1}\n", "Header as Unicode XML Document", service.GetHeader(blog));
            System.Console.WriteLine("{0}:\n{1}\n", "Exchange as Unicode XML Document", service.GetFullForExchange(blog));

            System.Console.WriteLine();

            serializerFactory         = new JsonSerializerFactory();
            service.SerializerFactory = serializerFactory;

            System.Console.WriteLine("{0}:\n{1}\n", "Full as JSON Document", service.GetFull(blog));
            System.Console.WriteLine("{0}:\n{1}\n", "Header as JSON Document", service.GetHeader(blog));
            System.Console.WriteLine("{0}:\n{1}\n", "Exchange as JSON Document", service.GetFullForExchange(blog));

            System.Console.WriteLine("Execution finished. Press a key to exit.");
            System.Console.ReadLine();
        }
        private static Streams BuildStreamsAsync(
            string streamRootDirectoryPath)
        {
            var serializerRepresentation = new SerializerRepresentation(SerializationKind.Json, typeof(IntegrationTestJsonSerializationConfiguration).ToRepresentation());
            var serializerFactory        = new JsonSerializerFactory();
            var resourceLocatorProtocols = new SingleResourceLocatorProtocols(new FileSystemDatabaseLocator(streamRootDirectoryPath));

            var clientOperationStream   = new FileStandardStream("client-operation", serializerRepresentation, SerializationFormat.String, serializerFactory, resourceLocatorProtocols);
            var notificationEventStream = new FileStandardStream("notification-event", serializerRepresentation, SerializationFormat.String, serializerFactory, resourceLocatorProtocols);
            var notificationSagaStream  = new FileStandardStream("notification-saga", serializerRepresentation, SerializationFormat.String, serializerFactory, resourceLocatorProtocols);
            var emailOperationStream    = new FileStandardStream("email-operation", serializerRepresentation, SerializationFormat.String, serializerFactory, resourceLocatorProtocols);
            var emailEventStream        = new FileStandardStream("email-event", serializerRepresentation, SerializationFormat.String, serializerFactory, resourceLocatorProtocols);
            var slackOperationStream    = new FileStandardStream("slack-operation", serializerRepresentation, SerializationFormat.String, serializerFactory, resourceLocatorProtocols);
            var slackEventStream        = new FileStandardStream("slack-event", serializerRepresentation, SerializationFormat.String, serializerFactory, resourceLocatorProtocols);

            clientOperationStream.Execute(new StandardCreateStreamOp(clientOperationStream.StreamRepresentation, ExistingStreamStrategy.Skip));
            notificationEventStream.Execute(new StandardCreateStreamOp(notificationEventStream.StreamRepresentation, ExistingStreamStrategy.Skip));
            notificationSagaStream.Execute(new StandardCreateStreamOp(notificationSagaStream.StreamRepresentation, ExistingStreamStrategy.Skip));
            emailOperationStream.Execute(new StandardCreateStreamOp(emailOperationStream.StreamRepresentation, ExistingStreamStrategy.Skip));
            emailEventStream.Execute(new StandardCreateStreamOp(emailEventStream.StreamRepresentation, ExistingStreamStrategy.Skip));
            slackOperationStream.Execute(new StandardCreateStreamOp(slackOperationStream.StreamRepresentation, ExistingStreamStrategy.Skip));
            slackEventStream.Execute(new StandardCreateStreamOp(slackEventStream.StreamRepresentation, ExistingStreamStrategy.Skip));

            var result = new Streams
            {
                ClientOperationStream   = clientOperationStream,
                NotificationEventStream = notificationEventStream,
                NotificationSagaStream  = notificationSagaStream,
                EmailOperationStream    = emailOperationStream,
                EmailEventStream        = emailEventStream,
                SlackOperationStream    = slackOperationStream,
                SlackEventStream        = slackEventStream,
            };

            return(result);
        }
Example #18
0
        public static void GenerateSerializer(String[] args)
        {
            var parms = new ParameterParser <ConsoleParameters>().Parse(args);

            // First we want to open the output file
            using (TextWriter output = File.CreateText(parms.Output ?? "out.cs"))
            {
                JsonSerializerFactory serFact     = new JsonSerializerFactory();
                CSharpCodeProvider    csProvider  = new CSharpCodeProvider();
                CodeCompileUnit       compileUnit = new CodeCompileUnit();

                // Add namespace
                compileUnit.Namespaces.Add(serFact.CreateCodeNamespace(parms.Namespace ?? Path.GetFileNameWithoutExtension(parms.AssemblyFile) + ".Json.Formatter", Assembly.LoadFile(parms.AssemblyFile)));
                compileUnit.ReferencedAssemblies.Add("System.dll");
                compileUnit.ReferencedAssemblies.Add("Newtonsoft.Json.dll");
                compileUnit.ReferencedAssemblies.Add(typeof(IdentifiedData).Assembly.Location);
                compileUnit.ReferencedAssemblies.Add(typeof(IJsonViewModelTypeFormatter).Assembly.Location);
                compileUnit.ReferencedAssemblies.Add(typeof(Tracer).Assembly.Location);
                csProvider.GenerateCodeFromCompileUnit(compileUnit, output, new CodeGeneratorOptions()
                {
                    BlankLinesBetweenMembers = true
                });
            }
        }
        public IExtern Create(
            ContentManagementOptions?contentManagementOptions,
            IHttpClientConfiguration clientConfiguration,
            IPollingStrategy?pollingStrategy,
            ICrypt?cryptoProvider,
            RequestTimeouts?requestTimeouts,
            IAuthenticator authenticator,
            IExternHttpClient?api,
            IHttpRequestFactory?httpRequestFactory,
            ILog log)
        {
            contentManagementOptions ??= ContentManagementOptions.Default;
            pollingStrategy ??= DefaultDelayPollingStrategy;
            cryptoProvider ??= DefaultCryptoProvider;
            requestTimeouts ??= new RequestTimeouts();

            var jsonSerializer = JsonSerializerFactory.CreateJsonSerializer();

            httpRequestFactory ??= CreateHttp(clientConfiguration, requestTimeouts, authenticator, jsonSerializer, log);
            api ??= new ExternHttpClient(httpRequestFactory);
            var services = new ExternClientServices(contentManagementOptions, httpRequestFactory, jsonSerializer, api, pollingStrategy, authenticator, cryptoProvider);

            return(new Extern(services));
        }
 public void SetUp()
 {
     serializer           = JsonSerializerFactory.CreateJsonSerializer();
     descriptionGenerator = new DocflowDescriptionGenerator();
 }
 public void SetUp()
 {
     serializer = JsonSerializerFactory.CreateJsonSerializer(ignoreNullValues: false);
     autoFaker  = new AutoFakerFactory().AddDraftsBuilderEntitiesGeneration().Create();
 }
Example #22
0
        public static IDrexBuilder AddWebApi(this IDrexBuilder builder,
                                             Action <IMvcCoreBuilder> configureMvc = null,
                                             IJsonSerializer jsonSerializer        = null, string sectionName = SectionName)
        {
            if (string.IsNullOrWhiteSpace(sectionName))
            {
                sectionName = SectionName;
            }

            if (!builder.TryRegister(RegistryName))
            {
                return(builder);
            }

            if (jsonSerializer is null)
            {
                var factory = new JsonSerializerFactory(new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver(),
                    Converters       = { new StringEnumConverter(true) }
                });
                jsonSerializer = factory.GetSerializer();
            }

            if (jsonSerializer.GetType().Namespace?.Contains("Newtonsoft") == true)
            {
                builder.Services.Configure <KestrelServerOptions>(o => o.AllowSynchronousIO = true);
                builder.Services.Configure <IISServerOptions>(o => o.AllowSynchronousIO     = true);
            }

            builder.Services.AddSingleton(jsonSerializer);
            builder.Services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            builder.Services.AddSingleton(new WebApiEndpointDefinitions());
            var options = builder.GetOptions <WebApiOptions>(sectionName);

            builder.Services.AddSingleton(options);
            _bindRequestFromRoute = options.BindRequestFromRoute;

            var mvcCoreBuilder = builder.Services
                                 .AddLogging()
                                 .AddMvcCore();

            mvcCoreBuilder.AddMvcOptions(o =>
            {
                o.OutputFormatters.Clear();
                o.OutputFormatters.Add(new JsonOutputFormatter(jsonSerializer));
                o.InputFormatters.Clear();
                o.InputFormatters.Add(new JsonInputFormatter(jsonSerializer));
            })
            .AddDataAnnotations()
            .AddApiExplorer()
            .AddAuthorization();

            configureMvc?.Invoke(mvcCoreBuilder);

            // This method gets called by the runtime. Use this method to add services to the container.
            builder.Services.Scan(s =>
                                  s.FromAssemblies(AppDomain.CurrentDomain.GetAssemblies())
                                  .AddClasses(c => c.AssignableTo(typeof(IRequestHandler <,>)))
                                  .AsImplementedInterfaces()
                                  .WithTransientLifetime());

            builder.Services.AddTransient <IRequestDispatcher, RequestDispatcher>();

            return(builder);
        }
 public void SetUp()
 {
     serializer           = JsonSerializerFactory.CreateJsonSerializer(ignoreNullValues: false);
     descriptionGenerator = new DocflowDocumentDescriptionGenerator();
 }
Example #24
0
 public LambdaExecutor() : this(new LambdaLoggerWrapper(), JsonSerializerFactory.CreateJsonPayloadSerializer(),
                                new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddInMemoryCollection(/* default config strings */)
                                .AddJsonFile("TemplateService.settings", true, true).Build())
 {
 }
Example #25
0
 /// <summary>Infrastructure. Creates and configures an instance of the default service client.</summary>
 /// <returns>The <see cref="IServiceClient"/>.</returns>
 private IServiceClient CreateServiceClient()
 {
     Uri baseUri = this.GetRepositoryUri();
     JsonSerializerFactory jsonSerializerFactory = new JsonSerializerFactory();
     GzipInflator gzipInflator = new GzipInflator();
     return new ServiceClient(baseUri, jsonSerializerFactory, jsonSerializerFactory, gzipInflator);
 }
Example #26
0
 /// <summary>Infrastructure. Creates and configures an instance of the default service client.</summary>
 /// <returns>The <see cref="IServiceClient"/>.</returns>
 private IServiceClient CreateRenderingServiceClient()
 {
     Uri baseUri = this.GetRenderingUri();
     BinarySerializerFactory imageSerializerFactory = new BinarySerializerFactory();
     JsonSerializerFactory jsonSerializerFactory = new JsonSerializerFactory();
     GzipInflator gzipInflator = new GzipInflator();
     return new ServiceClient(baseUri, imageSerializerFactory, jsonSerializerFactory, gzipInflator);
 }
Example #27
0
 public void SetUp() =>
 serializer = JsonSerializerFactory.CreateJsonSerializer();
Example #28
0
 static OscEndPoint()
 {
     SerializerFactory.LoadSerializer(typeof(EndPointSerializer));
     JsonSerializerFactory.LoadSerializer(typeof(EndPointJsonSerializer));
 }
Example #29
0
 static Log()
 {
     SubjectSerializerRepresentation = new SerializerRepresentation(SerializationKind.Json, typeof(LoggingJsonSerializationConfiguration).ToRepresentation());
     SubjectSerializerFactory        = new JsonSerializerFactory();
 }
Example #30
0
        public static void DescribeComponent(object instance, ScriptComponentDescriptor descriptor, IUrlResolutionService urlResolver, IControlResolver controlResolver)
        {
            // validate preconditions
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }
            if (descriptor == null)
            {
                throw new ArgumentNullException("descriptor");
            }
            if (urlResolver == null)
            {
                urlResolver = instance as IUrlResolutionService;
            }
            if (controlResolver == null)
            {
                controlResolver = instance as IControlResolver;
            }

            // describe properties
            // PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(instance);

            PropertyInfo[] properties = instance.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

            foreach (PropertyInfo prop in properties)
            {
                ScriptControlPropertyAttribute propAttr  = null;
                ScriptControlEventAttribute    eventAttr = null;
                string propertyName = prop.Name;

                System.ComponentModel.AttributeCollection attribs = new System.ComponentModel.AttributeCollection(Attribute.GetCustomAttributes(prop, false));

                // Try getting a property attribute
                propAttr = (ScriptControlPropertyAttribute)attribs[typeof(ScriptControlPropertyAttribute)];
                if (propAttr == null || !propAttr.IsScriptProperty)
                {
                    // Try getting an event attribute
                    eventAttr = (ScriptControlEventAttribute)attribs[typeof(ScriptControlEventAttribute)];
                    if (eventAttr == null || !eventAttr.IsScriptEvent)
                    {
                        continue;
                    }
                }

                // attempt to rename the property/event
                ClientPropertyNameAttribute nameAttr = (ClientPropertyNameAttribute)attribs[typeof(ClientPropertyNameAttribute)];
                if (nameAttr != null && !string.IsNullOrEmpty(nameAttr.PropertyName))
                {
                    propertyName = nameAttr.PropertyName;
                }

                // determine whether to serialize the value of a property.  readOnly properties should always be serialized
                //bool serialize = true;// prop.ShouldSerializeValue(instance) || prop.IsReadOnly;
                //if (serialize)
                //{
                // get the value of the property, skip if it is null
                Control c     = null;
                object  value = prop.GetValue(instance, new object[0] {
                });
                if (value == null)
                {
                    continue;
                }

                // convert and resolve the value
                if (eventAttr != null && prop.PropertyType != typeof(String))
                {
                    throw new InvalidOperationException("ScriptControlEventAttribute can only be applied to a property with a PropertyType of System.String.");
                }
                else
                {
                    if (!prop.PropertyType.IsPrimitive && !prop.PropertyType.IsEnum)
                    {
                        if (prop.PropertyType == typeof(Color))
                        {
                            value = ColorTranslator.ToHtml((Color)value);
                        }
                        else
                        {
                            // TODO: Determine if we should let ASP.NET AJAX handle this type of conversion, as it supports JSON serialization
                            //TypeConverter conv = prop.Converter;
                            //value = conv.ConvertToString(null, CultureInfo.InvariantCulture, value);

                            //if (prop.PropertyType == typeof(CssStyleCollection))
                            //    value = (new CssStyleCollectionJSCoverter()).Serialize(value, new JavaScriptSerializer());
                            //if (prop.PropertyType == typeof(Style))
                            //    value = (new CssStyleCollectionJSCoverter()).Serialize(((Style)value).GetStyleAttributes(null), new JavaScriptSerializer());

                            Type valueType = value.GetType();

                            JavaScriptConverterAttribute attr      = (JavaScriptConverterAttribute)attribs[typeof(JavaScriptConverterAttribute)];
                            JavaScriptConverter          converter = attr != null ?
                                                                     (JavaScriptConverter)TypeCreator.CreateInstance(attr.ConverterType) :
                                                                     JsonSerializerFactory.GetJavaScriptConverter(valueType);

                            if (converter != null)
                            {
                                value = converter.Serialize(value, JsonSerializerFactory.GetJavaScriptSerializer());
                            }
                            else
                            {
                                value = JsonHelper.PreSerializeObject(value);
                            }

                            //Dictionary<string, object> dict = value as Dictionary<string, object>;
                            //if (dict != null && !dict.ContainsKey("__type"))
                            //    dict["__type"] = valueType.AssemblyQualifiedName;
                        }
                    }
                    if (attribs[typeof(IDReferencePropertyAttribute)] != null && controlResolver != null)
                    {
                        c = controlResolver.ResolveControl((string)value);
                    }
                    if (attribs[typeof(UrlPropertyAttribute)] != null && urlResolver != null)
                    {
                        value = urlResolver.ResolveClientUrl((string)value);
                    }
                }

                // add the value as an appropriate description
                if (eventAttr != null)
                {
                    if (!string.IsNullOrEmpty((string)value))
                    {
                        descriptor.AddEvent(propertyName, (string)value);
                    }
                }
                else if (attribs[typeof(ElementReferenceAttribute)] != null)
                {
                    if (c == null && controlResolver != null)
                    {
                        c = controlResolver.ResolveControl((string)value);
                    }
                    if (c != null)
                    {
                        value = c.ClientID;
                    }
                    descriptor.AddElementProperty(propertyName, (string)value);
                }
                else if (attribs[typeof(ComponentReferenceAttribute)] != null)
                {
                    if (c == null && controlResolver != null)
                    {
                        c = controlResolver.ResolveControl((string)value);
                    }
                    if (c != null)
                    {
                        //ExtenderControlBase ex = c as ExtenderControlBase;
                        //if (ex != null && ex.BehaviorID.Length > 0)
                        //    value = ex.BehaviorID;
                        //else
                        value = c.ClientID;
                    }
                    descriptor.AddComponentProperty(propertyName, (string)value);
                }
                else
                {
                    if (c != null)
                    {
                        value = c.ClientID;
                    }
                    descriptor.AddProperty(propertyName, value);
                }
            }
            //}

            // determine if we should describe methods
            foreach (MethodInfo method in instance.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public))
            {
                ScriptControlMethodAttribute methAttr = (ScriptControlMethodAttribute)Attribute.GetCustomAttribute(method, typeof(ScriptControlMethodAttribute));
                if (methAttr == null || !methAttr.IsScriptMethod)
                {
                    continue;
                }

                // We only need to support emitting the callback target and registering the WebForms.js script if there is at least one valid method
                Control control = instance as Control;
                if (control != null)
                {
                    // Force WebForms.js
                    control.Page.ClientScript.GetCallbackEventReference(control, null, null, null);

                    // Add the callback target
                    descriptor.AddProperty("_callbackTarget", control.UniqueID);
                }
                break;
            }
        }
Example #31
0
 /// <summary>Infrastructure. Creates and configures an instance of an authorized service client.</summary>
 /// <param name="apiKey">The api key grating access to the authorized area.</param>
 /// <returns>The <see cref="IServiceClient"/>.</returns>
 private IServiceClient CreateAuthorizedServiceClient(string apiKey)
 {
     Uri baseUri = this.GetRepositoryUri();
     JsonSerializerFactory jsonSerializerFactory = new JsonSerializerFactory();
     GzipInflator gzipInflator = new GzipInflator();
     return new ServiceClientAuthorized(baseUri, apiKey, jsonSerializerFactory, jsonSerializerFactory, gzipInflator);
 }