Пример #1
0
 public IEnumerable<IUser> CreateUsersInBatch(IEnumerable<string> names, Contributions contribution, Sources source)
 {
     var newUsers =
         names.Where(name => !DoesUserExist(name)).Select(
             name => new User(name, userRepository.NonUserGeneratedPassword, string.Empty));
     Parallel.ForEach(newUsers, user =>
                                    {
                                        user.Source = source;
                                        user.AddContribution(contribution);
                                    });
     userRepository.AddUsers(newUsers);
     return newUsers;
 }
 public static Source GetSource(string novelTitle, int sourceID, Sources s)
 {
     Source rtnSource;
     switch (s)
     {
         case Sources.web69:
             rtnSource = new SourceWeb69(novelTitle, sourceID);
             break;
         default:
             rtnSource = null;
             break;
     }
     return rtnSource;
 }
 public static IAdapter GetCurentAdapterInstance(Sources source)
 {
     switch (source)
     {
         case Sources.DataBase:
             return new DatabaseAdapter();
         case Sources.Trello:
             return new TrelloManager();
         case Sources.Excel:
             return null;
         case Sources.GoogleSheets:
             return new GoogleSheetsAdapter();
         default:
             return null;
     }
 }
Пример #4
0
 public LabeledTextBox(Sources source , string value, string linkToTracker)
 {
     InitializeComponent();
     valueTextBox.Text = value;
     linkToTrackerTextBox.Hide();
     if (source == Sources.DataBase || source == Sources.Excel)
     {
         SourceLabel.Text = source.ToString() + ": "+ linkToTracker;
         linkToTrackerTextBox.Hide();
     }
     else
     {
         SourceLabel.Text = source.ToString();
         linkToTrackerTextBox.Show();
         linkToTrackerTextBox.Links.Add(0, 50, linkToTracker);
         linkToTrackerTextBox.Text = "Click to see this task in Source";
     }
 }
Пример #5
0
        public XASdkProject(string sdkVersion = "", string outputType = "Exe")
        {
            Sdk             = string.IsNullOrEmpty(sdkVersion) ? "Microsoft.Android.Sdk" : $"Microsoft.Android.Sdk/{sdkVersion}";
            TargetFramework = "net5.0";

            PackageName             = PackageName ?? string.Format("{0}.{0}", ProjectName);
            JavaPackageName         = JavaPackageName ?? PackageName.ToLowerInvariant();
            ExtraNuGetConfigSources = new List <string> {
                Path.Combine(XABuildPaths.BuildOutputDirectory, "nupkgs"),
                "https://dnceng.pkgs.visualstudio.com/public/_packaging/dotnet5/nuget/v3/index.json",
            };
            GlobalPackagesFolder = Path.Combine(XABuildPaths.TopDirectory, "packages");
            SetProperty(KnownProperties.OutputType, outputType);

            // Add relevant Android content to our project without writing it to the .csproj file
            if (outputType == "Exe")
            {
                Sources.Add(new BuildItem.Source("Properties\\AndroidManifest.xml")
                {
                    TextContent = () => default_android_manifest.Replace("${PROJECT_NAME}", ProjectName).Replace("${PACKAGENAME}", string.Format("{0}.{0}", ProjectName))
                });
            }
            Sources.Add(new BuildItem.Source($"MainActivity{Language.DefaultExtension}")
            {
                TextContent = () => ProcessSourceTemplate(MainActivity ?? DefaultMainActivity)
            });
            Sources.Add(new BuildItem.Source("Resources\\layout\\Main.axml")
            {
                TextContent = () => default_layout_main
            });
            Sources.Add(new BuildItem.Source("Resources\\values\\Strings.xml")
            {
                TextContent = () => default_strings_xml.Replace("${PROJECT_NAME}", ProjectName)
            });
            Sources.Add(new BuildItem.Source("Resources\\drawable-mdpi\\Icon.png")
            {
                BinaryContent = () => icon_binary_mdpi
            });
            Sources.Add(new BuildItem.Source($"Resources\\Resource.designer{Language.DefaultExtension}")
            {
                TextContent = () => string.Empty
            });
        }
        /// <summary>
        /// Delete the selected source
        /// </summary>
        /// <returns>Task Type</returns>
        private async Task DeleteSource()
        {
            if (IsWorking)
            {
                return;
            }
            IsWorking = true;

            try
            {
                MessageDialog showDialog = new MessageDialog("SourcesViewModelSourceDeleteAllRSSMessageDialog".GetLocalized());
                showDialog.Commands.Add(new UICommand("Yes".GetLocalized())
                {
                    Id = 0
                });
                showDialog.Commands.Add(new UICommand("No".GetLocalized())
                {
                    Id = 1
                });
                showDialog.DefaultCommandIndex = 0;
                showDialog.CancelCommandIndex  = 1;
                var result = await showDialog.ShowAsync();

                if ((int)result.Id == 0)
                {
                    await RSSDataService.DeleteManyFeedsAsync(x => x.PostSource.Id == SelectedSource.Id);
                }

                await SourceDataService.DeleteSourceAsync(SelectedSource);

                Sources.Remove(SelectedSource);
                ClearPopups();
                RefreshSourcesCommand.OnCanExecuteChanged();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            finally
            {
                IsWorking = false;
            }
        }
Пример #7
0
        public async void AddSubreddit()
        {
            string sub = await _dialog.ShowInputAsync("Add new Subreddit", "Please enter subreddit name");

            if (string.IsNullOrEmpty(sub))
            {
                return;
            }
            if (!sub.Contains("/r/"))
            {
                sub = "/r/" + sub;
            }
            var source = new WallpaperSource {
                Query = sub, Source = Source.Reddit
            };
            await _db.AddSource(source);

            Sources.Add(source);
        }
Пример #8
0
        /// <summary>
        /// Returns a collection of source sets that can be used to construct
        /// a `picture` element.
        /// </summary>
        public IList <ResponsiveMediaSource> GetSourceSets(int[] breakpoints)
        {
            var sourceSets                  = new List <ResponsiveMediaSource>();
            var orderedBreakpoints          = breakpoints.OrderByDescending(x => x).ToList();
            ResponsiveMediaSource lastMedia = null;

            for (var i = 0; i < orderedBreakpoints.Count; i++)
            {
                var media            = Sources.Where(x => x.Breakpoint == orderedBreakpoints[i]).FirstOrDefault();
                var isLastBreakpoint = i + 1 == orderedBreakpoints.Count;
                var nextBreakpoint   = isLastBreakpoint ? 0 : orderedBreakpoints[i + 1];

                if (media != null)
                {
                    lastMedia = new ResponsiveMediaSource {
                        Breakpoint = nextBreakpoint + 1, Url = Uri.EscapeUriString(media.Url)
                    };
                    sourceSets.Add(lastMedia);
                    continue;
                }

                if (!sourceSets.Any())
                {
                    continue;
                }

                var sourceSetToResize = sourceSets.Last();
                sourceSets.Add(new ResponsiveMediaSource {
                    Breakpoint = nextBreakpoint + 1, Url = $"{lastMedia.Url}?width={orderedBreakpoints[i]}"
                });
                continue;
            }

            if (!sourceSets.Any())
            {
                return(sourceSets);
            }

            SmallestImageUrl = sourceSets.Last().Url;
            sourceSets.Remove(sourceSets.Last());

            return(sourceSets);
        }
Пример #9
0
        public void AddSourceFile(string sourceId, IFileInfo file)
        {
            var sourceInfo = Sources.FirstOrDefault(info => info.SourceId == sourceId && info.FilePath == file.Path);

            if (sourceInfo == null)
            {
                sourceInfo = new ImportedFileInfo {
                    FilePath = file.Path, SourceId = sourceId
                }
            }
            ;
            else
            {
                Sources.Remove(sourceInfo);
            }

            sourceInfo.LastChange = file.LastChange;
            Sources.Add(sourceInfo);
        }
        private void CancelDownload()
        {
            _cancellationTokenSource?.Cancel();
            foreach (var source in Sources.Where(s => s.HasUrl))
            {
                switch (source.Status)
                {
                case DownloadStatus.NotStarted:
                    source.Message = Constants.Messages.NotStarted;
                    break;

                case DownloadStatus.Downloading:
                case DownloadStatus.Saving:
                    source.Message = Constants.Messages.Cancelled;
                    break;
                }
            }
            IsDownloading = false;
        }
Пример #11
0
        List <YouTubeResultCsv> ConvertData()
        {
            var result = Sources.Select(s =>
            {
                var sp = s.Split("___");
                return(new YouTubeResultCsv()
                {
                    KeyWord = KeyWord,
                    UserId = sp[0],
                    UserName = sp[1],
                    InfoId = sp[2],
                    ReleaseTime = DateTime.ParseExact(sp[3], "yyyyMMdd", null),
                    Text = sp[4],
                    ChannelId = sp[5],
                });
            }).ToList();

            return(result);
        }
Пример #12
0
        protected virtual IEnumerable <ContentItem> GetNodeChildren(ContentItem parent, string userInterface)
        {
            if (parent is IActiveChildren)
            {
                return(((IActiveChildren)parent).GetChildren(new AccessFilter(WebContext.User, Security)));
            }

            var query = new Query {
                Parent = parent, Interface = userInterface
            };

            if (!Settings.DisplayDataItems)
            {
                query.OnlyPages = true;
            }
            var children = Sources.GetChildren(query);

            return(children);
        }
Пример #13
0
        public override void SetSize(long size)
        {
            long currentSize = GetSize();

            if (currentSize == size)
            {
                return;
            }

            int currentSubFileCount = QuerySubFileCount(currentSize, SubFileSize);
            int newSubFileCount     = QuerySubFileCount(size, SubFileSize);

            if (size > currentSize)
            {
                IFile currentLastSubFile = Sources[currentSubFileCount - 1];
                long  newSubFileSize     = QuerySubFileSize(currentSubFileCount - 1, size, SubFileSize);

                currentLastSubFile.SetSize(newSubFileSize);

                for (int i = currentSubFileCount; i < newSubFileCount; i++)
                {
                    string newSubFilePath = ConcatenationFileSystem.GetSubFilePath(FilePath, i);
                    newSubFileSize = QuerySubFileSize(i, size, SubFileSize);

                    BaseFileSystem.CreateFile(newSubFilePath, newSubFileSize, CreateFileOptions.None);
                    Sources.Add(BaseFileSystem.OpenFile(newSubFilePath, Mode));
                }
            }
            else
            {
                for (int i = currentSubFileCount - 1; i > newSubFileCount - 1; i--)
                {
                    Sources[i].Dispose();
                    Sources.RemoveAt(i);

                    string subFilePath = ConcatenationFileSystem.GetSubFilePath(FilePath, i);
                    BaseFileSystem.DeleteFile(subFilePath);
                }

                long newLastFileSize = QuerySubFileSize(newSubFileCount - 1, size, SubFileSize);
                Sources[newSubFileCount - 1].SetSize(newLastFileSize);
            }
        }
 public void Validate(SqlServerValidationToolkitContext ctxSqlServer)
 {
     foreach (var source in Sources
              //include the errorType to get to the code of the wrong-values
              .Include(
                  s => s.Columns
                  .Select(c => c.ValidationRules
                          .Select(r => r.Validation_WrongValue
                                  .Select(wv => wv.Errortype)
                                  )
                          )
                  )
              )
     {
         source.Validate(ctxSqlServer.Database.Connection, this);
     }
     SaveChanges();
     this.Database.ExecuteSqlCommand("DELETE FROM Validation_WrongValue WHERE Is_Corrected=1");
 }
Пример #15
0
        /// <summary>
        /// Release resources.
        /// </summary>
        protected override void DisposeManaged()
        {
            // сначала удаляем поставщиков логов
            Sources.Clear();

            lock (_syncRoot)
            {
                _pendingMessages.Clear();
                _pendingMessages.Add(_disposeMessage);
            }

            // сбрасываем в логи то, что еще не сбросилось и выключаем таймер
            ImmediateFlush();

            _disposeMessage.Wait();
            _flushTimer.Dispose();

            base.DisposeManaged();
        }
Пример #16
0
        /// <summary>
        /// Merge
        /// </summary>
        /// <param name="append"></param>
        private void Merge(bool append)
        {
            FileMode fm = FileMode.Create;

            if (append)
            {
                fm = FileMode.Append;
            }
            bool   sourceIsTarget = (Sources.Contains(Targets[0]));
            string tmpFileName    = Path.GetTempFileName();

            // if source is target, use a temporary file that will be appended in the end. Otherwise, just use the given target.
            using (
                FileStream fs = sourceIsTarget
                    ? new FileStream(tmpFileName, FileMode.Create)
                    : Targets[0].GetFileInfo().Open(fm, FileAccess.Write))
            {
                foreach (var source in Sources)
                {
                    if (source.Exists())
                    {
                        using (Stream inStream = source.GetInputStream())
                        {
                            inStream.CopyTo(fs);
                        }
                    }
                    else
                    {
                        Error(source);
                    }
                }
            }
            if (sourceIsTarget)
            {
                //append tmpFile to existing target
                using (FileStream fsmerged = File.Open(Targets[0].GetFullPath(), fm, FileAccess.Write))
                    using (Stream tmpStream = new FileInfo(tmpFileName).OpenRead())
                    {
                        tmpStream.CopyTo(fsmerged);
                    }
                File.Delete(tmpFileName);
            }
        }
Пример #17
0
 //Загрузить сигналы указанного провайдера
 public void LoadSignals(string connectCode)
 {
     if (Project.SchemeSources.ContainsKey(connectCode))
     {
         if (!Sources.ContainsKey(connectCode))
         {
             Sources.Add(connectCode, new TablikSource(this, connectCode, Project.SchemeSources[connectCode].Complect));
         }
         Sources[connectCode].LoadSignals();
     }
     if (Project.SchemeReceivers.ContainsKey(connectCode))
     {
         if (!Receivers.ContainsKey(connectCode))
         {
             Receivers.Add(connectCode, new TablikReceiver(this, connectCode, Project.SchemeReceivers[connectCode].Complect));
         }
         Receivers[connectCode].LoadSignals();
     }
 }
Пример #18
0
        /// <summary>
        /// Propagates the source value to target. Used by runtime bindings.
        /// </summary>
        public async Task PropagateSourceToTargetMethod()
        {
            if (IsSimple)
            {
                var transformedValue = await TransformMethod();
            }

            switch (BindingType)
            {
            case BindingType.SingleBinding:
                var source = Sources[0] as RuntimeBindingPath;
                var value  = source.GetValue();

                var target = Target as RuntimeBindingPath;
                target.SetValue(value);
                break;


            case BindingType.MultiBindingTransform:
                if (TransformMethod == null)
                {
                    return;
                }

                var transformedValue = await TransformMethod();

                var transformTarget = Target as RuntimeBindingPath;
                transformTarget.SetValue(transformedValue);
                break;

            case BindingType.MultiBindingFormatString:
                var formatSourceValues = Sources.Select(x => (x as RuntimeBindingPath).GetValue()).ToArray();
                var formattedValue     = String.Format(FormatString, formatSourceValues);

                var formatStringTarget = Target as RuntimeBindingPath;
                formatStringTarget.SetValue(formattedValue);
                break;

            default:
                break;
            }
        }
Пример #19
0
        /// <summary>
        /// True if the configuration or security file has been modified
        /// </summary>
        public bool MustReload()
        {
            if (Configuration.FilePath != null && File.GetLastWriteTime(Configuration.FilePath) != Configuration.LastModification)
            {
                return(true);
            }
            if (Security.FilePath != null && File.GetLastWriteTime(Security.FilePath) != Security.LastModification)
            {
                return(true);
            }
            foreach (var item in Sources)
            {
                if (File.GetLastWriteTime(item.FilePath) != item.LastModification)
                {
                    return(true);
                }
            }
            foreach (var item in Devices.Where(i => i is OutputEmailDevice))
            {
                if (item.FilePath != null && File.GetLastWriteTime(item.FilePath) != ((OutputEmailDevice)item).LastModification)
                {
                    return(true);
                }
            }
            //Check for new files
            foreach (var file in Directory.GetFiles(SourcesFolder, "*." + SealConfigurationFileExtension))
            {
                if (!Sources.Exists(i => i.FilePath == file))
                {
                    return(true);
                }
            }
            foreach (var file in Directory.GetFiles(DevicesEmailFolder, "*." + SealConfigurationFileExtension))
            {
                if (!Devices.Exists(i => i.FilePath == file))
                {
                    return(true);
                }
            }

            return(false);
        }
Пример #20
0
        public static IMediaSourceHelper GetMediaSource(Sources source, IThemeRepository themeRepository)
        {
            switch (source)
            {
                case Sources.Nzz:
                    return new NzzHelper(themeRepository);
                case Sources.Blick:
                case Sources.BlickAmAbend:
                    return new BlickHelper(themeRepository);
                case Sources.Postillon:
                    return new PostillonHelper(themeRepository);
                case Sources.ZwanzigMin:
                    return new ZwanzigMinHelper(themeRepository);
                case Sources.Stern:
                    return new SternHelper(themeRepository);
                case Sources.Spiegel:
                    return new SpiegelHelper(themeRepository);
                case Sources.Bild:
                    return new BildHelper(themeRepository);
                case Sources.Zeit:
                    return new ZeitHelper(themeRepository);
                case Sources.Welt:
                    return new WeltHelper(themeRepository);

                case Sources.BaslerZeitung:
                case Sources.BernerZeitung:
                case Sources.DerBund:
                case Sources.Tagesanzeiger:
                case Sources.LeMatin:
                case Sources.VingtQuatreHeures:
                case Sources.TribuneDeGeneve:
                case Sources.ZuerichseeZeitung:
                case Sources.Landbote:
                case Sources.ZuericherUnterlaender:
                case Sources.BernerOeberlaender:
                case Sources.ThunerTagblatt:
                case Sources.LangenthalerTagblatt:
                    return new TamediaHelper(themeRepository);
                default:
                    throw new ArgumentOutOfRangeException(nameof(source), source, null);
            }
        }
Пример #21
0
        public override bool scrappear(string url, ref Sources serverLinks, ref string error)
        {
            string buffer   = string.Empty;
            string urlVideo = string.Empty;
            string urlSubs  = string.Empty;
            string urlThumb = string.Empty;

            if (0 == error.Length)
            {
                HttpHelper.requestGet(url, null, ref buffer, ref error);
            }

            if (0 == error.Length)
            {
                obtenerUrlSubs(url, buffer, ref urlSubs, ref error);
            }

            if (0 == error.Length)
            {
                obtenerUrlVideo(url, buffer, ref urlVideo, ref error);
            }

            if (0 == error.Length)
            {
                obtenerUrlThumb(url, buffer, ref urlThumb, ref error);
            }

            if (0 == error.Length)
            {
                if (base.esArchivoValido(urlVideo))
                {
                    serverLinks.Add(new Source(urlVideo, urlSubs, "Default", SERVER, urlThumb));
                }
            }

            if (error.Length > 0)
            {
                error = "ServerScrapperStreamango.scrappear -> " + error;
            }

            return(0 == error.Length);
        }
Пример #22
0
        public BuildFileResult Build()
        {
            var projectName = Path.GetRandomFileName();
            var references  = new List <MetadataReference>();

            foreach (var reference in References)
            {
                if (reference.CopyLocal)
                {
                    if (string.IsNullOrEmpty(reference.Path))
                    {
                        throw new InvalidOperationException("Could not find path for reference " + reference);
                    }

                    File.Copy(reference.Path, Path.Combine(TargetDir, Path.GetFileName(reference.Path)), overwrite: true);
                }

                references.AddRange(reference.References);
            }

            var compilation = CSharpCompilation.Create(
                projectName,
                Sources.Select(s => SyntaxFactory.ParseSyntaxTree(s)),
                references,
                new CSharpCompilationOptions(
                    OutputKind.DynamicallyLinkedLibrary,
                    nullableContextOptions: NullableReferenceTypes ? NullableContextOptions.Enable : NullableContextOptions.Disable));

            var targetPath = Path.Combine(TargetDir ?? Path.GetTempPath(), projectName + ".dll");

            using (var stream = File.OpenWrite(targetPath))
            {
                var result = compilation.Emit(stream);
                if (!result.Success)
                {
                    throw new InvalidOperationException(
                              $"Build failed. Diagnostics: {string.Join(Environment.NewLine, result.Diagnostics)}");
                }
            }

            return(new BuildFileResult(targetPath));
        }
Пример #23
0
        public bool UpdateRates(string name, Guid UserId)
        {
            var source = Sources.Find(src => src.Name == name);

            if (source == null)
            {
                return(false);
            }

            BaseCurrency = source.BaseCurrency;
            var userCurrencies = UserCurrenciesInit(UserId, BaseCurrency);

            if (source.Load(userCurrencies.Select(currency => currency.CurrencyType.ToString()).ToList()))
            {
                var          loadedTypes     = source.LoadedRates.Select(currency => currency.Key).ToList();
                Currency     currentCurrency = null;
                CurrencyRate rate            = null;

                foreach (var loadedRate in source.LoadedRates)
                {
                    currentCurrency = userCurrencies.FirstOrDefault(crncy => crncy.CurrencyType == loadedRate.Key);
                    var lastRate = Db.CurrencyRates
                                   .Where(x => x.CurrencyId == currentCurrency.Id)
                                   .OrderByDescending(x => x.DateTime)
                                   .FirstOrDefault();

                    if (currentCurrency != null && decimal.Round(lastRate.Value, 4) != decimal.Round(loadedRate.Value, 4))
                    {
                        currentCurrency.Value = loadedRate.Value;
                        rate = new CurrencyRate()
                        {
                            CurrencyId = currentCurrency.Id,
                            DateTime   = DateTime.Now,
                            Value      = decimal.Round(loadedRate.Value, 4)
                        };
                        Db.CurrencyRates.Add(rate);
                    }
                }
                Db.SaveChanges();
            }
            return(true);
        }
Пример #24
0
        private void RemoveSource(SourceViewModel svm)
        {
            Sources.Remove(svm);
            SVMLookup.Remove(svm.Data);

            List <ItemViewModel> itemsToRemove = new List <ItemViewModel>();

            foreach (var i in items)
            {
                if (i.SourceName == svm.SourceName)
                {
                    itemsToRemove.Add(i);
                }
            }

            foreach (var i in itemsToRemove)
            {
                items.Remove(i);
            }
        }
Пример #25
0
        public void Aggregate(string?source, string target, DateTime time, StatusAuditReport?additionalReport)
        {
            StatusAuditReport report = additionalReport ?? new StatusAuditReport(time, TimeSpan.Zero, null, StatusAuditAlert.None);

            if (CommonAlert != report.Alert)
            {
                throw new InvalidOperationException("Only results with the same alert can be aggregated!");
            }
            if (Target != RenderTarget(target))
            {
                throw new InvalidOperationException("Only results with the same target can be aggregated!");
            }
            RatingSum += report.Alert?.Rating ?? StatusRating.Okay;
            Sources.Add(RenderSource(source));
            TimeRange.AddSample(time);
            AuditStartRange.AddSample(report.AuditStartTime);
            AuditDurationRange.AddSample(report.AuditDuration);
            NextAuditTime  = (NextAuditTime == null) ? report.NextAuditTime : new DateTime(Math.Min(NextAuditTime.Value.Ticks, (report.NextAuditTime ?? DateTime.MaxValue).Ticks));
            PropertyRanges = new List <StatusPropertyRange>();
        }
Пример #26
0
        public static IAdapter GetCurentAdapterInstance(Sources source)
        {
            switch (source)
            {
            case Sources.DataBase:
                return(new DatabaseAdapter());

            case Sources.Trello:
                return(new TrelloManager());

            case Sources.Excel:
                return(null);

            case Sources.GoogleSheets:
                return(new GoogleSheetsAdapter());

            default:
                return(null);
            }
        }
Пример #27
0
        protected void RefreshSourcesInformation()
        {
            if (Sources != null && Sources.Count > 0)
            {
                Entropy = Sources.EntropyOnItemId(ItemId);

                DataSourcesCollection positive, negative;
                Sources.DivideOnHavingItem(ItemId, out positive, out negative);
                Probability = (double)positive.Count / Sources.Count;
                Positive    = positive;
                Negative    = negative;
            }
            else
            {
                Entropy     = double.NaN;
                Probability = double.NaN;
                Positive    = null;
                Negative    = null;
            }
        }
Пример #28
0
        public static IAccountToken GetCurrentInstanceForToken(Sources source)
        {
            switch (source)
            {
            case Sources.DataBase:
                return(new DatabaseAccountToken());

            case Sources.Trello:
                return(null);

            case Sources.Excel:
                return(new ExcelAccountToken());

            case Sources.GoogleSheets:
                return(null);

            default:
                return(null);
            }
        }
Пример #29
0
        public static IAccountSettings GetCurrentInstance(Sources source)
        {
            switch (source)
            {
            case Sources.DataBase:
                return(new DatabaseAccountSettings());

            case Sources.Trello:
                return(new TrelloAccountSettings());

            case Sources.Excel:
                return(new ExcelAccountSettings());;

            case Sources.GoogleSheets:
                return(new GoogleSheetsAccountSettings());

            default:
                return(null);
            }
        }
Пример #30
0
 public Image ToImage() => new Image
 {
     Id        = Id,
     Score     = Score,
     Width     = Width,
     Height    = Height,
     MediaType = MediaType,
     Tags      = new Dictionary <ImageTag, string[]>
     {
         { ImageTag.General, TagsGeneral },
         { ImageTag.Artist, TagsArtist },
         { ImageTag.Character, TagsCharacter },
         { ImageTag.Copyright, TagsCopyright },
         { ImageTag.Metadata, TagsMetadata },
         { ImageTag.Pool, TagsPool }
     }.RemoveNullValues(),
     Sources = Sources?.ToArray(ExternalSource.Parse),
     Rating  = Rating,
     Notes   = Notes?.ToArray(n => n.ToNote())
 };
        /// <summary>
        /// Writes an detail summary of a specific source
        /// </summary>
        /// <param name="name">The name of the source</param>
        /// <param name="logLevel">The log level</param>
        public void LogSourceDetails(string name, LogType logLevel = LogType.Information)
        {
            // Try and find a source by that name
            var foundSource = Sources?.FirstOrDefault(source => source.Name.EqualsIgnoreCase(name));

            // If we didn't find one...
            if (foundSource == null)
            {
                // Log it
                CoreLogger.Log($"Live Data Source '{name}' not found", type: logLevel);

                // Show available sources
                LogAllSources(logLevel);

                return;
            }

            // Log source details
            foundSource.Log(logLevel);
        }
Пример #32
0
        public Scheduler()
        {
            // Populate the routes model, wait for it
            Route.Populate().Wait();

            // Populate the current dataset, wait for it
            Sources.Populate().Wait();

            // Run the schedule updater every day at 3AM Eastern Time
            Schedule(async() => await Sources.Populate()).ToRunEvery(1).Days().At(3, 00);

            // Run the prediction updater now & every 30 seconds
            Schedule(async() => await Predicted.Update()).ToRunNow().AndEvery(30).Seconds();

            // Run the data updater now & every 3 seconds
            Schedule(async() => await Sources.Actual.Update()).ToRunNow().AndEvery(3).Seconds();

            // Save data to db every 30 seconds
            Schedule(() => Database.Capture()).ToRunEvery(30).Seconds();
        }
Пример #33
0
        private void FilterControl_Loaded(object sender, RoutedEventArgs e)
        {
            GetSource();

            RefreshCommand   = new RelayCommand(GetSource);
            NewFilterCommand = new RelayCommand(() =>
            {
                var newFilter = new Filter
                {
                    ConfigName     = "#Cau hinh " + FruitsNames[new Random().Next(0, FruitsNames.Length)],
                    NumberOfAction = 5
                };

                Sources.Add(newFilter);
                SelectedFilter = newFilter;
            });
            SaveConfigsCommand = new RelayCommand(() =>
            {
            });
        }
Пример #34
0
            /// <summary>
            /// Returns a source by its name
            /// </summary>
            /// <param name="name">Name of the source</param>
            /// <returns>Handle to the source or null</returns>
            public Source GetSource(string name)
            {
                if (string.IsNullOrEmpty(name))
                {
                    return(null);
                }

                if (name.StartsWith("#"))
                {
                    name = name.Substring(1, name.Length - 1);
                }

                if (Sources.ContainsKey(name))
                {
                    return(Sources[name]);
                }


                return(null);
            }
Пример #35
0
        /// <summary>
        /// Initialization method
        /// </summary>
        public async Task Initialize()
        {
            if (IsInitialized)
            {
                return;
            }
            var loadingProcess = ScenarioManager.Instance.loadingPanel.AddProgress();

            loadingProcess.Update("Initializing agents.");
            await ScenarioManager.Instance.WaitForExtension <InputManager>();

            var tasks                 = new Task[sources.Count];
            var sourceProgresses      = new Progress <float> [sources.Count];
            var sourceProgressesValue = new float[sources.Count];
            var progressUpdate        = new Action(() =>
            {
                var progressSum = sourceProgressesValue.Sum();
                progressSum    /= sources.Count;
                loadingProcess.Update($"Loading agents {progressSum:P}.");
            });

            for (var i = 0; i < sources.Count; i++)
            {
                var newSource = Instantiate(sources[i], transform);
                Sources.Add(newSource);
                var sourceId = i;
                sourceProgresses[i] = new Progress <float>(f =>
                {
                    sourceProgressesValue[sourceId] = f;
                    progressUpdate();
                });
                tasks[i] = newSource.Initialize(sourceProgresses[i]);
            }

            await Task.WhenAll(tasks);

            ScenarioManager.Instance.ScenarioReset += InstanceOnScenarioReset;
            IsInitialized = true;
            loadingProcess.NotifyCompletion();
            Debug.Log($"{GetType().Name} scenario editor extension has been initialized.");
        }
Пример #36
0
		public override void Prepare(Sources.IUpdateSource source)
		{
			if (string.IsNullOrEmpty(LocalPath))
			{
				UpdateManager.Instance.Logger.Log(Logger.SeverityLevel.Warning, "FileUpdateTask: LocalPath is empty, task is a noop");
				return; // Errorneous case, but there's nothing to prepare to, and by default we prefer a noop over an error
			}

			string fileName;
			if (!string.IsNullOrEmpty(UpdateTo))
				fileName = UpdateTo;
			else
				fileName = LocalPath;

			_tempFile = null;

			string baseUrl = UpdateManager.Instance.BaseUrl;
			string tempFileLocal = Path.Combine(UpdateManager.Instance.Config.TempFolder, Guid.NewGuid().ToString());

			UpdateManager.Instance.Logger.Log("FileUpdateTask: Downloading {0} with BaseUrl of {1} to {2}", fileName, baseUrl, tempFileLocal);

			if (!source.GetData(fileName, baseUrl, OnProgress, ref tempFileLocal))
				throw new UpdateProcessFailedException("FileUpdateTask: Failed to get file from source");

			_tempFile = tempFileLocal;
			if (_tempFile == null)
				throw new UpdateProcessFailedException("FileUpdateTask: Failed to get file from source");

			if (!string.IsNullOrEmpty(Sha256Checksum))
			{
				string checksum = Utils.FileChecksum.GetSHA256Checksum(_tempFile);
				if (!checksum.Equals(Sha256Checksum))
					throw new UpdateProcessFailedException(string.Format("FileUpdateTask: Checksums do not match; expected {0} but got {1}", Sha256Checksum, checksum));
			}

			_destinationFile = Path.Combine(Path.GetDirectoryName(UpdateManager.Instance.ApplicationPath), LocalPath);
			UpdateManager.Instance.Logger.Log("FileUpdateTask: Prepared successfully; destination file: {0}", _destinationFile);
		}
Пример #37
0
        internal Sources AllVisibleSources(OCL.User AccessingUser)
        {
            try
            {
                string sSQL = "";
                //bool CheckScene = false;

                if(!AccessingUser.mvarIsSuperUser)
                {
                    sSQL = "SELECT DISTINCT tblGroupTokens.ObjectId FROM tblGroupTokens left outer join tblSource ON " +
                        " tblSource.ID = tblGroupTokens.ObjectId WHERE UserId = " + AccessingUser.ID +
                        " AND tblGroupTokens.ObjectTypeId = " + Convert.ToInt32(OCL.OysterObjectType.Source) +
                        " AND tblGroupTokens.IsVisible <> 0" +
                        " AND tblSource.IsDefault = 0";
                    //CheckScene = true;
                }
                else
                {
                    /// User is either a SuperUser or can see all Sources in System
                    sSQL = "Select Id FROM tblSource WHERE IsDefault = 0";

                }
                Sources X = new Sources();
                DataSet DS = RF.GetDataSet(sSQL);
                DataTable DT = DS.Tables[0];
                //OCL.Scene DefaultScene = (OCL.Scene)GetUnassignedObject(OCL.OysterUnassignedObjects.Scene);

                foreach(DataRow R in DT.Rows)
                {
                    Source Ro = GetSource(Convert.ToInt32((object)R[0]));
                    if(Ro != null)
                    {
                        X.Add(Ro);
                    }
                }
                DT.Dispose();
                return X;
            }
            catch(Exception Err)
            {
                throw new ApplicationException(Err.Message);
            }
        }
Пример #38
0
        /// <summary>
        /// Returns all Streaming Encoders currently in this Scene
        /// </summary>
        /// <returns></returns>
        internal Sources ALLStreamingEncoders(double GroupId)
        {
            try
            {
                int iGroupId = Convert.ToInt32(GroupId);
                Sources X = new Sources();
                string sSQL = "Select * FROM tblGroupStreamingEncoderRel " +
                    "WHERE GroupId = " + iGroupId;

                DataSet DS = RF.GetDataSet(sSQL);
                DataTable DT = DS.Tables[0];
                foreach(DataRow R in DT.Rows)
                {
                    Source S = null;
                    S = GetSource(Convert.ToInt32((object)R[1]));
                    if(S != null)
                        X.Add(S);
                }
                return X;
            }
            catch(Exception Err)
            {
                throw new ApplicationException(Err.Message);
            }
        }
Пример #39
0
        /// <summary>
        /// Return all of sources that are visible to AccessingUser in a scene that is in this group
        /// </summary>
        /// <param name="AccessingUser"></param>
        /// <param name="TargetGroup"></param>
        /// <param name="TargetScene"></param>
        /// <returns></returns>
        internal Sources AllVisibleSources(OCL.User AccessingUser, OCL.Group TargetGroup,OCL.Scene TargetScene)
        {
            try
            {
                string sSQL = "";
                int GroupID = TargetGroup.mvarID;
                if(!AccessingUser.mvarIsSuperUser)
                {
                    sSQL = "SELECT DISTINCT tblGroupTokens.ObjectId FROM tblGroupTokens left outer join tblSource ON " +
                        " tblSource.ID = tblGroupTokens.ObjectId" +
                        " WHERE UserId = " + AccessingUser.ID +
                        " AND tblGroupTokens.ObjectTypeId = " + Convert.ToInt32(OCL.OysterObjectType.Source) +
                        " AND tblGroupTokens.IsVisible <> 0" +
                        " AND tblSource.IsDefault = 0" +
                        " AND tblSource.SceneId = " + TargetScene.mvarID +
                        " AND tblGroupTokens.GroupID = " + GroupID;

                }
                else
                {
                    //This is a Super User or User can see all Sources... show em every Source in this Group except the default group of course
                    sSQL = "SELECT DISTINCT tblGroupTokens.ObjectId FROM tblGroupTokens left outer join tblSource ON " +
                        " tblSource.ID = tblGroupTokens.ObjectId WHERE " +
                        " tblGroupTokens.ObjectTypeId = " + Convert.ToInt32(OCL.OysterObjectType.Source) +
                        " AND tblSource.IsDefault = 0" +
                        " AND tblSource.SceneId = " + TargetScene.mvarID +
                        " AND tblGroupTokens.GroupID = " + GroupID;
                }

                Sources X = new Sources();
                DataSet DS = RF.GetDataSet(sSQL);
                DataTable DT = DS.Tables[0];

                foreach(DataRow R in DT.Rows)
                {
                    Source Ro = GetSource(Convert.ToInt32((object)R[0]));
                    if(Ro != null)
                    {
                        X.Add(Ro);
                    }
                }
                DT.Dispose();
                return X;
            }
            catch(Exception Err)
            {
                throw new ApplicationException(Err.Message);
            }
        }
Пример #40
0
 public override void Prepare(Sources.IUpdateSource source)
 {
     // No preparation required
 }
Пример #41
0
 /// <summary>
 /// Returns all Streaming Encoders currently in the System
 /// </summary>
 /// <returns></returns>
 internal Sources ALLStreamingEncoders()
 {
     try
     {
         Sources X = new Sources();
         string sSQL = "SELECT tblSource.Id FROM tblSource " +
             "Left Outer Join tblScene ON tblScene.Id=tblSource.SceneId " +
             "Order By tblScene.Name";
         DataSet DS = RF.GetDataSet(sSQL);
         DataTable DT = DS.Tables[0];
         foreach(DataRow R in DT.Rows)
         {
             Source S = null;
             S = GetSource(Convert.ToInt32((object)R[0]));
             if(S != null)
                 X.Add(S);
         }
         DT.Dispose();
         return X;
     }
     catch(Exception Err)
     {
         throw new ApplicationException(Err.Message);
     }
 }
Пример #42
0
 /// <summary>
 /// Initializing constructor
 /// </summary>
 /// <param name="settings">GitHub connection source settings</param>
 public VerifyInfoRequest( Sources.SourceSettings settings ) : base( settings )
 {
 }
Пример #43
0
        public bool Prepare(Sources.IUpdateSource source)
        {
            if (string.IsNullOrEmpty(LocalPath))
                return true; // Errorneous case, but there's nothing to prepare to...

            string fileName;
            if (!string.IsNullOrEmpty(UpdateTo))
                fileName = UpdateTo;
            else
                fileName = LocalPath;

            tempFile = null;

            try
            {
                string tempFileLocal = Path.Combine(UpdateManager.Instance.TempFolder, Guid.NewGuid().ToString());
                if (!source.GetData(fileName, UpdateManager.Instance.BaseUrl, ref tempFileLocal))
                    return false;

                tempFile = tempFileLocal;
            }
            catch (Exception ex)
            {
                throw new UpdateProcessFailedException("Couldn't get Data from source", ex);
            }

            if (!string.IsNullOrEmpty(Sha256Checksum))
            {
                string checksum = Utils.FileChecksum.GetSHA256Checksum(tempFile);
                if (!checksum.Equals(Sha256Checksum))
                    return false;
            }

            return true;
        }
 public AnyCommand(Sources sources)
     : base(sources)
 {
 }
Пример #45
0
 /// <summary>
 /// Initializing constructor
 /// </summary>
 /// <param name="settings">GitHub connection source settings</param>
 public AddIssueRequest( Sources.SourceSettings settings ) : base( settings )
 {
 }
Пример #46
0
 /// <summary>
 /// Initializing constructor
 /// </summary>
 /// <param name="settings">GitHub connection source settings</param>
 public GetListOfIssuesRequest( Sources.SourceSettings settings ) : base( settings )
 {
 }
Пример #47
0
			public PrefsHolder(string prefsString, Sources source)
			{
				Source = source;
				previousPrefs = DeSerialise(prefsString);
				foreach (string key in previousPrefs.Keys)
					this[key] = new Pref(key, previousPrefs[key]);
			}
Пример #48
0
 public ListCommand(Sources sources)
     : base(sources)
 {
 }
Пример #49
0
 public static List<IAccountSettings> GetAllUserAccountsInSource(List<IAccountSettings> allAccounts, Sources sourceType)
 {
     List<IAccountSettings> acc;
     if (allAccounts != null)
     {
         acc = allAccounts.Select(x => x).Where(x => x.Source == sourceType).ToList();
     }
     else
     {
         acc = null;
     }
     return acc;
 }
Пример #50
0
 public bool Prepare(Sources.IUpdateSource source)
 {
     // No preparation required
     return true;
 }
Пример #51
0
 public RunTime()
 {
     TotalCalls = 0;
     Modules = new Dictionary<string, Dictionary<string, Tuple<float, float>>>();
     Paths = new Dictionary<int, CallPaths>();
     Functions = new Dictionary<int, Function>();
     SourceSections = new Sources();
 }
Пример #52
0
 /// <summary>
 /// Change the current source to the requested source
 /// </summary>
 /// <param name="source">Source to change to</param>
 private void ChangeSource(Sources source)
 {
     if (source != Source) // If selected source is not already chosen
     {
         // Make note of current source
         Sources previousSource = Source;
         // Start new source
         switch (source)
         {
             case Sources.STUDIO:
                 StartStudio();
                 break;
             case Sources.SRA:
                 StartChart();
                 break;
             case Sources.OB:
                 StartOB();
                 break;
             case Sources.EMERGENCY:
                 StartEmergency();
                 break;
         }
         // Stop old source
         switch (previousSource)
         {
             case Sources.STUDIO:
                 StopStudio();
                 break;
             case Sources.SRA:
                 StopChart();
                 break;
             case Sources.OB:
                 StopOB();
                 break;
             case Sources.EMERGENCY:
                 StopEmergency();
                 break;
         }
         // Send event showing source has been changed
         currentSource = source;
         if (SourceChanged != null)
         {
             SourceChanged(this, new EventArgs());
         }
         // Send source information to clock
         if (ClockIP != "" && ClockIP != null) // If an IP has been set
         {
             try
             {
                 TcpClient client = new TcpClient(ClockIP, 7000);
                 StreamWriter writer = new StreamWriter(client.GetStream());
                 writer.AutoFlush = true;
                 if (source == Sources.STUDIO)
                 {
                     writer.WriteLine("STUDIO ON");
                 }
                 else
                 {
                     writer.WriteLine("STUDIO OFF");
                 }
                 if (source == Sources.EMERGENCY)
                 {
                     writer.WriteLine("EMERGENCY ON");
                 }
                 else
                 {
                     writer.WriteLine("EMERGENCY OFF");
                 }
                 writer.WriteLine("EXIT");
                 client.GetStream().Close();
                 client.Close();
             }
             catch
             {
                 // Do nothing if an exception occurs
             }
         }
     }
 }
Пример #53
0
 public static IAccountToken GetCurrentInstanceForToken(Sources source)
 {
     switch (source)
     {
         case Sources.DataBase:
             return new DatabaseAccountToken();
         case Sources.Trello:
             return null;
         case Sources.Excel:
             return new ExcelAccountToken();
         case Sources.GoogleSheets:
             return null;
         default:
             return null;
     }
 }
        /// <summary>
        /// Watches source changes and dynamically adds/removes the record button in the toolbar
        /// </summary>
        /// <param name="args">
        /// A <see cref="Sources.SourceEventArgs"/> -- not used
        /// </param>
        void OnSourceChanged(Sources.SourceEventArgs args)
        {
            PrimarySource primary_source = action_service.GlobalActions.ActivePrimarySource;

            if (primary_source == null)
            {
                return;
            }

            if (!primary_source.IsLocal && ui_button_id == 0)
            {
                ui_button_id = action_service.UIManager.AddUiFromResource ("StreamrecorderButton.xml");
            }
            if (primary_source.IsLocal && ui_button_id > 0)
            {
                action_service.UIManager.RemoveUi(ui_button_id);
                ui_button_id = 0;
            }
        }
Пример #55
0
 /// does the logging.
 /// @param str the string to log
 /// @param category the category of the log
 /// @param source the source of the log
 /// @param logLevel what level to show and how to show it
 public virtual void Log(string str, Categories category, Sources source, VerboseLevel logLevel)
 {
     if (logLevel < m_minLevelToShow)
         return; // too low a level
     if (m_categoriesToShow[(int)category] && m_sourcesToShow[(int)source])
     {
         if (logLevel == VerboseLevel.Verbose)
             Debug.Log(str);
         else if (logLevel == VerboseLevel.Warning)
             Debug.LogWarning(str);
         else Debug.LogError(str);
     }
 }
Пример #56
0
        public static IAccountToken GetTokenByID(Int32 tokenId, Sources source)
        {
            IAccountToken targetToken = null;
            using (ISession session = sessionFactory.OpenSession())
            {
                TokenDAO tok = session.Get<TokenDAO>(tokenId);
                Token token = tok.TokenDAOToTokenDomain();
                targetToken = GetCurrentInstanceForToken(source);

                if (targetToken != null)
                {
                    targetToken = targetToken.Convert(token);
                }
            }
            return targetToken;
        }
        public List<TaskMainDTO> GetMatchedTasks(string taskID, Sources linkToTracker, Int32 tokenID)
        {
            TaskMainDAO taskMainDAO = TaskMainDAO.GetTaskFromDB(taskID, linkToTracker, tokenID);
            ITask taskMain = ConverterDAOtoDomain.TaskMainDaoToTaskMain(taskMainDAO);

            List<ITask> matchedTasks = new List<ITask>();
            matchedTasks.Add(taskMain);
            matchedTasks.AddRange(taskMain.MatchedTasks);

            List<TaskMainDTO> taskMainDTO = ConverterDomainToDTO.TaskMainToTaskMainDTO(matchedTasks);
            return taskMainDTO;
        }
Пример #58
0
 public static IAccountSettings GetCurrentInstance(Sources source)
 {
     switch (source)
     {
         case Sources.DataBase:
             return new DatabaseAccountSettings();
         case Sources.Trello:
             return new TrelloAccountSettings();
         case Sources.Excel:
             return new ExcelAccountSettings(); ;
         case Sources.GoogleSheets:
             return new GoogleSheetsAccountSettings();
         default:
             return null;
     }
 }
Пример #59
0
 private static string GetSingleValue(Sources[] values)
 {
     string[] stringValues = new string[values.Length];
     for (int i = 0; i < values.Length; i++)
     {
         stringValues[i] = values[i].ToString();
     }
     return string.Join(", ", stringValues);
 }
Пример #60
0
 /// <summary>
 /// Initializing constructor
 /// </summary>
 /// <param name="settings">GitHub connection source settings</param>
 public CloseIssueRequest( Sources.SourceSettings settings ) : base( settings )
 {
 }