Example #1
0
 public override void Initialize(JobProcessor thread)
 {
     base.ID = 0;
     base.Initialize(thread, UnifiedNetwork.LocationService.Operations.Operations.TypeConverters);
     base.ProcessorBuilder.Add(typeof(Register), (Operation op) => new RegisterProcessor(this, op as Register));
     base.ProcessorBuilder.Add(typeof(Query), (Operation op) => new QueryProcessor(this, op as Query));
 }
Example #2
0
        public static void Call <T>(Func <T> func, Action <T> onComplete, T exceptionCode)
        {
            JobProcessor mainThread = JobProcessor.Current;
            JobProcessor jobThread  = new JobProcessor();

            jobThread.ExceptionOccur += delegate(object s, EventArgs <Exception> e)
            {
                Log <GuildService> .Logger.Fatal("Exception occurred in AsyncFunc Thread", e.Value);
            };
            jobThread.Start();
            jobThread.Enqueue(Job.Create(delegate
            {
                T funcResult;
                try
                {
                    funcResult = func();
                }
                catch (Exception ex)
                {
                    Log <GuildService> .Logger.Error("Exception occurred in Async function call", ex);
                    funcResult = exceptionCode;
                }
                mainThread.Enqueue(Job.Create(delegate
                {
                    if (onComplete != null)
                    {
                        onComplete(funcResult);
                    }
                    jobThread.Stop(false);
                }));
            }));
        }
Example #3
0
        public static void StartService()
        {
            try
            {
                BService     service      = new BService();
                JobProcessor jobProcessor = new JobProcessor();
                jobProcessor.ExceptionOccur += delegate(object sender, EventArgs <Exception> e)
                {
                    Log <BService> .Logger.Error("StartService", e.Value);
                };
                service.Initialize(jobProcessor);
                jobProcessor.Start();
                Register registerop = new Register(typeof(BService));
                registerop.OnComplete += delegate(Operation op)
                {
                    Log <BService> .Logger.DebugFormat("{0} registered on {1} : port {2}", registerop.Category, registerop.ID, registerop.Port);

                    service.ID     = registerop.ID;
                    service.Suffix = registerop.Suffix;
                    service.Start(registerop.Port);
                };
                registerop.OnFail += delegate(Operation op)
                {
                    Log <BService> .Logger.ErrorFormat("cannot find LocationService or register failed : {0}", registerop.Category);

                    service.Dispose();
                };
                jobProcessor.Enqueue(Job.Create <string, Register>(new Action <string, Register>(service.RequestOperation), typeof(UnifiedNetwork.LocationService.LookUp).FullName, registerop));
            }
            catch (Exception ex)
            {
                Log <BService> .Logger.Error("StartService", ex);
            }
        }
Example #4
0
        public override void Initialize(JobProcessor thread)
        {
            ConnectionStringLoader.LoadFromServiceCore(Settings.Default);
            this.ThreadCount = ServiceCore.FeatureMatrix.GetInteger("MMOChannelThreadCount");
            base.Initialize(thread, MMOChannelServiceOperations.TypeConverters);
            base.RegisterMessage(OperationMessages.TypeConverters);
            base.RegisterAllProcessors(Assembly.GetExecutingAssembly());
            this.InitializeThreads();
            Log <MMOChannelService> .Logger.InfoFormat("Starting server with port {0}", HeroesSection.Instance.ChannelRelay.TcpPort);

            this.server = new Server(thread, HeroesSection.Instance.ChannelRelay.TcpPort);
            this.server.ClientIdentified += this.server_ClientIdentified;
            string[] files = Directory.GetFiles(ServiceCoreSettings.Default.MMOChannelMapFilePath, "*.dat", SearchOption.AllDirectories);
            foreach (string text in files)
            {
                Log <MMOChannelService> .Logger.InfoFormat("Loading {0}", text);

                string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(text);
                Map    item = new Map(fileNameWithoutExtension, text);
                this.maps.Add(item);
            }
            MMOChannelContents.Initialize();
            if (!ServiceCore.FeatureMatrix.IsEnable("MMOForceRecommend"))
            {
                this.perfMon = new PerformanceMonitor(thread, 30000);
                this.perfMon.ValueUpdated += this.perfMon_ValueUpdated;
            }
            Scheduler.Schedule(thread, Job.Create(new Action(this.PossessChannels)), 60000);
            if (ServiceCore.FeatureMatrix.IsEnable("Burn"))
            {
                Scheduler.Schedule(base.Thread, Job.Create(new Action(this.BurnGaugeBroadcastRepeat)), 60000);
            }
        }
Example #5
0
 public void Connect(JobProcessor thread, IPEndPoint endPoint, string serviceCode, byte serverNo)
 {
     this.thread      = thread;
     this.serviceCode = serviceCode;
     this.serverNo    = serverNo;
     this.connection.Connect(this.thread, endPoint, new PacketAnalyzer());
 }
Example #6
0
 private void CreateAsyncSocket(Socket socket, JobProcessor jobProcessor, IPacketAnalyzer packetAnalyzer)
 {
     this.asyncSocket = this.CreateAsyncSocket(socket, packetAnalyzer);
     this.crypto      = ((packetAnalyzer == null) ? null : packetAnalyzer.CryptoTransform);
     if (jobProcessor == null)
     {
         this.asyncSocket.PacketReceive += delegate(object sender, EventArgs <ArraySegment <byte> > e)
         {
             this.OnPacketReceive(e);
         };
         this.asyncSocket.SocketException += delegate(object sender, EventArgs <Exception> e)
         {
             this.OnExceptionOccur(e);
         };
         this.asyncSocket.SocketClose += delegate(object sender, EventArgs e)
         {
             this.active = false;
             this.OnDisconnected(e);
         };
         return;
     }
     this.asyncSocket.PacketReceive += delegate(object sender, EventArgs <ArraySegment <byte> > e)
     {
         jobProcessor.Enqueue(Job.Create <EventArgs <ArraySegment <byte> > >(new Action <EventArgs <ArraySegment <byte> > >(this.OnPacketReceive), e));
     };
     this.asyncSocket.SocketException += delegate(object sender, EventArgs <Exception> e)
     {
         jobProcessor.Enqueue(Job.Create <EventArgs <Exception> >(new Action <EventArgs <Exception> >(this.OnExceptionOccur), e));
     };
     this.asyncSocket.SocketClose += delegate(object sender, EventArgs e)
     {
         this.active = false;
         jobProcessor.Enqueue(Job.Create <EventArgs>(new Action <EventArgs>(this.OnDisconnected), e));
     };
 }
Example #7
0
 public void Connect(JobProcessor thread, IPEndPoint endPoint, byte domainSN, string domainName)
 {
     this.thread     = thread;
     this.domainSN   = domainSN;
     this.domainName = domainName;
     this.connection.Connect(this.thread, endPoint.Address, endPoint.Port, new PacketAnalyzer());
 }
        public MainWindow()
        {
            InitializeComponent();
            audio_languages = AudioLanguage.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
            foreach (DictionaryEntry entry in audio_languages)
            {
                String language = entry.Key.ToString();
                ia_language_1.Items.Add(new ComboBoxItem()
                {
                    Content = language,
                });
            }
            FileInfo lsmash = new FileInfo(".\\muxer.exe");

            if (!lsmash.Exists)
            {
                MessageBox.Show("muxer.exe is missing");
                isProcessing = false;
                SetStartButton(false);
                SetProgressValue(0);
                SetStatusText("muxer.exe is missing");
            }
            jobProcessor = new JobProcessor(lsmash.FullName);
            jobProcessor.ProgressChanged += progress => SetProgressValue(progress);
            jobProcessor.LogChanged      += data => AppendLogText(data);
            isProcessing = false;
            SetProgressValue(0);
            SetStatusText("Ready");
        }
Example #9
0
 private void InitializeThreads(int threadCount)
 {
     foreach (JobProcessor jobProcessor in this.threads)
     {
         jobProcessor.Stop();
     }
     this.threads.Clear();
     this.Thread_Perfs = null;
     if (threadCount <= 0)
     {
         return;
     }
     this.Thread_Perfs = new PerformanceTestRunner.ThreadPerformance[threadCount];
     for (int i = 0; i < threadCount; i++)
     {
         JobProcessor jobProcessor2 = new JobProcessor();
         jobProcessor2.ExceptionOccur += this.thread_ExceptionOccur;
         PerformanceTestRunner.ThreadPerformance threadPerformance = PerformanceTestRunner.ThreadPerformance.MakePerf(jobProcessor2);
         threadPerformance.ExceptionOccur += this.thread_ExceptionOccur;
         threadPerformance.Name            = string.Format("Thread{0}", i);
         this.Thread_Perfs[i]              = threadPerformance;
         jobProcessor2.Start();
         this.threads.Add(jobProcessor2);
     }
     this.AssignThreads();
 }
Example #10
0
 public void BindThread(JobProcessor thread)
 {
     this.thread            = thread;
     thread.ExceptionOccur += this.thread_ExceptionOccur;
     thread.Dequeued       += this.thread_Dequeued;
     thread.Done           += this.thread_Done;
 }
Example #11
0
        public void TagsGetsAddedToRepository()
        {
            var httpWrapperMock = new Mock <IHttpWrapper>();

            httpWrapperMock.Setup(x => x.GetPageContent(It.IsAny <string>()))
            .Returns(Task.FromResult(StaticWebPageContent.Html));

            var jobRepositoryMock = new Mock <IJobRepository>();

            var tagRepositoryMock = new Mock <ITagRepository>();

            var configurationMock = new Mock <IConfigurationProvider>();

            var jobProcessor = new JobProcessor(tagRepositoryMock.Object, jobRepositoryMock.Object, httpWrapperMock.Object, configurationMock.Object);

            jobProcessor.ProcessJob(new Job
            {
                Name       = "name",
                Url        = "URL",
                Replace    = true,
                Selections = new List <Selection>
                {
                    new Selection
                    {
                        Output     = OutputType.Tag,
                        SearchPath = "#templateInfo h2",
                        TagName    = "tagname"
                    }
                }
            }).Wait();

            tagRepositoryMock.Verify(x => x.AddTag("URL", "tagname", "&nbsp;<!-- FREE WEBSITE TEMPLATES -->", 1));
        }
Example #12
0
        public void HardcodedValuesGetsAddedToRepository()
        {
            var httpWrapperMock = new Mock <IHttpWrapper>();

            httpWrapperMock.Setup(x => x.GetPageContent(It.IsAny <string>()))
            .Returns(Task.FromResult(StaticWebPageContent.Html));

            var jobRepositoryMock = new Mock <IJobRepository>();

            var tagRepositoryMock = new Mock <ITagRepository>();

            var configurationMock = new Mock <IConfigurationProvider>();

            var jobProcessor = new JobProcessor(tagRepositoryMock.Object, jobRepositoryMock.Object, httpWrapperMock.Object, configurationMock.Object);

            jobProcessor.ProcessJob(new Job
            {
                Name       = "name",
                Url        = "URL",
                Replace    = true,
                Selections = new List <Selection>
                {
                    new Selection
                    {
                        Output    = OutputType.Tag,
                        Hardcoded = true,
                        TagName   = "tagname",
                        Value     = "HardCodedValue"
                    }
                }
            }).Wait();

            tagRepositoryMock.Verify(x => x.AddTag("URL", "tagname", "HardCodedValue", 1));
        }
Example #13
0
 public void Initialize <T>(JobProcessor thread, IDictionary <Type, int> typeConverters) where T : ITcpServer, new()
 {
     GlobalContext.Properties["Category"] = this.Category;
     this.Thread = thread;
     thread.Enqueue(Job.Create(delegate
     {
         System.Threading.Thread.CurrentThread.Name = this.Category;
     }));
     //VEH.Install();
     this.Thread.ExceptionFilter += this.Thread_ExceptionFilter;
     this.Thread.ExceptionOccur  += this.Thread_ExceptionOccur;
     this.acceptor             = new Acceptor((default(T) == null) ? Activator.CreateInstance <T>() : default(T), thread);
     this.acceptor.OnAccepted += this.acceptor_OnAccepted;
     if (typeConverters != null)
     {
         this.acceptor.RegisterPipeMessageGroup(typeConverters);
     }
     this.acceptor.RegisterPipeMessageGroup(UnifiedNetwork.Cooperation.Message.TypeConverters);
     if (this.Initializing != null)
     {
         this.Initializing(this, EventArgs.Empty);
     }
     if (Settings.Default.PrintPerformanceInfo)
     {
         new PerformanceTest(this).RegisterPerformanceTestJob();
     }
     this.RegisterMessage(Operations.TypeConverters);
     this.RegisterProcessor(typeof(RequestLookUpInfo), (Operation x) => new RequsetLookUpInfoProcessor(this, x as RequestLookUpInfo));
     this.RegisterProcessor(typeof(RequestUnderingList), (Operation x) => new RequsetUnderingListProcessor(this, x as RequestUnderingList));
     this.RegisterProcessor(typeof(RequestOperationTimeReport), (Operation x) => new RequestOperationTimeReportProcessor(this, x as RequestOperationTimeReport));
     this.RegisterProcessor(typeof(EnableOperationTimeReport), (Operation x) => new EnableOperationTimeReportProcessor(this, x as EnableOperationTimeReport));
     this.RegisterProcessor(typeof(RequestShutDownEntity), (Operation x) => new RequestShutDownEntityProcessor(this, x as RequestShutDownEntity));
 }
Example #14
0
        public JobProcessor AcquireNewThread()
        {
            JobProcessor jobProcessor = new JobProcessor();

            this.ThreadPublished.Add(jobProcessor);
            return(jobProcessor);
        }
Example #15
0
        public override void Initialize(JobProcessor thread)
        {
            ConnectionStringLoader.LoadFromServiceCore(Settings.Default);
            base.Initialize(thread, ExecutionServiceOperations.TypeConverters);
            base.RegisterMessage(OperationMessages.TypeConverters);
            base.RegisterProcessor(typeof(StartService), (Operation op) => new StartServiceProcessor(this, op as StartService));
            base.RegisterProcessor(typeof(QueryService), (Operation op) => new QueryServiceProcessor(this, op as QueryService));
            base.RegisterProcessor(typeof(ExecAppDomain), (Operation op) => new ExecAppDomainProcessor(this, op as ExecAppDomain));
            LocalServiceConfig localServiceConfig = this.Configuration.GetSection("LocalServiceConfig") as LocalServiceConfig;

            foreach (object obj in localServiceConfig.ServiceInfos)
            {
                LocalServiceConfig.Service service = (LocalServiceConfig.Service)obj;
                if (service.AutoStart)
                {
                    Scheduler.Schedule(base.Thread, Job.Create <string>(delegate(string serviceClass)
                    {
                        Log <ExecutionService> .Logger.DebugFormat("<Initialize : [{0}]> auto start...", serviceClass);
                        string text;
                        this.StartAppDomain(serviceClass, out text);
                        Log <ExecutionService> .Logger.DebugFormat("<Initialize : [{0}]> auto start invoked : {1}", serviceClass, text);
                    }, service.ServiceClass), 0);
                }
            }
            base.Disposed += delegate(object sender, EventArgs e)
            {
                foreach (string domainName in new List <string>(this.DomainList))
                {
                    this.StopAppDomain(domainName);
                }
            };
        }
Example #16
0
        private void EndConnect(IAsyncResult ar)
        {
            object[]        array          = (object[])ar.AsyncState;
            Socket          socket         = (Socket)array[0];
            JobProcessor    jobProcessor   = (JobProcessor)array[1];
            IPacketAnalyzer packetAnalyzer = (IPacketAnalyzer)array[2];

            if (jobProcessor != null && !jobProcessor.IsInThread())
            {
                jobProcessor.Enqueue(Job.Create <IAsyncResult>(new Action <IAsyncResult>(this.EndConnect), ar));
                return;
            }
            try
            {
                socket.EndConnect(ar);
                this.CreateAsyncSocket(socket, jobProcessor, packetAnalyzer);
                this.OnConnectionSucceed(EventArgs.Empty);
                this.asyncSocket.Activate();
            }
            catch (Exception value)
            {
                this.active = false;
                this.OnConnectionFail(new EventArgs <Exception>(value));
            }
        }
Example #17
0
 public Acceptor(ITcpServer tcpServer, JobProcessor thread)
 {
     this.acceptor           = tcpServer;
     this.Thread             = thread;
     this.MessageHandler     = new MessageHandlerFactory();
     this.PipeMessageHandler = new MessageHandlerFactory();
     this.RegisterNonPipeMessageGroup(Message.TypeConverters);
     this.acceptor.ClientAccept   += this.acceptor_ClientAccept;
     this.acceptor.ExceptionOccur += this.acceptor_ExceptionOccur;
     this.acceptor.DoOnHugeMessage = delegate(int size, string msg)
     {
         string log = string.Format("<HugeMessage> [{2}]Service Acceptor get huge size packet {0} :{1}", size, msg, this.EndPointAddress);
         try
         {
             FileLog.Log("HugeMessage.log", log);
         }
         catch (Exception)
         {
         }
     };
     this.acceptor.WriteLogFunc = delegate(string msg)
     {
         string log = string.Format("[Acceptor][{0}]{1}", this.acceptor.LocalEndPoint, msg);
         try
         {
             FileLog.Log("Peer.log", log);
         }
         catch (Exception)
         {
         }
     };
 }
Example #18
0
 public Server(JobProcessor thread, int port)
 {
     this.thread = thread;
     this.server = new TcpServer2();
     this.server.ClientAccept += this.server_ClientAccept;
     this.server.Start(thread, ServerBindType.PublicPrivate, port);
     this.mf.Register <Client>(Messages.TypeConverters, "ProcessMessage");
 }
Example #19
0
 public override void Initialize(JobProcessor thread)
 {
     ConnectionStringLoader.LoadFromServiceCore(Settings.Default);
     base.Initialize(thread, MessageID.TypeConverters);
     base.RegisterMessage(OperationMessages.TypeConverters);
     base.RegisterProcessor(typeof(Whisper), (Operation op) => new WhisperProcessor(this, op as Whisper));
     base.RegisterProcessor(typeof(WhisperToGameClient), (Operation op) => new WhisperToGameClientProcessor(this, op as WhisperToGameClient));
     this.InitializeRelayClient(ServiceCoreSettings.Default.TalkWcfService, string.Format("{0}:{1}", base.Category, Service.ServerCode));
 }
Example #20
0
 public ControlManager()
 {
     this.Thread        = new JobProcessor();
     this.clientNetwork = null;
     this.active        = false;
     this.MF            = new MessageHandlerFactory();
     this.MF.Register <ControlManager>(ControlMessages.TypeConverters, "ProcessMessage");
     this.MF.Register <RCClient>(RCClientMessages.TypeConverters, "ProcessMessage");
 }
Example #21
0
        public override void Initialize(JobProcessor thread)
        {
            IEnumerable <Type> types = OperationTypes.Types((Type type) => type.Namespace != null && type.Namespace == typeof(TradeServiceOperations).Namespace);

            ConnectionStringLoader.LoadFromServiceCore(Settings.Default);
            base.Initialize(thread, types.GetConverter());
            base.RegisterMessage(OperationMessages.TypeConverters);
            base.RegisterAllProcessors(Assembly.GetExecutingAssembly());
            this.TradeItemAvgPrice = new TradeItemAvgPrice(this);
        }
Example #22
0
        public void Start()
        {
            FetchSettings();

            JavaScriptSerializer js = new JavaScriptSerializer();


            Console.WriteLine("Connecting to Comet");

            HttpWebRequest request = WebRequest.CreateHttp(Host + "/api/comet/fetch?_=" + DateTime.UtcNow.Ticks);

            SetupAuth(request.Headers);

            HttpWebResponse response = request.GetResponse() as HttpWebResponse;

            if (response.StatusCode != HttpStatusCode.OK)
            {
                Console.WriteLine(response.StatusCode);
                Console.WriteLine(response.StatusDescription);
            }
            using (var s = response.GetResponseStream()){
                using (var sr = new StreamReader(s)) {
                    Console.WriteLine("Starting to read");

                    do
                    {
                        string line = sr.ReadLine();

                        try
                        {
                            var job = js.Deserialize <CometJob>(line);
                            if (job.JobID == 0)
                            {
                                Console.WriteLine(job.Message);
                                continue;
                            }
                            else
                            {
                                Task.Run(() => {
                                    using (JobProcessor jp = new JobProcessor(job)) {
                                        jp.Execute();
                                    }
                                });
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.ToString());
                            break;
                        }
                    } while (true);
                }
            }
        }
Example #23
0
 public override void Initialize(JobProcessor thread)
 {
     base.Initialize(thread, null);
     UnifiedNetwork.LocationService.LookUp baseLookUp = new UnifiedNetwork.LocationService.LookUp(this);
     base.LookUp.BaseLookUp = baseLookUp;
     base.LookUp.AddLocation(new ServiceInfo
     {
         ID       = 0,
         FullName = typeof(UnifiedNetwork.LocationService.LookUp).FullName,
         EndPoint = new IPEndPoint(IPAddress.Loopback, 3000)
     });
 }
Example #24
0
        public void Initialize(JobProcessor thread, int listenport)
        {
            base.ID = this.ReportServiceID;
            base.Initialize(thread, null);
            base.RegisterMessage(ReportServiceOperationMessages.TypeConverters);
            base.RegisterMessage(Messages.TypeConverters);
            this.acceptor.ClientAccept += this.server_ClientAccept;
            this.acceptor.Start(thread, listenport);
            Log <ReportService> .Logger.Debug("Starts ReportService");

            this.mf.Register <ReportAdminClient>(ReportServiceOperationMessages.TypeConverters, "ProcessMessage");
        }
Example #25
0
        public void ReplaceSettingWorksCorrectlyForTags()
        {
            var job = new Job
            {
                Name       = "name",
                Url        = "URL",
                Replace    = true,
                Selections = new List <Selection>
                {
                    new Selection
                    {
                        Output     = OutputType.Tag,
                        SearchPath = "#templateInfo h2",
                        TagName    = "tagname"
                    }
                }
            };

            var httpWrapperMock = new Mock <IHttpWrapper>();

            httpWrapperMock.Setup(x => x.GetPageContent(It.IsAny <string>()))
            .Returns(Task.FromResult(StaticWebPageContent.Html));

            var jobRepositoryMock = new Mock <IJobRepository>();

            var dbContextProvider = MockedDbContextFactory.GetMock();
            var tagRepository     = new TagRepository(dbContextProvider.Object);

            var configurationMock = new Mock <IConfigurationProvider>();

            var jobProcessor = new JobProcessor(tagRepository, jobRepositoryMock.Object, httpWrapperMock.Object, configurationMock.Object);

            jobProcessor.ProcessJob(job).Wait();

            int tagId;

            using (var context = dbContextProvider.Object.GetContext())
            {
                tagId = context.Tags.First().Id;
            }

            tagRepository.Clear("URL");

            jobProcessor.ProcessJob(job).Wait();

            using (var context = dbContextProvider.Object.GetContext())
            {
                Assert.Equal(1, context.Sites.Count());
                Assert.Equal(1, context.Tags.Count());
                Assert.True(context.Tags.First().Id > tagId);
            }
        }
Example #26
0
        public override void Initialize(JobProcessor thread)
        {
            base.Initialize(thread, MessageID.TypeConverters);
            base.RegisterMessage(OperationMessages.TypeConverters);
            base.RegisterProcessor(typeof(Login), (Operation op) => new LoginProcessor(this, op as Login));
            if (!this.Valid)
            {
                Log <CafeAuthJPNVersionService> .Logger.Warn("CafeAuth service is not initialized");

                return;
            }
            this.connectToCafeAuthServer();
        }
Example #27
0
 /// <summary>
 /// This function starts a job processor that will process all pending scan jobs.
 /// </summary>
 public void ProcessJobs()
 {
     if (m_JobProcessor == null)
     {
         MOE.Logger.DoLog("ProcessJobs: Initializing Job Processor.", MOE.Logger.LogLevel.lvlInfo);
         m_JobProcessor = new JobProcessor(JobProcessorFunc);
         m_JobProcessor.BeginInvoke(null, null);
     }
     else
     {
         MOE.Logger.DoLog("ProcessJobs: Job Processor is already running.", MOE.Logger.LogLevel.lvlDebug);
     }
 }
Example #28
0
 public override void Initialize(JobProcessor thread)
 {
     base.Initialize(thread, BOP.TypeConverters);
     UnifiedNetwork.LocationService.LookUp baseLookUp = new UnifiedNetwork.LocationService.LookUp(this);
     base.LookUp.BaseLookUp = baseLookUp;
     base.LookUp.AddLocation(new ServiceInfo
     {
         ID       = 0,
         FullName = typeof(UnifiedNetwork.LocationService.LookUp).FullName,
         EndPoint = new IPEndPoint(IPAddress.Loopback, 3000)
     });
     base.ProcessorBuilder.Add(typeof(TestOp), (Operation op) => new TestOpProcessor(this, op as TestOp));
 }
Example #29
0
        public void FindLocation(Location key, Action <IPEndPoint> callback)
        {
            JobProcessor currentProcessor = JobProcessor.Current;

            this.CategoryLookUp.FindLocation(key.Category, delegate(IPEndPoint endpoint)
            {
                if (endpoint == null)
                {
                    Log <LookUp> .Logger.ErrorFormat("Cannot find category {0}", key.Category);
                    currentProcessor.Enqueue(Job.Create <IPEndPoint>(callback, null));
                    return;
                }
                this.Service.ConnectToIP(endpoint, delegate(Peer peer)
                {
                    SelectEntity selectop = new SelectEntity
                    {
                        ID       = key.ID,
                        Category = key.Category
                    };
                    selectop.OnComplete += delegate(Operation op)
                    {
                        switch (selectop.Result)
                        {
                        case SelectEntity.ResultCode.Ok:
                            currentProcessor.Enqueue(Job.Create <IPEndPoint>(callback, endpoint));
                            return;

                        case SelectEntity.ResultCode.Redirect:
                            this.IDLookUp.FindLocation(selectop.RedirectServiceID, callback);
                            return;

                        default:
                            currentProcessor.Enqueue(Job.Create <IPEndPoint>(callback, null));
                            return;
                        }
                    };
                    selectop.OnFail += delegate(Operation op)
                    {
                        Log <LookUp> .Logger.ErrorFormat("SelectEntity failed : [{0}], [{1}], {2}, {3}", new object[]
                        {
                            selectop.Result,
                            key,
                            key.ID,
                            key.Category
                        });
                        currentProcessor.Enqueue(Job.Create <IPEndPoint>(callback, null));
                    };
                    this.Service.RequestOperation(peer, selectop);
                });
            });
        }
Example #30
0
 public void Start(JobProcessor jobProcessor, IPAddress bindAddress, int port)
 {
     if (this.active)
     {
         throw new InvalidOperationException("Already activated.");
     }
     this.active       = true;
     this.jobProcessor = jobProcessor;
     this.socket       = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     this.socket.Bind(new IPEndPoint(bindAddress, port));
     this.socket.Listen(200);
     this.socket.BeginAccept(0, new AsyncCallback(this.EndAccept), this.socket);
     this.LocalEndPoint = new IPEndPoint((bindAddress == IPAddress.Any) ? TcpServerBase <TClient> .GetLocalIP(ServerBindType.PublicPrivate) : bindAddress, (this.socket.LocalEndPoint as IPEndPoint).Port);
 }
Example #31
0
        /// <summary>
        /// This function gets asynchronously called by the job processor.
        /// It will process all pending scan jobs.
        /// </summary>
        private void JobProcessorFunc()
        {
            while (m_Jobs.Count != 0)
            {
                Monitor.Enter(m_Jobs);
                WOL2Host h = m_Jobs[0];
                Monitor.Exit(m_Jobs);

                // Wait for a free scan slot
                while (m_lScansRunning > 255)
                    Thread.Sleep(10);

                // Kick up a new scanner thread
                m_lScansRunning++;

                MOE.Logger.DoLog("JobProcessor: Spawning new scan process for: " + h.GetIpAddress(), MOE.Logger.LogLevel.lvlDebug);

                HostScanner hs = new HostScanner(ScanHost);
                hs.BeginInvoke(h,
                                 new AsyncCallback(HostScanFinished),
                                 0);

                Monitor.Enter(m_Jobs);
                m_Jobs.Remove(h);
                Monitor.Exit(m_Jobs);
            }

            // Done :-)
            MOE.Logger.DoLog("JobProcessor: All jobs done.", MOE.Logger.LogLevel.lvlDebug);
            // m_finishedCallback.Invoke( null );

            m_JobProcessor = null;
        }
Example #32
0
 /// <summary>
 /// This function starts a job processor that will process all pending scan jobs.
 /// </summary>
 public void ProcessJobs()
 {
     if (m_JobProcessor == null)
     {
         MOE.Logger.DoLog("ProcessJobs: Initializing Job Processor.", MOE.Logger.LogLevel.lvlInfo);
         m_JobProcessor = new JobProcessor(JobProcessorFunc);
         m_JobProcessor.BeginInvoke(null, null);
     }
     else
         MOE.Logger.DoLog("ProcessJobs: Job Processor is already running.", MOE.Logger.LogLevel.lvlDebug);
 }