Пример #1
0
        /// <summary>
        /// Loads the <see cref="RecurringJobInfo"/> for this source.
        /// </summary>
        /// <returns>The list of <see cref="RecurringJobInfo"/> for this provider.</returns>
        public override IEnumerable <RecurringJobInfo> Load()
        {
            var jsonContent = ReadFromFile();

            if (string.IsNullOrWhiteSpace(jsonContent))
            {
                throw new Exception("Json file content is empty.");
            }

            var jsonOptions = SerializationHelper.Deserialize <List <RecurringJobJsonOptions> >(jsonContent);

            foreach (var o in jsonOptions)
            {
                var types = o.strJobType.Split(",");
                if (types != null && types.Length == 2)
                {
                    o.JobType = Assembly.Load(types[1].Trim()).GetType(types[0]);
                }
                yield return(Convert(o));
            }
        }
Пример #2
0
        public void OnStateElection(ElectStateContext context)
        {
            if (String.IsNullOrEmpty(context.CurrentState))
            {
                return;
            }

            var serializedState = context.GetJobParameter <string>("Completion");

            if (!String.IsNullOrEmpty(serializedState))
            {
                if (context.CandidateState is ProcessingState || context.CandidateState.IsFinal)
                {
                    context.CandidateState = SerializationHelper.Deserialize <IState>(serializedState);
                }
            }
            else if (context.CandidateState.IsFinal)
            {
                context.SetJobParameter("Completion", SerializationHelper.Serialize(context.CandidateState));
            }
        }
Пример #3
0
 public void ProcessResponse(HttpWebResponse response, Stream resultStream)
 {
     if (response.StatusCode >= HttpStatusCode.Ambiguous)
     {
         try
         {
             resultStream.Position = 0;
             ExceptionInfo exception = (ExceptionInfo)SerializationHelper.Deserialize(resultStream, response.ContentType, typeof(ExceptionInfo));
             string        message   = exception.Message == null && exception.Error != null ? exception.Error.Message : exception.Message;
             throw new ApiException((int)response.StatusCode, message);
         }
         catch (ApiException)
         {
             throw;
         }
         catch (Exception)
         {
             throw new ApiException((int)response.StatusCode, response.StatusDescription);
         }
     }
 }
Пример #4
0
        private static JobList <TDto> DeserializeJobs <TDto>(
            ICollection <_Job> jobs,
            Func <_Job, Job, Dictionary <string, string>, TDto> selector)
        {
            var result = new List <KeyValuePair <string, TDto> >(jobs.Count);

            foreach (var job in jobs)
            {
                var deserializedData = SerializationHelper.Deserialize <Dictionary <string, string> >(job.StateData);
                var stateData        = deserializedData != null
                    ? new Dictionary <string, string>(deserializedData, StringComparer.OrdinalIgnoreCase)
                    : null;

                var dto = selector(job, DeserializeJob(job.InvocationData, job.Arguments), stateData);

                result.Add(new KeyValuePair <string, TDto>(
                               job.Id.ToString(), dto));
            }

            return(new JobList <TDto>(result));
        }
Пример #5
0
        private void RequestToken()
        {
            var requestUrl = _configuration.ApiBaseUrl + "/oauth2/token";

            var postData = "grant_type=client_credentials";

            postData += "&client_id=" + _configuration.ClientId;
            postData += "&client_secret=" + _configuration.ClientSecret;

            var responseString = _apiInvoker.InvokeApi(
                requestUrl,
                "POST",
                postData,
                contentType: "application/x-www-form-urlencoded");

            var result =
                (GetAccessTokenResult)SerializationHelper.Deserialize(responseString, typeof(GetAccessTokenResult));

            _accessToken  = result.AccessToken;
            _refreshToken = result.RefreshToken;
        }
Пример #6
0
    public static void SerializedTestsInSameCollectionRemainInSameCollection()
    {
        var sourceProvider = new NullSourceInformationProvider();
        var assemblyInfo   = Reflector.Wrap(Assembly.GetExecutingAssembly());
        var discoverer     = new XunitTestFrameworkDiscoverer(assemblyInfo, sourceProvider);
        var visitor        = new TestDiscoveryVisitor();

        discoverer.Find(typeof(ClassUnderTest).FullName, false, visitor, new XunitDiscoveryOptions());
        visitor.Finished.WaitOne();

        var first  = visitor.TestCases[0];
        var second = visitor.TestCases[1];

        Assert.True(TestCollectionComparer.Instance.Equals(first.TestCollection, second.TestCollection));

        var serializedFirst  = SerializationHelper.Deserialize <ITestCase>(SerializationHelper.Serialize(first));
        var serializedSecond = SerializationHelper.Deserialize <ITestCase>(SerializationHelper.Serialize(second));

        Assert.NotSame(serializedFirst.TestCollection, serializedSecond.TestCollection);
        Assert.True(TestCollectionComparer.Instance.Equals(serializedFirst.TestCollection, serializedSecond.TestCollection));
    }
        /// <summary>
        ///     Generate image with multiple barcodes and put new file on server
        /// </summary>
        /// <param name="request">Request. <see cref="PutGenerateMultipleRequest" /></param>
        /// <returns>
        ///     <see cref="ResultImageInfo" />
        /// </returns>
        public ResultImageInfo PutGenerateMultiple(PutGenerateMultipleRequest request)
        {
            // verify the required parameter 'name' is set
            if (request.name == null)
            {
                throw new ApiException(400, "Missing required parameter 'name' when calling PutGenerateMultiple");
            }
            // verify the required parameter 'generatorParamsList' is set
            if (request.generatorParamsList == null)
            {
                throw new ApiException(400, "Missing required parameter 'generatorParamsList' when calling PutGenerateMultiple");
            }
            // create path and map variables
            string resourcePath = _configuration.GetApiRootUrl() + "/barcode/{name}/generateMultiple";

            resourcePath = Regex
                           .Replace(resourcePath, "\\*", string.Empty)
                           .Replace("&amp;", "&")
                           .Replace("/?", "?");
            resourcePath = UrlHelper.AddPathParameter(resourcePath, "name", request.name);
            resourcePath = UrlHelper.AddQueryParameterToUrl(resourcePath, "format", request.format);
            resourcePath = UrlHelper.AddQueryParameterToUrl(resourcePath, "folder", request.folder);
            resourcePath = UrlHelper.AddQueryParameterToUrl(resourcePath, "storage", request.storage);


            string postBody = SerializationHelper.Serialize(request.generatorParamsList); // http body (model) parameter
            string response = _apiInvoker.InvokeApi(
                resourcePath,
                "PUT",
                postBody,
                null,
                null);

            if (response != null)
            {
                return((ResultImageInfo)SerializationHelper.Deserialize(response, typeof(ResultImageInfo)));
            }

            return(null);
        }
        /// <summary>
        ///     Recognition of a barcode from file on server with parameters in body.
        /// </summary>
        /// <param name="request">Request. <see cref="PutBarcodeRecognizeFromBodyRequest" /></param>
        /// <returns>
        ///     <see cref="BarcodeResponseList" />
        /// </returns>
        public BarcodeResponseList PutBarcodeRecognizeFromBody(PutBarcodeRecognizeFromBodyRequest request)
        {
            // verify the required parameter 'name' is set
            if (request.name == null)
            {
                throw new ApiException(400, "Missing required parameter 'name' when calling PutBarcodeRecognizeFromBody");
            }
            // verify the required parameter 'readerParams' is set
            if (request.readerParams == null)
            {
                throw new ApiException(400, "Missing required parameter 'readerParams' when calling PutBarcodeRecognizeFromBody");
            }
            // create path and map variables
            string resourcePath = _configuration.GetApiRootUrl() + "/barcode/{name}/recognize";

            resourcePath = Regex
                           .Replace(resourcePath, "\\*", string.Empty)
                           .Replace("&amp;", "&")
                           .Replace("/?", "?");
            resourcePath = UrlHelper.AddPathParameter(resourcePath, "name", request.name);
            resourcePath = UrlHelper.AddQueryParameterToUrl(resourcePath, "type", request.type);
            resourcePath = UrlHelper.AddQueryParameterToUrl(resourcePath, "storage", request.storage);
            resourcePath = UrlHelper.AddQueryParameterToUrl(resourcePath, "folder", request.folder);


            string postBody = SerializationHelper.Serialize(request.readerParams); // http body (model) parameter
            string response = _apiInvoker.InvokeApi(
                resourcePath,
                "PUT",
                postBody,
                null,
                null);

            if (response != null)
            {
                return((BarcodeResponseList)SerializationHelper.Deserialize(response, typeof(BarcodeResponseList)));
            }

            return(null);
        }
        public override JobData GetJobData(string jobId)
        {
            if (jobId == null)
            {
                throw new ArgumentNullException(nameof(jobId));
            }

            using var realm = _storage.GetRealm();
            var jobDto = realm.Find <JobDto>(jobId);

            if (jobDto == null)
            {
                return(null);
            }

            var invocationData = SerializationHelper.Deserialize <InvocationData>(jobDto.InvocationData);

            invocationData.Arguments = jobDto.Arguments;

            Job job = null;
            JobLoadException loadException = null;

            try
            {
                job = invocationData.DeserializeJob();
            }
            catch (JobLoadException ex)
            {
                _logger.WarnException($"Deserializing job {jobId} has failed.", ex);
                loadException = ex;
            }

            return(new JobData
            {
                Job = job,
                State = jobDto.StateName,
                CreatedAt = jobDto.Created.DateTime,
                LoadException = loadException
            });
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="TwitterizerException"/> class.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="innerException">The inner exception.</param>
        public TwitterizerException(string message, Exception innerException) :
            base(message, innerException)
        {
            if (innerException.GetType() == typeof(WebException))
            {
                HttpWebResponse response = (HttpWebResponse)((WebException)innerException).Response;

                if (response == null)
                {
                    return;
                }

                Stream responseStream = response.GetResponseStream();
                if (responseStream == null)
                {
                    return;
                }

                byte[] responseData = ConversionUtility.ReadStream(responseStream);

                this.ResponseBody = Encoding.UTF8.GetString(responseData, 0, responseData.Length);

                this.ParseRateLimitHeaders(response);

                if (response.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
                {
                    this.ErrorDetails = SerializationHelper <TwitterErrorDetails> .Deserialize(responseData, null);
                }
#if !SILVERLIGHT
                else if (response.ContentType.StartsWith("text/xml", StringComparison.OrdinalIgnoreCase))
                {
                    // Try to deserialize as XML (specifically OAuth requests)
                    System.Xml.Serialization.XmlSerializer ds =
                        new System.Xml.Serialization.XmlSerializer(typeof(TwitterErrorDetails));

                    this.ErrorDetails = ds.Deserialize(new MemoryStream(responseData)) as TwitterErrorDetails;
                }
#endif
            }
        }
        public void CreateExpiredJob_CreatesAJobInTheStorage_AndSetsItsParameters()
        {
            UseJobStorageConnectionWithSession((session, jobStorage) =>
            {
                var createdAt = new DateTime(2012, 12, 12);
                var jobId     = jobStorage.CreateExpiredJob(
                    Job.FromExpression(() => SampleMethod("Hello")),
                    new Dictionary <string, string> {
                    { "Key1", "Value1" }, { "Key2", "Value2" }
                },
                    createdAt,
                    TimeSpan.FromDays(1));

                Assert.NotNull(jobId);
                Assert.NotEmpty(jobId);

                var sqlJob = session.Query <_Job>().Single();
                Assert.Equal(jobId, sqlJob.Id.ToString());
                Assert.Equal(createdAt, sqlJob.CreatedAt);
                Assert.Equal(null, sqlJob.StateName);

                var invocationData       = SerializationHelper.Deserialize <InvocationData>(sqlJob.InvocationData);
                invocationData.Arguments = sqlJob.Arguments;

                var job = invocationData.DeserializeJob();
                Assert.Equal(typeof(FluentNHibernateStorageConnectionTests), job.Type);
                Assert.Equal("SampleMethod", job.Method.Name);
                Assert.Equal("\"Hello\"", job.Args[0]);

                Assert.True(createdAt.AddDays(1).AddMinutes(-1) < sqlJob.ExpireAt);
                Assert.True(sqlJob.ExpireAt < createdAt.AddDays(1).AddMinutes(1));

                var parameters = session.Query <_JobParameter>()
                                 .Where(i => i.Job.Id == long.Parse(jobId))
                                 .ToDictionary(x => x.Name, x => x.Value);

                Assert.Equal("Value1", parameters["Key1"]);
                Assert.Equal("Value2", parameters["Key2"]);
            });
        }
Пример #12
0
        public void OnAfterDeserialize()
        {
            m_SourceGraphGuid = SerializationHelper.Deserialize <SerializableGuid>(m_SerializeableSourceGraphGuid, GraphUtil.GetLegacyTypeRemapping());

            var nodes = SerializationHelper.Deserialize <INode>(m_SerializableNodes, GraphUtil.GetLegacyTypeRemapping());

            m_Nodes.Clear();
            foreach (var node in nodes)
            {
                m_Nodes.Add(node);
            }
            m_SerializableNodes = null;

            var edges = SerializationHelper.Deserialize <IEdge>(m_SerializableEdges, GraphUtil.GetLegacyTypeRemapping());

            m_Edges.Clear();
            foreach (var edge in edges)
            {
                m_Edges.Add(edge);
            }
            m_SerializableEdges = null;

            var properties = SerializationHelper.Deserialize <IShaderProperty>(m_SerilaizeableProperties, GraphUtil.GetLegacyTypeRemapping());

            m_Properties.Clear();
            foreach (var property in properties)
            {
                m_Properties.Add(property);
            }
            m_SerilaizeableProperties = null;

            var metaProperties = SerializationHelper.Deserialize <IShaderProperty>(m_SerializableMetaProperties, GraphUtil.GetLegacyTypeRemapping());

            m_MetaProperties.Clear();
            foreach (var metaProperty in metaProperties)
            {
                m_MetaProperties.Add(metaProperty);
            }
            m_SerializableMetaProperties = null;
        }
Пример #13
0
        public Form1()
        {
            InitializeComponent();

            ClearCueInfo();

            string filter = "J-Jax File (*.JJAX)|*.JJAX";

            saveDia.InitialDirectory = @"C:\";
            saveDia.Filter           = filter;

            openDia.InitialDirectory = @"C:\";
            openDia.Filter           = filter;

            openSndDia.InitialDirectory = @"C:\";
            openSndDia.Filter           = "Built Content File (*.xnb)|*.xnb";

            jjaxFile = new JJax();

            jjaxFile.SoundCategories = new List <string>()
            {
                "Background"
            };

            lstCate.Items.Add("Background");

            try
            {
                Crosswalk.Message temp =
                    SerializationHelper.Deserialize <Crosswalk.Message>("Temp", false, ".temp");

                projectFilepath = temp.Messages[0];
                rootPath        = temp.Messages[1];

                saveDia.InitialDirectory    = rootPath + "Content\\";
                openDia.InitialDirectory    = rootPath + "Content\\";
                openSndDia.InitialDirectory = rootPath + "Content\\";
            }
            catch { }
        }
        /// <summary>
        /// Check if storage exists
        /// </summary>
        /// <param name="request">Request. <see cref="StorageExistsRequest" /></param>
        /// <returns><see cref="StorageExist"/></returns>
        public StorageExist StorageExists(StorageExistsRequest request)
        {
            // verify the required parameter 'storageName' is set
            if (request.StorageName == null)
            {
                throw new ApiException(400, "Missing required parameter 'storageName' when calling StorageExists");
            }

            // create path and map variables
            var resourcePath = this.configuration.GetApiRootUrl() + "/classification/storage/{storageName}/exist";

            resourcePath = Regex
                           .Replace(resourcePath, "\\*", string.Empty)
                           .Replace("&amp;", "&")
                           .Replace("/?", "?");
            resourcePath = UrlHelper.AddPathParameter(resourcePath, "storageName", request.StorageName);

            try
            {
                var response = this.apiInvoker.InvokeApi(
                    resourcePath,
                    "GET",
                    null,
                    null,
                    null);
                if (response != null)
                {
                    return((StorageExist)SerializationHelper.Deserialize(response, typeof(StorageExist)));
                }
                return(null);
            }
            catch (ApiException ex)
            {
                if (ex.ErrorCode == 404)
                {
                    return(null);
                }
                throw;
            }
        }
        /// <summary>
        /// Removes the frames associated with uploading a photo from the back stack.
        /// </summary>
        /// <param name="categoryIdNavigatedTo">The category id that was navigated to after photo upload.</param>
        public void RemoveUploadPhotoFramesFromBackStack(string categoryIdNavigatedTo)
        {
            EnsureNavigationFrameIsAvailable();

            var framesToRemove = 0;

            foreach (var frameToTest in _frame.BackStack.Reverse())
            {
                if (IsTypePhotoUploadRelated(frameToTest.SourcePageType))
                {
                    framesToRemove++;
                }
                else
                {
                    // Check if the frame before photo upload began matches the current category stream page
                    if (frameToTest.SourcePageType == typeof(StreamPage))
                    {
                        try
                        {
                            var serializedArgs =
                                SerializationHelper.Deserialize <StreamViewModelArgs>(frameToTest.Parameter.ToString());

                            if (serializedArgs != null && serializedArgs.Category.Id.Equals(categoryIdNavigatedTo))
                            {
                                framesToRemove++;
                            }
                        }
                        catch (SerializationException)
                        {
                            // Swallow exception. Args were of different type than expected.
                        }
                    }

                    // Nothing else should be removed
                    break;
                }
            }

            RemoveBackStackFrames(framesToRemove);
        }
Пример #16
0
        public Form1()
        {
            InitializeComponent();

            saveDia.InitialDirectory = @"C:\";
            saveDia.Title            = "Save File";
            saveDia.Filter           = "3D Paritcle System File (*.Part3D)|*.Part3D";

            openDia.InitialDirectory = @"C:\";
            openDia.Title            = "Browze Files";
            openDia.Filter           = "3D Paritcle System File (*.Part3D)|*.Part3D";

            AssemblyManager.AddAssemblyRef("Eon.Particles");

            info          = new ParticleSystem3DInfo();
            info.Emitters = new EonDictionary <string, ParticleEmitterInfo>();

            try
            {
                temp = SerializationHelper.Deserialize <Crosswalk.Message>("Temp", false, ".temp");

                Type[] extraTypes = new Type[]
                {
                    typeof(ObjectListing),
                    typeof(FrameworkCreation)
                };

                ProjectFile project =
                    SerializationHelper.Deserialize <ProjectFile>(
                        temp.Messages[0], false, "", extraTypes);

                FileSource.Attachments   = project.CreatableObjects.ParticleAttachments;
                FileSource.Cycles        = project.CreatableObjects.ParticleCycles;
                FileSource.EmittionTypes = project.CreatableObjects.ParticleEmitters3D;
                FileSource.RenderTypes   = project.CreatableObjects.ParticleRenderMethods3D;

                FileSource.LoadAssemblies(temp.Messages[1]);
            }
            catch { }
        }
Пример #17
0
        public static CopyObject GetTemplate(DBMS dbms)
        {
            string templateFile = string.Format(@"{0}\config\template.xml", new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).FullName);

            if (File.Exists(templateFile))
            {
                List <CopyObject> templates = SerializationHelper.Deserialize <List <CopyObject> >(templateFile);

                if (templates != null && templates.Count > 0)
                {
                    return(templates.Find(hit => hit.SourceType == dbms));
                }
                else
                {
                    throw new Exception(string.Format("DBMS: {0} not found in {1}", dbms, templateFile));
                }
            }
            else
            {
                throw new Exception(string.Format("File not found: {0}", templateFile));
            }
        }
Пример #18
0
        public void Test()
        {
            UnityConfig.RegisterComponents(container =>
            {
                var factory = container.Resolve <ISessionFactory>();

                container.RegisterType <IWmsEnvironmentInfoProvider, SvcWmsEnvironmentInfoProvider>(new ContainerControlledLifetimeManager());
                container.RegisterType <ILocalData, ThreadStaticLocalData>(new ContainerControlledLifetimeManager());
                WmsEnvironment.Init(container.Resolve <IWmsEnvironmentInfoProvider>(), container.Resolve <ILocalData>());

                using (var session = factory.OpenSession())
                {
                    var qType = session.Query <IoQueueMessageType>().First(i => i.Code == "IP_LOAD_ART");
                    var q     =
                        session.Query <IoQueueIn>()
                        .Where(i => i.QueueMessageType == qType)
                        .OrderBy(i => i.DateIns)
                        .First();
                    var result = SerializationHelper.Deserialize <ArticleLoad>(q.Data);
                }
            });
        }
        public void ProcessRequest(HttpContext context)
        {
            var sb = new StringBuilder();

            if (HttpContext.Current != null && HttpContext.Current.Session != null)
            {
                foreach (string key in HttpContext.Current.Session.Keys)
                {
                    if (true) //key.IndexOf("HttpModuleTest_") == 0)
                    {
                        sb.AppendLine(key + " = " + HttpContext.Current.Session[key]);
                    }
                }

                HttpContext.Current.Session["HttpModuleTestHandler"] = "HttpModuleTestHandler";
            }
            else
            {
                sb.AppendLine("No session");
            }

            var f = System.IO.File.CreateText($"c:\\HttpModuleTest\\{DateTime.Now.ToString("HHmmssfff")}_GenericHandlerSessionCheck.txt");

            f.Write(sb.ToString());
            f.Close();

            var request = SerializationHelper.Deserialize <GenericHandlerRequest>(context.Request["request"], SerializationType.Json);

            var rand = new Random((int)DateTime.Now.Ticks);

            var response = new GenericHandlerResponse()
            {
                SomeRandomInt = rand.Next(request.SomeValue) + 1, //1..SomeValue
                SomeTimestamp = DateTime.Now
            };

            context.Response.ContentType = "application/json";
            context.Response.Write(SerializationHelper.Serialize(response, SerializationType.Json));
        }
Пример #20
0
        public async Task Dispatch(DashboardContext context)
        {
            var servers = context.Storage.GetMonitoringApi().Servers();
            var serverUtilizationViews = new List <ServerView>(servers.Count);

            using (var connection = context.Storage.GetConnection())
            {
                foreach (var serverDto in servers)
                {
                    var key  = Utils.FormatKey(serverDto.Name);
                    var hash = connection.GetAllEntriesFromHash(key);

                    if (hash == null)
                    {
                        continue;
                    }

                    foreach (var hashValue in hash)
                    {
                        var processInfo = SerializationHelper.Deserialize <ProcessInfo>(hashValue.Value);

                        serverUtilizationViews.Add(new ServerView
                        {
                            Name               = $"{serverDto.Name}:{processInfo.Id}",
                            DisplayName        = serverDto.Name,
                            ProcessName        = processInfo.ProcessName,
                            Timestamp          = processInfo.Timestamp.ToUnixTimeMilliseconds(),
                            ProcessId          = processInfo.Id.ToString(CultureInfo.InvariantCulture),
                            CpuUsagePercentage = processInfo.CpuUsage,
                            WorkingMemorySet   = processInfo.WorkingSet
                        });
                    }
                }
            }

            context.Response.ContentType = "application/json";
            var serialized = JsonConvert.SerializeObject(serverUtilizationViews, JsonSerializerSettings);
            await context.Response.WriteAsync(serialized);
        }
Пример #21
0
        public virtual void OnAfterDeserialize()
        {
            // have to deserialize 'globals' before nodes
            m_Properties = SerializationHelper.Deserialize <IShaderProperty>(m_SerializedProperties, GraphUtil.GetLegacyTypeRemapping());

            var nodes = SerializationHelper.Deserialize <INode>(m_SerializableNodes, GraphUtil.GetLegacyTypeRemapping());

            m_Nodes          = new List <AbstractMaterialNode>(nodes.Count);
            m_NodeDictionary = new Dictionary <Guid, INode>(nodes.Count);
            foreach (var node in nodes.OfType <AbstractMaterialNode>())
            {
                node.owner = this;
                node.UpdateNodeAfterDeserialization();
                node.tempId = new Identifier(m_Nodes.Count);
                m_Nodes.Add(node);
                m_NodeDictionary.Add(node.guid, node);

                if (m_GroupNodes.ContainsKey(node.groupGuid))
                {
                    m_GroupNodes[node.groupGuid].Add(node);
                }
                else
                {
                    m_GroupNodes.Add(node.groupGuid, new List <AbstractMaterialNode>()
                    {
                        node
                    });
                }
            }

            m_SerializableNodes = null;

            m_Edges             = SerializationHelper.Deserialize <IEdge>(m_SerializableEdges, GraphUtil.GetLegacyTypeRemapping());
            m_SerializableEdges = null;
            foreach (var edge in m_Edges)
            {
                AddEdgeToNodeEdges(edge);
            }
        }
Пример #22
0
        public byte[] Init(Stream inputStream, string httpMethod, uint user_id)
        {
            byte[] bytes = new byte[inputStream.Length];
            inputStream.Read(bytes, 0, bytes.Length);

            //设置当前流的位置为流的开始
            inputStream.Seek(0, SeekOrigin.Begin);

            object obj = SerializationHelper.Deserialize(NetMessageDef.RequestLogin, bytes);

            protos.Login.RequestLogin requestLogin = new protos.Login.RequestLogin();

            protos.ReturnMessage.ResDefaultInfo resInfo = new protos.ReturnMessage.ResDefaultInfo();

            if (string.IsNullOrEmpty(requestLogin.account))
            {
                resInfo.results = 0;
                resInfo.details = "账号不能为空";
            }
            else if (string.IsNullOrEmpty(requestLogin.password))
            {
                resInfo.results = 0;
                resInfo.details = "密码不能为空";
            }

            Model.Users userModle = new BLL.Users().GetModel(requestLogin.account, requestLogin.password);
            if (userModle != null)
            {
                resInfo.results = 1;
                resInfo.details = userModle.ID.ToString();
            }
            else
            {
                resInfo.results = 0;
                resInfo.details = "账号或密码错误";
            }

            return(SerializationHelper.Serialize(new MuffinMsg(NetMessageDef.ResponseReturnDefaultInfo, resInfo)));
        }
Пример #23
0
        private void RequestToken()
        {
            var requestUrl = this.configuration.ApiBaseUrl + "/connect/token";
            //// var requestUrl = "https://api-qa.groupdocs.cloud/connect/token";

            var postData = "grant_type=client_credentials";

            postData += "&client_id=" + this.configuration.AppSid;
            postData += "&client_secret=" + this.configuration.AppKey;

            var responseString = this.apiInvoker.InvokeApi(
                requestUrl,
                "POST",
                postData,
                contentType: "application/x-www-form-urlencoded");

            var result =
                (GetAccessTokenResult)SerializationHelper.Deserialize(responseString, typeof(GetAccessTokenResult));

            this.accessToken  = result.AccessToken;
            this.refreshToken = result.RefreshToken;
        }
Пример #24
0
        public static object ApplyUnaryTransformer <TKeyI, TPayloadI, TDatasetI, TKeyO, TPayloadO, TDatasetO>(object dataset, string unaryTransformer)
            where TDatasetI : IDataset <TKeyI, TPayloadI>
            where TDatasetO : IDataset <TKeyO, TPayloadO>
        {
            try
            {
                if (unaryTransformer != null)
                {
                    Expression transformer         = SerializationHelper.Deserialize(unaryTransformer);
                    var        compiledTransformer = Expression <Func <TDatasetI, TDatasetO> > .Lambda(transformer).Compile();

                    Delegate compiledTransformerConstructor = (Delegate)compiledTransformer.DynamicInvoke();
                    return(compiledTransformerConstructor.DynamicInvoke((TDatasetI)dataset));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: The CRA vertex failed to apply an unary transformer for an error of type " + e.GetType() + ": " + e.ToString());
            }

            return(null);
        }
        internal static void ThrowApiException(HttpResponseMessage response)
        {
            Exception resutException;

            try
            {
                var responseData  = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                var errorResponse = (WordsApiErrorResponse)SerializationHelper.Deserialize(responseData, typeof(WordsApiErrorResponse));
                if (string.IsNullOrEmpty(errorResponse.Error.Message))
                {
                    errorResponse.Error.Message = responseData;
                }

                resutException = new ApiException((int)response.StatusCode, errorResponse.Error.Message);
            }
            catch (Exception)
            {
                throw new ApiException((int)response.StatusCode, response.ReasonPhrase);
            }

            throw resutException;
        }
Пример #26
0
        /// <summary>
        /// Throws the API exception.
        /// </summary>
        /// <param name="webResponse">The web response.</param>
        /// <param name="resultStream">The result stream.</param>
        /// <exception cref="Aspose.Imaging.Cloud.Sdk.Client.ApiException"></exception>
        private void ThrowApiException(HttpWebResponse webResponse, Stream resultStream)
        {
            Exception resutException;
            string    responseData = null;

            try
            {
                resultStream.Position = 0;
                using (var responseReader = new StreamReader(resultStream))
                {
                    responseData = responseReader.ReadToEnd();
                    var error = (ApiError)SerializationHelper.Deserialize <ApiError>(responseData);
                    resutException = new ApiException((int)webResponse.StatusCode, error.Error.Message, error.Error);
                }
            }
            catch (Exception)
            {
                resutException = new ApiException((int)webResponse.StatusCode, responseData ?? webResponse.StatusDescription);
            }

            throw resutException;
        }
        public void HandlesChangingProcessOfInternalDataSerialization()
        {
            SerializationHelper.SetUserSerializerSettings(SerializerSettingsHelper.DangerousSettings);

            var continuationsJson = SerializationHelper.Serialize(new List <Continuation>
            {
                new Continuation {
                    JobId = "1", Options = JobContinuationOptions.OnAnyFinishedState
                },
                new Continuation {
                    JobId = "3214324", Options = JobContinuationOptions.OnlyOnSucceededState
                }
            }, SerializationOption.User);

            var continuations = SerializationHelper.Deserialize <List <Continuation> >(continuationsJson);

            Assert.Equal(2, continuations.Count);
            Assert.Equal("1", continuations[0].JobId);
            Assert.Equal(JobContinuationOptions.OnAnyFinishedState, continuations[0].Options);
            Assert.Equal("3214324", continuations[1].JobId);
            Assert.Equal(JobContinuationOptions.OnlyOnSucceededState, continuations[1].Options);
        }
Пример #28
0
        public Object SendMessageAndWaitAnswer(Object message)
        {
            if (OnMessageReceiveAndWaitAnserEvent != null)
            {
                String serializedMessage = ( String )message;

                MessagePacket packet = SerializationHelper.Deserialize <MessagePacket>(serializedMessage);

                Object messageObject = null;

                if (packet.message != null)
                {
                    messageObject = SerializationHelper.Deserialize <Object>(packet.message);
                }

                Object result = OnMessageReceiveAndWaitAnserEvent(packet.messageId, messageObject);

                return(SerializationHelper.Serialize(result));
            }

            return(null);
        }
Пример #29
0
        private void ThrowApiException(HttpWebResponse webResponse, Stream resultStream)
        {
            Exception resutException;

            try
            {
                resultStream.Position = 0;
                using (var responseReader = new StreamReader(resultStream))
                {
                    var responseData  = responseReader.ReadToEnd();
                    var errorResponse = (ApiException)SerializationHelper.Deserialize(responseData, typeof(ApiException));

                    resutException = new ApiException((int)webResponse.StatusCode, errorResponse.Message);
                }
            }
            catch (Exception)
            {
                throw new ApiException((int)webResponse.StatusCode, webResponse.StatusDescription);
            }

            throw resutException;
        }
Пример #30
0
        protected override void Configure()
        {
            Mapper.CreateMap <GridConfig, GridConfigViewModel>()
            .AfterMap(
                (s, d) =>
            {
                d.ViewColumns = SerializationHelper.Deserialize <List <ViewColumnViewModel> >(s.XmlText);
                if (d.ViewColumns != null)
                {
                    d.ViewColumns.ForEach(c => c.Text = c.Text ?? string.Empty);
                }
                //enable by default, later may come back to get from config
                d.AllowReorderColumn  = true;
                d.AllowResizeColumn   = true;
                d.AllowShowHideColumn = true;
            });

            Mapper.CreateMap <GridConfigViewModel, GridConfig>()
            .ForMember(x => x.XmlText, opt => opt.Ignore())
            .ForMember(x => x.LastModified, opt => opt.Ignore())
            .AfterMap((s, d) => d.XmlText = SerializationHelper.SerializeToXml(s.ViewColumns));
        }