예제 #1
0
 private void Upload(List <SampleCode> codes)
 {
     try
     {
         using (ServiceStack.Redis.RedisClient client = new ServiceStack.Redis.RedisClient(_ip, _port))
         {
             if (client.Ping())
             {
                 //using (var trans = client.CreatePipeline())
                 //{
                 //    for (int i = 0; i < codes.Count; i++)
                 //    {
                 //        String value = Newtonsoft.Json.JsonConvert.SerializeObject(codes[i]);
                 //        trans.QueueCommand(r => r.AddItemToList(_Channel, value));
                 //    }
                 //    trans.Flush();
                 //}
                 for (int i = 0; i < codes.Count; i++)
                 {
                     HNCAPI.Data.HncMessage <SampleCode> msg = new HncMessage <SampleCode>();
                     msg.Header = "SampleData";
                     msg.Body   = codes[i];
                     String message = Newtonsoft.Json.JsonConvert.SerializeObject(msg);
                     client.PublishMessage(_Channel, message);
                 }
             }
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine("publish Upload:" + ex.Message);
     }
 }
예제 #2
0
        public RedisContext(string connectionString)
        {
            this.innerContext = new ServiceStack.Redis.RedisClient(new Uri(connectionString));
            var entitySets = new List <IEntitySet>();

            var entitySetProperties =
                this.GetType().GetProperties()
                .Where(p => p.PropertyType.IsGenericType &&
                       (p.PropertyType.GetGenericTypeDefinition() == typeof(IEntitySet <,>) ||
                        p.PropertyType.GetGenericTypeDefinition() == typeof(EntitySet <,>)
                       ));

            foreach (var prop in entitySetProperties)
            {
                var keyType    = prop.PropertyType.GetGenericArguments()[0];
                var entityType = prop.PropertyType.GetGenericArguments()[1];

                var createEntitySetMethod = typeof(EntitySet <,>).MakeGenericType(new[] { keyType, entityType })
                                            .GetConstructor(
                    System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic,
                    null, new[] { typeof(RedisContext) }, null);

                var entitySet = createEntitySetMethod.Invoke(new object[] { this });
                prop.SetValue(this, entitySet, null);

                entitySets.Add(entitySet as IEntitySet);
            }

            this.entitySets = entitySets;
        }
예제 #3
0
        static void Main(string[] args)
        {
            //var dbs = DB.GetDatabases("127.0.0.1:6379");
            //Console.WriteLine(dbs.Length);

            redis = ServiceStack.Redis.RedisClient.New();
            Run().Wait();
            
        }
예제 #4
0
        public void Read()
        {
            System.IO.StreamReader reader = null;
            try
            {
                if (System.IO.File.Exists(_FileName) == false)
                {
                    return;
                }
                if (!IsTextFile())
                {
                    return;
                }
                String MacSN = _mac.MachineSN;
                if (String.IsNullOrEmpty(MacSN))
                {
                    return;
                }
                reader = new System.IO.StreamReader(_FileName);
                ServiceStack.Redis.RedisClient client = new ServiceStack.Redis.RedisClient("127.0.0.1", 6379);
                if (client.Ping() == false)
                {
                    return;
                }
                client.Db = _mac.LocalDB;
                using (var trans = client.CreatePipeline())
                {
                    if (client.Exists("GCODE:" + _GCodeFile) == 1)
                    {
                        trans.QueueCommand(r => r.Remove("GCODE:" + _GCodeFile));
                        trans.Flush();
                    }
                    while (!reader.EndOfStream)
                    {
                        String GCodetext = reader.ReadLine();
                        trans.QueueCommand(r => r.AddItemToList("GCODE:" + _GCodeFile, GCodetext));
                    }
                    trans.Flush();
                }

                // reader.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("GCodeSender" + e.Message);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
        }
예제 #5
0
 /// <summary>
 /// Writes request and response raw data into Redis
 /// </summary>
 /// <param name="data">Request and response metrics in raw form</param>
 /// <returns>A completed task</returns>
 public override async Task Write(RequestResponseData data)
 {
     try
     {
         ServiceStack.Redis.RedisClient client = new ServiceStack.Redis.RedisClient();
         client.Add<RequestResponseData>(data.ID.ToString(), data, TimeSpan.FromMinutes(15));
     }
     catch (Exception ex)
     {
         // We need to handle these exceptions
     }
 }
 /// <summary>
 /// Writes request and response raw data into Redis
 /// </summary>
 /// <param name="data">Request and response metrics in raw form</param>
 /// <returns>A completed task</returns>
 public override async Task Write(RequestResponseData data)
 {
     try
     {
         ServiceStack.Redis.RedisClient client = new ServiceStack.Redis.RedisClient();
         client.ConnectTimeout = 3;
         client.SendTimeout = 3;
         client.Add<RequestResponseData>(data.ID.ToString(), data, TimeSpan.FromMinutes(30));
     }
     catch (Exception ex)
     {
         Trace.Write(ex.Message);
     }
 }
예제 #7
0
 public void Publish(TEvnt data)
 {
     using (var redisPublisher = new ServiceStack.Redis.RedisClient(_host, _port))
     {
         try
         {
             redisPublisher.PublishMessage(MainChannel, data.SerializeToJSON());
         }
         catch (Exception ex)
         {
             System.Diagnostics.Debug.WriteLine(ex.Message);
             throw;
         }
     }
 }
예제 #8
0
        static void ServiceStack_Benchmark(int iterations)
        {
            var c = new ServiceStack.Redis.RedisClient("localhost", 6382);

            DateTime startTime = DateTime.UtcNow;

            for (int i = 0; i < iterations; ++i)
            {
                string key   = Guid.NewGuid().ToString();
                string value = Guid.NewGuid().ToString();

                c.Set(key, value);
                string v = c.GetValue(key);
                System.Diagnostics.Debug.Assert(v == value);
                int r = c.Del(key);
                System.Diagnostics.Debug.Assert(r == 1);
            }

            TimeSpan executionTime = DateTime.UtcNow - startTime;

            Console.WriteLine("Execution time: " + executionTime);
        }
예제 #9
0
        static void ServiceStack_Benchmark(int iterations)
        {
            var c = new ServiceStack.Redis.RedisClient("localhost", 6382);

            DateTime startTime = DateTime.UtcNow;

            for (int i = 0; i < iterations; ++i)
            {
                string key = Guid.NewGuid().ToString();
                string value = Guid.NewGuid().ToString();

                c.Set(key, value);
                string v = c.GetValue(key);
                System.Diagnostics.Debug.Assert(v == value);
                int r = c.Del(key);
                System.Diagnostics.Debug.Assert(r == 1);
            }

            TimeSpan executionTime = DateTime.UtcNow - startTime;

            Console.WriteLine("Execution time: " + executionTime);
        }
 public void TestMethod1()
 {
     var Client = new ServiceStack.Redis.RedisClient("www.ajiao.net", 6379, "123456");
     Client.GetAllKeys();
 }
예제 #11
0
        public RedisSubscription(string channelName)
        {
            _channelName = channelName;

            worker = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(o =>
            {
                try
                {
                    workerSyncContext = new SynchronizationContext();
                    redis             = ServiceStack.Redis.RedisClientFactory.Instance.CreateRedisClient("localhost", 6379);

                    //redis = RedisManager.GetClient();
                    subscription = redis.CreateSubscription();

                    subscription.OnMessage = (channel, msg) =>
                    {
                        try
                        {
                            if (isDisposed)
                            {
                                if (isSubscribed)
                                {
                                    subscription.UnSubscribeFromAllChannels();
                                    isSubscribed = false;
                                }
                                return;
                            }

                            //assume json
                            var typedMsg = msg.FromJson <T>();

                            lock (observers)
                            {
                                foreach (var observer in observers)
                                {
                                    observer.OnNext(typedMsg);
                                }
                            }
                        }
                        finally
                        {
                        }
                    };

                    isSubscribed = true;
                    subscription.SubscribeToChannels(_channelName);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    subscription.UnSubscribeFromAllChannels();
                    isSubscribed = false;
                    this.Dispose();
                }
                finally
                {
                    subscription.Dispose();
                }
            }));
            worker.Start();
        }
        public void TestMethod1()
        {
            var Client = new ServiceStack.Redis.RedisClient("www.ajiao.net", 6379, "123456");

            Client.GetAllKeys();
        }
        public List <PatientData> Select(string query, string[] filterData, string querySort, int skip, int take)
        {
            #region commented code

            /* Query without filter:
             *  { sf: { $elemMatch : {'val':'528a66f4d4332317acc5095f', 'fldn':'Problem', 'act':true}}}
             *
             * Query with single field filter:
             *  { $and : [
             *      { sf: { $elemMatch : {'val':'528a66f4d4332317acc5095f', 'fldn':'Problem', 'act':true}}},
             *      { $or : [
             *          { sf: { $elemMatch : {'val':/^<Single Field Text Here>/i, 'fldn':'FN'}}},
             *          { sf: { $elemMatch : {'val':/^<Single Field Text Here>/i, 'fldn':'LN'}}},
             *          { sf: { $elemMatch : {'val':/^<Single Field Text Here>/i, 'fldn':'PN'}}}
             *          ]
             *      }
             *   ]
             * }
             *
             * Query with double field filter:
             *  { $and : [
             *      { sf: { $elemMatch : {'val':'528a66f4d4332317acc5095f', 'fldn':'Problem', 'act':true}}},
             *      { $and : [
             *          { $or : [
             *              { sf : { $elemMatch: {'val':/^<First Field Text Here>/i, 'fldn':'FN'}}},
             *              { sf : { $elemMatch: {'val':/^<First Field Text Here>/i, 'fldn':'PN'}}}
             *            ]
             *          },
             *          { sf: { $elemMatch : {'val':/^<Second Field Text Here>/i, 'fldn':'LN'}}}
             *        ]
             *      }
             *    ]
             *  }
             *
             */

            #endregion

            try
            {
                string jsonQuery = string.Empty;
                string queryName = "TBD"; //Pass this into the method call
                string redisKey  = string.Empty;

                if (filterData[0].Trim() == string.Empty)
                {
                    jsonQuery = query;
                    redisKey  = string.Format("{0}{1}{2}", queryName, skip, take);
                }
                else
                {
                    if (filterData[1].Trim() == string.Empty)
                    {
                        redisKey = string.Format("{0}{1}{2}{3}", queryName, filterData[0].Trim(), skip, take);

                        jsonQuery  = "{ $and : [ ";
                        jsonQuery += string.Format("{0},  ", query);
                        jsonQuery += "{ $or : [  ";
                        jsonQuery += "{ sf: { $elemMatch : {'val':/^";
                        jsonQuery += string.Format("{0}/i, ", filterData[0].Trim());
                        jsonQuery += "'" + SearchField.FieldNameProperty + "':'FN'}}},  ";
                        jsonQuery += "{ sf: { $elemMatch : {'" + SearchField.ValueProperty + "':/^";
                        jsonQuery += string.Format("{0}/i, ", filterData[0].Trim());
                        jsonQuery += "'" + SearchField.FieldNameProperty + "':'LN'}}},  ";
                        jsonQuery += "{ sf: { $elemMatch : {'" + SearchField.ValueProperty + "':/^";
                        jsonQuery += string.Format("{0}/i, ", filterData[0].Trim());
                        jsonQuery += "'" + SearchField.FieldNameProperty + "':'PN'}}}]}]}";
                    }
                    else
                    {
                        redisKey = string.Format("{0}{1}{2}{3}{4}", queryName, filterData[0].Trim(), filterData[1].Trim(), skip, take);

                        jsonQuery  = "{ $and : [ ";
                        jsonQuery += string.Format("{0},  ", query);
                        jsonQuery += "{ $and : [  ";
                        jsonQuery += "{ $or : [  ";
                        jsonQuery += "{ sf : { $elemMatch: {'" + SearchField.ValueProperty + "':/^";
                        jsonQuery += string.Format("{0}/i, ", filterData[0].Trim());
                        jsonQuery += "'" + SearchField.FieldNameProperty + "':'FN'}}},  ";
                        jsonQuery += "{ sf : { $elemMatch: {'" + SearchField.ValueProperty + "':/^";
                        jsonQuery += string.Format("{0}/i, ", filterData[0].Trim());
                        jsonQuery += "'" + SearchField.FieldNameProperty + "':'PN'}}} ";
                        jsonQuery += "]}, ";
                        jsonQuery += "{ sf: { $elemMatch : {'" + SearchField.ValueProperty + "':/^";
                        jsonQuery += string.Format("{0}/i, ", filterData[1].Trim());
                        jsonQuery += "'" + SearchField.FieldNameProperty + "':'LN'}}}]}]}}";
                    }
                }

                string redisClientIPAddress = System.Configuration.ConfigurationManager.AppSettings.Get("RedisClientIPAddress");

                List <PatientData>             cohortPatientList = new List <PatientData>();
                ServiceStack.Redis.RedisClient client            = null;

                //TODO: Uncomment the following 2 lines to turn Redis cache on
                //if(string.IsNullOrEmpty(redisClientIPAddress) == false)
                //    client = new ServiceStack.Redis.RedisClient(redisClientIPAddress);

                //If the redisKey is already in Cache (REDIS) get it from there, else re-query
                if (client != null && client.ContainsKey(redisKey))
                {
                    //go get cohortPatientList from Redis using the redisKey now
                    cohortPatientList = client.Get <List <PatientData> >(redisKey);
                }
                else
                {
                    using (PatientMongoContext ctx = new PatientMongoContext(_dbName))
                    {
                        BsonDocument  searchQuery = BsonSerializer.Deserialize <BsonDocument>(jsonQuery);
                        QueryDocument queryDoc    = new QueryDocument(searchQuery);
                        SortByBuilder builder     = PatientsUtils.BuildSortByBuilder(querySort);

                        List <MECohortPatientView> meCohortPatients = ctx.CohortPatientViews.Collection.Find(queryDoc)
                                                                      .SetSortOrder(builder).SetSkip(skip).SetLimit(take).Distinct().ToList();

                        if (meCohortPatients != null && meCohortPatients.Count > 0)
                        {
                            meCohortPatients.ForEach(delegate(MECohortPatientView pat)
                            {
                                if (!pat.DeleteFlag)
                                {
                                    PatientData cohortPatient = new PatientData();
                                    cohortPatient.Id          = pat.PatientID.ToString();

                                    foreach (SearchField sf in pat.SearchFields)
                                    {
                                        cohortPatient.FirstName     = ((SearchField)pat.SearchFields.Where(x => x.FieldName == Constants.FN).FirstOrDefault()).Value;
                                        cohortPatient.LastName      = ((SearchField)pat.SearchFields.Where(x => x.FieldName == Constants.LN).FirstOrDefault()).Value;
                                        cohortPatient.Gender        = ((SearchField)pat.SearchFields.Where(x => x.FieldName == Constants.G).FirstOrDefault()).Value;
                                        cohortPatient.DOB           = CommonFormatter.FormatDateOfBirth(((SearchField)pat.SearchFields.Where(x => x.FieldName == Constants.DOB).FirstOrDefault()).Value);
                                        cohortPatient.MiddleName    = ((SearchField)pat.SearchFields.Where(x => x.FieldName == Constants.MN).FirstOrDefault()).Value;
                                        cohortPatient.Suffix        = ((SearchField)pat.SearchFields.Where(x => x.FieldName == Constants.SFX).FirstOrDefault()).Value;
                                        cohortPatient.PreferredName = ((SearchField)pat.SearchFields.Where(x => x.FieldName == Constants.PN).FirstOrDefault()).Value;
                                    }
                                    cohortPatientList.Add(cohortPatient);
                                }
                            });
                        }
                    }
                    //put cohortPatientList into cache using redisKey now
                    if (client != null)
                    {
                        client.Set <List <PatientData> >(redisKey, cohortPatientList);
                    }
                }
                return(cohortPatientList);
            }
            catch (Exception)
            {
                throw;
            }
        }
 public RedisRepository()
 {
     client = new RedisClient("localhost", 6379); // create redis client
 }