public void TestDictionary()
        {
            var d = new Dictionary<int, string> {{1, "one"}};
            Assert.AreEqual("one", d.GetValueOrDefault(1));
            Assert.AreEqual(null, d.GetValueOrDefault(2));

        }
Example #2
0
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            if (authInfo.ContainsKey("user_id"))
                tokens.UserId = authInfo.GetValueOrDefault("user_id");

            if (authInfo.ContainsKey("screen_name"))
                tokens.UserName = authInfo.GetValueOrDefault("screen_name");

            try
            {
                if (tokens.UserId != null)
                {
                    var json = AuthHttpGateway.DownloadTwitterUserInfo(tokens.UserId);
                    var objs = JsonObject.ParseArray(json);
                    if (objs.Count > 0)
                    {
                        var obj = objs[0];
                        tokens.DisplayName = obj.Get("name");
                    }
                }

                LoadUserOAuthProvider(userSession, tokens);
            }
            catch (Exception ex)
            {
                Log.Error("Could not retrieve twitter user info for '{0}'".Fmt(userSession.TwitterUserId), ex);
            }
        }
Example #3
0
 public Release(Dictionary<string,string> properties, DateTime date)
 {
     Title = properties.GetValueOrDefault("Title");
     ReleaseName = properties.GetValueOrDefault("Rlsname");
     Group = properties.GetValueOrDefault("Group");
     Tags = properties.GetValueOrDefault("Tags", string.Empty).Split(new char[] {','}).Select(str => str.Trim()).ToArray();
     Date = date;
 }
Example #4
0
 public void GetValueOrDefaultReturnsValueFromDictionary()
 {
     var dictionary = new Dictionary<string, int> { { "one", 1 }, { "two", 2 }, { "three", 3 } };
     foreach (var pair in dictionary)
     {
         Assert.AreEqual(pair.Value, dictionary.GetValueOrDefault(pair.Key));
         Assert.AreEqual(pair.Value, dictionary.GetValueOrDefault(pair.Key, -1));
     }
 }
        public override void ProcessStartElement(string name, Dictionary<string, string> attributes)
        {
            base.ProcessStartElement(name, attributes);

              int port;
              Int32.TryParse(attributes.GetValueOrDefault("Port", String.Empty), out port);
              var newSmtpServer = new SmtpServer(attributes.GetValueOrDefault("Name", null), attributes.GetValueOrDefault("Host", null), port);
              MailManager.Instance.RegisterMailServer(newSmtpServer);
        }
Example #6
0
        public void GetValueOrDefaultReturnsExpectedDefault()
        {
            var colors = new Dictionary<ConsoleColor, string> { { ConsoleColor.Red, "Red" }, { ConsoleColor.Green, "Green" }, { ConsoleColor.Blue, "Blue" } };
            Assert.AreEqual(null, colors.GetValueOrDefault(ConsoleColor.DarkMagenta));
            Assert.AreEqual("not found!", colors.GetValueOrDefault(ConsoleColor.Magenta) ?? "not found!");

            var numbers = new Dictionary<string, int> { { "one", 1 }, { "two", 2 }, { "three", 3 } };
            Assert.AreEqual(0, numbers.GetValueOrDefault("four"));
            Assert.AreEqual(-1, numbers.GetValueOrDefault("five", -1));
        }
        public void TestGetValueOrDefault()
        {
            // Arrange.
            var dictionary = new Dictionary<string, int>();
            dictionary.Add("one", 1);

            // Assert.
            Assert.AreEqual(1, dictionary.GetValueOrDefault("one", 0));

            Assert.AreEqual(0, dictionary.GetValueOrDefault("two"));
            Assert.AreEqual(0, dictionary.GetValueOrDefault("two", 0));
        }
Example #8
0
 public override void Init(Dictionary<string, string> data)
 {
     if (data.ContainsKey("art"))
     {
         byte[] artfile = ObjectHelper.OpenArtFile(data["art"], (Compression.CompressionType)Enum.Parse(typeof(Compression.CompressionType), data.GetValueOrDefault("artcmp", "Nemesis")));
         if (data.ContainsKey("map"))
             img = ObjectHelper.MapToBmp(artfile, Compression.Decompress(data["map"], (Compression.CompressionType)Enum.Parse(typeof(Compression.CompressionType), data.GetValueOrDefault("mapcmp", "Uncompressed"))), int.Parse(data["frame"], System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture), int.Parse(data.GetValueOrDefault("pal", "0"), System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture));
         else if (data.ContainsKey("mapasm"))
             img = ObjectHelper.MapASMToBmp(artfile, data["mapasm"], data["mapasmlbl"], int.Parse(data.GetValueOrDefault("pal", "0"), System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture));
     }
     spacing = int.Parse(data.GetValueOrDefault("spacing", "24"), System.Globalization.NumberStyles.Integer, System.Globalization.NumberFormatInfo.InvariantInfo);
 }
        public override void ProcessStartElement(string name, Dictionary<string, string> attributes)
        {
            base.ProcessStartElement(name, attributes);

              var tokenName = '#' + attributes.GetValueOrDefault("TokenName", string.Empty) + '#';
              var value = attributes.GetValueOrDefault("Value", string.Empty);
              var regExPattern = attributes.GetValueOrDefault("RegExPattern", string.Empty);
              if (string.IsNullOrEmpty(tokenName))
              {
            log.Warn(string.Format("No 'TokenName' was specified for {0}", name));
            return;
              }

              if (string.IsNullOrEmpty(value))
              {
            log.Warn(string.Format("No 'Value' was specified for {0}", name));
            return;
              }

              if (string.IsNullOrEmpty(regExPattern))
              {
            RepositoryInfoHub.Instance.AddToken(tokenName, () =>
              {
            log.DebugFormat("Setting custom replacement token {0} to [{1}]", tokenName, value);
            return value;
              });
              }
              else
              {
            var regex = new Regex(regExPattern, RegexOptions.Compiled);
            RepositoryInfoHub.Instance.AddToken(tokenName, () =>
              {
            var input = RepositoryInfoHub.Instance.ParseTokens(value);
            log.DebugFormat("Preparing custom replacement token {0}", tokenName);
            log.DebugFormat("Value: [{0}]", value);
            log.DebugFormat("Processses value: [{0}]", input);
            var match = regex.Match(input);
            if (match != null)
            {
              log.DebugFormat("RegEx group count: {0}", match.Groups.Count);
              if (match.Groups.Count > 1)
              {
                log.DebugFormat("Setting custom replacement token {0} to [{1}]", tokenName, match.Groups[1].Value);
                return match.Groups[1].Value;
              }
            }

            return string.Empty;
              });
              }
        }
        protected override bool DoTryGetSourceControlInfo(string solutionFullPath, out IDictionary<string, object> properties)
        {
            properties = new Dictionary<string, object>();

            if (!EnsureInternalSetup(solutionFullPath, ref properties))
                return false;

            var head_path = (string)properties.GetValueOrDefault("git:headPath", () => "");

            if (!File.Exists(head_path))
                return false;

            var head_content = File.ReadAllText(head_path);
            var branch_match = GitBranchRegex.Match(head_content);

            if (!branch_match.Success)
                return false;

            var branch_group = branch_match.Groups["branchName"];

            if (!branch_group.Success)
                return false;

            var branch_name = branch_group.Value;
            properties.Add("git:head", branch_name);

            properties.AddOrUpdate(KnownProperties.BranchName, branch_name);

            return true;
        }
 public void TestGetValueOrDefaultInexisting()
 {
     Dictionary<string, int> dictionary = new Dictionary<string, int>();
     dictionary["Dummy"] = 1;
     int result = dictionary.GetValueOrDefault("Dummy2");
     Assert.AreEqual(default(int), result);
 }
 public void GetValueOrDefault_NonEmptyDictionaryWithoutKey_ReturnsDefault()
 {
     IDictionary<object, object> dict = new Dictionary<object, object>
     {
         { "key", "value" }
     };
     object value = dict.GetValueOrDefault("anotherKey", "fallback");
     Assert.Equal("fallback", value);
 }
Example #13
0
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            if (authInfo.ContainsKey("user_id"))
                tokens.UserId = authInfo.GetValueOrDefault("user_id");

            if (authInfo.ContainsKey("screen_name"))
                tokens.UserName = authInfo.GetValueOrDefault("screen_name");

            try
            {
                if (tokens.UserId != null)
                {
                    var oauthToken = new OAuthAccessToken
                    {
                        OAuthProvider = this,
                        AccessToken = tokens.AccessToken,
                        AccessTokenSecret = tokens.AccessTokenSecret,
                    };
                    var json = AuthHttpGateway.DownloadTwitterUserInfo(oauthToken, tokens.UserId);
                    var objs = JsonObject.ParseArray(json);
                    if (objs.Count > 0)
                    {
                        var obj = objs[0];
                        tokens.DisplayName = obj.Get("name");

                        string profileUrl;
                        if (obj.TryGetValue("profile_image_url", out profileUrl))
                            tokens.Items[AuthMetadataProvider.ProfileUrlKey] = profileUrl;

                        if (SaveExtendedUserInfo)
                        {
                            obj.Each(x => authInfo[x.Key] = x.Value);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error($"Could not retrieve twitter user info for '{userSession.TwitterUserId}'", ex);
            }

            LoadUserOAuthProvider(userSession, tokens);
        }
Example #14
0
 public void GetValueOrDefault()
 {
     #region GetValueOrDefault
     var dict = new Dictionary<string, int> () {
         { "a", 1 },
     };
     Assert.AreEqual (1, dict.GetValueOrDefault ("a"));
     Assert.AreEqual (0, dict.GetValueOrDefault ("c"));
     Assert.AreEqual (3, dict.GetValueOrDefault ("c", 3));
     #endregion
 }
 protected override Instruction CreateInstruction(Dictionary<string, string> attributes)
 {
     var mailInstruction = new MailInstruction();
       mailInstruction.Body = attributes.GetValueOrDefault("Body", String.Empty);
       mailInstruction.BodyTemplateFile = attributes.GetValueOrDefault("BodyTemplateFile", String.Empty);
       mailInstruction.BccMailAddresses = attributes.GetValueOrDefault("BccMailAddresses", String.Empty);
       mailInstruction.CcMailAddresses = attributes.GetValueOrDefault("CcMailAddresses", String.Empty);
       mailInstruction.FromMailAddress = attributes.GetValueOrDefault("FromMailAddress", String.Empty);
       mailInstruction.ReplyToMailAddress = attributes.GetValueOrDefault("ReplyToMailAddress", String.Empty);
       mailInstruction.Subject = attributes.GetValueOrDefault("Subject", String.Empty);
       mailInstruction.ToMailAddresses = attributes.GetValueOrDefault("ToMailAddresses", String.Empty);
       return mailInstruction;
 }
        public static CommandLineArgs Parse(string[] args)
        {
            var dictionary = new Dictionary<string, string>();

            foreach (var a in args)
            {
                var keyValue = a.Split('=');
                var key = keyValue[0].Trim().ToLowerInvariant();
                var value = keyValue[1].Trim();

                dictionary.Add(key, value);
            }

            return new CommandLineArgs
            {
                MarkdownPath = dictionary.GetValueOrDefault("-output", "output.md"),
                DllPath = dictionary.GetValueOrDefault("-input", "."),
                UrlStringFormat = dictionary.GetValueOrDefault("-urlformat", "https://msdn.microsoft.com/en-us/library/{0}.aspx")
            };
        }
Example #17
0
        public void cachedobject_is_working_with_dict()
        {
            var dict = new Dictionary<string, string>();
            var cachedObject = new CachedObject<string>(() => dict.Add(Key, Value), () => dict.GetValueOrDefault(Key));

            dict.Count.ShouldEqual(0);
            cachedObject.Get().ShouldEqual(Value);
            dict.Count.ShouldEqual(1);

            cachedObject.Get().ShouldEqual(Value);
            dict.Count.ShouldEqual(1);
        }
        protected override Instruction CreateInstruction(Dictionary<string, string> attributes)
        {
            this.executeInstruction = new CommandLineInstruction();
              this.executeInstruction.FileName = attributes.GetValueOrDefault("FileName", string.Empty);
              this.executeInstruction.Arguments = attributes.GetValueOrDefault("Arguments", string.Empty);
              this.executeInstruction.NewLineReplacement = attributes.GetValueOrDefault("NewLineReplacement", string.Empty);

              int timeoutInMilliseconds;
              if (int.TryParse(attributes.GetValueOrDefault("TimeoutInMilliseconds", string.Empty), out timeoutInMilliseconds))
              {
            this.executeInstruction.TimeoutInMilliseconds = timeoutInMilliseconds;
              }

              int expectedExitCode;
              if (int.TryParse(attributes.GetValueOrDefault("ExpectedExitCode", string.Empty), out expectedExitCode))
              {
            this.executeInstruction.ExpectedExitCode = expectedExitCode;
              }

              return this.executeInstruction;
        }
Example #19
0
        private void AddGenericTheory(Dictionary<IAstTypeReference, ISet<IAstTypeReference>> genericTheories, IAstTypeReference genericType, IAstTypeReference argumentType)
        {
            if (argumentType is AstGenericPlaceholderType || argumentType.IsImplicit())
                return;

            var set = genericTheories.GetValueOrDefault(genericType);
            if (set == null) {
                genericTheories.Add(genericType, new HashSet<IAstTypeReference> { argumentType });
                return;
            }

            set.Add(argumentType);
        }
        public void GetValueOrDefault()
        {
            var dictionary = new Dictionary<int, string>();

            dictionary.GetValueOrDefault(0).ShouldBe(null);
            dictionary.GetValueOrDefault(0, "default").ShouldBe("default");
            dictionary.GetValueOrDefault(0, () => "default").ShouldBe("default");

            dictionary.Add(0, "zero");

            dictionary.GetValueOrDefault(0).ShouldBe("zero");
            dictionary.GetValueOrDefault(0, "default").ShouldBe("zero");
            dictionary.GetValueOrDefault(0, () => "default").ShouldBe("zero");
        }
        protected override bool DoTryGetSourceControlInfo(string solutionFullPath, out IDictionary<string, object> properties)
        {
            properties = new Dictionary<string, object>();

            if (!EnsureInternalSetup(solutionFullPath, ref properties))
                return false;

            var branch_path = (string)properties.GetValueOrDefault("hg:branchPath", () => "");

            if (!File.Exists(branch_path))
                return false;

            var branch_name = File.ReadAllText(branch_path);

            if (branch_name.IsNullOrEmpty())
                return false;

            properties.Add("hg:head", branch_name);

            properties.AddOrUpdate(KnownProperties.BranchName, branch_name);

            return true;
        }
		public RegistrationSettings(Dictionary<string, string> settings): this()
		{
            RandomPassword = settings.GetValueOrDefault("Registration_RandomPassword", RandomPassword);
            RedirectAfterRegistration = settings.GetValueOrDefault("Redirect_AfterRegistration", RedirectAfterRegistration);
            RedirectAfterLogout = settings.GetValueOrDefault("Redirect_AfterLogout", RedirectAfterLogout);
            RedirectAfterLogin = settings.GetValueOrDefault("Redirect_AfterLogin", RedirectAfterLogin);
            RegistrationFields = settings.GetValueOrDefault("Registration_RegistrationFields", RegistrationFields);
            ExcludeTerms = settings.GetValueOrDefault("Registration_ExcludeTerms", ExcludeTerms);
            RegistrationFormType = settings.GetValueOrDefault("Registration_RegistrationFormType", RegistrationFormType);
            RequirePasswordConfirm = settings.GetValueOrDefault("Registration_RequireConfirmPassword", RequirePasswordConfirm);
            RequireUniqueDisplayName = settings.GetValueOrDefault("Registration_RequireUniqueDisplayName", RequireUniqueDisplayName);
            UseAuthProviders = settings.GetValueOrDefault("Registration_UseAuthProviders", UseAuthProviders);
            UseEmailAsUserName = settings.GetValueOrDefault("Registration_UseEmailAsUserName", UseEmailAsUserName);
            UseProfanityFilter = settings.GetValueOrDefault("Registration_UseProfanityFilter", UseProfanityFilter);
            RequireValidProfile = settings.GetValueOrDefault("Security_RequireValidProfile", RequireValidProfile);
            RequireValidProfileAtLogin = settings.GetValueOrDefault("Security_RequireValidProfileAtLogin", RequireValidProfileAtLogin);
            UseCaptcha = settings.GetValueOrDefault("Security_CaptchaRegister", UseCaptcha);
            UserNameValidator = settings.GetValueOrDefault("Security_UserNameValidation", UserNameValidator);
            DisplayNameFormat = settings.GetValueOrDefault("Security_DisplayNameFormat", DisplayNameFormat);
            EmailValidator = settings.GetValueOrDefault("Security_EmailValidation", EmailValidator);

			ExcludeTermsRegex = "^(?:(?!" + ExcludeTerms.Replace(" ", "").Replace(",", "|") + ").)*$\\r?\\n?";
		}
Example #23
0
        public void CreatePackage(ServiceDefinition definition, 
            CloudProjectPathInfo paths, 
            DevEnv type,
            string azureSdkBinDirectory,
            out string standardOutput, 
            out string standardError)
        {
            if (definition == null)
            {
                throw new ArgumentNullException(
                    "definition",
                    string.Format(Resources.InvalidOrEmptyArgumentMessage, "Service definition"));
            }
            if (string.IsNullOrEmpty(paths.RootPath))
            {
                throw new ArgumentException(Resources.InvalidRootNameMessage, "rootPath");
            }

            // Track the directories that are created by GetOrCreateCleanPath
            // to avoid publishing iisnode log files so we can delete the temp
            // copies when we're finished packaging
            Dictionary<string, string> tempDirectories = new Dictionary<string, string>();
            try
            {
                string roles =
                    // Get the names of all web and worker roles
                    Enumerable.Concat(
                        definition.WebRole.NonNull().Select(role => role.name),
                        definition.WorkerRole.NonNull().Select(role => role.name))
                    // Get the name and safe path for each role (i.e., if the
                    // role has files that shouldn't be packaged, it'll be
                    // copied to a temp location without those files)
                    .Select(name => GetOrCreateCleanPath(paths.RolesPath, name, tempDirectories, type))
                    // Format the role name and path as a role argument
                    .Select(nameAndPath => string.Format(Resources.RoleArgTemplate, nameAndPath.Key, nameAndPath.Value))
                    // Join all the role arguments together into one
                    .DefaultIfEmpty(string.Empty)
                    .Aggregate(string.Concat);

                string sites =
                    // Get all of the web roles
                    definition.WebRole.NonNull()
                    // Get all the sites in each role and format them all as
                    // site arguments
                    .SelectMany(role =>
                        // Format each site as a site argument
                        role.Sites.Site.Select(site =>
                            string.Format(
                                Resources.SitesArgTemplate,
                                role.name,
                                site.name,
                                tempDirectories.GetValueOrDefault(role.name, paths.RolesPath))))
                    // Join all the site arguments together into one
                    .DefaultIfEmpty(string.Empty)
                    .Aggregate(string.Concat);

                string args = string.Format(
                    type == DevEnv.Local ? Resources.CsPackLocalArg : Resources.CsPackCloudArg,
                    paths.RootPath,
                    roles,
                    sites);

                // Run CsPack to generate the package
                ProcessHelper.StartAndWaitForProcess(
                    new ProcessStartInfo(
                        Path.Combine(azureSdkBinDirectory, Resources.CsPackExe),
                        args),
                    out standardOutput,
                    out standardError);
            }
            finally
            {
                // Cleanup any temp directories
                tempDirectories.Values.ForEach(dir => Directory.Delete(dir, true));
            }
        }
Example #24
0
        private void Run(object obj)
        {
            Dictionary<string, string> updatedSubmodules = new Dictionary<string, string>();

            while (!m_token.IsCancellationRequested)
            {
                // check for changes to the build repo itself (and reload the submodules if so)
                string commitId = m_gitHubClient.GetLatestCommitId(m_user, m_repo, m_branch);
                if (commitId == null)
                {
                    Log.Error("Getting last commit ID failed; will stop monitoring project.");
                    break;
                }

                if (commitId != m_lastBuildCommitId)
                {
                    if (m_lastBuildCommitId != null)
                    {
                        Log.Info("Build repo commit ID has changed from {0} to {1}; reloading submodules.", m_lastBuildCommitId, commitId);
                        StartBuild();
                    }

                    try
                    {
                        GetSubmodules();
                    }
                    catch (WatcherException ex)
                    {
                        Log.Error("Getting submodules failed; will stop monitoring project.", ex);
                        break;
                    }
                    updatedSubmodules.Clear();
                }
                else
                {
                    // check for changes in the submodules
                    bool submoduleChanged = false;
                    bool submoduleHasError = false;
                    foreach (var pair in m_submodules)
                    {
                        Submodule submodule = pair.Value;
                        commitId = m_gitHubClient.GetLatestCommitId(submodule.User, submodule.Repo, submodule.Branch);
                        if (commitId == null)
                        {
                            Log.Error("Submodule '{0}' doesn't have a latest commit for branch '{1}'; will stop monitoring project.", pair.Key, submodule.Branch);
                            submoduleHasError = true;
                        }
                        else if (commitId != submodule.LatestCommitId && commitId != updatedSubmodules.GetValueOrDefault(pair.Key))
                        {
                            Log.Info("Submodule '{0}' has changed from {1} to {2}; waiting for more changes.", pair.Key, submodule.LatestCommitId.Substring(0, 8), commitId.Substring(0, 8));
                            updatedSubmodules[pair.Key] = commitId;
                            submoduleChanged = true;
                        }
                    }

                    // abort if there were errors
                    if (submoduleHasError)
                        break;

                    // pause for five seconds between each check
                    m_token.WaitHandle.WaitOne(TimeSpan.FromSeconds(5));

                    // if any submodule changed, loop again (to allow changes to multiple submodules to be batched)
                    if (submoduleChanged)
                        continue;

                    // if there were updated submodules, create a new commit
                    if (updatedSubmodules.Count != 0)
                    {
                        try
                        {
                            UpdateSubmodules(updatedSubmodules);
                            updatedSubmodules.Clear();
                        }
                        catch (WatcherException ex)
                        {
                            Log.Error("Updating submodules failed; will stop monitoring project.", ex);
                            break;
                        }
                    }
                }
            }
        }
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IOAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            if (authInfo.ContainsKey("user_id"))
                tokens.UserId = authInfo.GetValueOrDefault("user_id");

            if (authInfo.ContainsKey("name"))
                tokens.DisplayName = authInfo.GetValueOrDefault("name");

            if (authInfo.ContainsKey("FullName"))
            {
                tokens.FullName = authInfo.GetValueOrDefault("FullName");
                if (tokens.DisplayName.IsNullOrEmpty())
                    tokens.DisplayName = tokens.FullName;
            }

            if (authInfo.ContainsKey("Email"))
                tokens.Email = authInfo.GetValueOrDefault("Email");

            if (authInfo.ContainsKey("BirthDate"))
                tokens.BirthDate = authInfo.GetValueOrDefault("BirthDate").FromJsv<DateTime?>();

            if (authInfo.ContainsKey("BirthDateRaw"))
                tokens.BirthDateRaw = authInfo.GetValueOrDefault("BirthDateRaw");

            if (authInfo.ContainsKey("Country"))
                tokens.Country = authInfo.GetValueOrDefault("Country");

            if (authInfo.ContainsKey("Culture"))
                tokens.Culture = authInfo.GetValueOrDefault("Culture");

            if (authInfo.ContainsKey("Gender"))
                tokens.Gender = authInfo.GetValueOrDefault("Gender");

            if (authInfo.ContainsKey("MailAddress"))
                tokens.MailAddress = authInfo.GetValueOrDefault("MailAddress");

            if (authInfo.ContainsKey("Nickname"))
                tokens.Nickname = authInfo.GetValueOrDefault("Nickname");

            if (authInfo.ContainsKey("PostalCode"))
                tokens.PostalCode = authInfo.GetValueOrDefault("PostalCode");

            if (authInfo.ContainsKey("TimeZone"))
                tokens.TimeZone = authInfo.GetValueOrDefault("TimeZone");

            LoadUserOAuthProvider(userSession, tokens);
        }
Example #26
0
        private string ReplaceToken(Match match, Dictionary<string, Func<TokenMatch, string>> tokenHandlers, NamingConfig namingConfig)
        {
            var tokenMatch = new TokenMatch
            {
                RegexMatch = match,
                Prefix = match.Groups["prefix"].Value,
                Separator = match.Groups["separator"].Value,
                Suffix = match.Groups["suffix"].Value,
                Token = match.Groups["token"].Value,
                CustomFormat = match.Groups["customFormat"].Value
            };

            if (tokenMatch.CustomFormat.IsNullOrWhiteSpace())
            {
                tokenMatch.CustomFormat = null;
            }

            var tokenHandler = tokenHandlers.GetValueOrDefault(tokenMatch.Token, m => string.Empty);

            var replacementText = tokenHandler(tokenMatch).Trim();

            if (tokenMatch.Token.All(t => !char.IsLetter(t) || char.IsLower(t)))
            {
                replacementText = replacementText.ToLower();
            }
            else if (tokenMatch.Token.All(t => !char.IsLetter(t) || char.IsUpper(t)))
            {
                replacementText = replacementText.ToUpper();
            }

            if (!tokenMatch.Separator.IsNullOrWhiteSpace())
            {
                replacementText = replacementText.Replace(" ", tokenMatch.Separator);
            }

            replacementText = CleanFileName(replacementText, namingConfig.ReplaceIllegalCharacters);

            if (!replacementText.IsNullOrWhiteSpace())
            {
                replacementText = tokenMatch.Prefix + replacementText + tokenMatch.Suffix;
            }

            return replacementText;
        }
Example #27
0
        private IEnumerable<WatchFolderItem> GetDownloadItems(string watchFolder, Dictionary<string, WatchFolderItem> lastWatchItems, TimeSpan waitPeriod)
        {
            foreach (var folder in _diskProvider.GetDirectories(watchFolder))
            {
                var title = FileNameBuilder.CleanFileName(Path.GetFileName(folder));

                var newWatchItem = new WatchFolderItem
                {
                    DownloadId = Path.GetFileName(folder) + "_" + _diskProvider.FolderGetCreationTime(folder).Ticks,
                    Title = title,

                    OutputPath = new OsPath(folder),

                    Status = DownloadItemStatus.Completed,
                    RemainingTime = TimeSpan.Zero
                };

                var oldWatchItem = lastWatchItems.GetValueOrDefault(newWatchItem.DownloadId);

                if (PreCheckWatchItemExpiry(newWatchItem, oldWatchItem))
                {
                    var files = _diskProvider.GetFiles(folder, SearchOption.AllDirectories);

                    newWatchItem.TotalSize = files.Select(_diskProvider.GetFileSize).Sum();
                    newWatchItem.Hash = GetHash(folder, files);

                    if (files.Any(_diskProvider.IsFileLocked))
                    {
                        newWatchItem.Status = DownloadItemStatus.Downloading;
                        newWatchItem.RemainingTime = null;
                    }

                    UpdateWatchItemExpiry(newWatchItem, oldWatchItem, waitPeriod);
                }

                yield return newWatchItem;
            }

            foreach (var videoFile in _diskScanService.GetVideoFiles(watchFolder, false))
            {
                var title = FileNameBuilder.CleanFileName(Path.GetFileName(videoFile));

                var newWatchItem = new WatchFolderItem
                {
                    DownloadId = Path.GetFileName(videoFile) + "_" + _diskProvider.FileGetLastWrite(videoFile).Ticks,
                    Title = title,

                    OutputPath = new OsPath(videoFile),

                    Status = DownloadItemStatus.Completed,
                    RemainingTime = TimeSpan.Zero
                };

                var oldWatchItem = lastWatchItems.GetValueOrDefault(newWatchItem.DownloadId);

                if (PreCheckWatchItemExpiry(newWatchItem, oldWatchItem))
                {
                    newWatchItem.TotalSize = _diskProvider.GetFileSize(videoFile);
                    newWatchItem.Hash = GetHash(videoFile);

                    if (_diskProvider.IsFileLocked(videoFile))
                    {
                        newWatchItem.Status = DownloadItemStatus.Downloading;
                    }

                    UpdateWatchItemExpiry(newWatchItem, oldWatchItem, waitPeriod);
                }

                yield return newWatchItem;
            }
        }
        public virtual void OnAuthenticated(IServiceBase oAuthService, IOAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            var provider = tokens.Provider;
            var authProvider = oAuthService.TryResolve<IUserAuthRepository>();
            if (authProvider != null)
                authProvider.LoadUserAuth(this, tokens);

            if (provider == TwitterAuthConfig.Name)
            {
                if (authInfo.ContainsKey("user_id"))
                    tokens.UserId = this.TwitterUserId = authInfo.GetValueOrDefault("user_id");

                if (authInfo.ContainsKey("screen_name"))
                    tokens.UserName = this.TwitterScreenName = authInfo.GetValueOrDefault("screen_name");

                try
                {
                    var json = AuthHttpGateway.DownloadTwitterUserInfo(this.TwitterUserId);
                    var obj = JsonObject.Parse(json);
                    tokens.DisplayName = obj.Get("name");
                    this.DisplayName = tokens.DisplayName ?? this.DisplayName;
                }
                catch (Exception ex)
                {
                    Log.Error("Could not retrieve twitter user info for '{0}'".Fmt(TwitterUserId), ex);
                }
            }
            else if (provider == FacebookAuthConfig.Name)
            {
                try
                {
                    var json = AuthHttpGateway.DownloadFacebookUserInfo(tokens.AccessTokenSecret);
                    var obj = JsonObject.Parse(json);
                    tokens.UserId = obj.Get("id");
                    tokens.UserName = obj.Get("username");
                    tokens.DisplayName = obj.Get("name");
                    tokens.FirstName = obj.Get("first_name");
                    tokens.LastName = obj.Get("last_name");
                    tokens.Email = obj.Get("email");

                    this.FacebookUserId = tokens.UserId ?? this.FacebookUserId;
                    this.FacebookUserName = tokens.UserName ?? this.FacebookUserName;
                    this.DisplayName = tokens.DisplayName ?? this.DisplayName;
                    this.FirstName = tokens.FirstName ?? this.FirstName;
                    this.LastName = tokens.LastName ?? this.LastName;
                    this.Email = tokens.Email ?? this.Email;
                }
                catch (Exception ex)
                {
                    Log.Error("Could not retrieve facebook user info for '{0}'".Fmt(tokens.DisplayName), ex);
                }
            }

            authInfo.ForEach((x, y) => tokens.Items[x] = y);

            SaveUserAuth(oAuthService.TryResolve<IUserAuthRepository>(), tokens);
            OnSaveUserAuth(oAuthService, this.UserAuthId);
        }
Example #29
0
        public static Metadata LoadMetadata(string target)
        {
            var types = new Dictionary<string, MetadataType>();
            var typeDefs = new Dictionary<MetadataType, TypeDef>();
            var metadata = new Metadata();

            // add easilly the bool type and other types in the future like Brushes posiibly
            var td = new CustomEnumTypeDef(typeof(bool).FullName, new[] { "True", "False" });
            types.Add(typeof(bool).FullName, new MetadataType() { Name = typeof(bool).FullName });
            typeDefs.Add(types[typeof(bool).FullName], td);

            foreach (var asm in LoadAssemblies(target))
            {
                var aliases = new Dictionary<string, string>();
                foreach (var attr in asm.CustomAttributes.FindAll("Avalonia.Metadata.XmlnsDefinitionAttribute"))
                    aliases[attr.ConstructorArguments[1].Value.ToString()] =
                        attr.ConstructorArguments[0].Value.ToString();

                foreach (var type in asm.Modules.SelectMany(m => m.GetTypes()).Where(x => !x.IsInterface && x.IsPublic))
                {
                    var mt = types[type.FullName] = new MetadataType
                    {
                        Name = type.Name,
                        IsStatic = type.IsSealed && type.IsAbstract,
                        IsMarkupExtension = IsMarkupExtensions(type)
                    };
                    typeDefs[mt] = type;
                    metadata.AddType("clr-namespace:" + type.Namespace + ";assembly=" + asm.Name, mt);
                    string alias = null;
                    if (aliases.TryGetValue(type.Namespace, out alias))
                        metadata.AddType(alias, mt);
                }
            }

            foreach (var type in types.Values)
            {
                var typeDef = typeDefs[type];
                while (typeDef != null)
                {
                    foreach (var prop in typeDef.Properties)
                    {
                        var setMethod = prop.SetMethod;
                        if (setMethod == null || setMethod.IsStatic || !setMethod.IsPublic)
                            continue;

                        var p = new MetadataProperty { Name = prop.Name };

                        if (setMethod.Parameters.Count == 2)
                        {
                            //1 param this, 2 param prop value
                            var mt = types.GetValueOrDefault(setMethod.Parameters[1].Type.FullName);

                            if (mt != null)
                                ResolvePropertyType(typeDefs[mt], p);
                        }

                        type.Properties.Add(p);
                    }
                    foreach (var methodDef in typeDef.Methods)
                    {
                        if (methodDef.Name.StartsWith("Set") && methodDef.IsStatic && methodDef.IsPublic
                            && methodDef.Parameters.Count == 2)
                        {
                            var p = new MetadataProperty() { Name = methodDef.Name.Substring(3), IsAttached = true };
                            var mt = types.GetValueOrDefault(methodDef.Parameters[1].Type.FullName);
                            if (mt != null)
                                ResolvePropertyType(typeDefs[mt], p);
                            type.Properties.Add(p);
                        }
                    }
                    typeDef = typeDef.GetBaseType().ResolveTypeDef();
                }
                type.HasAttachedProperties = type.Properties.Any(p => p.IsAttached);
            }

            return metadata;
        }
Example #30
0
        private void Run(object obj)
        {
            Dictionary<string, string> updatedSubmodules = new Dictionary<string, string>();

            while (!m_token.IsCancellationRequested)
            {
                // check for changes to the build repo itself (and reload the submodules if so)
                string commitId = m_gitHubClient.GetLatestCommitId(m_user, m_repo, m_branch, m_updatingSubmodulesFailed);
                if (commitId == null)
                {
                    Log.Info("Getting last commit ID failed; assuming branch doesn't exist.");
                    commitId = m_gitHubClient.GetLatestCommitId(m_user, m_repo, "master");
                    if (commitId == null)
                    {
                        Log.Error("Getting commit ID for 'master' failed; will stop monitoring project.");
                        break;
                    }

                    GitReference reference = m_gitHubClient.CreateReference(m_user, m_repo, m_branch, commitId);
                    if (reference == null)
                    {
                        Log.Error("Failed to create new branch '{0}' (based on master = {1}); will stop monitoring project.", m_branch, commitId);
                        break;
                    }

                    Log.Info("Sleeping for five seconds to allow GitHub API time to learn about the new branch.");
                    Thread.Sleep(TimeSpan.FromSeconds(5));
                }

                if (commitId != m_lastBuildCommitId)
                {
                    if (m_lastBuildCommitId != null)
                    {
                        Log.Info("Build repo commit ID has changed from {0} to {1}; reloading submodules.", m_lastBuildCommitId, commitId);
                        StartBuild();
                    }

                    try
                    {
                        GetSubmodules();
                    }
                    catch (WatcherException ex)
                    {
                        Log.Error("Getting submodules failed; will stop monitoring project.", ex);
                        break;
                    }
                    updatedSubmodules.Clear();
                }
                else
                {
                    // check for changes in the submodules
                    bool submoduleChanged = false;
                    bool submoduleHasError = false;
                    foreach (var pair in m_submodules)
                    {
                        Submodule submodule = pair.Value;
                        commitId = m_gitHubClient.GetLatestCommitId(submodule.User, submodule.Repo, submodule.Branch, m_updatingSubmodulesFailed);
                        if (commitId == null)
                        {
                            Log.Error("Submodule '{0}' doesn't have a latest commit for branch '{1}'; will stop monitoring project.", pair.Key, submodule.Branch);
                            submoduleHasError = true;
                        }
                        else if (commitId != submodule.LatestCommitId && commitId != updatedSubmodules.GetValueOrDefault(pair.Key))
                        {
                            Log.Info("Submodule '{0}' has changed from {1} to {2}; waiting for more changes.", pair.Key, submodule.LatestCommitId.Substring(0, 8), commitId.Substring(0, 8));
                            updatedSubmodules[pair.Key] = commitId;
                            submoduleChanged = true;
                        }
                    }

                    // abort if there were errors
                    if (submoduleHasError)
                        break;

                    // pause for five seconds between each check
                    m_token.WaitHandle.WaitOne(TimeSpan.FromSeconds(5));

                    // if any submodule changed, loop again (to allow changes to multiple submodules to be batched)
                    if (submoduleChanged)
                        continue;

                    // if there were updated submodules, create a new commit
                    m_updatingSubmodulesFailed = false;
                    if (updatedSubmodules.Count != 0)
                    {
                        try
                        {
                            if (UpdateSubmodules(updatedSubmodules))
                            {
                                m_retryDelay = TimeSpan.FromSeconds(15);
                            }
                            else
                            {
                                m_updatingSubmodulesFailed = true;
                                m_retryDelay = m_retryDelay + m_retryDelay;
                                TimeSpan maximumRetryDelay = TimeSpan.FromMinutes(30);
                                if (m_retryDelay > maximumRetryDelay)
                                    m_retryDelay = maximumRetryDelay;
                                Log.Info("Failed to update submodules; will wait {0} before trying again.", m_retryDelay);
                            }
                            updatedSubmodules.Clear();

                            // wait for the build to start, and/or for gitdata to be updated with the new commit data
                            m_token.WaitHandle.WaitOne(m_retryDelay);
                        }
                        catch (WatcherException ex)
                        {
                            Log.Error("Updating submodules failed; will stop monitoring project.", ex);
                            break;
                        }
                    }
                }
            }
        }