public static ThreadResult Parse(string data, int group, double variable)
            {
                var lines = data.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
                int count = lines.Count((string l) => { return(l.Trim().StartsWith("% ")); });

                if (count < 1)
                {
                    return(null);
                }
                var result = new ThreadResult(count, group, variable);
                int ptr    = 0;

                foreach (var line in lines)
                {
                    if (line.Trim().StartsWith("% "))
                    {
                        string raw   = line.Trim().Substring(2).Trim();
                        int    index = raw.LastIndexOf(':');
                        if (index < 0)
                        {
                            return(null);
                        }
                        result.Legends[ptr] = raw.Substring(0, index);
                        result.Values[ptr]  = 0;
                        double.TryParse(raw.Substring(index + 1), NumberStyles.Any, null, out result.Values[ptr]);
                        ptr++;
                    }
                }
                return(result);
            }
Exemple #2
0
        public void DurationWork_ShallTimeOutTest()
        {
            var duration  = TimeSpan.FromSeconds(2);
            var stopWatch = new Stopwatch();

            var service = new TestWorker
            {
                SleepDurationMilliseconds = 800
            };

            var logger       = new LoggerFactory().CreateLogger <Runner>();
            var threadResult = new ThreadResult();
            var worker       = new Runner(service, threadResult, logger);
            var messageA     = new HttpRequestMessage(HttpMethod.Get, "/a");
            var messageB     = new HttpRequestMessage(HttpMethod.Get, "/b");
            var resetEvent   = new ManualResetEventSlim(false);

            var cts = new CancellationTokenSource(100);
            var cancellationToken = cts.Token;

            Assert.ThrowsAsync <TaskCanceledException>(async() =>
            {
                await worker.DurationWork(new[] { messageA, messageB }, duration, stopWatch, resetEvent, cancellationToken);
            });
        }
Exemple #3
0
        public void Create()
        {
            ThreadContext context = ThreadCreator.Create("test", ThreadAction, true);
            ThreadResult  result  = context.Start().Cancel().Wait();

            Assert.IsNull(result.Error);
        }
Exemple #4
0
        public async Task DurationWork_ShallRunAllMessagesTest()
        {
            var duration  = TimeSpan.FromSeconds(1);
            var stopWatch = Stopwatch.StartNew();

            var service = new TestWorker
            {
                SleepDurationMilliseconds = 100
            };

            var logger       = new LoggerFactory().CreateLogger <Runner>();
            var threadResult = new ThreadResult();
            var worker       = new Runner(service, threadResult, logger);
            var messageA     = new HttpRequestMessage(HttpMethod.Get, "/a");
            var messageB     = new HttpRequestMessage(HttpMethod.Get, "/b");
            var resetEvent   = new ManualResetEventSlim(false);

            var cts = new CancellationTokenSource(2000);
            var cancellationToken = cts.Token;

            await worker.DurationWork(new[] { messageA, messageB }, duration, stopWatch, resetEvent, cancellationToken);

            var results = threadResult.Results;

            Assert.Equal(2, results.Count);
        }
Exemple #5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string requestId = Request.QueryString["RequestId"];

            if (!string.IsNullOrEmpty(requestId))
            {
                // if we found requestid means thread is processed
                if (ThreadResult.Contains(requestId))
                {
                    // get value
                    string result = (string)ThreadResult.Get(requestId);

                    // show message
                    lblResult.Text = result;

                    lblProcessing.Visible = false;
                    imgProgress.Visible   = false;
                    lblResult.Visible     = true;
                    btnClose.Visible      = true;
                    // Remove value from HashTable
                    ThreadResult.Remove(requestId);
                }
                else
                {
                    lblProcessing.Text = "Update....." + ThreadResult.Progress.ToString() + "   :   " + ThreadResult.UpdateString;
                    // keep refreshing progress window
                    Response.AddHeader("refresh", "2");
                }
            }
        }
 /// <summary>
 /// Executing the command according the ID with the help of the Command Dictionary.
 /// </summary>
 /// <param name="commandID">The id of the command</param>
 /// <param name="args">Arguments to the command</param>
 /// <param name="resultSuccesful">Set to true if the we succesed and false otherwise</param>
 /// <returns>The command result</returns>
 public string ExecuteCommand(int commandID, string[] args, out bool resultSuccesful)
 {
     //First checks if our command exists
     if (commands.ContainsKey(commandID))
     {
         //Creating task for each command to do it with threads.
         Task <ThreadResult> t = new Task <ThreadResult>(() =>
         {
             bool b;
             //Sleep to synchronyze between the threads.
             Thread.Sleep(1000);
             string ret     = commands[commandID].Execute(args, out b);
             ThreadResult r = new ThreadResult();
             //The arguments we return to know the result.
             r.ExcecuteResult = ret;
             r.BoolResult     = b;
             return(r);
         });
         //Excecute the command from the dictionary.(executing the above lines).
         t.Start();
         ThreadResult result = t.Result;
         resultSuccesful = result.BoolResult;
         return(result.ExcecuteResult);
     }
     //The command does not exists so we will return a message for it.
     else
     {
         resultSuccesful = false;
         return("Command does not exist");
     }
 }
Exemple #7
0
        public async Task Test200()
        {
            var mockHandler = new MockHttpMessageHandler();

            mockHandler
            .When("/")
            .Respond("application/json", "{'status' : 'OK'}");

            var client = mockHandler.ToHttpClient();
            var config = new AppConfig()
            {
                BaseAddress = "http://localhost/"
            };
            var options = Options.Create(config);
            var service = new HttpClientService(client, options);
            var message = new HttpRequestMessage(HttpMethod.Get, "/");
            var cts     = new CancellationTokenSource(100000);
            var result  = new ThreadResult();

            await service.Run(message, result, cts.Token);

            var item = result.Results.Single();

            Assert.Equal("/", item.Key);
            Assert.True(item.Value.StartDateTimes.Count == 1);
            Assert.True(item.Value.EndDateTimes.Count == 1);
            Assert.True(item.Value.IsSuccessStatusCodes[0]);
            Assert.Equal(200, item.Value.StatusCodes[0]);
            Assert.True(item.Value.HeaderLengths[0] > 0);
            Assert.True(item.Value.ResponseLengths[0] > 0);
            Assert.True(item.Value.RequestSentTicks[0] > 0);
            Assert.True(item.Value.ResponseTicks[0] > 0);
            Assert.True(item.Value.ResponseTicks.Count == 1);
            Assert.Equal(0, item.Value.Exceptions.Count);
        }
Exemple #8
0
        protected ThreadResult Update(ThreadProxy thread)
        {
            ActorCmd[] cmdList = null;
            lock (mInputLock)
            {
                if (mInput.Count > 0)
                {
                    cmdList = mInput.ToArray();
                    mInput.Clear();
                }
            }

            if (cmdList != null)
            {
                foreach (ActorCmd cmd in cmdList)
                {
                    if (OnCmd(cmd) == ThreadResult.Stop)
                    {
                        mLogger.LogInfo("命令" + cmd.Cmd + "关闭了线程", "Update");
                        return(ThreadResult.Stop);
                    }
                }
            }

            ThreadResult result = OnUpdate(thread);

            return(result);
        }
Exemple #9
0
 public BalanceThread(ThreadResult tr, Action initAction, bool autorun)
 {
     init(tr);
     if (autorun)
     {
         run();
     }
 }
Exemple #10
0
 public async ValueTask Run(HttpRequestMessage request, ThreadResult result, CancellationToken cancellationToken)
 {
     await Task.Factory.StartNew
         (() =>
     {
         Task.Delay(SleepDurationMilliseconds).Wait();
         result.Add(request.RequestUri.ToString(), DateTime.UtcNow, DateTime.UtcNow.AddSeconds(1), true, 200, 0, 0, 0, 0, null, null);
     }, cancellationToken);
 }
 private static Thread BuildThread <TResult>(Func <TResult> action)
 {
     return(new Thread(p =>
     {
         ThreadResult <TResult> r = p as ThreadResult <TResult>;
         try { r.Result = action(); r.WasSuccessful = true; }
         catch (Exception) { r.WasSuccessful = false; }
     }));
 }
Exemple #12
0
        /// <summary>
        /// Initializer
        /// </summary>
        /// <param name="tr"></param>
        private void init(ThreadResult tr)
        {
            _timer          = new System.Timers.Timer();
            _timer.Elapsed += _timerDone;
            _timer.Interval = _threadLifeTime == 0?1:_threadLifeTime;

            _threadResult        = tr;
            _thread              = getInstance();
            _thread.IsBackground = _shouldRunInBackground;
            _actions             = new List <Action>();
        }
Exemple #13
0
 protected void WorkerThread(object args)
 {
     if (Worker != null)
     {
         ThreadParameter par    = new ThreadParameter(args);
         ThreadResult    result = Worker(par);
         if (ThreadComplete != null)
         {
             ThreadComplete(result);
         }
     }
 }
Exemple #14
0
 public LoadBackgroundService(ThreadResult result, Runner runner, IHostApplicationLifetime applicationLifetime, IOptions <AppConfig> appConfig, ILogger <LoadBackgroundService> logger, CompositeRequestMessageProvider compositeMessageProvider, IResultStore resultStore, IEnvironment environment, IConfiguration configuration)
 {
     _runner = runner;
     _applicationLifetime = applicationLifetime;
     _appConfig           = appConfig.Value;
     _logger = logger;
     _compositeMessageProvider = compositeMessageProvider;
     _threadResult             = result;
     _resultStore   = resultStore;
     _environment   = environment;
     _configuration = configuration;
 }
Exemple #15
0
        public void AddTest()
        {
            // In-memory database only exists while the connection is open
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var options = new DbContextOptionsBuilder <EfDbContext>()
                              .UseSqlite(connection)
                              .Options;

                // Create the schema in the database
                using (var context = new EfDbContext(options))
                {
                    var environment = new Mock <IEnvironment>();
                    environment.Setup(x => x.SystemDateTimeUtc).Returns(new DateTime(2019, 8, 1));
                    environment.Setup(x => x.UserName).Returns("TestUser");

                    context.Database.EnsureCreated();
                    var service = new EfResultStore(context, environment.Object);

                    var projectName = "TestProject";
                    var attributes  = new Dictionary <string, string>();
                    attributes.Add(nameof(projectName), projectName);

                    var start  = new DateTime(2019, 8, 1);
                    var result = new ThreadResult();
                    result.Add("/", start, start.AddSeconds(1), true, 200, 100, 200, 300, 400, "Headers", new Exception("Test"));

                    service.Add(projectName, -1, attributes, result);

                    var projects      = context.Projects.ToArray();
                    var runAttributes = context.RunAttributes.ToArray();
                    var results       = context.Results.ToArray();

                    var sb = new StringBuilder();
                    sb.Append(JsonConvert.SerializeObject(projects));
                    sb.AppendLine();
                    sb.Append(JsonConvert.SerializeObject(runAttributes));
                    sb.AppendLine();
                    sb.Append(JsonConvert.SerializeObject(results));

                    Approvals.Verify(sb.ToString());
                }
            }
            finally
            {
                connection.Close();
            }
        }
        /// <summary>
        ///     Go to a specific <see cref="ForumThread" />
        /// </summary>
        /// <param name="lastPost">Go to last post</param>
        /// <param name="lastSeen">UNUSED</param>
        /// <param name="postID">A specific <see cref="ForumPost" /> ID to go to</param>
        /// <returns></returns>
        public ActionResult Thread(int id, int?postID)
        {
            var db = new ZkDataContext();
            var t  = db.ForumThreads.FirstOrDefault(x => x.ForumThreadID == id);

            // TODO - indicate thread has been deleted
            if (t == null)
            {
                return(RedirectToAction("Index"));
            }


            var cat = t.ForumCategory;

            if (cat != null)
            {
                if (cat.ForumMode == ForumMode.Missions && t.Missions.Any())
                {
                    return(RedirectToAction("Detail", "Missions", new { id = t.Missions.First().MissionID }));
                }
                if (cat.ForumMode == ForumMode.Maps && t.Resources.Any())
                {
                    return(RedirectToAction("Detail", "Maps", new { id = t.Resources.First().ResourceID }));
                }
                if (cat.ForumMode == ForumMode.SpringBattles && t.SpringBattles.Any())
                {
                    return(RedirectToAction("Detail", "Battles", new { id = t.SpringBattles.First().SpringBattleID }));
                }
                if (cat.ForumMode == ForumMode.Clans && t.Clan != null)
                {
                    return(RedirectToAction("Detail", "Clans", new { id = t.RestrictedClanID }));
                }
                if (cat.ForumMode == ForumMode.Planets && t.Planets.Any())
                {
                    return(RedirectToAction("Planet", "Planetwars", new { id = t.Planets.First().PlanetID }));
                }
            }

            var res = new ThreadResult();

            res.GoToPost = postID ?? t.UpdateLastRead(Global.AccountID, false);

            db.SaveChanges();

            res.Path          = cat?.GetPath() ?? new List <ForumCategory>();
            res.CurrentThread = t;

            return(View(res));
        }
 static void FaultyWorker()
 {
     try
     {
         Console.WriteLine("I am about to fail...");
         Thread.Sleep(1500);
         int i = 0, b = 10, c = b / i;
         threadOutput = "I did something great!";
         threadResult = ThreadResult.Success;
     }
     catch
     {
         threadResult = ThreadResult.Error;
     }
 }
Exemple #18
0
        static void Main(string[] args)
        {
            Console.WriteLine("Work in progress. Press 'c' to cancel.");

            Thread t = new Thread(Worker);

            t.Start();
            threadResult = ThreadResult.Working;

            while (threadResult == ThreadResult.Working)
            {
                if (Console.KeyAvailable)
                {
                    char ch = Console.ReadKey(true).KeyChar;
                    if (ch == 'c')
                    {
                        flagCancel = true;
                        t.Join();
                    }
                }
                Console.Write(".");
                Thread.Sleep(300);
            }
            Console.WriteLine();

            switch (threadResult)
            {
            case ThreadResult.Success:
                Console.WriteLine("Result: " + threadOutput);
                break;

            case ThreadResult.Canceled:
                Console.WriteLine("Operation was canceled.");
                break;

            case ThreadResult.Error:
                Console.WriteLine("Some error has occured.");
                break;

            default:
                throw new Exception("Operation not supported, call the developers!");
            }
            Console.WriteLine("Press ENTER to quit.");
            Console.ReadLine();
        }
        private void LongRuningTask(object data)
        {
            //  simulate long running task – your main logic should   go here
            ThreadResult.Progress = 0; ThreadResult.UpdateString = "Starting...";
            for (int i = 0; i < 100; i++)
            {
                ThreadResult.Progress++;
                double d1 = ThreadResult.Progress;
                double d2 = 100.0;
                ThreadResult.UpdateString = "Progress at " + (100 * d1 / d2).ToString() + "%";
                Thread.Sleep(4000);
            }


            // Add ThreadResult -- when this
            // line executes it  means task has been
            // completed
            ThreadResult.Add(requestId.ToString(), "Item Processed Successfully."); // you  can add your result in second parameter.
        }
Exemple #20
0
        /// <summary>
        ///     生产消息测试
        /// </summary>
        /// <param name="topic">kafka topic</param>
        /// <param name="recordCount">记录数</param>
        /// <param name="recordSize">记录大小</param>
        /// <param name="threadCount">发送线程数</param>
        public TestResult Produce(string topic, int recordCount, int recordSize, int threadCount = 1)
        {
            _testResult = new TestResult {
                Topic = topic, RecordCount = recordCount, ThreadCount = threadCount, RecordSize = recordSize
            };

            var countOfThread = recordCount / threadCount;
            var countLeft     = recordCount % threadCount;

            for (var i = 0; i < threadCount; i++)
            {
                var tr = new ThreadResult {
                    No            = i + 1,
                    StartId       = countOfThread * i,
                    EndId         = countOfThread * i + countOfThread - 1,
                    PlanCount     = countOfThread,
                    MessageLength = recordSize
                };
                if (i == threadCount - 1)
                {
                    tr.EndId     += countLeft;
                    tr.PlanCount += countLeft;
                }

                _testResult.ThreadResults.Add(tr);
            }

            var message = "".PadRight(recordSize, '0');

            foreach (var threadResult in _testResult.ThreadResults)
            {
                threadResult.Task = Task.Run(() => { ProduceThread(topic, message, threadResult); });
            }

            Task.WaitAll(_testResult.ThreadResults.Select(d => d.Task).ToArray());
            _testResult.Milliseconds =
                _testResult.ThreadResults.Where(d => d.Exception == null).Sum(d => d.Milliseconds) / threadCount;
            _testResult.FailCount = _testResult.ThreadResults.Count(d => d.Exception != null);
            return(_testResult);
        }
Exemple #21
0
        private ThreadResult CreateWebRequest(DataTable dtRecords, List <string> lstEmails, int index, string domain, string dns1, string dns2, string proxy,
                                              CancellationToken cancellationToken)
        {
            string       outSessionId = string.Empty;
            ThreadResult tr           = new ThreadResult
            {
                index     = index,
                sessionId = string.Empty
            };

            try
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                }

                //work starts here
                lock (dtRecords)
                {
                    dtRecords.Rows[index]["status"] = "working...";
                }
                DomainCreationRequest domainCreationRequest = new DomainCreationRequest(dtRecords, lstEmails, index, domain, dns1, dns2, proxy, cancellationToken);

                domainCreationRequest.MakeRequests();
            }
            catch (OperationCanceledException)
            {
                lock (dtRecords)
                {
                    dtRecords.Rows[index]["status"] = "Cancelled...";
                }
            }
            catch (Exception ex)
            {
                throw;
            }

            return(tr);
        }
Exemple #22
0
        /// <summary>
        ///     消费测试
        /// </summary>
        /// <param name="topic">kafka topic</param>
        /// <param name="consumeGroup">消费分组</param>
        /// <param name="recordCount">获取记录数</param>
        /// <param name="threadCount">记录大小</param>
        public TestResult Consume(string topic, string consumeGroup, int recordCount, int threadCount = 1)
        {
            _testResult = new TestResult {
                Topic = topic, Group = consumeGroup, RecordCount = recordCount, ThreadCount = threadCount
            };

            var countOfThread = recordCount / threadCount;
            var countLeft     = recordCount % threadCount;

            for (var i = 0; i < threadCount; i++)
            {
                var tr = new ThreadResult {
                    No        = i + 1,
                    StartId   = countOfThread * i,
                    EndId     = countOfThread * i + countOfThread - 1,
                    PlanCount = countOfThread
                };
                if (i == threadCount - 1)
                {
                    tr.EndId     += countLeft;
                    tr.PlanCount += countLeft;
                }

                _testResult.ThreadResults.Add(tr);
            }

            foreach (var threadResult in _testResult.ThreadResults)
            {
                threadResult.Task = Task.Run(() => { ConsumeThread(topic, consumeGroup, threadResult); });
            }

            Task.WaitAll(_testResult.ThreadResults.Select(d => d.Task).ToArray());
            _testResult.Milliseconds =
                _testResult.ThreadResults.Where(d => d.Exception == null).Sum(d => d.Milliseconds) / threadCount;
            var testResultSuccess = _testResult.ThreadResults.FirstOrDefault(d => d.Exception == null);

            _testResult.RecordSize = testResultSuccess?.MessageLength ?? 0;
            _testResult.FailCount  = _testResult.ThreadResults.Count(d => d.Exception != null);
            return(_testResult);
        }
Exemple #23
0
        public void CreateWorkerThreads_CountWorkTest()
        {
            var service = new TestWorker
            {
                SleepDurationMilliseconds = 100
            };

            var logger       = new LoggerFactory().CreateLogger <Runner>();
            var threadResult = new ThreadResult();
            var worker       = new Runner(service, threadResult, logger);
            var messageA     = new HttpRequestMessage(HttpMethod.Get, "/a");
            var messageB     = new HttpRequestMessage(HttpMethod.Get, "/b");

            var cts = new CancellationTokenSource(1000);
            var cancellationToken = cts.Token;

            worker.CreateWorkerThreads(1, TimeSpan.FromSeconds(0), 1, 0, new[] { messageA, messageB }, cancellationToken);

            var results = threadResult.Results;

            Assert.Equal(2, results.Count);
        }
Exemple #24
0
 static void Worker()
 {
     try
     {
         for (int i = 0; i < 10; i++)
         {
             if (flagCancel)
             {
                 //We must stop working.
                 threadOutput = ""; //Always clean after yourself.
                 threadResult = ThreadResult.Canceled;
                 return;
             }
             Thread.Sleep(1000);
             threadOutput = threadOutput + (Char)('A' + i);
         }
         threadResult = ThreadResult.Success;
     }
     catch
     {
         threadResult = ThreadResult.Error;
     }
 }
        private void ExecutionWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            var args = e.Argument as ThreadArguments;

            Process p = new Process();

            p.StartInfo.CreateNoWindow         = true;
            p.StartInfo.UseShellExecute        = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError  = true;
            p.StartInfo.FileName         = args.Executable;
            p.StartInfo.Arguments        = "-config " + "\"" + args.Config + "\" " + args.Arguments.Replace("%VAR", args.Variable.ToString());
            p.StartInfo.WorkingDirectory = Path.GetDirectoryName(args.Executable);

            LogQueue.Put("Starting execution with arguments [" + p.StartInfo.Arguments + "]...");
            p.Start();
            string s = p.StandardOutput.ReadToEnd();

            e.Result = ThreadResult.Parse(s, args.GroupIndex, (double)args.Variable);

            p.WaitForExit();
            LogQueue.Put("Execution with arguments [" + p.StartInfo.Arguments + "] finished.");
        }
Exemple #26
0
        public async Task CountWork_ShallRunOneMessagesTest()
        {
            var service = new TestWorker
            {
                SleepDurationMilliseconds = 100
            };

            var logger       = new LoggerFactory().CreateLogger <Runner>();
            var threadResult = new ThreadResult();
            var worker       = new Runner(service, threadResult, logger);
            var messageA     = new HttpRequestMessage(HttpMethod.Get, "/a");
            var messageB     = new HttpRequestMessage(HttpMethod.Get, "/b");
            var resetEvent   = new ManualResetEventSlim(false);

            var cts1 = new CancellationTokenSource(100);
            var cancellationToken = cts1.Token;

            await worker.CountWork(new[] { messageA, messageB }, 1, resetEvent, cancellationToken);

            var results = threadResult.Results;

            Assert.Equal(1, results.Count);
        }
    public static ThreadResult <TResult> DoWithTimeout <TResult>(Func <TResult> action, TimeSpan timeout, TimeSpan granularity)
    {
        Thread    thread              = BuildThread <TResult>(action);
        Stopwatch stopwatch           = Stopwatch.StartNew();
        ThreadResult <TResult> result = new ThreadResult <TResult>();

        thread.Start(result);
        do
        {
            if (thread.Join(granularity) && !result.WasSuccessful)
            {
                thread = BuildThread <TResult>(action);
                thread.Start(result);
            }
        } while (stopwatch.Elapsed < timeout && !result.WasSuccessful);
        stopwatch.Stop();

        if (thread.ThreadState == System.Threading.ThreadState.Running)
        {
            thread.Abort();
        }

        return(result);
    }
Exemple #28
0
        private void ProduceThread(string topic, string message, ThreadResult threadResult)
        {
            var conf = new ProducerConfig {
                BootstrapServers = _connection,
                // todo: 默认1000000,加上一个打包数据,实际能发999000;想发更大的包需要设置下面参数,否则会卡住既不报错也不能成功
                MessageMaxBytes = 2048000
            };
            var start = DateTime.Now;

            using (var p = new ProducerBuilder <Null, string>(conf).Build()) {
                for (var i = threadResult.StartId; i <= threadResult.EndId; i++)
                {
                    try {
                        // ReSharper disable once UnusedVariable
                        var result = p.ProduceAsync(topic, new Message <Null, string> {
                            Value = message
                        })
                                     .Result;
                    }
                    catch (ProduceException <Null, string> e) {
                        threadResult.Exception = e;
                        break;
                    }
                }
        public ThreadResult GetAllSongs()
        {
            errorException = null;
            if (gpApi == null)
            {
                return ThreadResult.UNINIT;
            }
            if (threadResult != ThreadResult.NONE)
            {
                return ThreadResult.BUSY;
            }
            threadResult = ThreadResult.BUSY;

            gpApi.GetAllSongs();

            threadHandler.WaitOne();
            ThreadResult result = threadResult;
            threadResult = ThreadResult.NONE;

            return result;
        }
 public void Logout()
 {
     if ((OnLogout != null) && OnLogout(this, null))
     {
         InterruptAction();
         threadResult = ThreadResult.LOGGEDOUT;
         if (allSongs != null)
             allSongs.Clear();
         if (allPlaylists != null)
         {
             allPlaylists.InstantMixes.Clear();
             allPlaylists.UserPlaylists.Clear();
         }
     }
 }
 private void CatchError(Exception e)
 {
     threadResult = ThreadResult.ERROR;
     errorException = e;
     threadHandler.Set();
 }
 private void GotAllPlaylists(GoogleMusicPlaylists playlists)
 {
     this.allPlaylists = playlists;
     threadResult = ThreadResult.GOTALLPL;
     threadHandler.Set();
 }
 private void GotAllSongs(List<GoogleMusicSong> songs)
 {
     this.allSongs = songs;
     threadResult = ThreadResult.GOTSONGS;
     threadHandler.Set();
 }
Exemple #34
0
        static void Main(string[] args)
        {
            #region Setup and Authentication

            var clientId  = File.ReadAllText(clientIdFile);
            var secretKey = File.ReadAllText(secretKeyFile);
            var code      = File.Exists(codeFile) ? File.ReadAllText(codeFile) : null;
            var authToken = File.Exists(tokenFile) ? JsonConvert.DeserializeObject <AuthToken>(File.ReadAllText(tokenFile)) : null;

            var api = new HFAPI(clientId, secretKey, authToken);
            if (authToken == null)
            {
                if (api.TryGetAuthToken(code, out authToken))
                {
                    File.WriteAllText(tokenFile, JsonConvert.SerializeObject(authToken));
                    api.SetAuthToken(authToken);
                }
                else
                {
                    Console.WriteLine("Failed to acquire authentication token from code in file: " + codeFile);
                    Console.WriteLine(authToken.ExceptionMessage);
                    Console.WriteLine("Press any key to exit...");
                    Console.ReadKey();
                    Environment.Exit(1);
                }
            }

            #endregion

            //--------------------- Reads -------------------------

            // Profile
            ProfileResult         profile             = api.ProfileRead();
            AdvancedProfileResult AdvancedProfileRead = api.AdvancedProfileRead();

            // Forums
            ForumResult ForumGet = api.ForumGet(2);

            // Threads
            ThreadResult ThreadGet = api.ThreadGet(6083735);
            // Automatically loads nested result types
            UserResult     firstPostUser        = ThreadGet.FirstPost.User;
            ThreadResult[] ThreadSearchByUserId = api.ThreadSearchByUserId(authToken.UserId, 55709, 3);

            // Posts
            PostResult   PostGet = api.PostGet(59991944);
            PostResult[] PostSearchByThreadId = api.PostSearchByThreadId(6083735, 1, 2);
            PostResult[] PostSearchByUserId   = api.PostSearchByUserId(55709, 1, 4);

            // Byte Transactions
            ByteTransactionResult[] ByteTransactionSearchByUserId     = api.ByteTransactionSearchByUserId(55709, 1, 2);
            ByteTransactionResult[] ByteTransactionSearchByFromUserId = api.ByteTransactionSearchByFromUserId(55709, 1, 3);
            ByteTransactionResult[] ByteTransactionSearchByToUserId   = api.ByteTransactionSearchByToUserId(55709, 1, 4);
            ByteTransactionResult   ByteTransactionGet = api.ByteTransactionGet(ByteTransactionSearchByUserId.First().Id);

            // Contracts
            ContractResult[] ContractSearchByUserId = api.ContractSearchByUserId(55709, 1, 1);
            ContractResult   ContractGet            = api.ContractGet(ContractSearchByUserId.First().Id);

            //--------------------- Writes -------------------------

            // ThreadResult createThread = api.ThreadCreate(375, "HFAPI.ThreadCreate Test", "Testing thread creation with my C# wrapper for the HF API.");
        }
 private void LoginSuccessful(object sender, EventArgs e)
 {
     threadResult = ThreadResult.LOGGEDIN;
     threadHandler.Set();
     OnLogIn(this, null);
 }
        /// <summary>
        /// Go to a specific <see cref="ForumThread"/>
        /// </summary>
        /// <param name="lastPost">Go to last post</param>
        /// <param name="lastSeen">UNUSED</param>
        /// <param name="postID">A specific <see cref="ForumPost"/> ID to go to</param>
        /// <returns></returns>
        public ActionResult Thread(int id, bool?lastPost, bool?lastSeen, int?postID, int?page)
        {
            var db = new ZkDataContext();
            var t  = db.ForumThreads.FirstOrDefault(x => x.ForumThreadID == id);

            // TODO - indicate thread has been deleted
            if (t == null)
            {
                return(RedirectToAction("Index"));
            }

            if (page == null)
            {
                if (postID == null)
                {
                    page = 0;
                }
                else
                {
                    var post = t.ForumPosts.FirstOrDefault(x => x.ForumPostID == postID);
                    page = GetPostPage(post);
                }
            }


            var cat = t.ForumCategory;

            if (cat != null)
            {
                if (cat.IsMissions)
                {
                    return(RedirectToAction("Detail", "Missions", new { id = t.Missions.First().MissionID }));
                }
                if (cat.IsMaps)
                {
                    return(RedirectToAction("Detail", "Maps", new { id = t.Resources.First().ResourceID }));
                }
                if (cat.IsSpringBattles)
                {
                    return(RedirectToAction("Detail", "Battles", new { id = t.SpringBattles.First().SpringBattleID }));
                }
                if (cat.IsClans)
                {
                    return(RedirectToAction("Detail", "Clans", new { id = t.RestrictedClanID }));
                }
                if (cat.IsPlanets)
                {
                    return(RedirectToAction("Planet", "Planetwars", new { id = t.Planets.First().PlanetID }));
                }
            }

            var res = new ThreadResult();

            res.GoToPost = postID ?? t.UpdateLastRead(Global.AccountID, false);

            db.SubmitChanges();

            res.Path          = GetCategoryPath(t.ForumCategoryID, db);
            res.CurrentThread = t;
            res.PageCount     = ((t.PostCount - 1) / PageSize) + 1;
            res.Page          = page;
            res.Posts         = t.ForumPosts.AsQueryable().Skip((page ?? 0) * PageSize).Take(PageSize).ToList();

            return(View(res));
        }
        public ThreadResult AttemptLogin(string name, string password)
        {
            errorException = null;
            if (gpApi == null)
            {
                return ThreadResult.UNINIT;
            }
            if (threadResult != ThreadResult.NONE)
            {
                return ThreadResult.BUSY;
            }
            threadResult = ThreadResult.BUSY;

            gpApi.Login(name, password);

            threadHandler.WaitOne();
            ThreadResult result = threadResult;
            threadResult = ThreadResult.NONE;

            return result;
        }
        public void InterruptAction()
        {
            if (threadResult == ThreadResult.NONE)
                return;

            threadResult = ThreadResult.TIMEDOUT;
            threadHandler.Set();
        }
        /// <summary>
        /// Go to a specific <see cref="ForumThread"/>
        /// </summary>
        /// <param name="lastPost">Go to last post</param>
        /// <param name="lastSeen">UNUSED</param>
        /// <param name="postID">A specific <see cref="ForumPost"/> ID to go to</param>
        /// <returns></returns>
		public ActionResult Thread(int id, bool? lastPost, bool? lastSeen, int? postID, int? page)
		{
			var db = new ZkDataContext();
			var t = db.ForumThreads.FirstOrDefault(x => x.ForumThreadID == id);

            // TODO - indicate thread has been deleted
            if (t == null) return RedirectToAction("Index");

		    if (page == null) {
		        if (postID == null) page = 0;
		        else {
		            var post = t.ForumPosts.FirstOrDefault(x => x.ForumPostID == postID);
		            page = GetPostPage(post);
		        }
		    }
		

			var cat = t.ForumCategory;
			if (cat != null)
			{
				if (cat.IsMissions) return RedirectToAction("Detail", "Missions", new { id = t.Missions.First().MissionID });
				if (cat.IsMaps) return RedirectToAction("Detail", "Maps", new { id = t.Resources.First().ResourceID });
				if (cat.IsSpringBattles) return RedirectToAction("Detail", "Battles", new { id = t.SpringBattles.First().SpringBattleID });
				if (cat.IsClans) return RedirectToAction("Detail", "Clans", new { id = t.RestrictedClanID});
				if (cat.IsPlanets) return RedirectToAction("Planet", "Planetwars", new { id = t.Planets.First().PlanetID});
			}

			var res = new ThreadResult();
			res.GoToPost = postID ?? t.UpdateLastRead(Global.AccountID, false);

			db.SubmitChanges();

			res.Path = GetCategoryPath(t.ForumCategoryID, db);
			res.CurrentThread = t;
			res.PageCount = ((t.PostCount-1)/PageSize) + 1;
            res.Page = page;
			res.Posts = t.ForumPosts.AsQueryable().Skip((page ?? 0)*PageSize).Take(PageSize).ToList();

			return View(res);
		}
        /// <summary>
        ///     Go to a specific <see cref="ForumThread" />
        /// </summary>
        /// <param name="lastPost">Go to last post</param>
        /// <param name="lastSeen">UNUSED</param>
        /// <param name="postID">A specific <see cref="ForumPost" /> ID to go to</param>
        /// <returns></returns>
        public ActionResult Thread(int id, int? postID) {
            var db = new ZkDataContext();
            var t = db.ForumThreads.FirstOrDefault(x => x.ForumThreadID == id);

            // TODO - indicate thread has been deleted
            if (t == null) return RedirectToAction("Index");


            var cat = t.ForumCategory;
            if (cat != null)
            {
                if (cat.ForumMode == ForumMode.Missions && t.Missions.Any()) return RedirectToAction("Detail", "Missions", new { id = t.Missions.First().MissionID });
                if (cat.ForumMode == ForumMode.Maps && t.Resources.Any()) return RedirectToAction("Detail", "Maps", new { id = t.Resources.First().ResourceID });
                if (cat.ForumMode == ForumMode.SpringBattles && t.SpringBattles.Any()) return RedirectToAction("Detail", "Battles", new { id = t.SpringBattles.First().SpringBattleID });
                if (cat.ForumMode == ForumMode.Clans && t.Clan!=null) return RedirectToAction("Detail", "Clans", new { id = t.RestrictedClanID });
                if (cat.ForumMode == ForumMode.Planets && t.Planets.Any()) return RedirectToAction("Planet", "Planetwars", new { id = t.Planets.First().PlanetID });
            }

            var res = new ThreadResult();
            res.GoToPost = postID ?? t.UpdateLastRead(Global.AccountID, false);

            db.SaveChanges();

            res.Path = cat?.GetPath() ?? new List<ForumCategory>();
            res.CurrentThread = t;

            return View(res);
        }