Ejemplo n.º 1
0
        private void _runOperation(SynchronizedCollection <IFileOperation> queue, ref bool queueRunningIndicator)
        {
            FileOperation op;

            lock (queue.SyncRoot)
                op = queue.FirstOrDefault() as FileOperation;
            while (op != null)
            {
                try
                {
                    queue.Remove(op);
                    if (!op.Aborted)
                    {
                        if (op.Do())
                        {
                            NotifyOperation(OperationCompleted, op);
                            op.Dispose();
                        }
                        else
                        {
                            if (op.TryCount > 0)
                            {
                                System.Threading.Thread.Sleep(500);
                                queue.Add(op);
                            }
                            else
                            {
                                op.Fail();
                                NotifyOperation(OperationCompleted, op);
                                if (op.DestMedia?.FileExists() == true)
                                {
                                    op.DestMedia.Delete();
                                }
                                op.Dispose();
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Logger.Error(e, "RunOperation exception");
                }
                lock (queue.SyncRoot)
                    op = queue.FirstOrDefault() as FileOperation;
            }
            lock (queue.SyncRoot)
                queueRunningIndicator = false;
        }
    public static string Get(string key, Func <string> getter)
    {
        //This allows multiple readers to run concurrently.
        Lock.EnterReadLock();
        try
        {
            var result = Collection.FirstOrDefault(kvp => kvp.Key == key);
            if (!Object.Equals(result, default(KeyValuePair <string, string>)))
            {
                return(result.Value);
            }
        }
        finally
        {
            Lock.ExitReadLock();
        }
        var data = getter();

        //This blocks all future EnterReadLock(), once all finish it allows the function to continue
        Lock.EnterWriteLock();
        try
        {
            Collection.Add(new KeyValuePair <string, string>(key, data));
            return(data);
        }
        finally
        {
            Lock.ExitWriteLock();
        }
    }
 protected override void OnFileRenamed(object source, RenamedEventArgs e)
 {
     try
     {
         Debug.WriteLine(e.FullPath, "OnFileRenamed");
         if (Path.GetExtension(e.Name).ToLowerInvariant() == ".xml")
         {
             string xf = _bMDXmlFiles.FirstOrDefault(s => s == e.OldFullPath);
             if (xf != null)
             {
                 _bMDXmlFiles.Remove(xf);
                 _bMDXmlFiles.Add(e.FullPath);
                 foreach (Media fd in FindMediaList(f => (f is IngestMedia) && (f as IngestMedia).XmlFile == xf))
                 {
                     ((IngestMedia)fd).XmlFile = e.FullPath;
                 }
             }
         }
         else
         {
             base.OnFileRenamed(source, e);
         }
     }
     catch { }
 }
 public static string Get(string key, Func <string> getter)
 {
     //This allows multiple readers to run concurrently.
     Lock.EnterReadLock();
     try
     {
         var result = Collection.FirstOrDefault(kvp => kvp.Key == key);
         if (!Object.Equals(result, default(KeyValuePair <string, string>)))
         {
             return(result.Value);
         }
     }
     finally
     {
         Lock.ExitReadLock();
     }
     //This allows unlimited EnterReadLock to run concurrently, but only one thread can be in upgrade mode, other threads will block.
     Lock.EnterUpgradeableReadLock();
     try
     {
         //We need to check to see if someone else filled the cache while we where waiting.
         var result = Collection.FirstOrDefault(kvp => kvp.Key == key);
         if (!Object.Equals(result, default(KeyValuePair <string, string>)))
         {
             return(result.Value);
         }
         var data = getter();
         //This blocks all future EnterReadLock(), once all finish it allows the function to continue
         Lock.EnterWriteLock();
         try
         {
             Collection.Add(new KeyValuePair <string, string>(key, data));
             return(data);
         }
         finally
         {
             Lock.ExitWriteLock();
         }
     }
     finally
     {
         Lock.ExitUpgradeableReadLock();
     }
 }
Ejemplo n.º 5
0
 public void AddVoucherItem(int id, int countryId, int retailerId, int voucherId, eState state, Guid session, string siteCode, string name)
 {
     lock (m_ItemCollection.SyncRoot)
     {
         if (m_ItemCollection.FirstOrDefault((ii) => ii is VoucherItem && ((VoucherItem)ii).Equals(countryId, retailerId, voucherId)) == null)
         {
             VoucherItem item = new VoucherItem(id, countryId, retailerId, voucherId, state, session, siteCode, name);
             m_ItemCollection.Add(item);
             FireNewItemAdded(item);
         }
     }
 }
Ejemplo n.º 6
0
 void OnTimerElapsed(object sender, ElapsedEventArgs arg)
 {
     while (true)
     {
         var item = m_CachedList.FirstOrDefault(i => i.ExpirationDate < arg.SignalTime);
         if (item == null)
         {
             break;
         }
         m_CachedList.Remove(item);
     }
 }
Ejemplo n.º 7
0
        public DocumentNode SelectDocumentNode(int docID, int curID)
        {
            SuspendLayout();
            DocumentNode node = documentNodes.FirstOrDefault(x => x.Key == docID).Value;

            node.SetCurID(curID);
            ResumeLayout();
            if (node != null)
            {
                SelectedNode = node;
            }
            return(node);
        }
Ejemplo n.º 8
0
        private void SelectN <T>(int id, SynchronizedCollection <T> coll)  where T : Node
        {
            if (coll == null)
            {
                return;
            }
            T selNode = coll.FirstOrDefault <T>(x => x.ID == id);

            if (selNode != null)
            {
                selNode.EnsureVisible();
                SelectedNode = selNode;
            }
        }
Ejemplo n.º 9
0
 public static IntPtr Value(IntPtr formHandle)
 {
     if (!ContainsKey(formHandle))
     {
         return(IntPtr.Zero);
     }
     try
     {
         return((IntPtr)wndHandleHashtable.FirstOrDefault(x => x.Key.Equals(formHandle)).Value[0]);
     }
     catch
     {
         return(IntPtr.Zero);
     }
 }
Ejemplo n.º 10
0
 public static Common.SendAnswerParams Value(Form form)
 {
     if (!Contains(form))
     {
         return(null);
     }
     try
     {
         return(answerCollection.FirstOrDefault(x => form.Equals(x.Form)));
     }
     catch
     {
         return(null);
     }
 }
Ejemplo n.º 11
0
        private Task <RunBuild> GetCurrentBuild()
        {
            return(Task.Run(async() =>
            {
                RunBuild currentBuild = null;

                while (currentBuild == null)
                {
                    currentBuild = Builds.FirstOrDefault();
                    if (currentBuild == null)
                    {
                        await Task.Delay(1000);
                    }
                }

                return currentBuild;
            }, _cancellationToken));
        }
Ejemplo n.º 12
0
        public async Task <T> GetResponse <T>(RequestType type)
        {
            var retryCount = 0;

            while (retryCount < 30)
            {
                var response = m_responses.FirstOrDefault(t => t.RequestType.Equals(type));

                if (response == null)
                {
                    await Task.Delay(100);

                    retryCount++;
                    continue;
                }

                m_responses.Remove(response);

                if (!response.Headers["Status"].Equals(nameof(ResponseStatus.Success)))
                {
                    return(default);
Ejemplo n.º 13
0
        /// <summary>
        /// Generates builds based on the instances variables.
        /// </summary>
        /// <param name="top">If non-zero, runs until N builds are generated</param>
        /// <param name="time">If non-zero, runs for N seconds</param>
        /// <param name="printTo">Periodically gives progress% and if it failed</param>
        /// <param name="progTo">Periodically gives the progress% as a double</param>
        /// <param name="dumpBads">If true, will only track new builds if they score higher than an other found builds</param>
        public void GenBuilds(int top = 0, int time = 0, Action<string> printTo = null, Action<double> progTo = null, bool dumpBads = false, bool saveStats = false)
        {
            if (runes.Any(r => r == null))
                return;

            // if to get awakened
            if (DownloadAwake && !mon.downloaded)
            {
                var mref = MonsterStat.FindMon(mon);
                if (mref != null)
                {
                    // download the current (unawakened monster)
                    var mstat = mref.Download();
                    // if the retrieved mon is unawakened, get the awakened
                    if (!mstat.Awakened && mstat.AwakenRef != null)
                    {
                        mon = mstat.AwakenRef.Download().GetMon(mon);
                    }
                }
            }
            // getting awakened also gets level 40, so...
            // only get lvl 40 stats if the monster isn't 40, wants to download AND isn't already downloaded (first and last are about the same)
            else if (mon.level < 40 && DownloadStats && !mon.downloaded)
            {
                var mref = MonsterStat.FindMon(mon);
                if (mref != null)
                {
                    mon = mref.Download().GetMon(mon);
                }
            }

            try
            {
                Best = null;
                SynchronizedCollection<Monster> tests = new SynchronizedCollection<Monster>();
                long count = 0;
                long total = runes[0].Count();
                total *= runes[1].Count();
                total *= runes[2].Count();
                total *= runes[3].Count();
                total *= runes[4].Count();
                total *= runes[5].Count();
                long complete = total;

                if (total == 0)
                {
                    if (printTo != null)
                        printTo.Invoke("0 perms");
                    Console.WriteLine("Zero permuations");
                    return;
                }
                if (!AllowBroken && BuildSets.Count == 1 && Rune.SetRequired(BuildSets[0]) == 4)
                {
                    if (printTo != null)
                        printTo.Invoke("Bad sets");
                    Console.WriteLine("Cannot use 4 set with no broken");
                    return;
                }

                bool hasSort = false;
                foreach (string stat in statNames)
                {
                    if (Sort[stat] != 0)
                    {
                        hasSort = true;
                        break;
                    }
                }
                foreach (string extra in extraNames)
                {
                    if (Sort.ExtraGet(extra) != 0)
                    {
                        hasSort = true;
                        break;
                    }
                }
                if (top == 0 && !hasSort)
                {
                    if (printTo != null)
                        printTo.Invoke("No sort");
                    Console.WriteLine("No method of determining best");
                    return;
                }

                DateTime begin = DateTime.Now;
                DateTime timer = DateTime.Now;

                Console.WriteLine(count + "/" + total + "  " + string.Format("{0:P2}", (count + complete - total) / (double)complete));

                // build the scoring function
                Func<Stats, double> sort = (m) =>
                {
                    double pts = 0;

                    foreach (string stat in statNames)
                    {
                    // if this stat is used for sorting
                    if (Sort[stat] != 0)
                        {
                        // sum points for the stat
                        pts += m[stat] / Sort[stat];
                        // if exceeding max, subtracted the gained points and then some
                        if (Threshold[stat] != 0)
                                pts -= Math.Max(0, m[stat] - Threshold[stat]) / Sort[stat];
                        }
                    }
                    // look, cool metrics!
                    foreach (string extra in extraNames)
                    {
                        if (Sort.ExtraGet(extra) != 0)
                        {
                            pts += m.ExtraValue(extra) / Sort.ExtraGet(extra);
                            if (Threshold.ExtraGet(extra) != 0)
                                pts -= Math.Max(0, m.ExtraValue(extra) - Threshold.ExtraGet(extra)) / Sort.ExtraGet(extra);
                        }
                    }
                    return pts;
                };

                int[] slotFakes = new int[6];
                bool[] slotPred = new bool[6];

                // crank the rune prediction
                for (int i = 0; i < 6; i++)
                {
                    Rune[] rs = runes[i];
                    int raiseTo = 0;
                    bool predictSubs = false;

                    // find the largest number to raise to
                    // if any along the tree say to predict, do it
                    if (runePrediction.ContainsKey("g"))
                    {
                        int glevel = runePrediction["g"].Key;
                        if (glevel > raiseTo)
                            raiseTo = glevel;
                        predictSubs |= runePrediction["g"].Value;
                    }
                    if (runePrediction.ContainsKey(((i % 2 == 0) ? "o" : "e")))
                    {
                        int mlevel = runePrediction[((i % 2 == 0) ? "o" : "e")].Key;
                        if (mlevel > raiseTo)
                            raiseTo = mlevel;
                        predictSubs |= runePrediction[((i % 2 == 0) ? "o" : "e")].Value;
                    }
                    if (runePrediction.ContainsKey((i + 1).ToString()))
                    {
                        int slevel = runePrediction[(i + 1).ToString()].Key;
                        if (slevel > raiseTo)
                            raiseTo = slevel;
                        predictSubs |= runePrediction[(i + 1).ToString()].Value;
                    }

                    slotFakes[i] = raiseTo;
                    slotPred[i] = predictSubs;

                }

                // set to running
                isRun = true;

                // Parallel the outer loop
                var loopRes = Parallel.ForEach<Rune>(runes[0], (r0, loopState) =>
                {
                    if (!isRun)
                    //break;
                    loopState.Break();

                // number of builds ruled out since last sync
                int kill = 0;
                // number of builds added since last sync
                int plus = 0;

                    foreach (Rune r1 in runes[1])
                    {
                        if (!isRun) // Can't break to a lable, don't want to goto
                        break;
                        foreach (Rune r2 in runes[2])
                        {
                            if (!isRun)
                                break;
                            foreach (Rune r3 in runes[3])
                            {
                                if (!isRun)
                                    break;
                                foreach (Rune r4 in runes[4])
                                {
                                    if (!isRun)
                                        break;
                                    foreach (Rune r5 in runes[5])
                                    {
                                        if (!isRun)
                                            break;

                                        Monster test = new Monster(mon);
                                        test.Current.shrines = shrines;
                                        test.Current.leader = leader;

                                        test.Current.FakeLevel = slotFakes;
                                        test.Current.PredictSubs = slotPred;

                                        test.ApplyRune(r0);
                                        test.ApplyRune(r1);
                                        test.ApplyRune(r2);
                                        test.ApplyRune(r3);
                                        test.ApplyRune(r4);
                                        test.ApplyRune(r5);

                                        if (saveStats)
                                        {
                                            foreach (Rune r in test.Current.runes)
                                            {
                                                r.manageStats_LoadGen++;
                                            }
                                        }

                                        var cstats = test.GetStats();

                                        bool maxdead = false;

                                        if (Maximum != null)
                                        {
                                            foreach (var stat in statNames)
                                            {
                                                if (Maximum[stat] > 0 && cstats[stat] > Maximum[stat])
                                                {
                                                    maxdead = true;
                                                    break;
                                                }
                                            }
                                        }

                                        // check if build meets minimum
                                        if (Minimum != null && !(cstats > Minimum))
                                        {
                                            kill++;
                                        }
                                        else if (maxdead)
                                        {
                                            kill++;
                                        }
                                        // if no broken sets, check for broken sets
                                        else if (!AllowBroken && !test.Current.SetsFull)
                                        {
                                            kill++;
                                        }
                                        // if there are required sets, ensure we have them
                                        else if (RequiredSets != null && RequiredSets.Count > 0
                                        // this Linq adds no overhead compared to GetStats() and ApplyRune()
                                            && !RequiredSets.All(s => test.Current.sets.Count(q => q == s) >= RequiredSets.Count(q => q == s)))
                                        {
                                            kill++;
                                        }
                                        else
                                        {
                                            // we found an okay build!
                                            plus++;

                                            if (saveStats)
                                            {
                                                foreach (Rune r in test.Current.runes)
                                                {
                                                    r.manageStats_LoadFilt++;
                                                }
                                            }

                                            // if we are to track all good builds, keep it
                                            if (!dumpBads)
                                            {
                                                tests.Add(test);
                                            }
                                            // if we only want to track really good builds
                                            else
                                            {
                                                // if there are currently no good builds, keep it
                                                if (tests.FirstOrDefault() == null)
                                                {
                                                    tests.Add(test);
                                                    Best = test;
                                                }
                                                else
                                                {
                                                    // if this build is better than the best, keep it
                                                    if (sort(Best.GetStats()) < sort(test.GetStats()))
                                                    {
                                                        Best = test;
                                                        tests.Add(test);
                                                    }
                                                }
                                            }
                                        }

                                        // every second, give a bit of feedback to those watching
                                        if (DateTime.Now > timer.AddSeconds(1))
                                        {
                                            timer = DateTime.Now;
                                            Console.WriteLine(count + "/" + total + "  " + String.Format("{0:P2}", (double)(count + complete - total) / (double)complete));
                                            if (printTo != null)
                                                printTo.Invoke(String.Format("{0:P2}", (double)(count + complete - total) / (double)complete));
                                            if (progTo != null)
                                                progTo.Invoke((double)(count + complete - total) / (double)complete);

                                            if (time > 0)
                                            {
                                                if (DateTime.Now > begin.AddSeconds(time))
                                                {
                                                    isRun = false;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    // sum up what work we've done
                                    Interlocked.Add(ref total, -kill);
                                    kill = 0;
                                    Interlocked.Add(ref count, plus);
                                    plus = 0;

                                    // if we've got enough, stop
                                    if (top > 0 && count >= top)
                                    {
                                        isRun = false;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                });

                // write out completion
                Console.WriteLine(isRun + " " + count + "/" + total + "  " + String.Format("{0:P2}", (double)(count + complete - total) / (double)complete));
                if (printTo != null)
                    printTo.Invoke("100%");
                if (progTo != null)
                    progTo.Invoke(1);

                // sort *all* the builds
                loads = tests.Where(t => t != null).OrderByDescending(r => sort(r.GetStats())).Take((top > 0 ? top : 1));

                // dump everything to console, if nothing to print to
                if (printTo == null)
                    foreach (var l in loads)
                    {
                        Console.WriteLine(l.GetStats().Health + "  " + l.GetStats().Attack + "  " + l.GetStats().Defense + "  " + l.GetStats().Speed
                            + "  " + l.GetStats().CritRate + "%" + "  " + l.GetStats().CritDamage + "%" + "  " + l.GetStats().Resistance + "%" + "  " + l.GetStats().Accuracy + "%");
                    }

                // sadface if no builds
                if (loads.Count() == 0)
                {
                    Console.WriteLine("No builds :(");
                    if (printTo != null)
                        printTo.Invoke("Zero :(");
                }
                else
                {
                    // remember the good one
                    Best = loads.First();
                    foreach (Rune r in Best.Current.runes)
                    {
                        r.manageStats_In = true;
                    }
                    for (int i = 0; i < 6; i++)
                    {
                        if (mon.Current.runes[i] != null && mon.Current.runes[i].ID != Best.Current.runes[i].ID)
                            mon.Current.runes[i].Swapped = true;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error " + e);
                if (printTo != null)
                    printTo.Invoke(e.ToString());
            }
        }
Ejemplo n.º 14
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            Deferral = taskInstance.GetDeferral();

            taskInstance.Canceled += TaskInstance_Canceled;

            AppServiceConnection IncomeConnection = (taskInstance.TriggerDetails as AppServiceTriggerDetails).AppServiceConnection;

            IncomeConnection.RequestReceived += Connection_RequestReceived;

            AppServiceResponse Response = await IncomeConnection.SendMessageAsync(new ValueSet { { "ExecuteType", "Identity" } });

            if (Response.Status == AppServiceResponseStatus.Success)
            {
                if (Response.Message.TryGetValue("Identity", out object Identity))
                {
                    switch (Convert.ToString(Identity))
                    {
                    case "FullTrustProcess":
                    {
                        if (Response.Message.TryGetValue("PreviousExplorerId", out object PreviousExplorerId))
                        {
                            if (ServiceAndClientConnections.FirstOrDefault((Pair) => Pair.ClientProcessId == Convert.ToString(PreviousExplorerId)) is ServerAndClientPair ConnectionPair)
                            {
                                if (ConnectionPair.Server != null)
                                {
                                    ConnectionPair.Server.Dispose();
                                }

                                ConnectionPair.Server = IncomeConnection;
                            }
                            else
                            {
                                throw new InvalidDataException("Could not find PreviousExplorerId in ServiceAndClientConnections");
                            }
                        }
                        else
                        {
                            if (ServiceAndClientConnections.FirstOrDefault((Pair) => Pair.Server == null) is ServerAndClientPair ConnectionPair)
                            {
                                ConnectionPair.Server = IncomeConnection;
                            }
                            else
                            {
                                ServiceAndClientConnections.Add(new ServerAndClientPair(IncomeConnection, null, string.Empty));
                            }
                        }

                        break;
                    }

                    case "UWP":
                    {
                        if (Response.Message.TryGetValue("ProcessId", out object ProcessId))
                        {
                            if (ServiceAndClientConnections.FirstOrDefault((Pair) => Pair.Client == null) is ServerAndClientPair ConnectionPair)
                            {
                                ConnectionPair.Client          = IncomeConnection;
                                ConnectionPair.ClientProcessId = Convert.ToString(ProcessId);
                            }
                            else
                            {
                                ServiceAndClientConnections.Add(new ServerAndClientPair(null, IncomeConnection, Convert.ToString(ProcessId)));
                            }
                        }
                        else
                        {
                            throw new InvalidDataException("Must contains ProcessId in response");
                        }

                        break;
                    }
                    }
                }
            }
        }
Ejemplo n.º 15
0
 public T GetService <T>() where T : IService => (T)_services.FirstOrDefault(s => s is T);
Ejemplo n.º 16
0
        /// <summary>
        /// Retrieves GTFS data for a specified agency.
        /// Data will be retrieved from an in-memory list if available and up-to-date.
        /// Otherwise the GTFS data will be requested from the GTFS Data Exchange website
        /// and stored for future use.
        /// </summary>
        /// <param name="agencyId">The GTFS-Data-Exchange agency identifier.</param>
        /// <param name="lastModified">If an "If-Modified-Since" header is present, that value can be used here. Otherwise omit.</param>
        /// <param name="etags">If the HTTP request contains "If-None-Match", it can be passed in here. Otherwise it can be omitted.</param>
        /// <returns>Returns a <see cref="FeedRequestResponse"/>.</returns>
        /// <exception cref="ArgumentException">Thrown if <paramref name="agencyId"/> is <see langword="null"/> or consists only of whitespace.</exception>
        /// <exception cref="AgencyQueryException">Thrown if the query to gtfs-data-exchange for information fails.</exception>
        public FeedRequestResponse GetGtfs(string agencyId,
                                           DateTimeOffset?lastModified = default(DateTimeOffset?),
                                           IEnumerable <EntityTagHeaderValue> etags = null)
        {
            if (string.IsNullOrWhiteSpace(agencyId))
            {
                throw new ArgumentException("The agencyId was not provided.");
            }

            // Get the record with the matching agency ID.
            var feedRecord = _feedList.FirstOrDefault(r => string.Compare(r.AgencyId, agencyId, true) == 0);

            // Check to see if there are matching Etags...
            if (feedRecord != null && feedRecord.Etag != null && etags != null)
            {
                var match = etags.FirstOrDefault(et => et == feedRecord.Etag);
                if (match != null)
                {
                    return(new FeedRequestResponse {
                        NotModified = true
                    });
                }
            }

            HttpClient           client  = null;
            GtfsFeed             gtfs    = feedRecord != null ? feedRecord.GtfsData : null;
            EntityTagHeaderValue outEtag = null;

            AgencyResponse      agencyResponse = null;
            FeedRequestResponse output         = null;

            try
            {
                // Check for an existing record...

                // Check online to see if there is a newer feed available.
                // This will be skipped if there is no matching GTFS feed stored for the specified agency.
                const string urlFmt = "http://www.gtfs-data-exchange.com/api/agency?agency={0}";
                Uri          uri    = new Uri(string.Format(urlFmt, agencyId));

                client = new HttpClient();
                client.DefaultRequestHeaders.IfModifiedSince = lastModified;
                if (etags != null)
                {
                    foreach (var etag in etags)
                    {
                        client.DefaultRequestHeaders.IfNoneMatch.Add(etag);
                    }
                }

                client.GetAsync(uri).ContinueWith((t) =>
                {
                    outEtag = t.Result.Headers.ETag;
                    if (t.Result.StatusCode == HttpStatusCode.NotModified)
                    {
                        output = new FeedRequestResponse
                        {
                            NotModified = true
                        };
                    }
                    else if (t.Result.StatusCode == HttpStatusCode.OK)
                    {
                        t.Result.Content.ReadAsStreamAsync().ContinueWith(streamTask => {
                            using (var streamReader = new StreamReader(streamTask.Result))
                                using (var jsonReader = new JsonTextReader(streamReader))
                                {
                                    var serializer = JsonSerializer.Create();
                                    agencyResponse = serializer.Deserialize <AgencyResponse>(jsonReader);
                                }
                        }).Wait();
                    }
                }).Wait();

                // If the request for GTFS info returned a "Not Modified" response, return now.
                if (output == null)
                {
                    if (agencyResponse.status_code != 200)
                    {
                        throw new AgencyQueryException(agencyResponse);
                    }

                    if (lastModified.HasValue && lastModified.Value >= agencyResponse.data.agency.date_last_updated.FromJSDateToDateTimeOffset())
                    {
                        if (feedRecord == null)
                        {
                            feedRecord = new FeedRecord
                            {
                                DateLastUpdated = lastModified.Value,
                                Etag            = outEtag
                            };
                        }
                    }
                    else
                    {
                        if (feedRecord == null || (agencyResponse.data.agency.date_last_updated.FromJSDateToDateTimeOffset() > feedRecord.DateLastUpdated))
                        {
                            // Get the GTFS file...
                            Uri zipUri = new Uri(String.Join("/", agencyResponse.data.agency.dataexchange_url.TrimEnd('/'), "latest.zip"));

                            // TODO: make the request and parse the GTFS...
                            if (client == null)
                            {
                                client = new HttpClient();
                            }
                            else
                            {
                                client.DefaultRequestHeaders.Clear();
                            }

                            client.GetStreamAsync(zipUri).ContinueWith(t =>
                            {
                                t.Result.ReadGtfsAsync().ContinueWith(gtfsTask => {
                                    gtfs = gtfsTask.Result;
                                    // Delete the existing feedRecord.
                                    if (feedRecord != null)
                                    {
                                        _feedList.Remove(feedRecord);
                                    }
                                    feedRecord = new FeedRecord
                                    {
                                        GtfsData        = gtfs,
                                        AgencyId        = agencyId,
                                        DateLastUpdated = agencyResponse.data.agency.date_last_updated.FromJSDateToDateTimeOffset(),
                                        Etag            = outEtag
                                    };
                                    // Add the new GTFS feed data to the in-memory collection.
                                    _feedList.Add(feedRecord);
                                }).Wait();
                            }).Wait();
                        }
                    }
                }
            }
            finally
            {
                if (client != null)
                {
                    client.Dispose();
                }
            }



            return(new FeedRequestResponse
            {
                FeedRecord = feedRecord
            });
        }
Ejemplo n.º 17
0
 private NetworkClient GetClientFromPeer(NetPeer peer)
 {
     return(_clients.FirstOrDefault(client => client.Id == peer.Id));
 }
Ejemplo n.º 18
0
 public IPAddress GetIPv4()
 {
     return(ips.FirstOrDefault(i => i.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork));
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Фиксация информации об исключении
        /// </summary>
        /// <param name="ex">Исключение, которое требуется зафиксировать</param>
        /// <param name="async">Выполинть запись асинхронно</param>
        internal void WriteEx(Exception ex, bool async)
        {
            lock (_sentMessages.SyncRoot)
            {
                try
                {
                    SentMessage[] tmp = _sentMessages.Where(x => x.DtCreate <= DateTime.Now.AddMinutes(-1 * SKIP_MESS_MINUTE)).ToArray();
                    tmp.Select(x => _sentMessages.Remove(x)).ToArray();
                }
                catch { }
            }

            if (ex == null)
            {
                return;
            }

            XmlElement xml = GetErrorXml(ex);

            if (((XmlElement)xml.SelectSingleNode("Info")).GetAttribute("mail") == "1")
            {
                // Заголовок - используется для автоматической разборки писем на сервере
                string subject = "";

                string pr = ((XmlElement)xml.SelectSingleNode("Info/Node[@id='Priority']")).GetAttribute("value");
                if (pr == Enum.GetName(typeof(Priority), Priority.Error))
                {
                    subject = "AppError";

                    // Доп. проверка на ExternalError
                    pr = GetPriority(ex, Priority.Error).ToString();
                    ((XmlElement)xml.SelectSingleNode("Info/Node[@id='Priority']")).SetAttribute("value", pr);
                }
                if (pr == Enum.GetName(typeof(Priority), Priority.ExternalError))
                {
                    subject = "Error ";
                }
                else if (pr == Enum.GetName(typeof(Priority), Priority.Info) || pr == Enum.GetName(typeof(Priority), Priority.Alarm))
                {
                    subject = "*" + pr + "* ";
                }

                if (string.IsNullOrEmpty(_domain_name) && (pr == Enum.GetName(typeof(Priority), Priority.ExternalError) || pr == Enum.GetName(typeof(Priority), Priority.Alarm)))
                {
                    return;
                }

                XmlElement component = (XmlElement)xml.SelectSingleNode("Info/Node[@id='Component']");
                string     build     = component != null?component.GetAttribute("value") : "";

                subject += String.Format((pr == Enum.GetName(typeof(Priority), Priority.Error) ? "[{0}]{1}:{2}" : "{2}"), _appName,
                                         (build != "" ? "[" + build + "]" : ""),
                                         ((XmlElement)xml.SelectSingleNode("Info")).GetAttribute("message")).Replace("\n", " ").Replace("\r", " ");

                if (subject.Length > MaxSubjLen)
                {
                    subject = subject.Substring(0, MaxSubjLen);
                }

                XmlElement  func = ((XmlElement)xml.SelectSingleNode("Info/Node[@id='Function']"));
                XmlElement  host = ((XmlElement)xml.SelectSingleNode("Info/Node[@id='Computer']"));
                XmlElement  user = ((XmlElement)xml.SelectSingleNode("Info/Node[@id='Computer']"));
                SentMessage sm   = new SentMessage((host != null ? host.GetAttribute("value") : ""), (user != null ? user.GetAttribute("value") : ""), (func != null ? func.GetAttribute("value") : ""), subject);
                lock (_sentMessages.SyncRoot)
                {
                    try
                    {
                        if (_sentMessages.FirstOrDefault(x => x.Equals(sm)) != null)
                        {
                            return;
                        }
                        _sentMessages.Add(sm);
                    }
                    catch { }
                }

                // Очистка информации о внутренней структуре приложения(стэк/ информацию о сборках) для внешних ошибок.
                if (pr == Enum.GetName(typeof(Priority), Priority.ExternalError))
                {
                    XmlElement excpt = ((XmlElement)xml.SelectSingleNode("Exceptions"));
                    if (excpt != null)
                    {
                        foreach (XmlElement exc in excpt.ChildNodes)
                        {
                            XmlElement cmpt = ((XmlElement)exc.SelectSingleNode("Node[@id='Component']"));
                            if (cmpt != null)
                            {
                                exc.RemoveChild(cmpt);
                            }
                            XmlElement mthd = ((XmlElement)exc.SelectSingleNode("Node[@id='Method']"));
                            if (mthd != null)
                            {
                                exc.RemoveChild(mthd);
                            }
                            XmlElement trce = ((XmlElement)exc.SelectSingleNode("Node[@id='Trace']"));
                            if (trce != null)
                            {
                                exc.RemoveChild(trce);
                            }
                        }
                        XmlElement info = ((XmlElement)xml.SelectSingleNode("Info"));
                        XmlElement frmw = ((XmlElement)xml.SelectSingleNode("Info/Node[@id='Framework']"));
                        if (frmw != null)
                        {
                            info.RemoveChild(frmw);
                        }
                        XmlElement memuse = ((XmlElement)xml.SelectSingleNode("Info/Node[@id='MemoryUsed']"));
                        if (memuse != null)
                        {
                            info.RemoveChild(memuse);
                        }
                    }
                }

                // Отправка письма
                IncState(1);

                if (async)
                {
                    TaskMailSend task = new TaskMailSend(this, subject, xml);
                    task.Execute();
                }
                else
                {
                    SendMail(subject, xml);
                }
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Generates builds based on the instances variables.
        /// </summary>
        /// <param name="top">If non-zero, runs until N builds are generated</param>
        /// <param name="time">If non-zero, runs for N seconds</param>
        /// <param name="printTo">Periodically gives progress% and if it failed</param>
        /// <param name="progTo">Periodically gives the progress% as a double</param>
        /// <param name="dumpBads">If true, will only track new builds if they score higher than an other found builds</param>
        public void GenBuilds(int top = 0, int time = 0, Action <string> printTo = null, Action <double> progTo = null, bool dumpBads = false, bool saveStats = false)
        {
            if (runes.Any(r => r == null))
            {
                return;
            }
            try
            {
                Best = null;
                SynchronizedCollection <Monster> tests = new SynchronizedCollection <Monster>();
                long count = 0;
                long total = runes[0].Count();
                total *= runes[1].Count();
                total *= runes[2].Count();
                total *= runes[3].Count();
                total *= runes[4].Count();
                total *= runes[5].Count();
                long complete = total;

                if (total == 0)
                {
                    if (printTo != null)
                    {
                        printTo.Invoke("0 perms");
                    }
                    Console.WriteLine("Zero permuations");
                    return;
                }
                if (!AllowBroken && BuildSets.Count == 1 && Rune.SetRequired(BuildSets[0]) == 4)
                {
                    if (printTo != null)
                    {
                        printTo.Invoke("Bad sets");
                    }
                    Console.WriteLine("Cannot use 4 set with no broken");
                    return;
                }

                bool hasSort = false;
                foreach (string stat in statNames)
                {
                    if (Sort[stat] != 0)
                    {
                        hasSort = true;
                        break;
                    }
                }
                foreach (string extra in extraNames)
                {
                    if (Sort.ExtraGet(extra) != 0)
                    {
                        hasSort = true;
                        break;
                    }
                }
                if (top == 0 && !hasSort)
                {
                    if (printTo != null)
                    {
                        printTo.Invoke("No sort");
                    }
                    Console.WriteLine("No method of determining best");
                    return;
                }

                DateTime begin = DateTime.Now;
                DateTime timer = DateTime.Now;

                Console.WriteLine(count + "/" + total + "  " + string.Format("{0:P2}", (count + complete - total) / (double)complete));

                // build the scoring function
                Func <Stats, double> sort = (m) =>
                {
                    double pts = 0;

                    foreach (string stat in statNames)
                    {
                        // if this stat is used for sorting
                        if (Sort[stat] != 0)
                        {
                            // sum points for the stat
                            pts += m[stat] / Sort[stat];
                            // if exceeding max, subtracted the gained points and then some
                            if (Threshold[stat] != 0)
                            {
                                pts -= Math.Max(0, m[stat] - Threshold[stat]) / Sort[stat];
                            }
                        }
                    }
                    // look, cool metrics!
                    foreach (string extra in extraNames)
                    {
                        if (Sort.ExtraGet(extra) != 0)
                        {
                            pts += m.ExtraValue(extra) / Sort.ExtraGet(extra);
                            if (Threshold.ExtraGet(extra) != 0)
                            {
                                pts -= Math.Max(0, m.ExtraValue(extra) - Threshold.ExtraGet(extra)) / Sort.ExtraGet(extra);
                            }
                        }
                    }

                    return(pts);
                };

                int[]  slotFakes = new int[6];
                bool[] slotPred  = new bool[6];

                // crank the rune prediction
                for (int i = 0; i < 6; i++)
                {
                    Rune[] rs          = runes[i];
                    int    raiseTo     = 0;
                    bool   predictSubs = false;

                    // find the largest number to raise to
                    // if any along the tree say to predict, do it
                    if (runePrediction.ContainsKey("g"))
                    {
                        int glevel = runePrediction["g"].Key;
                        if (glevel > raiseTo)
                        {
                            raiseTo = glevel;
                        }
                        predictSubs |= runePrediction["g"].Value;
                    }
                    if (runePrediction.ContainsKey(((i % 2 == 0) ? "o" : "e")))
                    {
                        int mlevel = runePrediction[((i % 2 == 0) ? "o" : "e")].Key;
                        if (mlevel > raiseTo)
                        {
                            raiseTo = mlevel;
                        }
                        predictSubs |= runePrediction[((i % 2 == 0) ? "o" : "e")].Value;
                    }
                    if (runePrediction.ContainsKey((i + 1).ToString()))
                    {
                        int slevel = runePrediction[(i + 1).ToString()].Key;
                        if (slevel > raiseTo)
                        {
                            raiseTo = slevel;
                        }
                        predictSubs |= runePrediction[(i + 1).ToString()].Value;
                    }

                    slotFakes[i] = raiseTo;
                    slotPred[i]  = predictSubs;
                }

                // set to running
                isRun = true;

                // Parallel the outer loop
                var loopRes = Parallel.ForEach <Rune>(runes[0], (r0, loopState) =>
                {
                    if (!isRun)
                    {
                        //break;
                        loopState.Break();
                    }

                    // number of builds ruled out since last sync
                    int kill = 0;
                    // number of builds added since last sync
                    int plus = 0;

                    foreach (Rune r1 in runes[1])
                    {
                        if (!isRun) // Can't break to a lable, don't want to goto
                        {
                            break;
                        }
                        foreach (Rune r2 in runes[2])
                        {
                            if (!isRun)
                            {
                                break;
                            }
                            foreach (Rune r3 in runes[3])
                            {
                                if (!isRun)
                                {
                                    break;
                                }
                                foreach (Rune r4 in runes[4])
                                {
                                    if (!isRun)
                                    {
                                        break;
                                    }
                                    foreach (Rune r5 in runes[5])
                                    {
                                        if (!isRun)
                                        {
                                            break;
                                        }

                                        Monster test         = new Monster(mon);
                                        test.Current.shrines = shrines;
                                        test.Current.leader  = leader;

                                        test.Current.FakeLevel   = slotFakes;
                                        test.Current.PredictSubs = slotPred;

                                        test.ApplyRune(r0);
                                        test.ApplyRune(r1);
                                        test.ApplyRune(r2);
                                        test.ApplyRune(r3);
                                        test.ApplyRune(r4);
                                        test.ApplyRune(r5);

                                        if (saveStats)
                                        {
                                            foreach (Rune r in test.Current.runes)
                                            {
                                                r.manageStats_LoadGen++;
                                            }
                                        }

                                        var cstats = test.GetStats();

                                        bool maxdead = false;

                                        if (Maximum != null)
                                        {
                                            foreach (var stat in statNames)
                                            {
                                                if (Maximum[stat] > 0 && cstats[stat] > Maximum[stat])
                                                {
                                                    maxdead = true;
                                                    break;
                                                }
                                            }
                                        }

                                        // check if build meets minimum
                                        if (Minimum != null && !(cstats > Minimum))
                                        {
                                            kill++;
                                        }
                                        else if (maxdead)
                                        {
                                            kill++;
                                        }
                                        // if no broken sets, check for broken sets
                                        else if (!AllowBroken && !test.Current.SetsFull)
                                        {
                                            kill++;
                                        }
                                        // if there are required sets, ensure we have them
                                        else if (RequiredSets != null && RequiredSets.Count > 0 && !RequiredSets.All(s => test.Current.sets.Contains(s)))
                                        {
                                            kill++;
                                        }
                                        else
                                        {
                                            // we found an okay build!
                                            plus++;

                                            if (saveStats)
                                            {
                                                foreach (Rune r in test.Current.runes)
                                                {
                                                    r.manageStats_LoadFilt++;
                                                }
                                            }

                                            // if we are to track all good builds, keep it
                                            if (!dumpBads)
                                            {
                                                tests.Add(test);
                                            }
                                            else
                                            {
                                                //lock (tests)
                                                //{
                                                // if there are currently no good builds, keep it

                                                if (tests.FirstOrDefault() == null)
                                                {
                                                    tests.Add(test);
                                                    Best = test;
                                                }
                                                else
                                                {
                                                    if (Best.GetStats() < test.GetStats())
                                                    {
                                                        Best = test;
                                                        tests.Add(test);
                                                    }

                                                    // take a snapshot of the builds (multithread /may/ cause a "collection modified" excepion in next step)

                                                    /*var tt = tests.ToList();
                                                     * // if this build is better than any other build, keep it
                                                     * // can't just keep a copy of Max becaues of threading
                                                     * if (tt.Max(t => sort(t.GetStats())) < sort(test.GetStats()))
                                                     * {
                                                     *  tests.Add(test);
                                                     * }*/
                                                }
                                                //}
                                            }
                                        }

                                        // every second, give a bit of feedback to those watching
                                        if (DateTime.Now > timer.AddSeconds(1))
                                        {
                                            timer = DateTime.Now;
                                            Console.WriteLine(count + "/" + total + "  " + String.Format("{0:P2}", (double)(count + complete - total) / (double)complete));
                                            if (printTo != null)
                                            {
                                                printTo.Invoke(String.Format("{0:P2}", (double)(count + complete - total) / (double)complete));
                                            }
                                            if (progTo != null)
                                            {
                                                progTo.Invoke((double)(count + complete - total) / (double)complete);
                                            }

                                            if (time > 0)
                                            {
                                                if (DateTime.Now > begin.AddSeconds(time))
                                                {
                                                    isRun = false;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    // sum up what work we've done
                                    Interlocked.Add(ref total, -kill);
                                    kill = 0;
                                    Interlocked.Add(ref count, plus);
                                    plus = 0;

                                    // if we've got enough, stop
                                    if (top > 0 && count >= top)
                                    {
                                        isRun = false;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                });

                // write out completion
                Console.WriteLine(isRun + " " + count + "/" + total + "  " + String.Format("{0:P2}", (double)(count + complete - total) / (double)complete));
                if (printTo != null)
                {
                    printTo.Invoke("100%");
                }
                if (progTo != null)
                {
                    progTo.Invoke(1);
                }

                // sort *all* the builds
                loads = tests.Where(t => t != null).OrderByDescending(r => sort(r.GetStats())).Take((top > 0 ? top : 1));

                // dump everything to console, if nothing to print to
                if (printTo == null)
                {
                    foreach (var l in loads)
                    {
                        Console.WriteLine(l.GetStats().Health + "  " + l.GetStats().Attack + "  " + l.GetStats().Defense + "  " + l.GetStats().Speed
                                          + "  " + l.GetStats().CritRate + "%" + "  " + l.GetStats().CritDamage + "%" + "  " + l.GetStats().Resistance + "%" + "  " + l.GetStats().Accuracy + "%");
                    }
                }

                // sadface if no builds
                if (loads.Count() == 0)
                {
                    Console.WriteLine("No builds :(");
                    if (printTo != null)
                    {
                        printTo.Invoke("Zero :(");
                    }
                }
                else
                {
                    // remember the good one
                    Best = loads.First();
                    foreach (Rune r in Best.Current.runes)
                    {
                        r.manageStats_In = true;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error " + e);
                if (printTo != null)
                {
                    printTo.Invoke(e.ToString());
                }
            }
        }
Ejemplo n.º 21
0
 private IWebSocketConnection GetSocket(string mac) => _macConnectionPairs.FirstOrDefault(x => x.Mac == mac).Socket;
Ejemplo n.º 22
0
 private static void _runOperation(SynchronizedCollection<FileOperation> queue, ref bool queueRunningIndicator)
 {
     FileOperation op;
     lock (queue.SyncRoot)
         op = queue.FirstOrDefault();
     while (op != null)
     {
         queue.Remove(op);
         if (!op.Aborted)
         {
             if (op.Do())
             {
                 if (OperationCompleted != null)
                     OperationCompleted(op);
                 if (op.SuccessCallback != null)
                     op.SuccessCallback();
             }
             else
             {
                 if (op.TryCount > 0)
                 {
                     System.Threading.Thread.Sleep(500);
                     queue.Add(op);
                 }
                 else
                 {
                     op.Fail();
                     if (OperationCompleted != null)
                         OperationCompleted(op);
                 }
             }
         }
         lock (queue.SyncRoot)
             op = queue.FirstOrDefault();
     }
     lock (queue.SyncRoot)
         queueRunningIndicator = false;
 }