Пример #1
0
        public AeronSubscription(Subscription subscription)
        {
            _subscription = subscription;


            // dataHandler method is called for every new datagram received

            _fragmentReassembler = new FragmentAssembler(HandlerHelper.ToFragmentHandler(CompleteMessageReceived));
        }
Пример #2
0
        public static async Task Main(string[] args)
        {
            var listenPort  = ushort.Parse(args[0]);
            var servicePort = ushort.Parse(args[1]);

            var seeds  = args.Skip(2).Select(Utils.IPEndPointFromString).ToArray();
            var logger = Utils.CreateLogger <Program>();

            var gossiper = await StartGossiper(listenPort, servicePort, seeds, logger);

            const int fragmentLimitCount = 10;
            string    channel            = "aeron:udp?endpoint=localhost:" + servicePort;

            // A unique identifier for a stream within a channel. Stream ID 0 is reserved
            // for internal use and should not be used by applications.
            const int streamId = 10;

            Console.WriteLine("Subscribing to " + channel + " on stream Id " + streamId);


            // dataHandler method is called for every new datagram received
            var fragmentHandler = HandlerHelper.ToFragmentHandler((buffer, offset, length, header) =>
            {
                var data = new byte[length];
                buffer.GetBytes(offset, data);

                Console.WriteLine($"Received message ({Encoding.UTF8.GetString(data)}) to stream {streamId:D} from session {header.SessionId:x} term id {header.TermId:x} term offset {header.TermOffset:D} ({length:D}@{offset:D})");
            });

            // Create a context, needed for client connection to media driver
            // A separate media driver process need to run prior to running this application
            var ctx = new Aeron.Context();

            // Create an Aeron instance with client-provided context configuration, connect to the
            // media driver, and add a subscription for the given channel and stream using the supplied
            // dataHandler method, which will be called with new messages as they are received.
            // The Aeron and Subscription classes implement AutoCloseable, and will automatically
            // clean up resources when this try block is finished.
            using (var aeron = Aeron.Connect(ctx))
                using (var subscription = aeron.AddSubscription(channel, streamId))
                {
                    IIdleStrategy idleStrategy = new BusySpinIdleStrategy();

                    // Try to read the data from subscriber
                    while (true)
                    {
                        // poll delivers messages to the dataHandler as they arrive
                        // and returns number of fragments read, or 0
                        // if no data is available.
                        var fragmentsRead = subscription.Poll(fragmentHandler, fragmentLimitCount);
                        // Give the IdleStrategy a chance to spin/yield/sleep to reduce CPU
                        // use if no messages were received.
                        idleStrategy.Idle(fragmentsRead);
                    }
                }
        }
Пример #3
0
        /// <summary>
        /// Return a reusable, parameterized <seealso cref="IFragmentHandler"/> that prints to stdout
        /// </summary>
        /// <param name="streamId"> to show when printing </param>
        /// <returns> subscription data handler function that prints the message contents </returns>
        public static IFragmentHandler PrintStringMessage(int streamId)
        {
            return(HandlerHelper.ToFragmentHandler((buffer, offset, length, header) =>
            {
                var data = new byte[length];
                buffer.GetBytes(offset, data);

                Console.WriteLine($"Message to stream {streamId:D} from session {header.SessionId:D} ({length:D}@{offset:D}) <<{Encoding.UTF8.GetString(data)}>>");
            }));
        }
Пример #4
0
        public void Test_CanCompress()
        {
            string config = @"<magick.net.web canCreateDirectories=""false"" cacheDirectory=""c:\cache"" enableGzip=""false""/>";

            MagickWebSettings settings = TestSectionLoader.Load(config);

            bool canCompress = HandlerHelper.CanCompress(settings, SvgFormatInfo);

            Assert.IsFalse(canCompress);
        }
        private void PollThread()
        {
            var idleStrategy    = _config.ClientIdleStrategy.GetClientIdleStrategy();
            var fragmentHandler = new FragmentAssembler(HandlerHelper.ToFragmentHandler(SubscriptionHandler));

            while (_isRunning && !_isTerminating)
            {
                idleStrategy.Idle(_subscription.Poll(fragmentHandler, _frameCountLimit));
            }
        }
Пример #6
0
        /// <summary>
        /// Handle the media file for http handling of image files.
        /// </summary>
        /// <param name="context"></param>
        public static void HandleMediaFile(HttpContext context)
        {
            string fileName = context.Request.Url.AbsolutePath;

            try
            {
                if (_enableLogging)
                {
                    Logging.Logger.Debug("HandleMediaFile: " + fileName);
                }
                MediaFile file = GetMediaFileContents(fileName);
                if (file != null)
                {
                    if (_enableLogging)
                    {
                        Logging.Logger.Debug("HandleMediaFile: file retrieved : name: " + file.Name + ", id: " + file.Id);
                    }
                    string extension   = file.Extension.Substring(1);
                    string contentType = string.Empty;

                    if (string.Compare(extension, "JPG") == 0)
                    {
                        contentType = "image/jpeg";
                    }
                    else
                    {
                        contentType = "image/" + extension;
                    }

                    int  hashCode    = file.FullName.GetHashCode();
                    bool isThumbnail = fileName.Contains("thumbnail");
                    HandlerHelper.SetHeaders(context, contentType, null, null, hashCode);
                    byte[] buffer = isThumbnail ? file.ContentsForThumbNail : file.Contents;
                    context.Response.OutputStream.Write(buffer, 0, buffer.Length);
                }
                else
                {
                    if (_enableLogging)
                    {
                        Logging.Logger.Info("HandleMediaFile: file NOT found : " + fileName);
                    }
                    context.Response.Redirect("/NotFound");
                }
            }
            catch (Exception ex)
            {
                if (_enableLogging)
                {
                    Logging.Logger.Error("Error handling media file", ex);
                }
                context.Response.Redirect("/NotFound");
            }
        }
Пример #7
0
        public JsonResult SaveRow(JObject jsonObj)
        {
            //_logger.LogInformation("开始运行");

            AjaxRtnJsonData ajaxRtnJsonData = HandlerHelper.ActionWrap(() =>
            {
                //参数
                string Id = HandlerHelper.GetValue(jsonObj, "Id");

                string ArtTitle = HandlerHelper.GetValue(jsonObj, "ArtTitle");
                string Tag      = HandlerHelper.GetValue(jsonObj, "Tag");

                string UserId = HandlerHelper.GetValue(jsonObj, "UserId");

                //更新/插入
                IFreeSql fsql = FreeSqlFactory.GetIFreeSql("rlfstock", FreeSql.DataType.Sqlite);

                StockArt model = null;

                if (string.IsNullOrEmpty(Id))
                {
                    model = new StockArt();
                }
                else
                {
                    model = fsql.Select <StockArt>().Where(t => t.Id == int.Parse(Id, CultureInfo.CurrentCulture)).ToOne();
                }

                model.ArtTitle = ArtTitle;
                model.Tag      = Tag;

                if (!string.IsNullOrEmpty(Id))
                {
                    fsql.Update <StockArt>().SetSource(model).ExecuteAffrows();
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(UserId))
                    {
                        throw new BusinessException("用户Id为空!");
                    }
                    model.UserId = int.Parse(UserId);
                    fsql.Insert <StockArt>(model).ExecuteAffrows();
                }

                return(null);
            });

            //_logger.LogInformation("结束运行");

            return(new JsonResult(ajaxRtnJsonData));
        }
Пример #8
0
        public void Test_CanOptimize()
        {
            string config = @"
<magick.net.web canCreateDirectories=""false"" cacheDirectory=""c:\cache"">
  <optimization enabled=""false""/>
</magick.net.web>";

            MagickWebSettings settings = TestSectionLoader.Load(config);

            bool canCompress = HandlerHelper.CanOptimize(settings, JpgFormatInfo);

            Assert.IsFalse(canCompress);
        }
Пример #9
0
 public AeronClientSession(AeronClient client,
                           string serverChannel,
                           Publication publication,
                           Subscription subscription,
                           Action onConnected,
                           Action onDisconnected,
                           AeronClientMessageReceivedHandler onMessageReceived)
 {
     _client            = client;
     _serverChannel     = serverChannel;
     _publication       = publication;
     _buffer            = new UnsafeBuffer();
     Subscription       = subscription;
     OnDisconnected     = onDisconnected;
     _onMessageReceived = onMessageReceived;
     _onConnected       = onConnected;
     _isConnected       = false;
     _fragmentAssembler = new FragmentAssembler(HandlerHelper.ToFragmentHandler(SubscriptionHandler));
 }
Пример #10
0
        public static void Main()
        {
            var ctx = new Aeron.Context()
                      .AvailableImageHandler(AvailablePongImageHandler);

            var fragmentAssembler = new FragmentAssembler(HandlerHelper.ToFragmentHandler(PongHandler));

            Console.WriteLine("Publishing Ping at " + PingChannel + " on stream Id " + PingStreamID);
            Console.WriteLine("Subscribing Pong at " + PongChannel + " on stream Id " + PongStreamID);
            Console.WriteLine("Message length of " + MessageLength + " bytes");

            using (var aeron = Aeron.Connect(ctx))
            {
                Console.WriteLine("Warming up... " + WarmupNumberOfIterations + " iterations of " + WarmupNumberOfMessages + " messages");

                using (var publication = aeron.AddPublication(PingChannel, PingStreamID))
                    using (var subscription = aeron.AddSubscription(PongChannel, PongStreamID))
                        using (var byteBuffer = BufferUtil.AllocateDirectAligned(MessageLength, BitUtil.CACHE_LINE_LENGTH))
                            using (var atomicBuffer = new UnsafeBuffer(byteBuffer))
                            {
                                Latch.Wait();

                                for (var i = 0; i < WarmupNumberOfIterations; i++)
                                {
                                    RoundTripMessages(atomicBuffer, fragmentAssembler, publication, subscription, WarmupNumberOfMessages);
                                }

                                Thread.Sleep(100);

                                do
                                {
                                    Histogram.Reset();
                                    Console.WriteLine("Pinging " + NumberOfMessages + " messages");

                                    RoundTripMessages(atomicBuffer, fragmentAssembler, publication, subscription, NumberOfMessages);
                                    Console.WriteLine("Histogram of RTT latencies in microseconds.");

                                    Histogram.OutputPercentileDistribution(Console.Out, outputValueUnitScalingRatio: 1000);
                                } while (Console.Read() == 'y');
                            }
            }
        }
Пример #11
0
        public JsonResult RequestToken1(JObject jsonObj)
        {
            //_logger.LogInformation("RequestToken 开始运行");

            string strAction = "RequestToken1";

            AjaxRtnJsonData ajaxRtnJsonData = HandlerHelper.ActionWrap(strAction, jsonObj, (strAction, jsonObj) =>
            {
                Dictionary <string, object> dictRtn = new Dictionary <string, object>();

                string username = HandlerHelper.GetValue(jsonObj, "username");
                string password = HandlerHelper.GetValue(jsonObj, "password");

                LoginRequestDTO loginRequestDTO = new LoginRequestDTO()
                {
                    Username = username, Password = password
                };

                if (!ModelState.IsValid)
                {
                    throw new BusinessException("无效请求!");
                }

                string token;
                string userid;

                bool isAuth = _authService.IsAuthenticated(loginRequestDTO, out token, out userid);
                if (isAuth == false)
                {
                    throw new BusinessException("用户名或密码错误!");
                }

                dictRtn.Add("Token", token);
                dictRtn.Add("UserId", userid);

                return(dictRtn);
            });

            //_logger.LogInformation("结束运行");

            return(new JsonResult(ajaxRtnJsonData));
        }
Пример #12
0
        /// <summary>
        /// Sends the given Graph to the Client via the HTTP Response
        /// </summary>
        /// <param name="context">HTTP Context</param>
        /// <param name="g">Graph to send</param>
        protected void SendResultsToClient(HttpContext context, IGraph g)
        {
            IRdfWriter writer;
            String     ctype;

            //Look up the MIME Type Definition - if none use GetWriter instead
            MimeTypeDefinition definition = MimeTypesHelper.GetDefinitions(HandlerHelper.GetAcceptTypes(context)).FirstOrDefault(d => d.CanWriteRdf);

            if (definition != null)
            {
                writer = definition.GetRdfWriter();
                ctype  = definition.CanonicalMimeType;
            }
            else
            {
                writer = MimeTypesHelper.GetWriter(HandlerHelper.GetAcceptTypes(context), out ctype);
            }

            //Set up the Writer
            if (writer is ICompressingWriter)
            {
                ((ICompressingWriter)writer).CompressionLevel = Options.DefaultCompressionLevel;
            }

            //Send Content to Client
            context.Response.ContentType = ctype;
            if (definition != null)
            {
                context.Response.ContentEncoding = definition.Encoding;
                writer.Save(g, new StreamWriter(context.Response.OutputStream, definition.Encoding));
            }
            else
            {
                writer.Save(g, new StreamWriter(context.Response.OutputStream));
            }
        }
Пример #13
0
        public JsonResult Search(JObject jsonObj)
        {
            _logger.LogInformation("Search 开始运行");

            AjaxRtnJsonData ajaxRtnJsonData = HandlerHelper.ActionWrap(() =>
            {
                Dictionary <string, object> dictRtn = new Dictionary <string, object>();

                string PerPageNum      = HandlerHelper.GetValue(jsonObj, "PerPageNum");
                string CurPage         = HandlerHelper.GetValue(jsonObj, "CurPage");
                string CompanyCode     = HandlerHelper.GetValue(jsonObj, "CompanyCode");
                string CompanyName     = HandlerHelper.GetValue(jsonObj, "CompanyName");
                string Tag             = HandlerHelper.GetValue(jsonObj, "Tag");
                string HoldCompanyName = HandlerHelper.GetValue(jsonObj, "HoldCompanyName");

                string UserId = HandlerHelper.GetValue(jsonObj, "UserId");

                IFreeSql fsql = FreeSqlFactory.GetIFreeSql("rlfstock", FreeSql.DataType.Sqlite);

                //where 条件
                Expression <Func <Company, bool> > where = x => true;

                if (!string.IsNullOrEmpty(UserId))
                {
                    where = where.And(x => x.UserId == int.Parse(UserId));
                }

                //证券代码
                if (!string.IsNullOrEmpty(CompanyCode))
                {
                    where = where.And(x => x.CompanyCode == CompanyCode);
                }
                //证券名称
                if (!string.IsNullOrEmpty(CompanyName))
                {
                    string[] array = CompanyName.Split(' ');

                    Expression <Func <Company, bool> > whereSub = x => x.CompanyName.Contains(array[0]);
                    foreach (string one in array)
                    {
                        if (array[0].Equals(HoldCompanyName))
                        {
                            continue;
                        }
                        whereSub = whereSub.Or(x => x.CompanyName.Contains(one));
                    }
                    where = where.And(whereSub);
                }
                //概念/标签
                if (!string.IsNullOrEmpty(Tag))
                {
                    string[] arrayTag = Tag.Split(' ');

                    Expression <Func <Company, bool> > whereSub = x => x.Tag.Contains(arrayTag[0]);
                    foreach (string tag in arrayTag)
                    {
                        if (arrayTag[0].Equals(tag))
                        {
                            continue;
                        }
                        whereSub = whereSub.And(x => x.Tag.Contains(tag));
                    }
                    where = where.And(whereSub);
                }
                //控股公司
                if (!string.IsNullOrEmpty(HoldCompanyName))
                {
                    string[] array = HoldCompanyName.Split(' ');

                    Expression <Func <Company, bool> > whereSub = x => x.HoldCompanyName.Contains(array[0]);
                    foreach (string one in array)
                    {
                        if (array[0].Equals(HoldCompanyName))
                        {
                            continue;
                        }
                        whereSub = whereSub.Or(x => x.HoldCompanyName.Contains(one));
                    }
                    where = where.And(whereSub);
                }

                //var sql = fsql.Select<Company>()
                //  .Where(where)
                //  .OrderBy("Id asc")
                //  .Page(int.Parse(CurPage, CultureInfo.CurrentCulture), int.Parse(PerPageNum, CultureInfo.CurrentCulture)).ToSql();

                var lstModel = fsql.Select <Company>()
                               .Where(where)
                               .Count(out var total) //总记录数量
                               .OrderBy("Id asc")
                               .Page(int.Parse(CurPage, CultureInfo.CurrentCulture), int.Parse(PerPageNum, CultureInfo.CurrentCulture)).ToList();

                dictRtn.Add("GridData", lstModel);

                dictRtn.Add("Count", total);

                return(dictRtn);
            });

            //_logger.LogInformation("Search 结束运行");

            return(new JsonResult(ajaxRtnJsonData));
        }
Пример #14
0
 /// <summary>
 /// Construct an adapter to reassemble message fragments and _delegate on only whole messages.
 /// </summary>
 /// <param name="fragmentHandler">            onto which whole messages are forwarded. </param>
 /// <param name="initialBufferLength"> to be used for each session. </param>
 public ImageFragmentAssembler(FragmentHandler fragmentHandler, int initialBufferLength = BufferBuilder.MIN_ALLOCATED_CAPACITY)
 {
     _delegate = HandlerHelper.ToFragmentHandler(fragmentHandler);
     _builder  = new BufferBuilder(initialBufferLength);
 }
Пример #15
0
 /// <summary>
 /// Return a reusable, parameteried <seealso cref="IFragmentHandler"/> that calls into a
 /// <seealso cref="RateReporter"/>.
 /// </summary>
 /// <param name="reporter"> for the rate </param>
 /// <returns> <seealso cref="IFragmentHandler"/> that records the rate information </returns>
 public static IFragmentHandler RateReporterHandler(RateReporter reporter)
 {
     return(HandlerHelper.ToFragmentHandler((buffer, offset, length, header) => reporter.OnMessage(1, length)));
 }
Пример #16
0
 /// <summary>
 /// Construct an adapter to reassemble message fragments and _delegate on only whole messages.
 /// </summary>
 /// <param name="fragmentHandler">            onto which whole messages are forwarded. </param>
 /// <param name="initialBufferLength"> to be used for each session. </param>
 public FragmentAssembler(FragmentHandler fragmentHandler, int initialBufferLength = BufferBuilder.MIN_ALLOCATED_CAPACITY)
 {
     _initialBufferLength = initialBufferLength;
     _delegate            = HandlerHelper.ToFragmentHandler(fragmentHandler);
 }
Пример #17
0
        public JsonResult Search(JObject jsonObj)
        {
            //_logger.LogInformation("开始运行");

            AjaxRtnJsonData ajaxRtnJsonData = HandlerHelper.ActionWrap(() =>
            {
                Dictionary <string, object> dictRtn = new Dictionary <string, object>();

                string PerPageNum = HandlerHelper.GetValue(jsonObj, "PerPageNum");
                string CurPage    = HandlerHelper.GetValue(jsonObj, "CurPage");
                string ArtTitle   = HandlerHelper.GetValue(jsonObj, "ArtTitle");
                string Tag        = HandlerHelper.GetValue(jsonObj, "Tag");

                string UserId = HandlerHelper.GetValue(jsonObj, "UserId");

                IFreeSql fsql = FreeSqlFactory.GetIFreeSql("rlfstock", FreeSql.DataType.Sqlite);

                //where 条件
                Expression <Func <StockArt, bool> > where = x => x.Deleted == 0;

                if (!string.IsNullOrEmpty(UserId))
                {
                    where = where.And(x => x.UserId == int.Parse(UserId));
                }

                //标题
                if (!string.IsNullOrEmpty(ArtTitle))
                {
                    string[] array = ArtTitle.Split(' ');

                    Expression <Func <StockArt, bool> > whereSub = x => x.ArtTitle.Contains(array[0]);
                    foreach (string one in array)
                    {
                        if (array[0].Equals(one))
                        {
                            continue;
                        }
                        whereSub = whereSub.And(x => x.ArtTitle.Contains(one));
                    }
                    where = where.And(whereSub);
                }
                //标签
                if (!string.IsNullOrEmpty(Tag))
                {
                    string[] array = Tag.Split(' ');

                    Expression <Func <StockArt, bool> > whereSub = x => x.Tag.Contains(array[0]);
                    foreach (string one in array)
                    {
                        if (array[0].Equals(one))
                        {
                            continue;
                        }
                        whereSub = whereSub.And(x => x.Tag.Contains(one));
                    }
                    where = where.And(whereSub);
                }

                var lstModel = fsql.Select <StockArt>()
                               .Where(where)
                               .Count(out var total) //总记录数量
                               .OrderBy("Id desc")
                               .Page(int.Parse(CurPage), int.Parse(PerPageNum)).ToList();

                dictRtn.Add("gridData", lstModel);

                dictRtn.Add("count", total);

                return(dictRtn);
            });

            //_logger.LogInformation("结束运行");

            return(new JsonResult(ajaxRtnJsonData));
        }
Пример #18
0
        public static void Main()
        {
            // Maximum number of message fragments to receive during a single 'poll' operation
            const int fragmentLimitCount = 10;

            // The channel (an endpoint identifier) to receive messages from
            const string channel = "aeron:udp?endpoint=localhost:40123";

            // A unique identifier for a stream within a channel. Stream ID 0 is reserved
            // for internal use and should not be used by applications.
            const int streamId = 10;

            Console.WriteLine("Subscribing to " + channel + " on stream Id " + streamId);

            var running = new AtomicBoolean(true);

            // Register a SIGINT handler for graceful shutdown.
            Console.CancelKeyPress += (s, e) => running.Set(false);

            // dataHandler method is called for every new datagram received
            var fragmentHandler = HandlerHelper.ToFragmentHandler((buffer, offset, length, header) =>
            {
                var data = new byte[length];
                buffer.GetBytes(offset, data);

                Console.WriteLine($"Received message ({Encoding.UTF8.GetString(data)}) to stream {streamId:D} from session {header.SessionId:x} term id {header.TermId:x} term offset {header.TermOffset:D} ({length:D}@{offset:D})");

                // Received the intended message, time to exit the program
                running.Set(false);
            });

            // Create a context, needed for client connection to media driver
            // A separate media driver process need to run prior to running this application
            var ctx = new Aeron.Context();

            // Create an Aeron instance with client-provided context configuration, connect to the
            // media driver, and add a subscription for the given channel and stream using the supplied
            // dataHandler method, which will be called with new messages as they are received.
            // The Aeron and Subscription classes implement AutoCloseable, and will automatically
            // clean up resources when this try block is finished.
            using (var aeron = Aeron.Connect(ctx))
                using (var subscription = aeron.AddSubscription(channel, streamId))
                {
                    IIdleStrategy idleStrategy = new BusySpinIdleStrategy();

                    // Try to read the data from subscriber
                    while (running)
                    {
                        // poll delivers messages to the dataHandler as they arrive
                        // and returns number of fragments read, or 0
                        // if no data is available.
                        var fragmentsRead = subscription.Poll(fragmentHandler, fragmentLimitCount);
                        // Give the IdleStrategy a chance to spin/yield/sleep to reduce CPU
                        // use if no messages were received.
                        idleStrategy.Idle(fragmentsRead);
                    }

                    Console.WriteLine("Press any key...");
                    Console.ReadLine();
                }
        }
Пример #19
0
 /// <summary>
 /// Construct an adapter to reassemble message fragments and _delegate on only whole messages.
 /// </summary>
 /// <param name="fragmentHandler">            onto which whole messages are forwarded. </param>
 /// <param name="initialBufferLength"> to be used for each session. </param>
 public FragmentAssembler(FragmentHandler fragmentHandler, int initialBufferLength = 0)
 {
     _initialBufferLength = initialBufferLength;
     _delegate            = HandlerHelper.ToFragmentHandler(fragmentHandler);
 }
Пример #20
0
        /// <summary>
        /// Poll for new messages in a stream. If new messages are found beyond the last consumed position then they
        /// will be delivered to the <seealso cref="FragmentHandler"/> up to a limited number of fragments as specified or
        /// the maximum position specified.
        /// <para>
        /// Use a <seealso cref="FragmentAssembler"/> to assemble messages which span multiple fragments.
        ///
        /// </para>
        /// </summary>
        /// <param name="handler">       to which message fragments are delivered. </param>
        /// <param name="limitPosition"> to consume messages up to. </param>
        /// <param name="fragmentLimit"> for the number of fragments to be consumed during one polling operation. </param>
        /// <returns> the number of fragments that have been consumed. </returns>
        /// <seealso cref="FragmentAssembler" />
        /// <seealso cref="ImageFragmentAssembler" />
        public int BoundedPoll(FragmentHandler handler, long limitPosition, int fragmentLimit)
        {
            var fragmentHandler = HandlerHelper.ToFragmentHandler(handler);

            return(BoundedPoll(fragmentHandler, limitPosition, fragmentLimit));
        }
Пример #21
0
        ///// <summary>
        ///// The <seealso cref="FileChannel"/> to the raw log of the Image.
        ///// </summary>
        ///// <returns> the <seealso cref="FileChannel"/> to the raw log of the Image. </returns>
        //public FileChannel FileChannel()
        //{
        //    return logBuffers.FileChannel();
        //}

        /// <summary>
        /// Poll for new messages in a stream. If new messages are found beyond the last consumed position then they
        /// will be delivered to the <seealso cref="FragmentHandler"/> up to a limited number of fragments as specified.
        ///
        /// Use a <see cref="FragmentAssembler"/> to assemble messages which span multiple fragments.
        /// </summary>
        /// <param name="fragmentHandler"> to which message fragments are delivered. </param>
        /// <param name="fragmentLimit">   for the number of fragments to be consumed during one polling operation. </param>
        /// <returns> the number of fragments that have been consumed. </returns>
        /// <seealso cref="FragmentAssembler" />
        /// <seealso cref="ImageFragmentAssembler" />
        public int Poll(FragmentHandler fragmentHandler, int fragmentLimit)
        {
            var handler = HandlerHelper.ToFragmentHandler(fragmentHandler);

            return(Poll(handler, fragmentLimit));
        }
Пример #22
0
        //TODO: Support Protocol Requests?
        ///// <summary>
        ///// Processes Protocol requests
        ///// </summary>
        ///// <param name="context">HTTP Context</param>
        //public void ProcessProtocolRequest(HttpListenerContext context)
        //{
        //    if (this._config.ProtocolProcessor == null)
        //    {
        //        context.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
        //        return;
        //    }

        //    //Q: Support authentication?
        //    ////Check whether we need to use authentication
        //    //if (!HandlerHelper.IsAuthenticated(context, this._config.UserGroups, context.Request.HttpMethod)) return;

        //    try
        //    {
        //        //Invoke the appropriate method on our protocol processor
        //        switch (context.Request.HttpMethod)
        //        {
        //            case "GET":
        //                this._config.ProtocolProcessor.ProcessGet(context);
        //                break;
        //            case "PUT":
        //                this._config.ProtocolProcessor.ProcessPut(context);
        //                break;
        //            case "POST":
        //                this._config.ProtocolProcessor.ProcessPost(context);
        //                break;
        //            case "DELETE":
        //                this._config.ProtocolProcessor.ProcessDelete(context);
        //                break;
        //            default:
        //                //For any other HTTP Verb we send a 405 Method Not Allowed
        //                context.Response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
        //                break;
        //        }

        //        //Update the Cache as the request may have changed the endpoint
        //        this.UpdateConfig(context);
        //    }
        //    catch (SparqlHttpProtocolUriResolutionException)
        //    {
        //        //If URI Resolution fails we send a 400 Bad Request
        //        context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
        //    }
        //    catch (SparqlHttpProtocolUriInvalidException)
        //    {
        //        //If URI is invalid we send a 400 Bad Request
        //        context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
        //    }
        //    catch (NotSupportedException)
        //    {
        //        //If Not Supported we send a 405 Method Not Allowed
        //        context.Response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
        //    }
        //    catch (NotImplementedException)
        //    {
        //        //If Not Implemented we send a 501 Not Implemented
        //        context.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
        //    }
        //    catch (RdfWriterSelectionException)
        //    {
        //        //If we can't select a valid Writer when returning content we send a 406 Not Acceptable
        //        context.Response.StatusCode = (int)HttpStatusCode.NotAcceptable;
        //    }
        //    catch (RdfParserSelectionException)
        //    {
        //        //If we can't select a valid Parser when receiving content we send a 415 Unsupported Media Type
        //        context.Response.StatusCode = (int)HttpStatusCode.UnsupportedMediaType;
        //    }
        //    catch (RdfParseException)
        //    {
        //        //If we can't parse the received content successfully we send a 400 Bad Request
        //        context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
        //    }
        //    catch (Exception)
        //    {
        //        //For any other error we'll send a 500 Internal Server Error
        //        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        //    }
        //}

        #region Error Handling

        /// <summary>
        /// Handles errors in processing SPARQL Query Requests
        /// </summary>
        /// <param name="context">Context of the HTTP Request</param>
        /// <param name="title">Error title</param>
        /// <param name="query">Sparql Query</param>
        /// <param name="ex">Error</param>
        protected virtual void HandleQueryErrors(HttpServerContext context, String title, String query, Exception ex)
        {
            HandlerHelper.HandleQueryErrors(new ServerContext(context), this._config, title, query, ex);
            context.Response.OutputStream.Flush();
        }
Пример #23
0
 /// <summary>
 /// Construct an adapter to reassemble message fragments and _delegate on only whole messages.
 /// </summary>
 /// <param name="fragmentHandler">            onto which whole messages are forwarded. </param>
 /// <param name="initialBufferLength"> to be used for each session. </param>
 public ImageFragmentAssembler(FragmentHandler fragmentHandler, int initialBufferLength = 0)
 {
     _delegate = HandlerHelper.ToFragmentHandler(fragmentHandler);
     _builder  = new BufferBuilder(initialBufferLength);
 }
Пример #24
0
        public JsonResult SaveRow(JObject jsonObj)
        {
            //_logger.LogInformation("开始运行");

            AjaxRtnJsonData ajaxRtnJsonData = HandlerHelper.ActionWrap(() =>
            {
                //参数
                string Id = HandlerHelper.GetValue(jsonObj, "Id");

                string TradeTime         = HandlerHelper.GetValue(jsonObj, "TradeTime");
                string CompanyCode       = HandlerHelper.GetValue(jsonObj, "CompanyCode");
                string CompanyName       = HandlerHelper.GetValue(jsonObj, "CompanyName");
                string AgentType         = HandlerHelper.GetValue(jsonObj, "AgentType");
                string TradeVol          = HandlerHelper.GetValue(jsonObj, "TradeVol");
                string TradePriceAverage = HandlerHelper.GetValue(jsonObj, "TradePriceAverage");
                string TradePrice        = HandlerHelper.GetValue(jsonObj, "TradePrice");
                string Commission        = HandlerHelper.GetValue(jsonObj, "Commission");
                string TradeFees         = HandlerHelper.GetValue(jsonObj, "TradeFees");
                string StampTax          = HandlerHelper.GetValue(jsonObj, "StampTax");
                string TransferFees      = HandlerHelper.GetValue(jsonObj, "TransferFees");
                string TradeMkPlace      = HandlerHelper.GetValue(jsonObj, "TradeMkPlace");
                string Tag = HandlerHelper.GetValue(jsonObj, "Tag");

                string UserId = HandlerHelper.GetValue(jsonObj, "UserId");

                //更新/插入
                IFreeSql fsql = FreeSqlFactory.GetIFreeSql("rlfstock", FreeSql.DataType.Sqlite);

                TradeLog tradelog = null;

                if (string.IsNullOrEmpty(Id))
                {
                    tradelog = new TradeLog();
                }
                else
                {
                    tradelog = fsql.Select <TradeLog>().Where(t => t.Id == int.Parse(Id, CultureInfo.CurrentCulture)).ToOne();
                }

                //tradelog.UserId = int.Parse(UserId);
                tradelog.TradeTime         = Convert.ToDateTime(TradeTime, CultureInfo.CurrentCulture);
                tradelog.CompanyCode       = CompanyCode;
                tradelog.CompanyName       = CompanyName;
                tradelog.AgentType         = AgentType;
                tradelog.TradeVol          = int.Parse(TradeVol, CultureInfo.CurrentCulture);
                tradelog.TradePriceAverage = float.Parse(TradePriceAverage, CultureInfo.CurrentCulture);
                tradelog.TradePrice        = float.Parse(TradePrice, CultureInfo.CurrentCulture);

                tradelog.Commission   = float.Parse(Commission, CultureInfo.CurrentCulture);
                tradelog.TradeFees    = float.Parse(TradeFees, CultureInfo.CurrentCulture);
                tradelog.StampTax     = float.Parse(StampTax, CultureInfo.CurrentCulture);
                tradelog.TransferFees = float.Parse(TransferFees, CultureInfo.CurrentCulture);

                tradelog.TradeMkPlace = TradeMkPlace;
                tradelog.Tag          = Tag;

                if (!string.IsNullOrEmpty(Id))
                {
                    fsql.Update <TradeLog>().SetSource(tradelog).ExecuteAffrows();
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(UserId))
                    {
                        throw new BusinessException("用户Id为空!");
                    }
                    tradelog.UserId = int.Parse(UserId);
                    fsql.Insert <TradeLog>(tradelog).ExecuteAffrows();
                }

                return(null);
            });

            //_logger.LogInformation("结束运行");

            return(new JsonResult(ajaxRtnJsonData));
        }
Пример #25
0
 /// <summary>
 /// Handles errors in processing SPARQL Update Requests
 /// </summary>
 /// <param name="context">Context of the HTTP Request</param>
 /// <param name="title">Error title</param>
 /// <param name="update">SPARQL Update</param>
 /// <param name="ex">Error</param>
 /// <param name="statusCode">HTTP Status code to return</param>
 protected virtual void HandleUpdateErrors(HttpServerContext context, String title, String update, Exception ex, int statusCode)
 {
     HandlerHelper.HandleUpdateErrors(new ServerContext(context), this._config, title, update, ex, statusCode);
     context.Response.OutputStream.Flush();
 }
Пример #26
0
        private static void Main(string[] args)
        {
            var options = new CommandOptions(args);

            // Configuration 읽기
            Configuration.Load(options.Get("--config", @"Config.xml"));

            // 설정 덮어쓰기
            options.Override("--port", ref Configuration.Port);
            options.Override("--pylonHost", ref Configuration.PylonHost);
            options.Override("--pylonPort", ref Configuration.PylonPort);
            options.Override("--mongodb", ref Configuration.UseMongoDatabase);
            options.Override("--xmldb", ref Configuration.UseXmlDatabase);
            options.Override("--sync", ref Configuration.UseDatabaseSync);

            // Sync를 사용할 경우에는 모든 EntityBind가 등록되어야 한다.
            if (Configuration.UseDatabaseSync)
            {
                Configuration.UseMongoDatabase = true;
                Configuration.UseXmlDatabase   = true;
            }

            // Datasheet 읽기
            DataCenter.Instance.Load(Configuration.DatasheetFileDirectory, Configuration.DatasheetFilePattern);

            // 모든 handler 등록 (Sync 쓸 때는 Handler 실행 안되도록 한다.)
            if (!Configuration.UseDatabaseSync)
            {
                HandlerHelper.Register(Assembly.GetExecutingAssembly());
            }

            // System Entity 생성
            EntityManager.Instance.Create(EntityManager.SystemId, DataCenter.Instance.GetCreateInfo(EntityTemplate.Ids.System));

            // Database 연결
            if (Configuration.UseMongoDatabase)
            {
                EntityBinder.Instance.AddBinder(new MongoBind(
                                                    Configuration.MongoDatabaseHost, Configuration.MongoDatabasePort,
                                                    Configuration.MongoDatabaseName, Configuration.MongoDatabaseCollectionName));
            }

            if (Configuration.UseXmlDatabase)
            {
                EntityBinder.Instance.AddBinder(new XmlBind(Configuration.XmlDatabaseDirectory));
            }

            if (Configuration.UseDatabaseSync)
            {
                EntityBinder.Instance.Sync(Configuration.SyncFromDatabaseType, Configuration.SyncToDatabaseType);

                Logger.Write("Sync Completed.");
                Console.ReadLine();
                return;
            }

            // EntityManager caching 및 준비
            EntityBinder.Instance.ForEach(each =>
            {
                if (each.Has <Player>())
                {
                    each.Get <Player>().Logged = false;

                    if (each.Has <Nameplate>())
                    {
                        var playerName = each.Get <Nameplate>().Name;
                        NameCache.Instance.Add(playerName, each.Id);
                    }
                }

                if (!each.Has <Player>() && each.Has <Pos>())
                {
                    PositionSystem.Global.Appear(each);
                }

                EntityManager.Instance.Add(each);
            });
            EntityManager.Instance.TrimIdSerial();
            Logger.Write("Player [{0}] loaded.", NameCache.Instance.Count);

            // Network 시작
            var listener = MessageSessionManager.Instance.CreateListener();

            Task.Factory.StartNew(() => listener.Start(Configuration.Port), TaskCreationOptions.LongRunning);

            // Pylon 등록
            PylonConnector.Instance.Start();

            Logger.Write("Server is ready.");
            Console.ReadLine();
        }
Пример #27
0
        /// <summary>
        /// Poll for new messages in a stream. If new messages are found beyond the last consumed position then they
        /// will be delivered to the <seealso cref="ControlledFragmentHandler"/> up to a limited number of fragments as specified.
        ///
        /// Use a <see cref="ControlledFragmentAssembler"/>. to assemble messages which span multiple fragments.
        ///
        /// </summary>
        /// <param name="handler"> to which message fragments are delivered. </param>
        /// <param name="fragmentLimit">   for the number of fragments to be consumed during one polling operation. </param>
        /// <returns> the number of fragments that have been consumed. </returns>
        /// <seealso cref="ControlledFragmentAssembler" />
        /// <seealso cref="ImageControlledFragmentAssembler" />
        public int ControlledPoll(ControlledFragmentHandler handler, int fragmentLimit)
        {
            var fragmentHandler = HandlerHelper.ToControlledFragmentHandler(handler);

            return(ControlledPoll(fragmentHandler, fragmentLimit));
        }
Пример #28
0
        public JsonResult Upload(IFormFile file)
        {
            AjaxRtnJsonData ajaxRtnJsonData = HandlerHelper.ActionWrap(() =>
            {
                Dictionary <string, object> dictRtn = new Dictionary <string, object>();

                //NLog.LogManager.GetLogger("rlf").Debug("参数:");

                if (file == null)
                {
                    var files = Request.Form.Files;
                    if (files == null || files.Count <= 0)
                    {
                        throw new BusinessException("参数为空!");
                    }
                    else
                    {
                        file = files[0];
                    }
                }
                //if (jsonObj == null)
                //{
                //    throw new BusinessException("参数为空!");
                //}

                var fileDir = @"C:\rlf\uploadspace\image";

                if (!Directory.Exists(fileDir))
                {
                    Directory.CreateDirectory(fileDir);
                }

                //文件名称
                string strExt          = Path.GetExtension(file.FileName).ToLower();
                string projectFileName = Path.GetFileNameWithoutExtension(file.FileName) + "_" + System.DateTime.Now.ToString("yyyyMMddhhmmss") + strExt;

                //上传的文件的路径
                string filePath = fileDir + $@"\{projectFileName}";
                using (FileStream fs = System.IO.File.Create(filePath))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }

                string strImgPath = $"http://image.rlf99.com/image/{projectFileName}";
                dictRtn.Add("FileUrl", strImgPath);

                //文件类型
                string strFileType = string.Empty;
                if (strExt.IndexOf("jpg") > -1 ||
                    strExt.IndexOf("jpeg") > -1 ||
                    strExt.IndexOf("png") > -1)
                {
                    strFileType = "image";
                }
                if (strExt.IndexOf("mp4") > -1 ||
                    strExt.IndexOf("avi") > -1 ||
                    strExt.IndexOf("mpeg") > -1)
                {
                    strFileType = "video";
                }
                if (strExt.IndexOf("mp3") > -1 ||
                    strExt.IndexOf("wav") > -1 ||
                    strExt.IndexOf("m4a") > -1)
                {
                    strFileType = "audio";
                }
                dictRtn.Add("FileType", strFileType);

                return(dictRtn);
            });

            return(new JsonResult(ajaxRtnJsonData));
        }
Пример #29
0
        public long ControlledPeek(long initialPosition, ControlledFragmentHandler handler, long limitPosition)
        {
            var fragmentHandler = HandlerHelper.ToControlledFragmentHandler(handler);

            return(ControlledPeek(initialPosition, fragmentHandler, limitPosition));
        }
Пример #30
0
        public JsonResult SaveRow(JObject jsonObj)
        {
            //_logger.LogInformation("开始运行");

            AjaxRtnJsonData ajaxRtnJsonData = HandlerHelper.ActionWrap(() =>
            {
                //参数
                string Id = HandlerHelper.GetValue(jsonObj, "Id");

                string PositionStartTime = HandlerHelper.GetValue(jsonObj, "PositionStartTime");
                string PositionEndTime   = HandlerHelper.GetValue(jsonObj, "PositionEndTime");
                string CompanyCode       = HandlerHelper.GetValue(jsonObj, "CompanyCode");
                string CompanyName       = HandlerHelper.GetValue(jsonObj, "CompanyName");
                string PositionVol       = HandlerHelper.GetValue(jsonObj, "PositionVol");
                string CostPrice         = HandlerHelper.GetValue(jsonObj, "CostPrice");
                string CurrentPrice      = HandlerHelper.GetValue(jsonObj, "CurrentPrice");
                string TradeMkPlace      = HandlerHelper.GetValue(jsonObj, "TradeMkPlace");
                string Tag = HandlerHelper.GetValue(jsonObj, "Tag");

                string UserId = HandlerHelper.GetValue(jsonObj, "UserId");

                //更新/插入
                IFreeSql fsql = FreeSqlFactory.GetIFreeSql("rlfstock", FreeSql.DataType.Sqlite);

                PositionAnalysis model = null;

                if (string.IsNullOrEmpty(Id))
                {
                    model = new PositionAnalysis();
                }
                else
                {
                    model = fsql.Select <PositionAnalysis>().Where(t => t.Id == int.Parse(Id, CultureInfo.CurrentCulture)).ToOne();

                    //插入更新日志
                    if (model.Tag.IndexOf("更新日志") == -1)
                    {
                        model.Tag = "更新日志";
                        fsql.Insert <PositionAnalysis>(model).ExecuteAffrows();
                    }
                }

                //model.UserId = int.Parse(UserId);
                model.PositionStartTime = string.IsNullOrEmpty(PositionStartTime) ? (DateTime?)null : Convert.ToDateTime(PositionStartTime, CultureInfo.CurrentCulture);
                model.PositionEndTime   = string.IsNullOrEmpty(PositionEndTime) ? (DateTime?)null : Convert.ToDateTime(PositionEndTime, CultureInfo.CurrentCulture);
                model.CompanyCode       = CompanyCode;
                model.CompanyName       = CompanyName;
                model.PositionVol       = int.Parse(PositionVol, CultureInfo.CurrentCulture);
                model.CostPrice         = float.Parse(CostPrice, CultureInfo.CurrentCulture);
                model.CurrentPrice      = float.Parse(CurrentPrice, CultureInfo.CurrentCulture);
                model.TradeMkPlace      = TradeMkPlace;
                model.Tag = Tag;

                if (!string.IsNullOrEmpty(Id))
                {
                    fsql.Update <PositionAnalysis>().SetSource(model).ExecuteAffrows();
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(UserId))
                    {
                        throw new BusinessException("用户Id为空!");
                    }
                    model.UserId = int.Parse(UserId);
                    fsql.Insert <PositionAnalysis>(model).ExecuteAffrows();
                }

                return(null);
            });

            //_logger.LogInformation("结束运行");

            return(new JsonResult(ajaxRtnJsonData));
        }