public void ShouldBeSerializable()
        {
            Exception innerException = new Exception("inner exception message");
            AdapterException exception = new AdapterException(HttpStatusCode.InternalServerError, "exception message", innerException);

            SerializationHelper helper = new SerializationHelper();
            AdapterException deserialized = helper.Roundtrip(exception);

            Assert.AreEqual(exception.StatusCode, deserialized.StatusCode, "The status code was not serialized.");
            Assert.AreEqual(exception.Message, deserialized.Message, "The message was not serialized.");
            Assert.AreEqual(innerException.Message, deserialized.InnerException.Message, "The inner exception was not serialized.");
        }
        public void ShouldBeSerializable()
        {
            Exception innerException = new Exception("Inner Error Message");
            const string message = "Error message";
            ServiceException exception = new ServiceException(message, innerException);

            SerializationHelper helper = new SerializationHelper();
            ServiceException deserialized = helper.Roundtrip(exception);

            Assert.AreEqual(message, deserialized.Message, "The message was not serialized.");
            Assert.AreEqual(innerException.Message, deserialized.InnerException.Message, "The inner exception was not serialized.");
        }
Beispiel #3
0
 /// <summary>
 /// Converts a SSAPBodyBulkReturnMessage collection in a Json string
 /// </summary>
 /// <param name="collection">SSAPBodyBulkReturnMessage collection</param>
 /// <param name="fields">Fields to serialize</param>
 /// <returns>Json string</returns>
 public static string ToJson(ICollection <SSAPBodyBulkReturnMessage> collection, List <string> fields)
 {
     return(SerializationHelper <SSAPBodyBulkReturnMessage> .ToJson(collection, fields));
 }
Beispiel #4
0
 public void CanBeDeserialized(string validJson, Workspace validObject)
 {
     SerializationHelper.CanBeDeserialized(validJson, validObject);
 }
Beispiel #5
0
 public bool Save()
 {
     return(SerializationHelper.Save(this, GetType(), null));
 }
Beispiel #6
0
 /// <summary>
 /// Deserialize response object.
 /// </summary>
 /// <param name="message">Response message.</param>
 /// <returns>Response type.</returns>
 public object DeserializeResponse(HttpResponseMessage message)
 {
     return(SerializationHelper.Deserialize(message.Content.ReadAsStringAsync().GetAwaiter().GetResult(), typeof(DrawingObjectResponse)));
 }
Beispiel #7
0
        public void DataAccess()
        {
            //add two new items
            var item1 = new CacheableTypeOk(1, 1001, "aaa", new DateTime(2010, 10, 10), 1500);

            _client.Put(item1);

            var item2 = new CacheableTypeOk(2, 1002, "aaa", new DateTime(2010, 10, 10), 1600);

            _client.Put(item2);

            var item3 = new CacheableTypeOk(3, 1003, "bbb", new DateTime(2010, 10, 10), 1600);

            _client.Put(item3);

            {
                _logger.Reset();
                var cmd = _parser.Parse("count CacheableTypeOk where IndexKeyFolder=aaa");
                Assert.IsTrue(cmd.CanExecute);
                Assert.IsNotNull(cmd.TryExecute(_client));
                var response = _logger.Buffer;

                var items = ExtractOne(@"\s*found\s*([0-9]*?)\s*items", response);
                Assert.AreEqual(items, "2");
            }

            {
                _logger.Reset();
                var cmd = _parser.Parse("select CacheableTypeOk where IndexKeyValue > 1000");
                Assert.IsTrue(cmd.CanExecute);
                Assert.NotNull(cmd.TryExecute(_client));
                var response = _logger.Buffer;


                // check that the response is valid json array

                var objects = SerializationHelper.DeserializeJson <List <CacheableTypeOk> >(response);

                Assert.AreEqual(3, objects.Count);
            }

            {
                _logger.Reset();
                var cmd = _parser.Parse("count CacheableTypeOk where IndexKeyFolder=bbb");
                Assert.IsTrue(cmd.CanExecute);
                Assert.IsNotNull(cmd.TryExecute(_client));
                var response = _logger.Buffer;

                var items = ExtractOne(@"\s*found\s*([0-9]*?)\s*items", response);
                Assert.AreEqual(items, "1");
            }

            {
                _logger.Reset();
                var cmd = _parser.Parse("delete CacheableTypeOk where IndexKeyFolder=bbb");
                Assert.IsTrue(cmd.CanExecute);
                Assert.IsNotNull(cmd.TryExecute(_client));
                var response = _logger.Buffer;

                var items = ExtractOne(@"\s*deleted\s*([0-9]*?)\s*item", response);
                Assert.AreEqual(items, "1");
            }

            {
                _logger.Reset();
                var cmd = _parser.Parse("count CacheableTypeOk where IndexKeyFolder=bbb");
                Assert.IsTrue(cmd.CanExecute);
                Assert.IsNotNull(cmd.TryExecute(_client));
                var response = _logger.Buffer;

                var items = ExtractOne(@"\s*found\s*([0-9]*?)\s*items", response);
                Assert.AreEqual(items, "0");
            }

            {
                _logger.Reset();
                var cmd = _parser.Parse("delete CacheableTypeOk where IndexKeyFolder=aaa");
                Assert.IsTrue(cmd.CanExecute);
                Assert.IsNotNull(cmd.TryExecute(_client));
                var response = _logger.Buffer;

                var items = ExtractOne(@"\s*deleted\s*([0-9]*?)\s*item", response);
                Assert.AreEqual(items, "2");
            }

            {
                var item = new CacheableTypeOk(3, 1003, "bbb", new DateTime(2010, 10, 10), 1600);
                _client.Put(item);

                _logger.Reset();
                var cmd = _parser.Parse("truncate CacheableTypeOk");
                Assert.IsTrue(cmd.CanExecute);
                Assert.IsNotNull(cmd.TryExecute(_client));
                var response = _logger.Buffer;
                Assert.IsTrue(response.Contains("Deleted 1 items."));
            }


            GetServerInfo();
        }
Beispiel #8
0
 /// <summary>
 /// INTERNAL METHOD, FOR TESTING PURPOSES ONLY. DO NOT CALL.
 /// </summary>
 protected string Serialize(Xunit1TestCase testCase) =>
 SerializationHelper.Serialize(testCase);
 public void Base64ToByteArray()
 {
     string base64EncodedData  = "DmVvc2lvOjphYmkvMS4wAQxhY2NvdW50X25hbWUEbmFtZQcIdHJhbnNmZXIABARmcm9tDGFjY291bnRfbmFtZQJ0bwxhY2NvdW50X25hbWUIcXVhbnRpdHkFYXNzZXQEbWVtbwZzdHJpbmcGY3JlYXRlAAIGaXNzdWVyDGFjY291bnRfbmFtZQ5tYXhpbXVtX3N1cHBseQVhc3NldAVpc3N1ZQADAnRvDGFjY291bnRfbmFtZQhxdWFudGl0eQVhc3NldARtZW1vBnN0cmluZwZyZXRpcmUAAghxdWFudGl0eQVhc3NldARtZW1vBnN0cmluZwVjbG9zZQACBW93bmVyDGFjY291bnRfbmFtZQZzeW1ib2wGc3ltYm9sB2FjY291bnQAAQdiYWxhbmNlBWFzc2V0DmN1cnJlbmN5X3N0YXRzAAMGc3VwcGx5BWFzc2V0Cm1heF9zdXBwbHkFYXNzZXQGaXNzdWVyDGFjY291bnRfbmFtZQUAAABXLTzNzQh0cmFuc2ZlcucFIyMgVHJhbnNmZXIgVGVybXMgJiBDb25kaXRpb25zCgpJLCB7e2Zyb219fSwgY2VydGlmeSB0aGUgZm9sbG93aW5nIHRvIGJlIHRydWUgdG8gdGhlIGJlc3Qgb2YgbXkga25vd2xlZGdlOgoKMS4gSSBjZXJ0aWZ5IHRoYXQge3txdWFudGl0eX19IGlzIG5vdCB0aGUgcHJvY2VlZHMgb2YgZnJhdWR1bGVudCBvciB2aW9sZW50IGFjdGl2aXRpZXMuCjIuIEkgY2VydGlmeSB0aGF0LCB0byB0aGUgYmVzdCBvZiBteSBrbm93bGVkZ2UsIHt7dG99fSBpcyBub3Qgc3VwcG9ydGluZyBpbml0aWF0aW9uIG9mIHZpb2xlbmNlIGFnYWluc3Qgb3RoZXJzLgozLiBJIGhhdmUgZGlzY2xvc2VkIGFueSBjb250cmFjdHVhbCB0ZXJtcyAmIGNvbmRpdGlvbnMgd2l0aCByZXNwZWN0IHRvIHt7cXVhbnRpdHl9fSB0byB7e3RvfX0uCgpJIHVuZGVyc3RhbmQgdGhhdCBmdW5kcyB0cmFuc2ZlcnMgYXJlIG5vdCByZXZlcnNpYmxlIGFmdGVyIHRoZSB7e3RyYW5zYWN0aW9uLmRlbGF5fX0gc2Vjb25kcyBvciBvdGhlciBkZWxheSBhcyBjb25maWd1cmVkIGJ5IHt7ZnJvbX19J3MgcGVybWlzc2lvbnMuCgpJZiB0aGlzIGFjdGlvbiBmYWlscyB0byBiZSBpcnJldmVyc2libHkgY29uZmlybWVkIGFmdGVyIHJlY2VpdmluZyBnb29kcyBvciBzZXJ2aWNlcyBmcm9tICd7e3RvfX0nLCBJIGFncmVlIHRvIGVpdGhlciByZXR1cm4gdGhlIGdvb2RzIG9yIHNlcnZpY2VzIG9yIHJlc2VuZCB7e3F1YW50aXR5fX0gaW4gYSB0aW1lbHkgbWFubmVyLgoAAAAAAKUxdgVpc3N1ZQAAAAAAqGzURQZjcmVhdGUAAAAAAKjrsroGcmV0aXJlAAAAAAAAhWlEBWNsb3NlAAIAAAA4T00RMgNpNjQBCGN1cnJlbmN5AQZ1aW50NjQHYWNjb3VudAAAAAAAkE3GA2k2NAEIY3VycmVuY3kBBnVpbnQ2NA5jdXJyZW5jeV9zdGF0cwAAAA===";
     var    base64EncodedBytes = SerializationHelper.Base64FcStringToByteArray(base64EncodedData);
 }
 public void CanBeDeserialized()
 {
     SerializationHelper.CanBeDeserialized(validJson, validObject);
 }
 /// <summary>
 /// Deserialize the response from the Configuration Server
 /// </summary>
 /// <param name="stream">the stream representing the response from the Configuration Server</param>
 /// <returns>The ConfigEnvironment object representing the response from the server</returns>
 protected internal virtual ConfigEnvironment Deserialize(Stream stream)
 {
     return(SerializationHelper.Deserialize <ConfigEnvironment>(stream, _logger));
 }
Beispiel #12
0
 public void CanBeSerialized()
 {
     SerializationHelper.CanBeSerialized(validJson, validClient);
 }
Beispiel #13
0
 /// <summary>
 ///  读取站点配置文件
 /// </summary>
 public Model.userconfig loadConfig(string configFilePath)
 {
     return((Model.userconfig)SerializationHelper.Load(typeof(Model.userconfig), configFilePath));
 }
Beispiel #14
0
 public void SerializeAchievements()
 {
     AchievementCollectionString = SerializationHelper.SerializeData(NumericAchievementCollection);
     TotalTimePlayedString       = TotalTimePlayed.ToString();
 }
Beispiel #15
0
        public void GetTypeFromHeader_NoHeader_NullReturned()
        {
            var type = SerializationHelper.GetTypeFromHeaders(new MessageHeaderCollection());

            type.Should().BeNull();
        }
		public UnicornDumpItemCommand(SerializationHelper helper)
		{
			_helper = helper;
		}
Beispiel #17
0
        /// <summary>
        /// </summary>
        /// <param name="signedData"></param>
        /// <param name="chainValidate">Проверять цепочку сертификатов на отозванные сертификаты</param>
        /// <returns></returns>
        public bool VerifyN3Gost(string signedData, bool chainValidate = false)
        {
            var x509 = new X509Certificate2();

            var signData = new SerializationHelper<SignData>().Deserialize(signedData);
            var cspBlob = Convert.FromBase64String(signData.public_key);
            x509.Import(cspBlob);
            if (chainValidate) {
                var chain = new X509Chain
                            {
                                ChainPolicy =
                                {
                                    RevocationFlag = X509RevocationFlag.EntireChain,
                                    RevocationMode = X509RevocationMode.Online,
                                    VerificationFlags = X509VerificationFlags.NoFlag
                                }
                            };
                var verify = chain.Build(x509);
                if (!verify) return false;
            }

            var hash = Md5Helper.GetGost3411Hash(signData.data);
            var sign = Convert.FromBase64String(signData.sign);

            var rsaDeformatter = new GostSignatureDeformatter(x509.PublicKey.Key);
            rsaDeformatter.SetHashAlgorithm("Gost3411");

            return rsaDeformatter.VerifySignature(hash, sign);
        }
        /// <summary>
        /// Processes buffer data
        /// </summary>
        protected virtual void ProcessBuffer()
        {
            var handBuilder = ServiceLocator.Current.GetInstance <IPokerBaaziHandBuilder>();
            var windows     = new Dictionary <uint, IntPtr>();

            while (!cancellationTokenSource.IsCancellationRequested)
            {
                try
                {
                    if (!packetBuffer.TryTake(out string capturedData))
                    {
                        Task.Delay(NoDataDelay).Wait();
                        continue;
                    }

                    if (!PokerBaaziPackage.TryParse(capturedData, out PokerBaaziPackage package))
                    {
                        continue;
                    }

                    var windowHandle = IntPtr.Zero;

                    if (package.PackageType == PokerBaaziPackageType.InitResponse)
                    {
                        var windowsToRemove = windows.Where(x => !WinApi.IsWindow(x.Value)).ToArray();
                        windowsToRemove.ForEach(x => windows.Remove(x.Key));
                    }

                    // Get window related to the package
                    if (package.RoomId != 0 && !windows.TryGetValue(package.RoomId, out windowHandle))
                    {
                        var windowsToRemove = windows.Where(x => !WinApi.IsWindow(x.Value)).ToArray();
                        windowsToRemove.ForEach(x => windows.Remove(x.Key));

                        var initResponse = handBuilder.FindInitResponse(package.RoomId);

                        if (initResponse != null)
                        {
                            var existingWindows = new HashSet <IntPtr>(windows.Values);

                            windowHandle = FindWindow(initResponse, existingWindows);

                            if (windowHandle != IntPtr.Zero)
                            {
                                windows.Add(package.RoomId, windowHandle);

                                Task.Run(() =>
                                {
                                    Task.Delay(ShowPreHUDDelay).Wait();
                                    SendPreImporedData("Notifications_HudLayout_PreLoadingText_PB", windowHandle);
                                });
                            }
                        }
                    }

                    if (!handBuilder.TryBuild(package, out HandHistory handHistory, out PokerBaaziHandBuilderError builderError))
                    {
                        if (builderError == PokerBaaziHandBuilderError.TournamentDetailsNotFound &&
                            windowHandle != IntPtr.Zero)
                        {
                            Task.Run(() =>
                            {
                                Task.Delay(ShowPreHUDDelay).Wait();
                                SendPreImporedData("Notifications_HudLayout_PreLoadingText_NoTournamentDetails", windowHandle);
                            });
                        }

                        continue;
                    }

                    var handHistoryText = SerializationHelper.SerializeObject(handHistory);

#if DEBUG
                    if (!Directory.Exists("Hands"))
                    {
                        Directory.CreateDirectory("Hands");
                    }

                    File.WriteAllText($"Hands\\pokerbaazi_hand_exported_{handHistory.HandId}.xml", handHistoryText);
#endif

                    var gameInfo = new GameInfo
                    {
                        WindowHandle = windowHandle.ToInt32(),
                        PokerSite    = EnumPokerSites.PokerBaazi,
                        GameNumber   = handHistory.HandId,
                        Session      = windowHandle.ToString()
                    };

                    ProcessHand(handHistoryText, gameInfo);
                }
                catch (Exception e)
                {
                    LogProvider.Log.Error(this, $"Could not process captured data. [{SiteString}]", e);
                }
            }
        }
Beispiel #19
0
 /// <summary>
 /// INTERNAL METHOD, FOR TESTING PURPOSES ONLY. DO NOT CALL.
 /// </summary>
 protected Xunit1TestCase?Deserialize(string value) =>
 SerializationHelper.Deserialize <Xunit1TestCase>(value);
Beispiel #20
0
 public void Serialize(StateMap sd, SerializationHelper helper)
 {
     sd.Set(nameof(_curr), _curr);
     sd.Set(nameof(_folder), _folder);
 }
        public static void CannotRoundTripTypesFromTheGAC()
        {
            var ex = Assert.Throws <ArgumentException>("type", () => SerializationHelper.GetTypeNameForSerialization(typeof(Uri)));

            Assert.StartsWith("We cannot serialize type System.Uri because it lives in the GAC", ex.Message);
        }
Beispiel #22
0
 public void Serialize(StateMap sd, SerializationHelper helper)
 {
 }
 public override void OnBeforeSerialize()
 {
     base.OnBeforeSerialize();
     m_SerializableSubShaders = SerializationHelper.Serialize<T>(m_SubShaders);
 }
Beispiel #24
0
 public void Serialize(StateMap sd, SerializationHelper helper)
 {
     sd.Set(nameof(_any), _any);
     sd.Set(nameof(_currentMax), _currentMax);
 }
Beispiel #25
0
 public static Ticker FromFile(string fileName, Type tickerType)
 {
     return((Ticker)SerializationHelper.FromFile(fileName, tickerType));
 }
Beispiel #26
0
 public void Serialize(StateMap sd, SerializationHelper helper) => sd.Set(nameof(_count), _count);
Beispiel #27
0
 public bool Load()
 {
     return(SerializationHelper.Load(this, GetType()));
 }
Beispiel #28
0
 public override void Serialize(StateMap sd, SerializationHelper helper)
 => sd.Set(nameof(_inner), _inner);
Beispiel #29
0
        private void ProcessQueue(DataTable q, int siteId, string indexPath)
        {
            rowsProcessed = 0;
            rowsToProcess = q.Rows.Count;

            // first process deletes with reader
            try
            {
                using (Lucene.Net.Store.Directory searchDirectory = IndexHelper.GetDirectory(siteId))
                {
                    using (IndexReader reader = IndexReader.Open(searchDirectory, false))
                    {
                        foreach (DataRow row in q.Rows)
                        {
                            Term term = new Term("Key", row["ItemKey"].ToString());
                            try
                            {
                                reader.DeleteDocuments(term);
                                log.Debug("reader.DeleteDocuments(term) for Key " + row["ItemKey"].ToString());
                            }
                            catch (Exception ge)
                            {
                                // TODO: monitor what real exceptions if any occur and then
                                // change this catch to catch only the expected ones
                                // instead of non specific exception
                                log.Error(ge);
                            }

                            bool removeOnly = Convert.ToBoolean(row["RemoveOnly"]);
                            if (removeOnly)
                            {
                                Int64 rowId = Convert.ToInt64(row["RowId"]);
                                IndexingQueue.Delete(rowId);
                            }


                            if (DateTime.UtcNow > nextStatusUpdateTime)
                            {
                                // don't mark as complete because there may be more qu items
                                //for different index paths in a multi site installation
                                bool markAsComplete = false;
                                ReportStatus(markAsComplete);
                            }
                        }
                    }
                }
            }
            catch (System.IO.IOException ex)
            {
                log.Info("IndexWriter swallowed exception this is expected if building or rebuilding the search index ", ex);
                errorCount += 1;
            }
            catch (TypeInitializationException ex)
            {
                log.Info("IndexWriter swallowed exception ", ex);
                errorCount += 1;
            }


            // next add items with writer
            using (Lucene.Net.Store.Directory searchDirectory = IndexHelper.GetDirectory(siteId))
            {
                using (IndexWriter indexWriter = GetWriter(siteId, searchDirectory))
                {
                    if (indexWriter == null)
                    {
                        log.Error("failed to get IndexWriter for path: " + indexPath);
                        errorCount += 1;
                        return;
                    }

                    foreach (DataRow row in q.Rows)
                    {
                        bool removeOnly = Convert.ToBoolean(row["RemoveOnly"]);
                        if (!removeOnly)
                        {
                            try
                            {
                                IndexItem indexItem
                                    = (IndexItem)SerializationHelper.DeserializeFromString(typeof(IndexItem), row["SerializedItem"].ToString());
                                // if the content is locked down to only admins it is a special case
                                // we just won't add it to the search index
                                // because at search time we avoid the role check for all admins, content admins and siteeditors
                                // we don't have a good way to prevent content admins and site editors from seeing the content
                                // in search
                                if ((indexItem.ViewRoles != "Admins;") && (indexItem.ModuleViewRoles != "Admins;"))
                                {
                                    if (indexItem.ViewPage.Length > 0)
                                    {
                                        Document doc = GetDocument(indexItem);
                                        WriteToIndex(doc, indexWriter);
                                        log.Debug("called WriteToIndex(doc, indexWriter) for key " + indexItem.Key);
                                    }
                                }

                                Int64 rowId = Convert.ToInt64(row["RowId"]);
                                IndexingQueue.Delete(rowId);
                            }
                            catch (Exception ex)
                            {
                                log.Error(ex);
                            }
                        }

                        if (DateTime.UtcNow > nextStatusUpdateTime)
                        {
                            // don't mark as complete because there may be more qu items
                            //for different index paths in a multi site installation
                            bool markAsComplete = false;
                            ReportStatus(markAsComplete);
                        }
                    }

                    try
                    {
                        indexWriter.Optimize();
                    }
                    catch (System.IO.IOException ex)
                    {
                        log.Error(ex);
                    }
                }
            }
        }
        private static void OnVerify(object state)
        {
            mDetectionTimer.Change(-1, -1);
            if (string.IsNullOrEmpty(ProcessMonitor.CurrentServerId))
            {
                mDetectionTimer.Change(1000 * 1, 1000 * 1);
                return;
            }

            try
            {
                using (var connection = JobStorage.Current.GetConnection())
                {
                    //拿到所有的周期性job
                    var jobagentServerList = new Dictionary <string, Tuple <string, string, string> >();
                    var jobList            = connection.GetRecurringJobs();
                    foreach (var job in jobList)
                    {
                        var httpJob = job.Job.Args.FirstOrDefault() as HttpJobItem;
                        //只处理agentjob
                        if (httpJob == null || string.IsNullOrEmpty(httpJob.AgentClass))
                        {
                            continue;
                        }
                        var key = httpJob.GetUrlHost();
                        if (!jobagentServerList.ContainsKey(key))
                        {
                            jobagentServerList.Add(key, new Tuple <string, string, string>(httpJob.Url, httpJob.BasicUserName, httpJob.BasicPassword));
                        }
                    }

                    if (!jobagentServerList.Any())
                    {
                        return;
                    }
                    IWriteOnlyTransaction writeTransaction = null;
                    if (!isInit)
                    {
                        writeTransaction = connection.CreateWriteTransaction();
                    }
                    var index = 1;
                    foreach (var jobagent in jobagentServerList)
                    {
                        if (!isInit)
                        {
                            var data = new ProcessInfo
                            {
                                Id          = index,
                                Server      = jobagent.Key,
                                ProcessName = "waiting...",
                                CpuUsage    = 0.0,
                                WorkingSet  = 0,
                                Timestamp   = DateTimeOffset.UtcNow.AddMinutes(-2)
                            };
                            var values = new Dictionary <string, string>
                            {
                                [jobagent.Key] = SerializationHelper.Serialize(data)
                            };
                            writeTransaction?.SetRangeInHash("AgentHeart:" + ProcessMonitor.CurrentServerId, values);
                            index++;
                        }
                        new Task(async() =>
                        {
                            await SendHeartbeat(jobagent.Key, jobagent.Value.Item1, jobagent.Value.Item2, jobagent.Value.Item3);
                        }).Start();
                    }

                    if (!isInit)
                    {
                        isInit = true;
                        // if storage supports manual expiration handling
                        if (writeTransaction is JobStorageTransaction jsTransaction)
                        {
                            jsTransaction.ExpireHash("AgentHeart:" + ProcessMonitor.CurrentServerId, TimeSpan.FromMinutes(1));
                        }
                        writeTransaction?.Commit();
                        writeTransaction?.Dispose();
                    }
                }
            }
            catch
            {
                // ignored
            }
            finally
            {
                mDetectionTimer.Change(1000 * 5, 1000 * 5);
            }
        }
Beispiel #31
0
        /// <summary>
        /// Creates a SSAPBodyBulkReturnMessage instance with the given json string.
        /// </summary>
        /// <param name="json">Json string</param>
        /// <returns>A SSAPBodyBulkReturnMessage instance</returns>
        public static SSAPBodyBulkReturnMessage FromJson(string json)
        {
            return(SerializationHelper <SSAPBodyBulkReturnMessage> .FromJson(json, new JsonSSAPBodyBulkReturnMessageConverter()));

            //return SerializationHelper<SSAPBodyBulkReturnMessage>.FromJson(json);
        }
        /// <summary>
        /// 给agent发送命令后 agent自己会上报数据到storage的
        /// </summary>
        /// <returns></returns>
        private static async Task SendHeartbeat(string agentKey, string url, string basicUserName, string basicPassword)
        {
            var agentServerId = string.Empty;

            try
            {
                var stroageString = HttpJob.GetJobStorage().Value;
                if (string.IsNullOrEmpty(stroageString))
                {
                    return;
                }

                HttpClient client  = HangfireHttpClientFactory.Instance.GetHttpClient(url);
                var        request = new HttpRequestMessage(new HttpMethod("Post"), url);
                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                if (!string.IsNullOrEmpty(basicUserName) && !string.IsNullOrEmpty(basicPassword))
                {
                    var byteArray = Encoding.ASCII.GetBytes(basicUserName + ":" + basicPassword);
                    request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
                }
                request.Headers.Add("x-job-storage", Convert.ToBase64String(Encoding.UTF8.GetBytes(stroageString)));
                request.Headers.Add("x-job-agent-action", "heartbeat");
                var uri = new Uri(url);
                request.Headers.Add("x-job-agent-server", uri.Host + ":" + uri.Port);
                if (!string.IsNullOrEmpty(ProcessMonitor.CurrentServerId))
                {
                    request.Headers.Add("x-job-server", Convert.ToBase64String(Encoding.UTF8.GetBytes(ProcessMonitor.CurrentServerId)));
                }
                var cancelToken = new CancellationTokenSource(TimeSpan.FromSeconds(5));

                var content = await client.SendAsync(request, cancelToken.Token);

                //jobagent的话 在header里面有一个agentServerId
                agentServerId = content.Headers.GetValues("agentServerId").FirstOrDefault() ?? "";
            }
            catch (Exception e)
            {
                //ignore agent挂了就到这
                Logger.ErrorException("send agent heartbeat fail,agent:" + url, e);
            }

            try
            {
                using (var connection = JobStorage.Current.GetConnection())
                    using (var writeTransaction = connection.CreateWriteTransaction())
                    {
                        var values = new Dictionary <string, string>
                        {
                            [agentKey] = SerializationHelper.Serialize(new { id = agentServerId, time = DateTime.UtcNow })
                        };
                        var hashKey = "activeAgent:" + agentKey;
                        writeTransaction.SetRangeInHash(hashKey, values);
                        if (writeTransaction is JobStorageTransaction jsTransaction)
                        {
                            jsTransaction.ExpireHash(hashKey, TimeSpan.FromDays(1));
                        }
                        writeTransaction.Commit();
                    }
            }
            catch (Exception e)
            {
                //ignore
                Logger.ErrorException("get agent heartbeat fail", e);
            }
        }
		public UnicornLoadTreeCommand(SerializationHelper helper)
		{
			_helper = helper;
		}
        /// <summary>
        /// 获取agent服务器列表
        /// </summary>
        /// <returns></returns>
        internal static string GetAgentServerListHtml(string baseUrl)
        {
            //拿到所有的周期性job
            var jobagentServerList = new Dictionary <string, ServerView>();

            using (var connection = JobStorage.Current.GetConnection())
            {
                var jobList = connection.GetRecurringJobs();
                foreach (var job in jobList)
                {
                    var httpJob = job.Job.Args.FirstOrDefault() as HttpJobItem;
                    //只处理agentjob
                    if (httpJob == null || string.IsNullOrEmpty(httpJob.AgentClass))
                    {
                        continue;
                    }
                    var key = httpJob.GetUrlHost();
                    if (!jobagentServerList.ContainsKey(key))
                    {
                        jobagentServerList.Add(key, new ServerView
                        {
                            Name        = key,//服务器
                            Error       = true,
                            Timestamp   = 1,
                            ProcessName = "waiting"//最后心跳时间
                        });
                    }
                    else
                    {
                        jobagentServerList[key].Timestamp++;//job的数量
                    }
                }

                if (!jobagentServerList.Any())
                {
                    return("");
                }
                if (!string.IsNullOrEmpty(ProcessMonitor.CurrentServerId))
                {
                    //获取jobagent的心跳包
                    var agentList = connection.GetAllEntriesFromHash("AgentHeart:" + ProcessMonitor.CurrentServerId);
                    if (agentList != null)
                    {
                        foreach (var agent in agentList)
                        {
                            var processInfo = SerializationHelper.Deserialize <ProcessInfo>(agent.Value);
                            if (!jobagentServerList.TryGetValue(agent.Key, out var view))
                            {
                                continue;
                            }

                            view.DisplayName = view.Timestamp + "";
                            view.Timestamp   = processInfo.Timestamp.ToUnixTimeSeconds();
                            view.Error       = ((DateTimeOffset.UtcNow - processInfo.Timestamp).TotalSeconds > 10);
                            view.ProcessName = processInfo.Timestamp.ToString("yyyy/MM/dd HH:mm:ss");
                        }
                    }
                }
            }
            //<span class=\"glyphicon glyphicon-ok text-success\" title=\"Active\"></span>\n"

            var rowTemplete = @"<tr>" +
                              "                                        <td>\n" +
                              "                                            @ERROR@" +
                              "                                            <span class='labe label-defult text-uppercase' ><a href='@Url' target='_blank'>@SERVER@</a></span>\n" +
                              "                                        </td>\n" +
                              "                                        <td>\n" +
                              "                                           @JOBCOUNT@" +
                              "                                        </td>\n" +
                              "                                        <td>\n" +
                              "                                            <span data-moment='@Timestamp@'>@TimeString@</span>\n" +
                              "                                        </td>\n" +
                              "                                    </tr>\n";

            var html = " <div class=\"col-md-12\">" +
                       "                        <h1 class=\"page-header\">Agent</h1>" +
                       "                        <div class=\"table-responsive\">\n" +
                       "                            <table class=\"table\">\n" +
                       "                                <thead>\n" +
                       "                                    <tr>\n" +
                       "                                        <th>" + Strings.AgentServer + "</th>\n" +
                       "                                        <th>" + Strings.AgentJobCount + "</th>\n" +
                       "                                        <th>" + Strings.AgentServerBeat + "</th>\n" +
                       "                                    </tr>\n" +
                       "                                </thead>\n" +
                       "                                <tbody>\n@TEMP@" +
                       "                                </tbody>" +
                       "                            </table>" +
                       "                        </div>" +
                       "                    </div>";

            var htmlList = new List <string>();

            foreach (var agentDetail in jobagentServerList)
            {
                var agent     = agentDetail.Value;
                var agentInfo = rowTemplete.Replace("@ERROR@",
                                                    "<span class='glyphicon " +
                                                    (agent.Error ? "glyphicon-remove text-danger" : "glyphicon-ok text-success") + "' title'" +
                                                    (agent.Error ? "Waiting" : "Active") + "'></span>")
                                .Replace("@SERVER@", agent.Name)
                                .Replace("@Url", baseUrl + "/recurring?search=name:" + agent.Name)
                                .Replace("@JOBCOUNT@", agent.DisplayName + "")
                                .Replace("@Timestamp@", agent.Timestamp + "")
                                .Replace("@TimeString@", agent.ProcessName);

                htmlList.Add(agentInfo);
            }
            return(html.Replace("@TEMP@", string.Join("\n", htmlList)));
        }
Beispiel #35
0
        public bool VerifyN3Rsa(string signedData)
        {
            var signData = new SerializationHelper<SignData>().Deserialize(signedData);
            var cspBlob = Convert.FromBase64String(signData.public_key);
            var hash = Md5Helper.GetMd5Hash(signData.data);
            var sign = Convert.FromBase64String(signData.sign);

            var key = new RSACryptoServiceProvider();
            key.ImportCspBlob(cspBlob);

            var rsaDeformatter = new RSAPKCS1SignatureDeformatter(key);
            rsaDeformatter.SetHashAlgorithm("MD5");

            return rsaDeformatter.VerifySignature(hash, sign);
        }
Beispiel #36
0
 /// <summary>
 /// 页面初始化
 /// </summary>
 static AdminPage( )
 {
     //加载页面代码
     pagePowerList = SerializationHelper.Deserialize(typeof(List <ModulePage>), TextUtility.GetRealPath("/config/power.config")) as List <ModulePage>;
 }