コード例 #1
0
 public void ContainsValue_DuplicateValues(string value)
 {
     StringDictionary stringDictionary = new StringDictionary();
     stringDictionary.Add("key1", value);
     stringDictionary.Add("key2", value);
     Assert.True(stringDictionary.ContainsValue(value));
 }
コード例 #2
0
    protected void Page_Load(object sender, EventArgs e)
    {
        SettingsPropertyCollection profileProperties = ProfileCommon.Properties;

        string[] settings;
        ArrayList keys = new ArrayList();
        ArrayList alias = new ArrayList();
        ArrayList name = new ArrayList();
        foreach (SettingsProperty prop in profileProperties)
        {
            if (prop.Attributes["CustomProviderData"].ToString() != "None")
            {
                settings = prop.Attributes["CustomProviderData"].ToString().Split(';');
                name.Add(settings[1] + prop.Name);
                alias.Add(settings[1] + settings[0]);
            }
        }
        name.Sort();
        alias.Sort();

        ArrayList name1 = ArrayList.Repeat("", name.Count);
        foreach (String item in name) name1[name.IndexOf(item)] = item.Substring(1);

        ArrayList alias1 = ArrayList.Repeat("", alias.Count);
        foreach (String item in alias) alias1[alias.IndexOf(item)] = item.Substring(1);

        int n = 0;
        StringDictionary properties = new StringDictionary();
        foreach (string item in name1) { properties[item] = alias1[n].ToString(); n++; }

        rptProfile.DataSource = properties;
        rptProfile.DataBind();
    }
コード例 #3
0
        //public StringHashTable WildVars;
        //the following fields stores only default settings used for the simulation, so there is no need to change them after parsing.
        //public FairnessType FairnessType;
        //public bool CalculateParticipatingProcess;
        //public bool TimedRefinementAssertion;
        //public int TimedRefinementClockCeiling;
        //public int TimedRefinementClockFloor;
        //public CSPDataStore DataManager;
        public SharedDataObjectBase()
        {
            //DataManager = new CSPDataStore();
            //AlphaDatabase = new Dictionary<string, EventCollection>(8);
            VariableLowerBound = new StringDictionary<int>(8);
            VariableUpperLowerBound = new StringDictionary<int>(8);
            ValutionHashTable = new StringDictionary<string>(Ultility.Ultility.MC_INITIAL_SIZE);

            SyncrhonousChannelNames = new List<string>();
            HasSyncrhonousChannel = false;
            HasAtomicEvent = false;
            //TimedRefinementAssertion = false;

            CSharpMethods = new Dictionary<string, System.Reflection.MethodInfo>();
            CSharpDataType = new Dictionary<string, Type>();
            //MacroDefinition = new Dictionary<string, KeyValuePair<List<string>, Expression>>();

            //FairnessType = FairnessType.NO_FAIRNESS;
            //CalculateParticipatingProcess = false;
            //CalculateCreatedProcess = false;

            //TimedRefinementClockCeiling = Common.Classes.Ultility.Ultility.TIME_REFINEMENT_CLOCK_CEILING;
            //TimedRefinementClockFloor = Common.Classes.Ultility.Ultility.TIME_REFINEMENT_CLOCK_FLOOR;

            LocalVars = null;
            //WildVars = null;
        }
コード例 #4
0
ファイル: Profiles.aspx.cs プロジェクト: rajgit31/RajBlog
    /// <summary>
    /// Binds the country dropdown list with countries retrieved
    /// from the .NET Framework.
    /// </summary>
    public void BindCountries()
    {
        StringDictionary dic = new StringDictionary();
        List<string> col = new List<string>();

        foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
        {
            RegionInfo ri = new RegionInfo(ci.Name);
            if (!dic.ContainsKey(ri.EnglishName))
                dic.Add(ri.EnglishName, ri.TwoLetterISORegionName.ToLowerInvariant());

            if (!col.Contains(ri.EnglishName))
                col.Add(ri.EnglishName);
        }

        // Add custom cultures
        if (!dic.ContainsValue("bd"))
        {
            dic.Add("Bangladesh", "bd");
            col.Add("Bangladesh");
        }

        col.Sort();

        ddlCountry.Items.Add(new ListItem("[Not specified]", ""));
        foreach (string key in col)
        {
            ddlCountry.Items.Add(new ListItem(key, dic[key]));
        }

        SetDefaultCountry();
    }
コード例 #5
0
		public UserCommandMessage(StringDictionary StringResources, MessageDirection Direction, byte[] Buffer, int StartIndex = 0) 
            : base () 
        {
            this.TransferDirection = Direction;
            this.StringResources = StringResources;
            ReadFrom(Buffer, StartIndex);
        }
コード例 #6
0
ファイル: TextClient.cs プロジェクト: jsoldi/SearchFight
        public override async Task<string> GetResponseText(Uri uri, StringDictionary headers)
        {
            using (HttpClient client = new HttpClient(new HttpClientHandler() { AutomaticDecompression = System.Net.DecompressionMethods.Deflate | System.Net.DecompressionMethods.GZip }))
            {
                if (Timeout > 0)
                    client.Timeout = TimeSpan.FromMilliseconds(Timeout);
                else
                    client.Timeout = TimeSpan.FromMilliseconds(DefaultTimeout);

                if (headers != null)
                {
                    foreach (var header in headers)
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }

                try
                {
                    return await client.GetStringAsync(uri);
                }
                catch (HttpRequestException ex)
                {
                    throw new WebRequestException(ex.Message, ex);
                }
                catch (TaskCanceledException ex)
                {
                    throw new WebRequestException("The request timed out.", ex);
                }
            }
        }
コード例 #7
0
        public void Add()
        {
            int count = 10;
            StringDictionary stringDictionary = new StringDictionary();
            for (int i = 0; i < count; i++)
            {
                string key = "Key_" + i;
                string value = "Value_" + i;

                stringDictionary.Add(key, value);
                Assert.Equal(i + 1, stringDictionary.Count);

                Assert.True(stringDictionary.ContainsKey(key));
                Assert.True(stringDictionary.ContainsValue(value));
                Assert.Equal(value, stringDictionary[key]);
            }

            Assert.False(stringDictionary.ContainsValue(null));

            stringDictionary.Add("nullkey", null);
            Assert.Equal(count + 1, stringDictionary.Count);
            Assert.True(stringDictionary.ContainsKey("nullkey"));
            Assert.True(stringDictionary.ContainsValue(null));
            Assert.Null(stringDictionary["nullkey"]);
        }
コード例 #8
0
 public void ContainsKey_IsCaseInsensitive()
 {
     StringDictionary stringDictionary = new StringDictionary();
     stringDictionary.Add("key", "value");
     Assert.True(stringDictionary.ContainsKey("KEY"));
     Assert.True(stringDictionary.ContainsKey("kEy"));
     Assert.True(stringDictionary.ContainsKey("key"));
 }
コード例 #9
0
 public void ContainsValue_IsCaseSensitive()
 {
     StringDictionary stringDictionary = new StringDictionary();
     stringDictionary.Add("key", "value");
     Assert.False(stringDictionary.ContainsValue("VALUE"));
     Assert.False(stringDictionary.ContainsValue("vaLue"));
     Assert.True(stringDictionary.ContainsValue("value"));
 }
コード例 #10
0
 public void Item_Get_IsCaseInsensitive()
 {
     StringDictionary stringDictionary = new StringDictionary();
     stringDictionary.Add("key", "value");
     Assert.Equal("value", stringDictionary["KEY"]);
     Assert.Equal("value", stringDictionary["kEy"]);
     Assert.Equal("value", stringDictionary["key"]);
 }
コード例 #11
0
ファイル: PIDecoder.cs プロジェクト: GJiin/meridian59-dotnet
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="StringResources">A threadsafe dictionary used to resolve Meridian Strings from.</param>
		public PIDecoder(StringDictionary StringResources)
        {
            this.stringResources = StringResources;
            
            if (StringResources == null)
                stringBytes = Encoding.Default.GetBytes(FALLBACKSTRING);
            
            Reset();
        }
コード例 #12
0
ファイル: PIEncoder.cs プロジェクト: GJiin/meridian59-dotnet
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="StringResources">A threadsafe dictionary used to resolve Meridian Strings from.</param>
		public PIEncoder(StringDictionary StringResources)
        {
            this.stringResources = StringResources;
            
            if (StringResources == null)
                hashString = Encoding.Default.GetBytes(StaticFallbackHashString);
            
            Reset();
        }
コード例 #13
0
        public void Item_Set_IsCaseInsensitive()
        {
            StringDictionary stringDictionary = new StringDictionary();
            stringDictionary["KEY"] = "value1";
            stringDictionary["kEy"] = "value2";
            stringDictionary["key"] = "value3";

            Assert.Equal(1, stringDictionary.Count);
            Assert.Equal("value3", stringDictionary["key"]);
        }
コード例 #14
0
ファイル: widget.ascx.cs プロジェクト: TrueSystems/SitesWEB
    private string RenderPosts(List<Post> posts, StringDictionary settings)
    {
        if (posts.Count == 0)
        {
            //HttpRuntime.Cache.Insert("widget_recentposts", "<p>" + Resources.labels.none + "</p>");
            return "<p>" + Resources.labels.none + "</p>";
        }

        StringBuilder sb = new StringBuilder();
        sb.Append("<ul class=\"recentPosts\" id=\"recentPosts\">");

        bool showComments = DEFAULT_SHOW_COMMENTS;
        bool showRating = DEFAULT_SHOW_RATING;
        if (settings.ContainsKey("showcomments"))
        {
            bool.TryParse(settings["showcomments"], out showComments);
        }

        if (settings.ContainsKey("showrating"))
        {
            bool.TryParse(settings["showrating"], out showRating);
        }

        foreach (Post post in posts)
        {
            if (!post.IsVisibleToPublic)
                continue;

            string rating = Math.Round(post.Rating, 1).ToString(System.Globalization.CultureInfo.InvariantCulture);

            string link = "<li><a href=\"{0}\">{1}</a>{2}{3}</li>";

            string comments = string.Format("<span>{0}: {1}</span>", Resources.labels.comments, post.ApprovedComments.Count);

            if(BlogSettings.Instance.ModerationType == BlogSettings.Moderation.Disqus)
                comments = string.Format("<span><a href=\"{0}#disqus_thread\">{1}</a></span>", post.PermaLink, Resources.labels.comments);

            string rate = string.Format("<span>{0}: {1} / {2}</span>", Resources.labels.rating, rating, post.Raters);

            if (!showComments || !BlogSettings.Instance.IsCommentsEnabled)
                comments = null;

            if (!showRating || !BlogSettings.Instance.EnableRating)
                rate = null;

            if (post.Raters == 0)
                rating = Resources.labels.notRatedYet;

            sb.AppendFormat(link, post.RelativeLink, HttpUtility.HtmlEncode(post.Title), comments, rate);
        }

        sb.Append("</ul>");
        //HttpRuntime.Cache.Insert("widget_recentposts", sb.ToString());
        return sb.ToString();
    }
コード例 #15
0
ファイル: Helpers.cs プロジェクト: MichalStrehovsky/corefx
        public static StringDictionary CreateStringDictionary(int count)
        {
            StringDictionary stringDictionary = new StringDictionary();

            for (int i = 0; i < count; i++)
            {
                stringDictionary.Add("Key_" + i, "Value_" + i);
            }

            return stringDictionary;
        }
コード例 #16
0
        public void Ctor()
        {
            StringDictionary stringDictionary = new StringDictionary();
            Assert.Equal(0, stringDictionary.Count);
            Assert.False(stringDictionary.IsSynchronized);
            Assert.Equal(0, stringDictionary.Keys.Count);
            Assert.Equal(0, stringDictionary.Values.Count);

            stringDictionary.Add("key", "value");
            Assert.False(stringDictionary.IsSynchronized);
        }
コード例 #17
0
        public void Item_Get_DuplicateValues()
        {
            StringDictionary stringDictionary = new StringDictionary();
            stringDictionary.Add("key1", "value");
            stringDictionary.Add("key2", "different-value");
            stringDictionary.Add("key3", "value");

            Assert.Equal("value", stringDictionary["key1"]);
            Assert.Equal("different-value", stringDictionary["key2"]);
            Assert.Equal("value", stringDictionary["key3"]);
        }
コード例 #18
0
        public void Add_Invalid()
        {
            StringDictionary stringDictionary = new StringDictionary();
            stringDictionary.Add("Key", "Value");

            Assert.Throws<ArgumentNullException>("key", () => stringDictionary.Add(null, "value"));

            // Duplicate key
            Assert.Throws<ArgumentException>(null, () => stringDictionary.Add("Key", "value"));
            Assert.Throws<ArgumentException>(null, () => stringDictionary.Add("KEY", "value"));
            Assert.Throws<ArgumentException>(null, () => stringDictionary.Add("key", "value"));
        }
コード例 #19
0
    private void BindGrid()
    {
        StringCollection col = StaticDataService.LoadPingServices();
        StringDictionary dic = new StringDictionary();
        foreach (string services in col)
        {
          dic.Add(services, services);
        }

        grid.DataKeyNames = new string[] { "key" };
        grid.DataSource = dic;
        grid.DataBind();
    }
コード例 #20
0
        public void Remove_DuplicateValues()
        {
            StringDictionary stringDictionary = new StringDictionary();
            stringDictionary.Add("key1", "value");
            stringDictionary.Add("key2", "value");

            stringDictionary.Remove("key1");
            Assert.Equal(1, stringDictionary.Count);
            Assert.False(stringDictionary.ContainsKey("key1"));
            Assert.True(stringDictionary.ContainsValue("value"));

            stringDictionary.Remove("key2");
            Assert.Equal(0, stringDictionary.Count);
            Assert.False(stringDictionary.ContainsKey("key2"));
            Assert.False(stringDictionary.ContainsValue("value"));
        }
コード例 #21
0
ファイル: Profiles.aspx.cs プロジェクト: bpanjavan/Blog
    /// <summary>
    /// Binds the country dropdown list with countries retrieved
    /// from the .NET Framework.
    /// </summary>
    public void BindCountries()
    {
        StringDictionary dic = new StringDictionary();
        List<string> col = new List<string>();

        foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
        {
            RegionInfo ri = new RegionInfo(ci.Name);
            if (!dic.ContainsKey(ri.EnglishName))
                dic.Add(ri.EnglishName, ri.TwoLetterISORegionName.ToLowerInvariant());

            if (!col.Contains(ri.EnglishName))
                col.Add(ri.EnglishName);
        }

        // Add custom cultures
        if (!dic.ContainsValue("bd"))
        {
            dic.Add("Bangladesh", "bd");
            col.Add("Bangladesh");
        }

        col.Sort();

        ddlCountry.Items.Add(new ListItem("[Not specified]", ""));
        foreach (string key in col)
        {
            ddlCountry.Items.Add(new ListItem(key, dic[key]));
        }

        if (ddlCountry.SelectedIndex == 0 && Request.UserLanguages != null && Request.UserLanguages[0].Length == 5)
        {
            ddlCountry.SelectedValue = Request.UserLanguages[0].Substring(3);
            SetFlagImageUrl();
        }
    }
コード例 #22
0
        private void FeedXmlElement(XmlWriter xmlWriter, IDataReader reader, StringDictionary dict, string catalog, string identifier, string feedFilePath)
        {
            var counter = new ProcessingCounters();
            var time    = _effectiveFromTime.HasValue ? _effectiveFromTime.Value : DateTime.Now;

            PlaRelatedFeedUtils.StartXmlDocument(xmlWriter, GoogleRunFeedType.Google, time);

            //<entry>
            while (reader.Read())
            {
                Log.DebugFormat("{0}::Processing record [{1}]: {2}", identifier, (counter.GetTotalProcessed()), reader["PID"]);

                var id    = reader[dict["gId"]].ToString();
                var title = reader[dict["title"]].ToString();
                try
                {
                    var haveExclusionRulesChanged = _runnerFeedRulesHelper.HaveExclusionRulesChanged();
                    var sku             = reader[dict["sku"]].ToString();
                    var brandName       = !dict.ContainsKey("gBrand") ? string.Empty : reader[dict["gBrand"]].ToString();
                    var cContributors   = PlaRelatedFeedUtils.ContributorAttributes(dict, reader, id);
                    var contributor     = cContributors ?? null;
                    var defaultCategory = FeedUtils.GetFeedGeneratorIndigoCategory(_feedGeneratorCategoryService, reader, dict, catalog, Log);
                    var productData     = FeedUtils.GetProductData(dict, reader, sku, catalog, brandName, contributor, defaultCategory);
                    var sanitizedTitle  = (string.IsNullOrWhiteSpace(title)) ? string.Empty : FeedUtils.SanitizeString(title);
                    var gAvailability   = !dict.ContainsKey("gAvailability") ? FeedUtils.GetGoogleAvailability(1)
                            : FeedUtils.GetGoogleAvailability(int.Parse(reader[dict["gAvailability"]].ToString()));
                    var availability = !dict.ContainsKey("gAvailability") ? 1 : int.Parse(reader[dict["gAvailability"]].ToString());
                    var recordType   = !dict.ContainsKey("recordType") ? string.Empty : reader[dict["recordType"]].ToString();
                    var hasImage     = true;
                    if (!SkipHasImageCheck)
                    {
                        hasImage = (!dict.ContainsKey("hasImage")) || int.Parse(reader[dict["hasImage"]].ToString()) > 0;
                    }

                    string message;
                    var    isExcluded = false;
                    if (_isIncrementalRun)
                    {
                        var statusId = int.Parse(reader["StatusId"].ToString());
                        switch (statusId)
                        {
                        // New product
                        case 1:
                            counter.NumberOfNew++;
                            continue;

                        // Unchanged product
                        case 3:
                            if (!haveExclusionRulesChanged)
                            {
                                Log.DebugFormat("Product with id {0} is skipped in incremental mode as it wasn't modified and the rules haven't changed.", id);
                                counter.NumberOfUnchanged++;
                                continue;
                            }

                            var oldExclusionResult     = _runnerFeedRulesHelper.IsExcludedFromFeed(productData, true);
                            var currentExclusionResult = _runnerFeedRulesHelper.IsExcludedFromFeed(productData, false);
                            if (oldExclusionResult == currentExclusionResult)
                            {
                                Log.DebugFormat("Product with id {0} is skipped in incremental mode as it wasn't modified, rules had changed but exclusion rule evaluation's result remained the same.", id);
                                counter.NumberOfUnchanged++;
                                continue;
                            }

                            // If the product is excluded at the moment, then perform the "exclusion logic" per business requirements,
                            // otherwise (i.e. product is included at the moment, treat it as "new")
                            if (!currentExclusionResult)
                            {
                                Log.DebugFormat("Product with id {0} is marked as new and skipped in incremental mode as it wasn't modified, rules had changed but exclusion rule evaluation's result changed and currently product isn't excluded.", id);
                                counter.NumberOfNew++;
                                continue;
                            }

                            Log.DebugFormat("Product with id {0} is marked as excluded in incremental mode as it wasn't modified, rules had changed but exclusion rule evaluation's result changed and currently product is being excluded.", id);
                            isExcluded = true;
                            break;

                        // Modified product
                        case 2:
                            var isEntryExcluded = IndigoBreadcrumbRepositoryUtils.IsExcludedDueToData(GooglePlaFeedId, sanitizedTitle, hasImage, availability, recordType, false, out message);
                            if (isEntryExcluded)
                            {
                                Log.DebugFormat("Product with id {0} is marked as excluded in incremental mode as it was modified, and it failed the data requirements for inclusion.", id);
                                isExcluded = true;
                                break;
                            }

                            // If product was excluded from the feed due to rules, then mark it as excluded
                            if (_runnerFeedRulesHelper.IsExcludedFromFeed(productData, false))
                            {
                                Log.DebugFormat("Product with id {0} is marked as excluded in incremental mode as it was modified, and it's matching one of the exclusion rules.", id);
                                isExcluded = true;
                            }
                            break;

                        default:
                            throw new ApplicationException("Invalid StatusId during an incremental run.");
                        }
                    }
                    else
                    {
                        isExcluded = IndigoBreadcrumbRepositoryUtils.IsExcludedDueToData(GooglePlaFeedId, sanitizedTitle, hasImage, availability, recordType, false, out message);
                        if (isExcluded)
                        {
                            Log.DebugFormat("Product with id {0} is marked as excluded in full mode as it failed the data requirements for inclusion.", id);
                        }

                        if (!isExcluded)
                        {
                            isExcluded = _runnerFeedRulesHelper.IsExcludedFromFeed(productData, false);
                        }

                        if (isExcluded)
                        {
                            Log.DebugFormat("Product with id {0} is marked as excluded in full mode as it's matching one of the exclusion rules.", id);
                        }
                    }

                    // At this point, we know if the product is excluded or not, regardless of which type of run is being executed.
                    // If we aren't supposed to be sending excluded product data, then update the skipped counter and exit
                    if (isExcluded)
                    {
                        counter.NumberOfExcluded++;
                        if (!SendExcludedProductData)
                        {
                            Log.Debug("Skipped the product because it was excluded.");
                            continue;
                        }

                        gAvailability = ExcludedProductGoogleAvailabilityText;
                    }

                    var     regularPrice  = (decimal)reader[dict["price"]];
                    var     adjustedPrice = string.IsNullOrEmpty(dict["adjustedPrice"]) ? "" : reader[dict["adjustedPrice"]].ToString();
                    decimal?salePrice     = null;
                    if (!string.IsNullOrWhiteSpace(adjustedPrice))
                    {
                        var salePriceFromDatabase = Decimal.Parse(adjustedPrice);
                        if (salePriceFromDatabase != regularPrice)
                        {
                            if (salePriceFromDatabase > regularPrice)
                            {
                                regularPrice = salePriceFromDatabase;
                                salePrice    = null;
                            }
                            else
                            {
                                salePrice = salePriceFromDatabase;
                            }
                        }
                    }

                    var entry = EntryAttribute(id, regularPrice, salePrice, gAvailability);
                    entry.WriteTo(xmlWriter);
                    counter.NumberOfProcessed++;
                }
                catch (Exception e)
                {
                    counter.NumberOfErrored++;
                    var errorMessage = string.Format("Can't process the item. Id:{0};title:{1},catalog:{2},Message:{3}", id, title, catalog, e.Message);

                    Log.Error(errorMessage);

                    Log.DebugFormat("Error stack trace: {0}", e);
                    _executionLogLogger.AddCustomMessage(string.Format("Can't process the item. Id: {0};title: {1}, file identifier: {2}", id, title, identifier));
                    if (_isIncrementalRun && !AllowItemErrorsInFiles)
                    {
                        _hasError = true;
                    }
                }
            }

            // If the setting for sending deleted products is set to true in an incremental run, then get the deleted products since the last run
            // and send them as the "special" deleted products, i.e. pid + availability of "out of stock"
            if (_isIncrementalRun && SendExcludedProductData)
            {
                AddDeletedProducts(xmlWriter, identifier, ref counter);
            }

            PlaRelatedFeedUtils.EndXmlDocument(xmlWriter);
            var infoLogMessage = string.Format("[WriteFeedFile] {0} completed processed record count: {1}, error record count: {2}, unchanged record count: {3}, " +
                                               "new record count: {4}, excluded record count: {5}, deleted record count: {6}. ",
                                               feedFilePath, counter.NumberOfProcessed, counter.NumberOfErrored, counter.NumberOfUnchanged, counter.NumberOfNew, counter.NumberOfExcluded, counter.NumberOfDeleted);

            if (SendExcludedProductData)
            {
                infoLogMessage += "Excluded produces were included in processed count.";
            }

            Log.Info(infoLogMessage);
        }
コード例 #23
0
ファイル: Arguments.cs プロジェクト: pedrolimajesus/template
        public Arguments(string[] Args)
        {
            _parameters = new StringDictionary();

            var splitter = new Regex(@"^-{1,2}|^/|=|:",
                                     RegexOptions.IgnoreCase | RegexOptions.Compiled);

            var remover = new Regex(@"^['""]?(.*?)['""]?$",
                                    RegexOptions.IgnoreCase | RegexOptions.Compiled);

            string parameter = null;


            foreach (var txt in Args)
            {
                var parts = splitter.Split(txt, 3).ToArray();

                switch (parts.Length)
                {
                // Found a value (for the last parameter
                // found (space separator))
                case 1:
                    if (parameter != null)
                    {
                        if (!_parameters.ContainsKey(parameter))
                        {
                            parts[0] =
                                remover.Replace(parts[0], "$1");

                            _parameters.Add(parameter.ToLowerInvariant(), parts[0]);
                        }
                        parameter = null;
                    }

                    break;


                case 2:

                    if (parameter != null)
                    {
                        if (!_parameters.ContainsKey(parameter))
                        {
                            _parameters.Add(parameter.ToLowerInvariant(), "true");
                        }
                    }
                    parameter = parts[1];
                    break;

                // given value
                case 3:

                    if (parameter != null)
                    {
                        if (!_parameters.ContainsKey(parameter))
                        {
                            _parameters.Add(parameter.ToLowerInvariant(), "true");
                        }
                    }

                    parameter = parts[1];


                    if (!_parameters.ContainsKey(parameter))
                    {
                        parts[2] = remover.Replace(parts[2], "$1");
                        _parameters.Add(parameter.ToLowerInvariant(), parts[2]);
                    }

                    parameter = null;
                    break;
                }
            }

            if (parameter != null)
            {
                if (!_parameters.ContainsKey(parameter))
                {
                    _parameters.Add(parameter.ToLowerInvariant(), "true");
                }
            }
        }
コード例 #24
0
        public static IntResult CreateOrganization(int packageId, string organizationId,
                                                   string domain, string adminName, string adminEmail, string adminPassword)
        {
            IntResult result = new IntResult();

            result.IsSuccess = true;

            try
            {
                // initialize task manager
                TaskManager.StartTask(TaskManagerSource, "CREATE_ORGANIZATION");
                TaskManager.WriteParameter("packageId", packageId);
                TaskManager.WriteParameter("organizationId", organizationId);
                TaskManager.WriteParameter("domain", domain);
                TaskManager.WriteParameter("adminName", adminName);
                TaskManager.WriteParameter("adminEmail", adminEmail);
                TaskManager.WriteParameter("adminPassword", adminPassword);

                // get Exchange service ID
                int serviceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.ExchangeHostedEdition);
                if (serviceId < 1)
                {
                    return(Error <IntResult>(ExchangeServiceNotEnabledError));
                }

                #region Check Space and Account
                // Check account
                int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
                if (accountCheck < 0)
                {
                    return(Warning <IntResult>((-accountCheck).ToString()));
                }

                // Check space
                int packageCheck = SecurityContext.CheckPackage(packageId, DemandPackage.IsActive);
                if (packageCheck < 0)
                {
                    return(Warning <IntResult>((-packageCheck).ToString()));
                }
                #endregion

                // get Exchange service
                ExchangeServerHostedEdition exchange = GetExchangeService(serviceId);

                // load service settings to know ProgramID, OfferID
                StringDictionary serviceSettings = ServerController.GetServiceSettings(serviceId);
                string           programId       = serviceSettings["programID"];
                string           offerId         = serviceSettings["offerID"];

                // check settings
                if (String.IsNullOrEmpty(programId))
                {
                    result.ErrorCodes.Add(ProgramIdIsNotSetError);
                }
                if (String.IsNullOrEmpty(offerId))
                {
                    result.ErrorCodes.Add(OfferIdIsNotSetError);
                }

                if (result.ErrorCodes.Count > 0)
                {
                    result.IsSuccess = false;
                    return(result);
                }

                #region Create organization
                int itemId = -1;
                ExchangeOrganization org = null;
                try
                {
                    // create organization
                    exchange.CreateOrganization(organizationId, programId, offerId, domain, adminName, adminEmail, adminPassword);

                    // save item into meta-base
                    org           = new ExchangeOrganization();
                    org.Name      = organizationId;
                    org.PackageId = packageId;
                    org.ServiceId = serviceId;
                    itemId        = PackageController.AddPackageItem(org);
                }
                catch (Exception ex)
                {
                    // log error
                    TaskManager.WriteError(ex);
                    return(Error <IntResult>(CreateOrganizationError));
                }
                #endregion

                #region Update organization quotas
                // update max org quotas
                UpdateOrganizationQuotas(org);

                // override quotas
                ResultObject quotasResult = ExchangeHostedEditionController.UpdateOrganizationQuotas(itemId,
                                                                                                     org.MaxMailboxCountQuota,
                                                                                                     org.MaxContactCountQuota,
                                                                                                     org.MaxDistributionListCountQuota);

                if (!quotasResult.IsSuccess)
                {
                    return(Error <IntResult>(quotasResult, CreateOrganizationError));
                }
                #endregion

                #region Add temporary domain
                // load settings
                PackageSettings settings           = GetExchangePackageSettings(org);
                string          tempDomainTemplate = settings[TempDomainSetting];
                if (!String.IsNullOrEmpty(tempDomainTemplate))
                {
                    // add temp domain
                    string tempDomain = String.Format("{0}.{1}", domain, tempDomainTemplate);
                    AddOrganizationDomain(itemId, tempDomain);
                }

                #endregion

                result.Value = itemId;
                return(result);
            }
            catch (Exception ex)
            {
                // log error
                TaskManager.WriteError(ex);

                // exit with error code
                return(Error <IntResult>(GeneralError, ex.Message));
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
コード例 #25
0
ファイル: EventModel.cs プロジェクト: fangld/EDGolog
        public EventModel(PlanningParser.EventModelContext context, IReadOnlyDictionary <string, Event> eventDict, StringDictionary assignment)
        {
            MaxPlausibilityDegree = context.LB() == null ? 0 : 1;

            GenerateEventArray(context, eventDict, assignment);
            GenerateBelievePrecondition();
            GenerateBelievePssa();
            GenerateKnowPrecondition();
            GenerateKnowPssa();
        }
コード例 #26
0
 public static void UploadFile(Wiki wiki, StringDictionary query, byte[] file, string fileName, //string fileMimeType,
                               string fileParamName, Action <XmlDocument> onSuccess)
 {
     UploadFile(wiki, query, file, fileName, fileParamName, onSuccess, DefaultErrorHandler);
 }
コード例 #27
0
ファイル: NicamHelper.cs プロジェクト: vsrathore2/SES-8.0
        /// <summary>
        /// </summary>
        /// <param name="user">
        /// </param>
        /// <param name="userOptions">
        /// </param>
        /// <param name="userProfile">
        /// </param>
        public static void UpdateUserProfile(User user, StringDictionary userOptions, StringDictionary userProfile)
        {
            if (User.Exists(user.Name))
            {
                UserProfile profile = user.Profile;
                using (new SecurityDisabler())
                {
                    Item item = Client.CoreDatabase.GetItem(userOptions["UserProfile"]);
                    profile.ProfileItemId = item.ID.ToString();
                    profile.FullName      = userOptions["FullName"];
                    profile.Email         = userOptions["Email"];
                    profile.Comment       = string.Empty;
                    profile.Portrait      = userOptions["Portrait"];
                    foreach (string key in userProfile.Keys)
                    {
                        profile.SetCustomProperty(key, userProfile[key]);
                    }

                    profile.Save();
                }
            }
        }
コード例 #28
0
        // Constructor
        public CommandLineArguments(string[] Args)
        {
            Parameters = new StringDictionary();
            Regex  Spliter   = new Regex(@"^-{1,2}|^/|=|:", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            Regex  Remover   = new Regex(@"^['""]?(.*?)['""]?$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            string Parameter = null;

            string[] Parts;

            // Valid parameters forms:
            // {-,/,--}param{ ,=,:}((",')value(",'))
            // Examples: -param1 value1 --param2 /param3:"Test-:-work" /param4=happy -param5 '--=nice=--'
            foreach (string Txt in Args)
            {
                // Look for new parameters (-,/ or --) and a possible enclosed value (=,:)
                Parts = Spliter.Split(Txt, 3);
                switch (Parts.Length)
                {
                // Found a value (for the last parameter found (space separator))
                case 1:
                    if (Parameter != null)
                    {
                        if (!Parameters.ContainsKey(Parameter))
                        {
                            Parts[0] = Remover.Replace(Parts[0], "$1");
                            Parameters.Add(Parameter, Parts[0]);
                        }
                        Parameter = null;
                    }
                    // else Error: no parameter waiting for a value (skipped)
                    break;

                // Found just a parameter
                case 2:
                    // The last parameter is still waiting. With no value, set it to true.
                    if (Parameter != null)
                    {
                        if (!Parameters.ContainsKey(Parameter))
                        {
                            Parameters.Add(Parameter, "true");
                        }
                    }
                    Parameter = Parts[1];
                    break;

                // Parameter with enclosed value
                case 3:
                    // The last parameter is still waiting. With no value, set it to true.
                    if (Parameter != null)
                    {
                        if (!Parameters.ContainsKey(Parameter))
                        {
                            Parameters.Add(Parameter, "true");
                        }
                    }
                    Parameter = Parts[1];
                    // Remove possible enclosing characters (",')
                    if (!Parameters.ContainsKey(Parameter))
                    {
                        Parts[2] = Remover.Replace(Parts[2], "$1");
                        Parameters.Add(Parameter, Parts[2]);
                    }
                    Parameter = null;
                    break;
                }
            }
            // In case a parameter is still waiting
            if (Parameter != null)
            {
                if (!Parameters.ContainsKey(Parameter))
                {
                    Parameters.Add(Parameter, "true");
                }
            }
        }
コード例 #29
0
        /// <summary>
        /// Deletes SharePoint site collection with given id.
        /// </summary>
        /// <param name="itemId">Site collection id within metabase.</param>
        /// <returns>?</returns>
        public static int DeleteSiteCollection(int itemId)
        {
            // Check account.
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);

            if (accountCheck < 0)
            {
                return(accountCheck);
            }

            // Load original meta item
            SharePointSiteCollection origItem = (SharePointSiteCollection)PackageController.GetPackageItem(itemId);

            if (origItem == null)
            {
                return(BusinessErrorCodes.ERROR_SHAREPOINT_PACKAGE_ITEM_NOT_FOUND);
            }

            // Get service settings.
            StringDictionary hostedSharePointSettings = ServerController.GetServiceSettings(origItem.ServiceId);
            Uri    rootWebApplicationUri = new Uri(hostedSharePointSettings["RootWebApplicationUri"]);
            string domainName            = origItem.Name.Replace(String.Format("{0}://", rootWebApplicationUri.Scheme), String.Empty);

            // Log operation.
            TaskManager.StartTask("HOSTEDSHAREPOINT", "DELETE_SITE", origItem.Name);
            TaskManager.ItemId = itemId;

            try
            {
                // Delete site collection on server.
                HostedSharePointServer hostedSharePointServer = GetHostedSharePointServer(origItem.ServiceId);
                hostedSharePointServer.DeleteSiteCollection(origItem.Url);
                // Delete record in metabase.
                PackageController.DeletePackageItem(origItem.Id);

                int dnsServiceId = PackageController.GetPackageServiceId(origItem.PackageId, ResourceGroups.Dns);
                if (dnsServiceId > 0)
                {
                    DomainInfo domain = ServerController.GetDomain(domainName);
                    if (domain != null)
                    {
                        ServerController.DeleteDnsZoneRecord(domain.DomainId, String.Empty, DnsRecordType.A, hostedSharePointSettings["RootWebApplicationIpAddress"]);
                        ServerController.DeleteDnsZoneRecord(domain.DomainId, "www", DnsRecordType.A, hostedSharePointSettings["RootWebApplicationIpAddress"]);

                        if (!String.IsNullOrEmpty(domain.WebSiteName))
                        {
                            DnsRecord[] records = ServerController.GetDnsZoneRecords(domain.DomainId);
                            foreach (DnsRecord record in records)
                            {
                                if (record.RecordType.Equals(DnsRecordType.A) && record.RecordName.Equals("www", StringComparison.CurrentCultureIgnoreCase))
                                {
                                    ServerController.AddDnsZoneRecord(domain.DomainId, String.Empty, DnsRecordType.A,
                                                                      record.RecordData, 0);
                                    break;
                                }
                            }
                        }
                    }
                }


                return(0);
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
コード例 #30
0
        public static ResultObject UpdateOrganizationServicePlan(int itemId, int newServiceId)
        {
            ResultObject result = new ResultObject();

            result.IsSuccess = true;

            try
            {
                // initialize task manager
                TaskManager.StartTask(TaskManagerSource, "UPDATE_SERVICE");
                TaskManager.WriteParameter("itemId", itemId);
                TaskManager.WriteParameter("newServiceId", newServiceId);

                // load organization item
                ExchangeOrganization item = PackageController.GetPackageItem(itemId) as ExchangeOrganization;
                if (item == null)
                {
                    return(Error <ResultObject>(OrganizationNotFoundError));
                }

                #region Check Space and Account
                // Check account
                int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsAdmin | DemandAccount.IsActive);
                if (accountCheck < 0)
                {
                    return(Warning <ResultObject>((-accountCheck).ToString()));
                }

                // Check space
                int packageCheck = SecurityContext.CheckPackage(item.PackageId, DemandPackage.IsActive);
                if (packageCheck < 0)
                {
                    return(Warning <ResultObject>((-packageCheck).ToString()));
                }
                #endregion

                // get Exchange service
                ExchangeServerHostedEdition exchange = GetExchangeService(item.ServiceId);

                // load service settings to know ProgramID, OfferID
                StringDictionary serviceSettings = ServerController.GetServiceSettings(newServiceId);
                string           programId       = serviceSettings["programID"];
                string           offerId         = serviceSettings["offerID"];

                // check settings
                if (String.IsNullOrEmpty(programId))
                {
                    result.ErrorCodes.Add(ProgramIdIsNotSetError);
                }
                if (String.IsNullOrEmpty(offerId))
                {
                    result.ErrorCodes.Add(OfferIdIsNotSetError);
                }

                // update service plan
                exchange.UpdateOrganizationServicePlan(item.Name, programId, offerId);

                // move item between services
                int moveResult = PackageController.MovePackageItem(itemId, newServiceId);
                if (moveResult < 0)
                {
                    return(Error <ResultObject>((-moveResult).ToString()));
                }

                return(result);
            }
            catch (Exception ex)
            {
                // log error
                TaskManager.WriteError(ex);

                // exit with error code
                return(Error <ResultObject>(UpdateServicePlanError, ex.Message));
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
コード例 #31
0
 public static void PostApi(Wiki wiki, StringDictionary query, Action <XmlDocument> onSuccess)
 {
     PostApi(wiki, query, onSuccess, DefaultErrorHandler, false, false);
 }
コード例 #32
0
 public static void PostApi(Wiki wiki, StringDictionary query, Action <XmlDocument> onSuccess,
                            Action <string> onError, bool synchronous)
 {
     PostApi(wiki, query, onSuccess, onError, false, synchronous);
 }
コード例 #33
0
ファイル: Response.cs プロジェクト: fangld/EDGolog
 public Response(PlanningParser.ResponseDefineContext context, IReadOnlyDictionary <string, Event> eventDict,
                 StringDictionary assignment, string[] constArray) : base(constArray)
 {
     Name       = context.responseSymbol().GetText();
     EventModel = context.eventModel().GetEventModel(eventDict, assignment);
 }
コード例 #34
0
        private void AddTraceSource(IDictionary d, Hashtable sources, XmlNode node)
        {
            string           name   = null;
            SourceLevels     levels = SourceLevels.Error;
            StringDictionary atts   = new StringDictionary();

            foreach (XmlAttribute a in node.Attributes)
            {
                switch (a.Name)
                {
                case "name":
                    name = a.Value;
                    break;

                case "switchValue":
                    levels = (SourceLevels)Enum.Parse(typeof(SourceLevels), a.Value);
                    break;

                default:
                    atts [a.Name] = a.Value;
                    break;
                }
            }
            if (name == null)
            {
                throw new ConfigurationException("Mandatory attribute 'name' is missing in 'source' element.");
            }

            // ignore duplicate ones (no error occurs)
            if (sources.ContainsKey(name))
            {
                return;
            }

            TraceSourceInfo sinfo = new TraceSourceInfo(name, levels, configValues);

            sources.Add(sinfo.Name, sinfo);

            foreach (XmlNode child in node.ChildNodes)
            {
                XmlNodeType t = child.NodeType;
                if (t == XmlNodeType.Whitespace || t == XmlNodeType.Comment)
                {
                    continue;
                }
                if (t == XmlNodeType.Element)
                {
                    if (child.Name == "listeners")
                    {
                        AddTraceListeners(d, child, sinfo.Listeners);
                    }
                    else
                    {
                        ThrowUnrecognizedElement(child);
                    }
                    ValidateInvalidAttributes(child.Attributes, child);
                }
                else
                {
                    ThrowUnrecognizedNode(child);
                }
            }
        }
コード例 #35
0
        public static void UploadFile(Wiki wiki, StringDictionary query, byte[] file, string fileName, //string fileMimeType,
                                      string fileParamName, Action <XmlDocument> onSuccess, Action <string> onError)
        {
            // thanks to http://www.paraesthesia.com/archive/2009/12/16/posting-multipartform-data-using-.net-webrequest.aspx

            query.Add("format", "xml");

            WebRequest req = HttpWebRequest.Create(GetApiUri(wiki));

            ((HttpWebRequest)req).UserAgent = UserAgent;
            req.Method = "POST";

            LoginInfo session = LoginSessions[wiki];

            if (session.LoggedIn)
            {
                CookieContainer jar    = new CookieContainer();
                string          domain = GetDomainForCookies(wiki);
                jar.Add(new Cookie(session.CookiePrefix + "_session", session.SessionID, "/", domain));
                jar.Add(new Cookie(session.CookiePrefix + "UserName", Uri.EscapeDataString(session.UserName).Replace("%20", "+"), "/", domain));
                jar.Add(new Cookie("centralauth_User", Uri.EscapeDataString(session.UserName).Replace("%20", "+"), "/", domain));
                jar.Add(new Cookie(session.CookiePrefix + "UserID", session.UserID, "/", domain));
                jar.Add(new Cookie("centralauth_Token", Uri.EscapeDataString(session.CAToken).Replace("%20", "+"), "/", domain));
                jar.Add(new Cookie("centralauth_Session", Uri.EscapeDataString(session.CASession).Replace("%20", "+"), "/", domain));
                ((HttpWebRequest)req).CookieContainer = jar;
            }

            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");

            req.ContentType = "multipart/form-data; boundary=" + boundary;

            req.BeginGetRequestStream(delegate(IAsyncResult innerResult)
            {
                Stream stream = req.EndGetRequestStream(innerResult);

                foreach (DictionaryEntry e in query)
                {
                    string item = String.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: 8bit\r\n\r\n{2}\r\n",
                                                boundary, e.Key.ToString(), e.Value.ToString());
                    byte[] bytes = Encoding.UTF8.GetBytes(item);
                    stream.Write(bytes, 0, bytes.Length);
                }

                if (file != null)
                {
                    string header = String.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n",
                                                  boundary, fileParamName, fileName, "text/plain; charset=UTF-8"); // last param was |fileMimeType|
                    byte[] headerbytes = Encoding.UTF8.GetBytes(header);
                    stream.Write(headerbytes, 0, headerbytes.Length);

                    stream.Write(file, 0, file.Length);

                    byte[] newline = Encoding.UTF8.GetBytes("\r\n");
                    stream.Write(newline, 0, newline.Length);
                }
                byte[] endBytes = Encoding.UTF8.GetBytes("--" + boundary + "--");
                stream.Write(endBytes, 0, endBytes.Length);
                stream.Close();
            }, null);

            IAsyncResult result = (IAsyncResult)req.BeginGetResponse(new AsyncCallback(delegate(IAsyncResult innerResult)
            {
                WebResponse resp = null;
                try
                {
                    resp = req.EndGetResponse(innerResult);
                }
                catch (WebException e)
                {
                    onError(Localization.GetString("MorebitsDotNet_NetRequestFailure") + "\n\n" + e.Message);
                    return;
                }

                XmlDocument doc = new XmlDocument();
                doc.Load(resp.GetResponseStream());

                XmlNodeList list = doc.GetElementsByTagName("error");
                if (list.Count == 0)
                {
                    onSuccess(doc);
                }
                else
                {
                    onError(Localization.GetString("MorebitsDotNet_ApiError") + "\n\n" + list[0].Attributes["info"].Value);
                }
            }), null);

            ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), req, UploadTimeout, true);
        }
コード例 #36
0
        public int Run(string command, StringDictionary keyValues, out string output)
        {
            if (traceSwitch.TraceVerbose)
            {
                trace.TraceVerbose("Run(): Entered.");
            }

#if DEBUG
            // comment back in to debug..
            //Console.WriteLine("Attach debugger and/or press enter to continue..");
            //Console.ReadLine();
#endif

            int              iReturn = 0;
            string           sResult = string.Empty;
            DeploymentType   deploymentType;
            WizardDeployment wizardDeployment = null;

            // determine command type..
            switch (command)
            {
            case f_csIMPORT_COMMAND:
                deploymentType = DeploymentType.Import;
                break;

            case f_csEXPORT_COMMAND:
                deploymentType = DeploymentType.Export;
                break;

            default:
                throw new ConfigurationErrorsException("Error - unexpected command! Supported commands are 'RunWizardImport' and 'RunWizardExport'.");
                break;
            }

            // validate passed settings..
            string sValidationMessage = validateSettings(keyValues, deploymentType);

            if (string.IsNullOrEmpty(sValidationMessage))
            {
                string sSettingsFilePath = keyValues[f_csSETTINGS_FILE_PARAM];
                if (keyValues[f_csQUIET_PARAM] != null)
                {
                    f_quiet = true;
                }

                using (XmlTextReader xReader = new XmlTextReader(sSettingsFilePath))
                {
                    wizardDeployment = new WizardDeployment(xReader, deploymentType);

                    // ask deployment API to validate settings..
                    try
                    {
                        wizardDeployment.ValidateSettings();
                        if (traceSwitch.TraceInfo)
                        {
                            trace.TraceInfo("Run(): Settings validated successfully.");
                        }
                    }
                    catch (Exception e)
                    {
                        if (traceSwitch.TraceWarning)
                        {
                            trace.TraceWarning("Run(): Failed to validate deployment settings! Deployment will not be done, showing error message.");
                        }

                        sResult = string.Format("Error - unable to validate the deployment settings you chose. Please ensure, for example, you are not exporting a web " +
                                                "and specific child objects in the same operation. Message = '{0}'.", e.Message);
                    }

                    if (string.IsNullOrEmpty(sResult))
                    {
                        // now run job..
                        wizardDeployment.ProgressUpdated += new EventHandler <SPDeploymentEventArgs>(wizardDeployment_ProgressUpdated);

                        if (deploymentType == DeploymentType.Export)
                        {
                            wizardDeployment.ValidChangeTokenNotFound += new EventHandler <InvalidChangeTokenEventArgs>(wizardDeployment_ValidChangeTokenNotFound);
                            sResult = runExportTask(wizardDeployment);
                        }
                        else if (deploymentType == DeploymentType.Import)
                        {
                            sResult = runImportTask(wizardDeployment);
                        }
                    }
                }
            }
            else
            {
                sResult = sValidationMessage;
            }

            if (traceSwitch.TraceVerbose)
            {
                trace.TraceVerbose("Run(): Returning '{0}'.", iReturn);
            }

            output = sResult;
            return(iReturn);
        }
コード例 #37
0
        public void SetEnvironmentVariables(
            int agentPort,
            int aspNetCorePort,
            string processPath,
            StringDictionary environmentVariables)
        {
            var    processName     = processPath;
            string profilerEnabled = _requiresProfiling ? "1" : "0";
            string profilerPath;

            if (IsCoreClr())
            {
                environmentVariables["CORECLR_ENABLE_PROFILING"] = profilerEnabled;
                environmentVariables["CORECLR_PROFILER"]         = EnvironmentTools.ProfilerClsId;

                profilerPath = GetProfilerPath();
                environmentVariables["CORECLR_PROFILER_PATH"] = profilerPath;
                environmentVariables["DD_DOTNET_TRACER_HOME"] = Path.GetDirectoryName(profilerPath);
            }
            else
            {
                environmentVariables["COR_ENABLE_PROFILING"] = profilerEnabled;
                environmentVariables["COR_PROFILER"]         = EnvironmentTools.ProfilerClsId;

                profilerPath = GetProfilerPath();
                environmentVariables["COR_PROFILER_PATH"]     = profilerPath;
                environmentVariables["DD_DOTNET_TRACER_HOME"] = Path.GetDirectoryName(profilerPath);

                processName = Path.GetFileName(processPath);
            }

            if (DebugModeEnabled)
            {
                environmentVariables["DD_TRACE_DEBUG"] = "1";
            }

            environmentVariables["DD_PROFILER_PROCESSES"] = processName;

            string integrations = string.Join(";", GetIntegrationsFilePaths());

            environmentVariables["DD_INTEGRATIONS"]         = integrations;
            environmentVariables["DD_TRACE_AGENT_HOSTNAME"] = "localhost";
            environmentVariables["DD_TRACE_AGENT_PORT"]     = agentPort.ToString();

            // for ASP.NET Core sample apps, set the server's port
            environmentVariables["ASPNETCORE_URLS"] = $"http://localhost:{aspNetCorePort}/";

            foreach (var name in new[] { "SERVICESTACK_REDIS_HOST", "STACKEXCHANGE_REDIS_HOST" })
            {
                var value = Environment.GetEnvironmentVariable(name);
                if (!string.IsNullOrEmpty(value))
                {
                    environmentVariables[name] = value;
                }
            }

            foreach (var key in CustomEnvironmentVariables.Keys)
            {
                environmentVariables[key] = CustomEnvironmentVariables[key];
            }
        }
コード例 #38
0
ファイル: EventModel.cs プロジェクト: fangld/EDGolog
        private void GenerateEventArray(PlanningParser.EventModelContext context, IReadOnlyDictionary <string, Event> eventDict, StringDictionary assignment)
        {
            if (MaxPlausibilityDegree == 0)
            {
                _believeEventArray = context.gdEvent().ToEventCollection(eventDict, assignment);
                _knowEventArray    = _believeEventArray;
            }
            else
            {
                _believeEventArray = context.plGdEvent(0).gdEvent().ToEventCollection(eventDict, assignment);
                var eventArray1       = context.plGdEvent(1).gdEvent().ToEventCollection(eventDict, assignment);
                int eventArray0Length = _believeEventArray.Length;
                int eventArray1Length = eventArray1.Length;

                _knowEventArray = new Event[eventArray0Length + eventArray1Length];
                Array.Copy(_believeEventArray, _knowEventArray, eventArray0Length);
                Array.Copy(eventArray1, 0, _knowEventArray, eventArray0Length, eventArray1Length);
            }
        }
コード例 #39
0
        private static void RunService(CommandLineParser parser, Action <StringDictionary> environment, ILog logger)
        {
            if (ServiceEnvironmentManagementEx.IsServiceDisabled(parser.Target))
            {
                logger.ErrorFormat("The service '{0}' is disabled. Please enable the service.",
                                   parser.Target);
                return;
            }

            var service = new ServiceController(parser.Target);

            try
            {
                if (service.Status != ServiceControllerStatus.Stopped)
                {
                    logger.ErrorFormat(
                        "The service '{0}' is already running. The profiler cannot attach to an already running service.",
                        parser.Target);
                    return;
                }

                // now to set the environment variables
                var profilerEnvironment = new StringDictionary();
                environment(profilerEnvironment);

                var serviceEnvironment = new ServiceEnvironmentManagement();

                try
                {
                    serviceEnvironment.PrepareServiceEnvironment(
                        parser.Target,
                        parser.ServiceEnvironment,
                        (from string key in profilerEnvironment.Keys
                         select string.Format("{0}={1}", key, profilerEnvironment[key])).ToArray());

                    // now start the service
                    var old = service;
                    service = new ServiceController(parser.Target);
                    old.Dispose();

                    if (parser.Target.ToLower().Equals("w3svc"))
                    {
                        // Service will not automatically start
                        if (!TerminateCurrentW3SvcHost(logger) ||
                            !ServiceEnvironmentManagementEx.IsServiceStartAutomatic(parser.Target))
                        {
                            service.Start();
                        }
                    }
                    else
                    {
                        service.Start();
                    }
                    logger.InfoFormat("Service starting '{0}'", parser.Target);
                    service.WaitForStatus(ServiceControllerStatus.Running, parser.ServiceStartTimeout);
                    logger.InfoFormat("Service started '{0}'", parser.Target);
                }
                catch (InvalidOperationException fault)
                {
                    logger.FatalFormat("Service launch failed with '{0}'", fault);
                }
                finally
                {
                    // once the serice has started set the environment variables back - just in case
                    serviceEnvironment.ResetServiceEnvironment();
                }

                // and wait for it to stop
                service.WaitForStatus(ServiceControllerStatus.Stopped);
                logger.InfoFormat("Service stopped '{0}'", parser.Target);

                // Stopping w3svc host
                if (parser.Target.ToLower().Equals("w3svc"))
                {
                    logger.InfoFormat("Stopping svchost to clean up environment variables for {0}", parser.Target);
                    if (ServiceEnvironmentManagementEx.IsServiceStartAutomatic(parser.Target))
                    {
                        logger.InfoFormat("Please note that the 'w3svc' service may automatically start");
                    }
                    TerminateCurrentW3SvcHost(logger);
                }
            }
            finally
            {
                service.Dispose();
            }
        }
コード例 #40
0
        static void Main()
        {
            // Join Unicode
            Console.OutputEncoding = Encoding.Unicode;

            // set size of console
            Console.SetWindowSize(80, 60);
            Console.SetBufferSize(80, 60);

            #region Hashtable
#if false
            Hashtable ht = new Hashtable();
            {
                List <string> keys = new List <string>();
                for (int i = 0; i < rnd.Next(10, 28); i++)
                {
                    // на випадок повторень ключа
                    try
                    {
                        keys.Add(GetFullName());
                        ht.Add(keys.Last(), GetProduct());
                    }
                    catch (ArgumentException)
                    {
                        keys.RemoveAt(i--);
                    }
                }

                // виведення
                foreach (var i in keys)
                {
                    GetRes(i, (string)ht[i]);
                }
            }
#endif
            #endregion

            #region ListDictionary
#if false
            ListDictionary ld = new ListDictionary();
            {
                List <string> keys = new List <string>();
                for (int i = 0; i < rnd.Next(10, 28); i++)
                {
                    // на випадок повторень ключа
                    try
                    {
                        keys.Add(GetFullName());
                        ld.Add(keys.Last(), GetProduct());
                    }
                    catch (ArgumentException)
                    {
                        keys.RemoveAt(i--);
                    }
                }

                // виведення
                foreach (var i in keys)
                {
                    GetRes(i, (string)ld[i]);
                }
            }
#endif
            #endregion

            #region HybridDictionary
#if false
            HybridDictionary hd = new HybridDictionary();
            {
                List <string> keys = new List <string>();
                for (int i = 0; i < rnd.Next(10, 28); i++)
                {
                    // на випадок повторень ключа
                    try
                    {
                        keys.Add(GetFullName());
                        hd.Add(keys.Last(), GetProduct());
                    }
                    catch (ArgumentException)
                    {
                        keys.RemoveAt(i--);
                    }
                }

                // виведення
                foreach (var i in keys)
                {
                    GetRes(i, (string)hd[i]);
                }
            }
#endif
            #endregion

            #region SortedList
#if false
            SortedList <string, string> sl = new SortedList <string, string>();
            for (int i = 0; i < rnd.Next(10, 28); i++)
            {
                try
                {
                    sl.Add(GetFullName(), GetProduct());
                }
                catch (ArgumentException)
                {
                    i--;
                }
            }

            // виведення
            foreach (var i in sl)
            {
                GetRes(i.Key, i.Value);
            }
#endif
            #endregion

            #region OrderedDictionary
#if false
            OrderedDictionary od = new OrderedDictionary();
            {
                List <string> keys = new List <string>();
                for (int i = 0; i < rnd.Next(10, 28); i++)
                {
                    try
                    {
                        keys.Add(GetFullName());
                        od.Add(keys.Last(), GetProduct());
                    }
                    catch (ArgumentException)
                    {
                        keys.RemoveAt(i--);
                    }
                }

                // виведення
                foreach (var i in keys)
                {
                    GetRes(i, (string)od[i]);
                }
            }
#endif
            #endregion

            #region StringDictionary
#if false
            StringDictionary sd = new StringDictionary();
            {
                List <string> keys = new List <string>();
                for (int i = 0; i < rnd.Next(10, 28); i++)
                {
                    try
                    {
                        keys.Add(GetFullName());
                        sd.Add(keys.Last(), GetProduct());
                    }
                    catch (ArgumentException)
                    {
                        keys.RemoveAt(i--);
                    }
                }

                // виведення
                foreach (var i in keys)
                {
                    GetRes(i, sd[i]);
                }
            }
#endif
            #endregion

            #region NameValueCollection
#if false
            NameValueCollection nvc = new NameValueCollection();
            for (int i = 0; i < rnd.Next(10, 28); i++)
            {
                nvc.Add(GetFullName(), GetProduct());
            }

            // виведення
            foreach (var i in nvc.AllKeys)
            {
                GetRes(i, nvc[i]);
            }
#endif
            #endregion

            #region List
#if false
            List <Customer> list = new List <Customer>();
            for (int i = 0; i < rnd.Next(10, 28); i++)
            {
                list.Add(GetCustomer());
            }

            // виведення
            foreach (var i in list)
            {
                GetRes(i.FullName, i.CategoryProdact);
            }
#endif
            #endregion

            #region Dictionary
#if false
            Dictionary <string, string> d = new Dictionary <string, string>();
            for (int i = 0; i < rnd.Next(10, 28); i++)
            {
                try
                {
                    d.Add(GetFullName(), GetProduct());
                }
                catch (ArgumentException)
                {
                    i--;
                }
            }

            // виведення
            foreach (var i in d)
            {
                GetRes(i.Key, i.Value);
            }
#endif
            #endregion

            #region SortedDictionary
#if false
            SortedDictionary <string, string> sd = new SortedDictionary <string, string>();
            for (int i = 0; i < rnd.Next(10, 28); i++)
            {
                try
                {
                    sd.Add(GetFullName(), GetProduct());
                }
                catch (ArgumentException)
                {
                    i--;
                }
            }

            // виведення
            foreach (var i in sd)
            {
                GetRes(i.Key, i.Value);
            }
#endif
            #endregion

            #region LinkedList
#if false
            LinkedList <Customer> ll = new LinkedList <Customer>();
            for (int i = 0; i < rnd.Next(10, 28); i++)
            {
                ll.AddLast(GetCustomer());
            }

            // виведення
            foreach (var i in ll)
            {
                GetRes(i.FullName, i.CategoryProdact);
            }
#endif
            #endregion

            #region ArrayList
#if false
            ArrayList al = new ArrayList();
            for (int i = 0; i < rnd.Next(10, 28); i++)
            {
                al.Add(GetCustomer());
            }

            // виведення
            foreach (var i in al)
            {
                GetRes(((Customer)i).FullName, ((Customer)i).CategoryProdact);
            }
#endif
            #endregion

            #region Queue
#if false
            Queue <Customer> q = new Queue <Customer>();
            List <Customer>  l = new List <Customer>();
            for (int i = 0; i < rnd.Next(10, 28); i++)
            {
                l.Add(GetCustomer());
                q.Enqueue(l.Last());
            }

            // виведення
            foreach (var i in l)
            {
                GetRes(i.FullName, i.CategoryProdact);
            }
            Console.WriteLine();
#if false
            foreach (var i in q)
            {
                GetRes(i.FullName, i.CategoryProdact);
            }
#if false    // можна отримати доступ і після проходження всього перебору
            {
                Customer i = q.Dequeue();
                GetRes(i.FullName, i.CategoryProdact);
            }
#endif
#endif
#if true
            while (q.Count > 0)
            {
                Customer i = q.Dequeue();
                GetRes(i.FullName, i.CategoryProdact);
            }
#endif
#endif
            #endregion

            #region Stack
#if true
            Stack <Customer> s = new Stack <Customer>();
            List <Customer>  l = new List <Customer>();
            for (int i = 0; i < rnd.Next(10, 28); i++)
            {
                l.Add(GetCustomer());
                s.Push(l.Last());
            }

            // виведення
            foreach (var i in l)
            {
                GetRes(i.FullName, i.CategoryProdact);
            }
            Console.WriteLine();
#if false
            foreach (var i in s)
            {
                GetRes(i.FullName, i.CategoryProdact);
            }
#if true    // можна отримати доступ і після проходження всього перебору
            {
                Customer i = s.Pop();
                GetRes(i.FullName, i.CategoryProdact);
            }
#endif
#endif
#if true
            while (s.Count > 0)
            {
                Customer i = s.Pop();
                GetRes(i.FullName, i.CategoryProdact);
            }
#endif
#endif
            #endregion

            // repeat
            DoExitOrRepeat();
        }
コード例 #41
0
        public void TestEnvironmentVariablesPropertyUnix()
        {
            ProcessStartInfo psi = new ProcessStartInfo();

            // Creating a detached ProcessStartInfo will pre-populate the environment
            // with current environmental variables.

            StringDictionary environmentVariables = psi.EnvironmentVariables;

            Assert.NotEqual(0, environmentVariables.Count);

            int CountItems = environmentVariables.Count;

            environmentVariables.Add("NewKey", "NewValue");
            environmentVariables.Add("NewKey2", "NewValue2");

            Assert.Equal(CountItems + 2, environmentVariables.Count);
            environmentVariables.Remove("NewKey");
            Assert.Equal(CountItems + 1, environmentVariables.Count);

            //Exception not thrown with invalid key
            AssertExtensions.Throws <ArgumentException>(null, () => { environmentVariables.Add("NewKey2", "NewValue2"); });
            Assert.False(environmentVariables.ContainsKey("NewKey"));

            environmentVariables.Add("newkey2", "newvalue2");
            Assert.True(environmentVariables.ContainsKey("newkey2"));
            Assert.Equal("newvalue2", environmentVariables["newkey2"]);
            Assert.Equal("NewValue2", environmentVariables["NewKey2"]);

            environmentVariables.Clear();

            Assert.Equal(0, environmentVariables.Count);

            environmentVariables.Add("NewKey", "newvalue");
            environmentVariables.Add("newkey2", "NewValue2");
            Assert.False(environmentVariables.ContainsKey("newkey"));
            Assert.False(environmentVariables.ContainsValue("NewValue"));

            string result = null;
            int    index  = 0;

            foreach (string e1 in environmentVariables.Values)
            {
                index++;
                result += e1;
            }
            Assert.Equal(2, index);
            Assert.Equal("newvalueNewValue2", result);

            result = null;
            index  = 0;
            foreach (string e1 in environmentVariables.Keys)
            {
                index++;
                result += e1;
            }
            Assert.Equal("NewKeynewkey2", result);
            Assert.Equal(2, index);

            result = null;
            index  = 0;
            foreach (DictionaryEntry e1 in environmentVariables)
            {
                index++;
                result += e1.Key;
            }
            Assert.Equal("NewKeynewkey2", result);
            Assert.Equal(2, index);

            //Key not found
            Assert.Throws <KeyNotFoundException>(() =>
            {
                string stringout = environmentVariables["NewKey99"];
            });

            //Exception not thrown with invalid key
            Assert.Throws <ArgumentNullException>(() =>
            {
                string stringout = environmentVariables[null];
            });

            //Exception not thrown with invalid key
            Assert.Throws <ArgumentNullException>(() => environmentVariables.Add(null, "NewValue2"));

            AssertExtensions.Throws <ArgumentException>(null, () => environmentVariables.Add("newkey2", "NewValue2"));

            //Use DictionaryEntry Enumerator
            var x = environmentVariables.GetEnumerator() as IEnumerator;

            x.MoveNext();
            var y1 = (DictionaryEntry)x.Current;

            Assert.Equal("NewKey newvalue", y1.Key + " " + y1.Value);
            x.MoveNext();
            y1 = (DictionaryEntry)x.Current;
            Assert.Equal("newkey2 NewValue2", y1.Key + " " + y1.Value);

            environmentVariables.Add("newkey3", "newvalue3");

            KeyValuePair <string, string>[] kvpa = new KeyValuePair <string, string> [10];
            environmentVariables.CopyTo(kvpa, 0);
            Assert.Equal("NewKey", kvpa[0].Key);
            Assert.Equal("newkey3", kvpa[2].Key);
            Assert.Equal("newvalue3", kvpa[2].Value);

            string[] kvp = new string[10];
            AssertExtensions.Throws <ArgumentException>(null, () => { environmentVariables.CopyTo(kvp, 6); });
            environmentVariables.CopyTo(kvpa, 6);
            Assert.Equal("NewKey", kvpa[6].Key);
            Assert.Equal("newvalue", kvpa[6].Value);

            Assert.Throws <ArgumentOutOfRangeException>(() => { environmentVariables.CopyTo(kvpa, -1); });

            AssertExtensions.Throws <ArgumentException>(null, () => { environmentVariables.CopyTo(kvpa, 9); });

            Assert.Throws <ArgumentNullException>(() =>
            {
                KeyValuePair <string, string>[] kvpanull = null;
                environmentVariables.CopyTo(kvpanull, 0);
            });
        }
コード例 #42
0
        private static void PostApi(Wiki wiki, StringDictionary query, Action <XmlDocument> onSuccess,
                                    Action <string> onError, bool loggingIn, bool synchronous)
        {
            string requestContent = "format=xml&";

            foreach (DictionaryEntry i in query)
            {
                requestContent += Uri.EscapeDataString((string)i.Key) + "=" + Uri.EscapeDataString((string)i.Value ?? "") + "&";
            }
            requestContent = requestContent.TrimEnd('&');

            WebRequest req = HttpWebRequest.Create(GetApiUri(wiki));

            ((HttpWebRequest)req).UserAgent = UserAgent;
            req.Method      = "POST";
            req.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";

            LoginInfo session = LoginSessions[wiki];

            if (session.LoggedIn || loggingIn)
            {
                CookieContainer jar    = new CookieContainer();
                string          domain = GetDomainForCookies(wiki);
                jar.Add(new Cookie(session.CookiePrefix + "_session", session.SessionID, "/", domain));
                if (!loggingIn)
                {
                    jar.Add(new Cookie(session.CookiePrefix + "UserName", Uri.EscapeDataString(session.UserName).Replace("%20", "+"), "/", domain));
                    jar.Add(new Cookie("centralauth_User", Uri.EscapeDataString(session.UserName).Replace("%20", "+"), "/", domain));
                    jar.Add(new Cookie(session.CookiePrefix + "UserID", session.UserID, "/", domain));
                    jar.Add(new Cookie("centralauth_Token", Uri.EscapeDataString(session.CAToken).Replace("%20", "+"), "/", domain));
                    jar.Add(new Cookie("centralauth_Session", Uri.EscapeDataString(session.CASession).Replace("%20", "+"), "/", domain));
                }
                ((HttpWebRequest)req).CookieContainer = jar;
            }

            // login doesn't seem to work properly when done asycnhronously
            if (loggingIn || synchronous)
            {
                Stream s     = req.GetRequestStream();
                byte[] bytes = Encoding.UTF8.GetBytes(requestContent);
                s.Write(bytes, 0, bytes.Length);
                s.Close();
            }
            else
            {
                req.BeginGetRequestStream(delegate(IAsyncResult innerResult)
                {
                    using (Stream s = req.EndGetRequestStream(innerResult))
                    {
                        byte[] bytes = Encoding.UTF8.GetBytes(requestContent);
                        s.Write(bytes, 0, bytes.Length);
                        s.Close();
                    }
                }, null);
            }

            IAsyncResult result = (IAsyncResult)req.BeginGetResponse(delegate(IAsyncResult innerResult)
            {
                WebResponse resp = null;
                try
                {
                    resp = req.EndGetResponse(innerResult);
                }
                catch (WebException e)
                {
                    onError(Localization.GetString("MorebitsDotNet_NetRequestFailure") + "\n\n" + e.Message);
                    return;
                }

                XmlDocument doc = new XmlDocument();
                doc.Load(resp.GetResponseStream());

                if (loggingIn)
                {
                    // have to handle login errors (wrong password, etc.) before cookies are read
                    try
                    {
                        XmlNode login = doc.GetElementsByTagName("login")[0];
                        if (login.Attributes["result"].Value != "Success")
                        {
                            onError(Localization.GetString("MorebitsDotNet_LoginFailure", login.Attributes["result"].Value));
                            return;
                        }
                    }
                    catch (Exception x)
                    {
                        onError(Localization.GetString("MorebitsDotNet_UnknownLoginFailure") + "\n\n" + x.Message + "\n\nHere is some debugging info:\n" + doc.OuterXml);
                    }

                    LoginSessions[wiki].CAToken   = Regex.Match(resp.Headers["Set-Cookie"], "centralauth_Token=([0-9a-f]+);").Groups[1].Value;
                    LoginSessions[wiki].CASession = Regex.Match(resp.Headers["Set-Cookie"], "centralauth_Session=([0-9a-f]+);").Groups[1].Value;
                }

                XmlNodeList list = doc.GetElementsByTagName("error");
                if (list.Count == 0)
                {
                    onSuccess(doc);
                }
                else
                {
                    onError(Localization.GetString("MorebitsDotNet_ApiError") + "\n\n" + list[0].Attributes["info"].Value);
                }
            }, null);

            ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), req, DefaultTimeout, true);
        }
コード例 #43
0
 public void BindSettings(StringDictionary settings)
 {
 }
コード例 #44
0
        private Control ProcessToken(string tokenName)
        {
            switch (tokenName.ToUpper())
            {
            case "DETAILTITLE":
                if (!_inList)
                {
                    Label lblTitle = new Label
                    {
                        CssClass = "StoreDetailTitle",
                        Text     = Localization.GetString("DetailTitle", LocalResourceFile)
                    };
                    return(lblTitle);
                }

                return(null);

            case "CARTWARNING":
                if (!_inList && _cartWarning && CurrentCart.ProductIsInCart(PortalId, StoreSettings.SecureCookie, _product.ProductID))
                {
                    Label lblWarningMessage = new Label
                    {
                        CssClass = "StoreDetailWarningMessage",
                        Text     = Localization.GetString("WarningMessage", LocalResourceFile)
                    };
                    return(lblWarningMessage);
                }

                return(null);

            case "IMAGE":
                // No control in this case
                if (!_showThumbnail || string.IsNullOrEmpty(_product.ProductImage))
                {
                    return(null);
                }

                Image imgProduct = new Image
                {
                    ImageUrl      = GetImageUrl(_product.ProductImage),
                    AlternateText = Localization.GetString("ImageAlt.Text", LocalResourceFile),
                    CssClass      = "StoreProductImage"
                };

                if (_inList & _showDetail)
                {
                    StringDictionary rplcImage = new StringDictionary
                    {
                        { "ProductID", _product.ProductID.ToString() }
                    };
                    if (StoreSettings.SEOFeature == true)
                    {
                        rplcImage.Add("Product", _product.SEOName);
                    }

                    HyperLink lnkImage = new HyperLink
                    {
                        NavigateUrl = _catalogNav.GetNavigationUrl(_detailID, rplcImage),
                        ToolTip     = SEO(Localization.GetString("LinkDetail", LocalResourceFile), MetaTags.Title),
                        CssClass    = "StoreProductLinkImage"
                    };
                    lnkImage.Controls.Add(imgProduct);
                    return(lnkImage);
                }

                imgProduct.ToolTip = SEO(Localization.GetString("ImageTitle.Text", LocalResourceFile), MetaTags.Title);
                return(imgProduct);

            case "IMAGEURL":
                // No control in this case
                if (string.IsNullOrEmpty(_product.ProductImage))
                {
                    return(null);
                }

                return(new LiteralControl(GetImageUrl(_product.ProductImage)));

            case "IMAGERAWURL":
                // No control in this case
                if (string.IsNullOrEmpty(_product.ProductImage))
                {
                    return(null);
                }

                return(new LiteralControl(_product.ProductImage));

            case "EDIT":
                if (IsEditable)
                {
                    ImageButton imgEdit = new ImageButton
                    {
                        CssClass        = "StoreButtonEdit",
                        CommandArgument = _product.ProductID.ToString()
                    };
                    imgEdit.Click        += btnEdit_Click;
                    imgEdit.ImageUrl      = "~/images/Edit.gif";
                    imgEdit.AlternateText = Localization.GetString("Edit.Text", LocalResourceFile);
                    return(imgEdit);
                }

                return(null);

            case "CATEGORYNAME":
                Label lblProductCategory = new Label
                {
                    Text     = string.Format(Localization.GetString("CategoryName.Text", LocalResourceFile), _category.Name),
                    CssClass = "StoreCategoryName"
                };
                return(lblProductCategory);

            case "MANUFACTURER":
                Label lblManufacturer = new Label
                {
                    Text     = string.Format(Localization.GetString("Manufacturer.Text", LocalResourceFile), _product.Manufacturer),
                    CssClass = "StoreProductManufacturer"
                };
                return(lblManufacturer);

            case "MODELNUMBER":
                Label lblModelNumber = new Label
                {
                    Text     = string.Format(Localization.GetString("ModelNumber.Text", LocalResourceFile), _product.ModelNumber),
                    CssClass = "StoreProductModelNumber"
                };
                return(lblModelNumber);

            case "MODELNAME":
                Label lblModelName = new Label
                {
                    Text     = string.Format(Localization.GetString("ModelName.Text", LocalResourceFile), _product.ModelName),
                    CssClass = "StoreProductModelName"
                };
                return(lblModelName);

            case "TITLE":
                if (_inList & _showDetail)
                {
                    StringDictionary rplcTitle = new StringDictionary
                    {
                        { "ProductID", _product.ProductID.ToString() }
                    };
                    if (StoreSettings.SEOFeature)
                    {
                        rplcTitle.Add("Product", _product.SEOName);
                    }

                    HyperLink lnkTitle = new HyperLink
                    {
                        Text        = _product.ProductTitle,
                        NavigateUrl = _catalogNav.GetNavigationUrl(_detailID, rplcTitle),
                        CssClass    = "CommandButton StoreProductLinkTitle"
                    };
                    return(lnkTitle);
                }

                Label lblProductTitle = new Label
                {
                    Text     = _product.ProductTitle,
                    CssClass = "StoreProductTitle"
                };
                return(lblProductTitle);

            case "LINKDETAIL":
                if (_inList & _showDetail)
                {
                    StringDictionary rplcLink = new StringDictionary
                    {
                        { "ProductID", _product.ProductID.ToString() }
                    };
                    if (StoreSettings.SEOFeature)
                    {
                        rplcLink.Add("Product", _product.SEOName);
                    }

                    HyperLink lnkDetail = new HyperLink
                    {
                        Text        = Localization.GetString("LinkDetail", LocalResourceFile),
                        NavigateUrl = _catalogNav.GetNavigationUrl(_detailID, rplcLink),
                        CssClass    = "CommandButton StoreLinkDetail"
                    };
                    return(lnkDetail);
                }

                return(null);

            case "PRINTDETAIL":
                if (!_inList)
                {
                    string url = _catalogNav.GetNavigationUrl() + "&mid=" + ModuleId + "&SkinSrc=" + Globals.QueryStringEncode("[G]" + SkinController.RootSkin + "/" + Globals.glbHostSkinFolder + "/" + "No Skin") + "&ContainerSrc=" + Globals.QueryStringEncode("[G]" + SkinController.RootContainer + "/" + Globals.glbHostSkinFolder + "/" + "No Container");

                    HyperLink lnkPrintDetail = new HyperLink
                    {
                        Text        = Localization.GetString("PrintDetail", LocalResourceFile),
                        NavigateUrl = url,
                        Target      = "_blank",
                        CssClass    = "CommandButton StorePrintDetail"
                    };
                    return(lnkPrintDetail);
                }

                return(null);

            case "LINKDETAILIMG":
                if (_inList & _showDetail)
                {
                    ImageButton btnLinkDetailImg = new ImageButton
                    {
                        ImageUrl        = GetImagePath("LinkDetailImg"),
                        ToolTip         = Localization.GetString("LinkDetail", LocalResourceFile),
                        CommandArgument = _product.ProductID.ToString()
                    };
                    btnLinkDetailImg.Click   += btnLinkDetailImg_Click;
                    btnLinkDetailImg.CssClass = "StoreLinkDetailImg";
                    return(btnLinkDetailImg);
                }

                return(null);

            case "SUMMARY":
                Label lblSummary = new Label
                {
                    Text     = string.Format(Localization.GetString("Summary.Text", LocalResourceFile), _product.Summary),
                    CssClass = "StoreProductSummary"
                };
                return(lblSummary);

            case "WEIGHT":
                Label lblWeight = new Label
                {
                    Text     = string.Format(Localization.GetString("WeightText", LocalResourceFile), _product.ProductWeight.ToString(Localization.GetString("WeightFormat", LocalResourceFile), _localFormat)),
                    CssClass = "StoreProductWeight"
                };
                return(lblWeight);

            case "HEIGHT":
                Label lblHeight = new Label
                {
                    Text     = string.Format(Localization.GetString("HeightText", LocalResourceFile), _product.ProductHeight.ToString(Localization.GetString("HeightFormat", LocalResourceFile), _localFormat)),
                    CssClass = "StoreProductHeight"
                };
                return(lblHeight);

            case "LENGTH":
                Label lblLength = new Label
                {
                    Text     = string.Format(Localization.GetString("LengthText", LocalResourceFile), _product.ProductLength.ToString(Localization.GetString("LengthFormat", LocalResourceFile), _localFormat)),
                    CssClass = "StoreProductLength"
                };
                return(lblLength);

            case "WIDTH":
                Label lblWidth = new Label
                {
                    Text     = string.Format(Localization.GetString("WidthText", LocalResourceFile), _product.ProductWidth.ToString(Localization.GetString("WidthFormat", LocalResourceFile), _localFormat)),
                    CssClass = "StoreProductWidth"
                };
                return(lblWidth);

            case "SURFACE":
                Label   lblSurface = new Label();
                decimal dblSurface = _product.ProductLength * _product.ProductWidth;
                lblSurface.Text     = string.Format(Localization.GetString("SurfaceText", LocalResourceFile), dblSurface.ToString(Localization.GetString("SurfaceFormat", LocalResourceFile), _localFormat));
                lblSurface.CssClass = "StoreProductSurface";
                return(lblSurface);

            case "VOLUME":
                Label   lblVolume = new Label();
                decimal dblVolume = _product.ProductHeight * _product.ProductLength * _product.ProductWidth;
                lblVolume.Text     = string.Format(Localization.GetString("VolumeText", LocalResourceFile), dblVolume.ToString(Localization.GetString("VolumeFormat", LocalResourceFile), _localFormat));
                lblVolume.CssClass = "StoreProductVolume";
                return(lblVolume);

            case "DIMENSIONS":
                Label  lblDimensions = new Label();
                string strHeight     = _product.ProductHeight.ToString(Localization.GetString("HeightFormat", LocalResourceFile), _localFormat);
                string strLength     = _product.ProductLength.ToString(Localization.GetString("LengthFormat", LocalResourceFile), _localFormat);
                string strWidth      = _product.ProductWidth.ToString(Localization.GetString("WidthFormat", LocalResourceFile), _localFormat);
                lblDimensions.Text     = string.Format(Localization.GetString("DimensionsText", LocalResourceFile), strHeight, strLength, strWidth);
                lblDimensions.CssClass = "StoreProductDimensions";
                return(lblDimensions);

            case "PRICE":
                Label  lblPrice      = new Label();
                string formatedPrice = string.Format(Localization.GetString("Price", LocalResourceFile), _product.UnitCost.ToString("C", _localFormat));
                if (_product.Featured && DateTime.Now > _product.SaleStartDate && DateTime.Now < _product.SaleEndDate)
                {
                    //Product is on sale...
                    string formatedSalePrice = string.Format(Localization.GetString("Price", LocalResourceFile), _product.SalePrice.ToString("C", _localFormat));
                    lblPrice.Text     = string.Format(Localization.GetString("SpecialOffer", LocalResourceFile), formatedPrice, formatedSalePrice);
                    lblPrice.CssClass = "StoreProductPrice StoreProductSpecialOffer";
                }
                else
                {
                    lblPrice.Text     = formatedPrice;
                    lblPrice.CssClass = "StoreProductPrice";
                }
                return(lblPrice);

            case "VATPRICE":
                if (_showTax)
                {
                    Label   lblVATPrice      = new Label();
                    decimal dblVATPrice      = (_product.UnitCost + (_product.UnitCost * (_defaultTaxRate / 100)));
                    string  formatedVATPrice = string.Format(Localization.GetString("VATPrice", LocalResourceFile), dblVATPrice.ToString("C", _localFormat));
                    if (_product.Featured && DateTime.Now > _product.SaleStartDate && DateTime.Now < _product.SaleEndDate)
                    {
                        //Product is on sale...
                        decimal dblVATSalePrice      = (_product.SalePrice + (_product.SalePrice * (_defaultTaxRate / 100)));
                        string  formatedVATSalePrice = string.Format(Localization.GetString("VATPrice", LocalResourceFile), dblVATSalePrice.ToString("C", _localFormat));
                        lblVATPrice.Text     = string.Format(Localization.GetString("SpecialOffer", LocalResourceFile), formatedVATPrice, formatedVATSalePrice);
                        lblVATPrice.CssClass = "StoreProductVATPrice StoreProductSpecialOffer";
                    }
                    else
                    {
                        lblVATPrice.Text     = formatedVATPrice;
                        lblVATPrice.CssClass = "StoreProductVATPrice";
                    }
                    lblVATPrice.CssClass = "StoreProductVATPrice";
                    return(lblVATPrice);
                }

                return(null);

            case "REGULARPRICE":
                Label lblRegularPrice = new Label
                {
                    Text     = string.Format(Localization.GetString("RegularPrice", LocalResourceFile), _product.RegularPrice.ToString("C", _localFormat)),
                    CssClass = "StoreProductRegularPrice"
                };
                return(lblRegularPrice);

            case "REGULARVATPRICE":
                if (_showTax)
                {
                    Label   lblRegularVATPrice = new Label();
                    decimal dblRegularVATPrice = (_product.RegularPrice + (_product.RegularPrice * (_defaultTaxRate / 100)));
                    lblRegularVATPrice.Text     = string.Format(Localization.GetString("RegularVATPrice", LocalResourceFile), dblRegularVATPrice.ToString("C", _localFormat));
                    lblRegularVATPrice.CssClass = "StoreProductRegularVATPrice";
                    return(lblRegularVATPrice);
                }

                return(null);

            case "PURCHASE":
                // Hide control in this case
                if (StoreSettings.InventoryManagement && StoreSettings.ProductsBehavior == (int)Behavior.HideControls && _product.StockQuantity < 1)
                {
                    return(null);
                }

                LinkButton btnPurchase = new LinkButton
                {
                    Text            = Localization.GetString("Purchase", LocalResourceFile),
                    CommandArgument = _product.ProductID.ToString()
                };
                btnPurchase.Click   += btnPurchase_Click;
                btnPurchase.CssClass = "CommandButton StoreButtonPurchase";
                return(btnPurchase);

            case "PURCHASEIMG":
                // Hide control in this case
                if (StoreSettings.InventoryManagement && StoreSettings.ProductsBehavior == (int)Behavior.HideControls & _product.StockQuantity < 1)
                {
                    return(null);
                }

                ImageButton btnPurchaseImg = new ImageButton
                {
                    ImageUrl        = GetImagePath("PurchaseImg"),
                    ToolTip         = Localization.GetString("Purchase", LocalResourceFile),
                    CommandArgument = _product.ProductID.ToString()
                };
                btnPurchaseImg.Click   += btnPurchaseImg_Click;
                btnPurchaseImg.CssClass = "StoreButtonPurchaseImg";
                return(btnPurchaseImg);

            case "ADDTOCART":
                // Hide control in this case
                if (StoreSettings.InventoryManagement && StoreSettings.ProductsBehavior == (int)Behavior.HideControls & _product.StockQuantity < 1)
                {
                    return(null);
                }

                LinkButton btnAddToCart = new LinkButton
                {
                    Text            = Localization.GetString("AddToCart", LocalResourceFile),
                    CommandArgument = _product.ProductID.ToString()
                };
                btnAddToCart.Click   += btnAddToCart_Click;
                btnAddToCart.CssClass = "CommandButton StoreButtonAddToCart";
                return(btnAddToCart);

            case "ADDTOCARTIMG":
                // Hide control in this case
                if (StoreSettings.InventoryManagement && StoreSettings.ProductsBehavior == (int)Behavior.HideControls & _product.StockQuantity < 1)
                {
                    return(null);
                }

                ImageButton btnAddToCartImg = new ImageButton
                {
                    ImageUrl        = GetImagePath("AddToCartImg"),
                    ToolTip         = Localization.GetString("AddToCart", LocalResourceFile),
                    CommandArgument = _product.ProductID.ToString()
                };
                btnAddToCartImg.Click   += btnAddToCartImg_Click;
                btnAddToCartImg.CssClass = "StoreButtonAddToCartImg";
                return(btnAddToCartImg);

            case "ADDQUANTITY":
                // Hide control in this case
                if (StoreSettings.InventoryManagement && StoreSettings.ProductsBehavior == (int)Behavior.HideControls & _product.StockQuantity < 1)
                {
                    return(null);
                }

                Label          lblQuantity     = new Label();
                LiteralControl litQuantity     = new LiteralControl(Localization.GetString("Quantity", LocalResourceFile));
                TextBox        txtAddToCartQty = new TextBox
                {
                    ID       = "txtQuantity" + _product.ProductID,
                    CssClass = "StoreQuantityTextBox",
                    Text     = "1"
                };
                lblQuantity.Controls.Add(litQuantity);
                lblQuantity.Controls.Add(txtAddToCartQty);
                lblQuantity.CssClass = "StoreAddQuantity";
                return(lblQuantity);

            case "DESCRIPTION":
                Panel pnlDescription = new Panel
                {
                    CssClass = "StoreProductDescription"
                };
                Literal litDescription = new Literal
                {
                    Text = System.Web.HttpUtility.HtmlDecode(_product.Description)
                };
                pnlDescription.Controls.Add(litDescription);
                return(pnlDescription);

            case "LOCALE":
                return(new LiteralControl(System.Threading.Thread.CurrentThread.CurrentCulture.ToString()));

            case "TEMPLATESBASEURL":
                return(new LiteralControl(_templatePath));

            case "IMAGESBASEURL":
                return(new LiteralControl(_imagesPath));

            case "PRODUCTDETAILURL":
                if (_showDetail)
                {
                    StringDictionary urlLink = new StringDictionary
                    {
                        { "ProductID", _product.ProductID.ToString() }
                    };
                    if (StoreSettings.SEOFeature)
                    {
                        urlLink.Add("Product", _product.SEOName);
                    }
                    return(new LiteralControl(_catalogNav.GetNavigationUrl(_detailID, urlLink)));
                }

                return(null);

            case "STOCKQUANTITY":
                if (StoreSettings.InventoryManagement)
                {
                    Label lblStockQuantity = new Label();
                    if (_product.StockQuantity > 0)
                    {
                        lblStockQuantity.Text = string.Format(Localization.GetString("StockQuantity", LocalResourceFile), _product.StockQuantity);
                    }
                    else
                    {
                        switch (StoreSettings.OutOfStock)
                        {
                        case (int)StockMessage.Quantity:
                            lblStockQuantity.Text = string.Format(Localization.GetString("StockQuantity", LocalResourceFile), _product.StockQuantity);
                            break;

                        case (int)StockMessage.Unavailable:
                            lblStockQuantity.Text = Localization.GetString("OOStockUnavailable", LocalResourceFile);
                            break;

                        case (int)StockMessage.Restocking:
                            lblStockQuantity.Text = Localization.GetString("OOStockRestocking", LocalResourceFile);
                            break;
                        }
                    }
                    lblStockQuantity.CssClass = "StoreProductStockQuantity";
                    return(lblStockQuantity);
                }

                return(null);

            case "TELLAFRIEND":
                if (!_inList)
                {
                    HyperLink btnTellAFriend = new HyperLink
                    {
                        Text = Localization.GetString("TellAFriend", LocalResourceFile)
                    };
                    string subject = Localization.GetString("TellAFriendSubject", LocalResourceFile);
                    string body    = Localization.GetString("TellAFriendBody", LocalResourceFile);
                    CatalogTokenReplace tkCatalog = new CatalogTokenReplace();
                    _category.StorePageID   = TabId;
                    tkCatalog.Category      = _category;
                    _product.StorePageID    = TabId;
                    tkCatalog.Product       = _product;
                    tkCatalog.StoreSettings = StoreSettings;
                    subject = tkCatalog.ReplaceCatalogTokens(subject);
                    body    = tkCatalog.ReplaceCatalogTokens(body);
                    btnTellAFriend.NavigateUrl = string.Format(Localization.GetString("TellAFriendHRef", LocalResourceFile), subject, System.Web.HttpUtility.HtmlEncode(System.Web.HttpUtility.UrlPathEncode(body)));
                    btnTellAFriend.CssClass    = "CommandButton StoreButtonTellAFriend";
                    return(btnTellAFriend);
                }

                return(null);

            case "TELLAFRIENDIMG":
                if (!_inList)
                {
                    HyperLink btnTellAFriendImg = new HyperLink
                    {
                        Text = Localization.GetString("TellAFriend", LocalResourceFile)
                    };
                    string subject = Localization.GetString("TellAFriendSubject", LocalResourceFile);
                    string body    = Localization.GetString("TellAFriendBody", LocalResourceFile);
                    CatalogTokenReplace tkCatalog = new CatalogTokenReplace();
                    _category.StorePageID   = TabId;
                    tkCatalog.Category      = _category;
                    _product.StorePageID    = TabId;
                    tkCatalog.Product       = _product;
                    tkCatalog.StoreSettings = StoreSettings;
                    subject = tkCatalog.ReplaceCatalogTokens(subject);
                    body    = tkCatalog.ReplaceCatalogTokens(body);
                    btnTellAFriendImg.NavigateUrl = string.Format(Localization.GetString("TellAFriendHRef", LocalResourceFile), subject, System.Web.HttpUtility.HtmlEncode(System.Web.HttpUtility.UrlPathEncode(body)));
                    btnTellAFriendImg.CssClass    = "CommandButton StoreButtonTellAFriend";
                    HtmlImage imgButton = new HtmlImage
                    {
                        Src = GetImagePath("TellAFriendImg"),
                        Alt = Localization.GetString("TellAFriend", this.LocalResourceFile)
                    };
                    btnTellAFriendImg.Controls.Add(imgButton);
                    return(btnTellAFriendImg);
                }

                return(null);

            default:
                LiteralControl litText = new LiteralControl(tokenName);
                return(litText);
            }
        }
コード例 #45
0
        /// <summary>
        /// Adds SharePoint site collection.
        /// </summary>
        /// <param name="item">Site collection description.</param>
        /// <returns>Created site collection id within metabase.</returns>
        public static int AddSiteCollection(SharePointSiteCollection item)
        {
            string domainName = item.Name;
            // Check account.
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);

            if (accountCheck < 0)
            {
                return(accountCheck);
            }

            // Check package.
            int packageCheck = SecurityContext.CheckPackage(item.PackageId, DemandPackage.IsActive);

            if (packageCheck < 0)
            {
                return(packageCheck);
            }

            // Check quota.
            OrganizationStatistics orgStats = OrganizationController.GetOrganizationStatistics(item.OrganizationId);

            //QuotaValueInfo quota = PackageController.GetPackageQuota(item.PackageId, Quotas.HOSTED_SHAREPOINT_SITES);

            if (orgStats.AllocatedSharePointSiteCollections > -1 &&
                orgStats.CreatedSharePointSiteCollections >= orgStats.AllocatedSharePointSiteCollections)
            {
                return(BusinessErrorCodes.ERROR_SHAREPOINT_RESOURCE_QUOTA_LIMIT);
            }

            // Check if stats resource is available
            int serviceId = PackageController.GetPackageServiceId(item.PackageId, ResourceGroups.HostedSharePoint);

            if (serviceId == 0)
            {
                return(BusinessErrorCodes.ERROR_SHAREPOINT_RESOURCE_UNAVAILABLE);
            }
            StringDictionary hostedSharePointSettings = ServerController.GetServiceSettings(serviceId);
            Uri rootWebApplicationUri = new Uri(hostedSharePointSettings["RootWebApplicationUri"]);

            item.Name = String.Format("{0}://{1}", rootWebApplicationUri.Scheme, item.Name);
            if (rootWebApplicationUri.Port > 0 && rootWebApplicationUri.Port != 80 && rootWebApplicationUri.Port != 443)
            {
                item.PhysicalAddress = String.Format("{0}:{1}", item.Name, rootWebApplicationUri.Port);
            }
            else
            {
                item.PhysicalAddress = item.Name;
            }

            Organization org = OrganizationController.GetOrganization(item.OrganizationId);

            item.MaxSiteStorage = RecalculateMaxSize(org.MaxSharePointStorage, (int)item.MaxSiteStorage);
            item.WarningStorage = item.MaxSiteStorage == -1 ? -1 : Math.Min((int)item.WarningStorage, item.MaxSiteStorage);


            // Check package item with given name already exists.
            if (PackageController.GetPackageItemByName(item.PackageId, item.Name, typeof(SharePointSiteCollection)) != null)
            {
                return(BusinessErrorCodes.ERROR_SHAREPOINT_PACKAGE_ITEM_EXISTS);
            }

            // Log operation.
            TaskManager.StartTask("HOSTEDSHAREPOINT", "ADD_SITE_COLLECTION", item.Name);

            try
            {
                // Create site collection on server.
                HostedSharePointServer hostedSharePointServer = GetHostedSharePointServer(serviceId);

                hostedSharePointServer.CreateSiteCollection(item);
                // Make record in metabase.
                item.ServiceId = serviceId;
                int itemId = PackageController.AddPackageItem(item);

                int dnsServiceId = PackageController.GetPackageServiceId(item.PackageId, ResourceGroups.Dns);
                if (dnsServiceId > 0)
                {
                    DomainInfo domain = ServerController.GetDomain(domainName);
                    if (domain != null)
                    {
                        string website = domain.WebSiteName;

                        if (!String.IsNullOrEmpty(domain.WebSiteName))
                        {
                            DnsRecord[] records = ServerController.GetDnsZoneRecords(domain.DomainId);
                            foreach (DnsRecord record in records)
                            {
                                if (record.RecordType.Equals(DnsRecordType.A) && String.IsNullOrEmpty(record.RecordName))
                                {
                                    ServerController.DeleteDnsZoneRecord(domain.DomainId, String.Empty, DnsRecordType.A, record.RecordData);
                                    break;
                                }
                            }
                        }
                        ServerController.AddDnsZoneRecord(domain.DomainId, String.Empty, DnsRecordType.A, hostedSharePointSettings["RootWebApplicationIpAddress"], 0);
                    }
                }

                TaskManager.ItemId = itemId;
                return(itemId);
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
コード例 #46
0
		public UserCommandLookPlayer(StringDictionary LookupList, byte[] Buffer, int StartIndex = 0)
        {
            stringResources = LookupList;
            ReadFrom(Buffer, StartIndex);
        }
コード例 #47
0
        static async Task CreateSite(string rgName, string appServicePlanName, string siteName, string location)
        {
            // Create/Update the resource group
            var rgCreateResult = await _resourceGroupClient.ResourceGroups.CreateOrUpdateAsync(rgName, new ResourceGroup { Location = location });

            // Create/Update the App Service Plan
            var serverFarmWithRichSku = new ServerFarmWithRichSku
            {
                Location = location,
                Sku = new SkuDescription
                {
                    Name = "F1",
                    Tier = "Free"
                }
            };
            serverFarmWithRichSku = await _websiteClient.ServerFarms.CreateOrUpdateServerFarmAsync(rgName, appServicePlanName, serverFarmWithRichSku);

            // Create/Update the Website
            var site = new Site
            {
                Location = location,
                ServerFarmId = appServicePlanName
            };
            site = await _websiteClient.Sites.CreateOrUpdateSiteAsync(rgName, siteName, site);

            // Create/Update the Website configuration
            var siteConfig = new SiteConfig
            {
                Location = location,
                PhpVersion = "5.6"
            };
            siteConfig = await _websiteClient.Sites.CreateOrUpdateSiteConfigAsync(rgName, siteName, siteConfig);

            // Create/Update some App Settings
            var appSettings = new StringDictionary
            {
                Location = location,
                Properties = new Dictionary<string, string>
                {
                    { "MyFirstKey", "My first value" },
                    { "MySecondKey", "My second value" }
                }
            };
            await _websiteClient.Sites.UpdateSiteAppSettingsAsync(rgName, siteName, appSettings);

            // Create/Update some Connection Strings
            var connStrings = new ConnectionStringDictionary
            {
                Location = location,
                Properties = new Dictionary<string, ConnStringValueTypePair>
                {
                    { "MyFirstConnString", new ConnStringValueTypePair { Value = "My SQL conn string", Type = DatabaseServerType.SQLAzure }},
                    { "MySecondConnString", new ConnStringValueTypePair { Value = "My custom conn string", Type = DatabaseServerType.Custom }}
                }
            };
            await _websiteClient.Sites.UpdateSiteConnectionStringsAsync(rgName, siteName, connStrings);
        }
コード例 #48
0
ファイル: PathRootTable.cs プロジェクト: ikvm/cloudb
 public PathRootTable(DataFile data)
 {
     dictionary = new StringDictionary(data);
 }
コード例 #49
0
ファイル: Response.cs プロジェクト: fangld/EDGolog
 public Response(PlanningParser.ResponseDefineContext context, IReadOnlyDictionary <string, Event> eventDict,
                 StringDictionary assignment) : this(context, eventDict, assignment, Globals.EmptyConstArray)
 {
 }
コード例 #50
0
ファイル: CommandLineParser.cs プロジェクト: roedicker/NArgs
        /// <summary>
        /// Gets the usage for the current configuration
        /// </summary>
        /// <param name="executable">Current executable name</param>
        /// <returns>Usage output for the current configuration</returns>
        internal string GetUsage(string executable)
        {
            StringBuilder    Result                   = new StringBuilder();
            List <Parameter> lstParameters            = new List <Parameter>();
            StringCollection colParametersSyntaxUsage = new StringCollection();
            StringDictionary dicOptions               = new StringDictionary();
            StringCollection colOptionsSyntaxUsage    = new StringCollection();
            int iMaxParameterNameLength               = 0;
            int iMaxOptionCompleteNameLength          = 0;

            foreach (System.Reflection.PropertyInfo oInfo in this.PropertyService.GetProperties())
            {
                if (oInfo.GetCustomAttributes(typeof(Parameter), true).FirstOrDefault() is Parameter oParameter)
                {
                    lstParameters.Add(oParameter);

                    if (oParameter.Name?.Length > iMaxParameterNameLength)
                    {
                        iMaxParameterNameLength = (int)oParameter.Name.Length;
                    }
                }
                else
                {
                    if (oInfo.GetCustomAttributes(typeof(Option), true).FirstOrDefault() is Option oOption)
                    {
                        StringCollection colOptionNames = new StringCollection();

                        if (!String.IsNullOrWhiteSpace(oOption.Name))
                        {
                            colOptionNames.AddDistinct($"{this.Tokenizer.ArgumentOptionDefaultNameIndicator}{oOption.Name}");
                        }

                        if (!String.IsNullOrWhiteSpace(oOption.AlternativeName))
                        {
                            colOptionNames.AddDistinct($"{this.Tokenizer.ArgumentOptionDefaultNameIndicator}{oOption.AlternativeName}");
                        }

                        if (!String.IsNullOrWhiteSpace(oOption.LongName))
                        {
                            colOptionNames.AddDistinct($"{this.Tokenizer.ArgumentOptionLongNameIndicator}{oOption.LongName}");
                        }

                        string sOptionCompleteName = colOptionNames.ToString(" | ");

                        if (oOption.Required)
                        {
                            if (oInfo.PropertyType.FullName == PropertyTypeFullName.Boolean)
                            {
                                colOptionsSyntaxUsage.Add($"{sOptionCompleteName}");
                            }
                            else
                            {
                                colOptionsSyntaxUsage.Add($"{sOptionCompleteName} <{oOption.UsageTypeDisplayName}>");
                            }
                        }
                        else
                        {
                            if (oInfo.PropertyType.FullName == PropertyTypeFullName.Boolean)
                            {
                                colOptionsSyntaxUsage.Add($"[{sOptionCompleteName}]");
                            }
                            else
                            {
                                colOptionsSyntaxUsage.Add($"[{sOptionCompleteName} <{oOption.UsageTypeDisplayName}>]");
                            }
                        }

                        dicOptions.Add(sOptionCompleteName, String.IsNullOrWhiteSpace(oOption.Description) ? Resources.NotApplicableValue : oOption.Description);

                        if (sOptionCompleteName.Length > iMaxOptionCompleteNameLength)
                        {
                            iMaxOptionCompleteNameLength = sOptionCompleteName.Length;
                        }
                    }
                }
            }

            // sort parameters by their ordinal numbers
            lstParameters.Sort((l, r) => l.OrdinalNumber.CompareTo(r.OrdinalNumber));

            Result.AppendLine($"{Resources.SyntaxCapitalizedName}:");
            Result.Append($"  {executable} ");

            if (lstParameters.Count > 0)
            {
                foreach (Parameter oParameter in lstParameters)
                {
                    Result.AppendFormat(CultureInfo.InvariantCulture, "<{0}> ", String.IsNullOrWhiteSpace(oParameter.Name) ? Resources.NotApplicableValue : oParameter.Name);
                }
            }

            StringBuilder sbIndention = new StringBuilder();

            for (int i = 0; i < executable.Length + 3; i++)
            {
                sbIndention.Append(' ');
            }

            Result.Append($"{colOptionsSyntaxUsage.ToString($"{Environment.NewLine}{sbIndention}")}{Environment.NewLine}");

            if (lstParameters.Count > 0)
            {
                Result.AppendLine($"{Environment.NewLine}{Resources.ParametersCapitalizedName}:");

                foreach (Parameter oParameter in lstParameters)
                {
                    Result.AppendFormat(CultureInfo.InvariantCulture, "  {0, " + Convert.ToString(-iMaxParameterNameLength, CultureInfo.InvariantCulture) + "}     {1}{2}", String.IsNullOrWhiteSpace(oParameter.Name) ? "n/a" : oParameter.Name, String.IsNullOrWhiteSpace(oParameter.Description) ? "n/a" : oParameter.Description, Environment.NewLine);
                }
            }

            if (dicOptions.Count > 0)
            {
                Result.AppendLine($"{Environment.NewLine}{Resources.OptionsCapitalizedName}:");

                foreach (string sKey in dicOptions.Keys)
                {
                    Result.AppendFormat(CultureInfo.InvariantCulture, "  {0, " + Convert.ToString(-iMaxOptionCompleteNameLength, CultureInfo.InvariantCulture) + "}     {1}{2}", sKey, dicOptions[sKey], Environment.NewLine);
                }
            }

            return(Result.ToString());
        }
コード例 #51
0
ファイル: co8761remove_str.cs プロジェクト: ArildF/masters
 public virtual bool runTest()
 {
     Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver: " + s_strDtTmVer);
     int iCountErrors = 0;
     int iCountTestcases = 0;
     IntlStrings intl;
     String strLoc = "Loc_000oo";
     StringDictionary sd; 
     string [] values = 
     {
         "",
         " ",
         "a",
         "aa",
         "text",
         "     spaces",
         "1",
         "$%^#",
         "2222222222222222222222222",
         System.DateTime.Today.ToString(),
         Int32.MaxValue.ToString()
     };
     string [] keys = 
     {
         "zero",
         "one",
         " ",
         "",
         "aa",
         "1",
         System.DateTime.Today.ToString(),
         "$%^#",
         Int32.MaxValue.ToString(),
         "     spaces",
         "2222222222222222222222222"
     };
     int cnt = 0;
     try
     {
         intl = new IntlStrings(); 
         Console.WriteLine("--- create dictionary ---");
         strLoc = "Loc_001oo"; 
         iCountTestcases++;
         sd = new StringDictionary();
         Console.WriteLine("1. Remove() from empty dictionary");
         iCountTestcases++;
         if (sd.Count > 0)
             sd.Clear();
         for (int i = 0; i < keys.Length; i++) 
         {
             sd.Remove(keys[0]);
         }
         Console.WriteLine("2. Remove() on filled dictionary");  
         strLoc = "Loc_002oo"; 
         int len = values.Length;
         iCountTestcases++;
         sd.Clear();
         for (int i = 0; i < len; i++) 
         {
             sd.Add(keys[i], values[i]);
         }
         if (sd.Count != len) 
         {
             iCountErrors++;
             Console.WriteLine("Err_0002a, count is {0} instead of {1}", sd.Count, len);
         } 
         for (int i = 0; i < len; i++) 
         {
             iCountTestcases++;
             cnt = sd.Count;
             sd.Remove(keys[i]);
             if (sd.Count != cnt - 1) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_0002b_{0}, didn't remove element with {0} key", i);
             } 
             iCountTestcases++;
             if ( sd.ContainsValue(values[i]) ) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_0002c_{0}, removed wrong value", i);
             } 
             iCountTestcases++;
             if ( sd.ContainsKey(keys[i]) ) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_0002d_{0}, removed wrong value", i);
             } 
         }
         Console.WriteLine("3. Remove() on dictionary with duplicate values ");
         strLoc = "Loc_003oo"; 
         iCountTestcases++;
         sd.Clear();
         string intlStr = intl.GetString(MAX_LEN, true, true, true);
         sd.Add("keykey1", intlStr);        
         for (int i = 0; i < len; i++) 
         {
             sd.Add(keys[i], values[i]);
         }
         sd.Add("keykey2", intlStr);        
         if (sd.Count != len+2) 
         {
             iCountErrors++;
             Console.WriteLine("Err_0003a, count is {0} instead of {1}", sd.Count, len+2);
         } 
         iCountTestcases++;
         sd.Remove("keykey2");
         if (!sd.ContainsValue(intlStr)) 
         {
             iCountErrors++;
             Console.WriteLine("Err_0003b, removed both duplicates");
         }
         if ( sd.ContainsKey("keykey2") ) 
         {
             iCountErrors++;
             Console.WriteLine("Err_0003c, removed not given instance");
         }
         if (! sd.ContainsKey("keykey1") ) 
         {
             iCountErrors++;
             Console.WriteLine("Err_0003d, removed wrong instance");
         }
         Console.WriteLine("4. Remove() from dictionary with intl strings");
         strLoc = "Loc_004oo"; 
         string [] intlValues = new string [len*2];
         for (int i = 0; i < len*2; i++) 
         {
             string val = intl.GetString(MAX_LEN, true, true, true);
             while (Array.IndexOf(intlValues, val) != -1 )
                 val = intl.GetString(MAX_LEN, true, true, true);
             intlValues[i] = val;
         } 
         sd.Clear();
         for (int i = 0; i < len; i++) 
         {
             sd.Add(intlValues[i+len], intlValues[i]);
         }
         if (sd.Count != len) 
         {
             iCountErrors++;
             Console.WriteLine("Err_0004a, count is {0} instead of {1}", sd.Count, len);
         }
         for (int i = 0; i < len; i++) 
         {
             iCountTestcases++;
             cnt = sd.Count;
             sd.Remove(intlValues[i+len]);
             if (sd.Count != cnt - 1) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_0004b_{0}, didn't remove element with {0} key", i+len);
             } 
             iCountTestcases++;
             if ( sd.ContainsValue(intlValues[i]) ) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_0004c_{0}, removed wrong value", i);
             } 
             iCountTestcases++;
             if ( sd.ContainsKey(intlValues[i+len]) ) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_0004d_{0}, removed wrong key", i);
             } 
         }
         Console.WriteLine("5. Case sensitivity");
         strLoc = "Loc_005oo"; 
         iCountTestcases++;
         sd.Clear();
         string [] intlValuesUpper = new string [len];
         for (int i = 0; i < len * 2; i++) 
         {
             intlValues[i] = intlValues[i].ToLower();
         }
         for (int i = 0; i < len; i++) 
         {
             intlValuesUpper[i] = intlValues[i+len].ToUpper();
         } 
         sd.Clear();
         Console.WriteLine(" ... add Lowercased ...");
         for (int i = 0; i < len; i++) 
         {
             sd.Add(intlValues[i+len], intlValues[i]);     
         }
         if (sd.Count != len) 
         {
             iCountErrors++;
             Console.WriteLine("Err_0005a, count is {0} instead of {1}", sd.Count, len);
         } 
         Console.WriteLine(" ... remove Uppercased ..."); 
         for (int i = 0; i < len; i++) 
         {
             iCountTestcases++;
             cnt = sd.Count;
             sd.Remove(intlValuesUpper[i]);
             if (sd.Count != cnt - 1) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_0005b_{0}, didn't remove element with {0} lower key", i+len);
             } 
             iCountTestcases++;
             if ( sd.ContainsValue(intlValues[i]) ) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_0005c_{0}, removed wrong value", i);
             } 
             iCountTestcases++;
             if ( sd.ContainsKey(intlValuesUpper[i]) ) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_0005d_{0}, removed wrong key", i);
             } 
         }
         Console.WriteLine("6. Remove(null)");
         strLoc = "Loc_006oo"; 
         iCountTestcases++;
         try 
         {
             sd.Remove(null);
             iCountErrors++;
             Console.WriteLine("Err_0006a, no exception");
         }
         catch (NullReferenceException ex) 
         {
             Console.WriteLine("  expected exception: " + ex.Message);
         }
         catch (Exception e) 
         {
             iCountErrors++;
             Console.WriteLine("Err_0006b, unexpected exception: {0}", e.ToString());
         }
     } 
     catch (Exception exc_general ) 
     {
         ++iCountErrors;
         Console.WriteLine (s_strTFAbbrev + " : Error Err_general!  strLoc=="+ strLoc +", exc_general==\n"+exc_general.ToString());
     }
     if ( iCountErrors == 0 )
     {
         Console.WriteLine( "Pass.   "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases);
         return true;
     }
     else
     {
         Console.WriteLine("Fail!   "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums );
         return false;
     }
 }
コード例 #52
0
        public ArgumentParser(string[] args)
        {
            arguments = new StringDictionary();

            // Don't break on colons (:) as they are used in IPv6 addresses
            Regex  splitter  = new Regex(@"^-{1,2}|^/|=", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            Regex  remover   = new Regex(@"^['""]?(.*?)['""]?$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            string parameter = null;

            string[] parts;

            // Valid parameters forms:
            // {-,/,--}param{ ,=,:}((",')value(",'))
            // Examples: -param1 value1 --param2 /param3:"Test-:-work" /param4=happy -param5 '--=nice=--'
            foreach (string arg in args)
            {
                // Look for new parameters (-,/ or --) and a possible enclosed value (=,:)
                parts = splitter.Split(arg, 3);
                switch (parts.Length)
                {
                // Found a value (for the last parameter found (space separator))
                case 1:
                    if (parameter != null)
                    {
                        if (!arguments.ContainsKey(parameter))
                        {
                            parts[0] = remover.Replace(parts[0], "$1");
                            arguments.Add(parameter, parts[0]);
                        }
                        parameter = null;
                    }
                    // else Error: no parameter waiting for a value (skipped)
                    break;

                // Found just a parameter
                case 2:
                    // The last parameter is still waiting. With no value, set it to true.
                    if (parameter != null)
                    {
                        if (!arguments.ContainsKey(parameter))
                        {
                            arguments.Add(parameter, "true");
                        }
                    }
                    parameter = parts[1];
                    break;

                // parameter with enclosed value
                case 3:
                    // The last parameter is still waiting. With no value, set it to true.
                    if (parameter != null)
                    {
                        if (!arguments.ContainsKey(parameter))
                        {
                            arguments.Add(parameter, "true");
                        }
                    }
                    parameter = parts[1];
                    // Remove possible enclosing characters (",')
                    if (!arguments.ContainsKey(parameter))
                    {
                        parts[2] = remover.Replace(parts[2], "$1");
                        arguments.Add(parameter, parts[2]);
                    }
                    parameter = null;
                    break;
                }
            }
            // In case a parameter is still waiting
            if (parameter != null)
            {
                if (!arguments.ContainsKey(parameter))
                {
                    arguments.Add(parameter, "true");
                }
            }
        }
コード例 #53
0
    public void SaveSettings(StringDictionary settings)
    {
        // save engines
        ES.Services.HeliconZoo.SetEngines(PanelRequest.ServiceId, new List<HeliconZooEngine>(GetEngines().Values).ToArray());

        // save switcher
        ES.Services.HeliconZoo.SwithEnginesEnabled(PanelRequest.ServiceId, !QuotasEnabled.Checked);

        ES.Services.HeliconZoo.SetWebCosoleEnabled(PanelRequest.ServiceId, WebCosoleEnabled.Checked);
    }
コード例 #54
0
        private void ExportAllData()
        {
            using (var stream = TempStream.Create())
            {
                var contactDao     = _daoFactory.GetContactDao();
                var contactInfoDao = _daoFactory.GetContactInfoDao();
                var dealDao        = _daoFactory.GetDealDao();
                var casesDao       = _daoFactory.GetCasesDao();
                var taskDao        = _daoFactory.GetTaskDao();
                var historyDao     = _daoFactory.GetRelationshipEventDao();
                var invoiceItemDao = _daoFactory.GetInvoiceItemDao();

                _totalCount += contactDao.GetAllContactsCount();
                _totalCount += dealDao.GetDealsCount();
                _totalCount += casesDao.GetCasesCount();
                _totalCount += taskDao.GetAllTasksCount();
                _totalCount += historyDao.GetAllItemsCount();
                _totalCount += invoiceItemDao.GetInvoiceItemsCount();

                using (var zipStream = new ZipOutputStream(stream, true))
                {
                    zipStream.PutNextEntry("contacts.csv");
                    var contactData  = contactDao.GetAllContacts();
                    var contactInfos = new StringDictionary();
                    contactInfoDao.GetAll()
                    .ForEach(item =>
                    {
                        var contactInfoKey = String.Format("{0}_{1}_{2}", item.ContactID, (int)item.InfoType, item.Category);
                        if (contactInfos.ContainsKey(contactInfoKey))
                        {
                            contactInfos[contactInfoKey] += "," + item.Data;
                        }
                        else
                        {
                            contactInfos.Add(contactInfoKey, item.Data);
                        }
                    });

                    var zipEntryData = new MemoryStream(Encoding.UTF8.GetBytes(ExportContactsToCSV(contactData, contactInfos)));
                    zipEntryData.StreamCopyTo(zipStream);

                    zipStream.PutNextEntry("oppotunities.csv");
                    var dealData = dealDao.GetAllDeals();
                    zipEntryData = new MemoryStream(Encoding.UTF8.GetBytes(ExportDealsToCSV(dealData)));
                    zipEntryData.StreamCopyTo(zipStream);

                    zipStream.PutNextEntry("cases.csv");
                    var casesData = casesDao.GetAllCases();
                    zipEntryData = new MemoryStream(Encoding.UTF8.GetBytes(ExportCasesToCSV(casesData)));
                    zipEntryData.StreamCopyTo(zipStream);

                    zipStream.PutNextEntry("tasks.csv");
                    var taskData = taskDao.GetAllTasks();
                    zipEntryData = new MemoryStream(Encoding.UTF8.GetBytes(ExportTasksToCSV(taskData)));
                    zipEntryData.StreamCopyTo(zipStream);

                    zipStream.PutNextEntry("history.csv");
                    var historyData = historyDao.GetAllItems();
                    zipEntryData = new MemoryStream(Encoding.UTF8.GetBytes(ExportHistoryToCSV(historyData)));
                    zipEntryData.StreamCopyTo(zipStream);

                    zipStream.PutNextEntry("products_services.csv");
                    var invoiceItemData = invoiceItemDao.GetAll();
                    zipEntryData = new MemoryStream(Encoding.UTF8.GetBytes(ExportInvoiceItemsToCSV(invoiceItemData)));
                    zipEntryData.StreamCopyTo(zipStream);

                    zipStream.Flush();
                    zipStream.Close();

                    stream.Position = 0;
                }

                var assignedURI = _dataStore.SavePrivate(String.Empty, "exportdata.zip", stream, DateTime.Now.AddDays(1));
                Status = assignedURI;
                _notifyClient.SendAboutExportCompleted(_author.ID, assignedURI);
                Complete();
            }
        }
コード例 #55
0
ファイル: ApiTest.cs プロジェクト: iitr-ankur/CloudinaryMono
        public void TestImageTag()
        {
            Transformation transformation = new Transformation().Width(100).Height(101).Crop("crop");

            StringDictionary dict = new StringDictionary();
            dict["alt"] = "my image";

            String result = api.UrlImgUp.Transform(transformation).BuildImageTag("test", dict);
            Assert.AreEqual("<img src='http://res.cloudinary.com/testcloud/image/upload/c_crop,h_101,w_100/test' alt='my image' width='100' height='101'/>", result);
        }
コード例 #56
0
        private void ExportPartData()
        {
            _totalCount = _externalData.Count;

            if (_totalCount == 0)
            {
                throw new ArgumentException(CRMErrorsResource.ExportToCSVDataEmpty);
            }

            if (_externalData is List <Contact> )
            {
                var contactInfoDao = _daoFactory.GetContactInfoDao();

                var contacts = (List <Contact>)_externalData;

                var contactInfos = new StringDictionary();

                contactInfoDao.GetAll(contacts.Select(item => item.ID).ToArray())
                .ForEach(item =>
                {
                    var contactInfoKey = String.Format("{0}_{1}_{2}", item.ContactID,
                                                       (int)item.InfoType,
                                                       item.Category);

                    if (contactInfos.ContainsKey(contactInfoKey))
                    {
                        contactInfos[contactInfoKey] += "," + item.Data;
                    }
                    else
                    {
                        contactInfos.Add(contactInfoKey, item.Data);
                    }
                });

                Status = ExportContactsToCSV(contacts, contactInfos);
            }
            else if (_externalData is List <Deal> )
            {
                Status = ExportDealsToCSV((List <Deal>)_externalData);
            }
            else if (_externalData is List <ASC.CRM.Core.Entities.Cases> )
            {
                Status = ExportCasesToCSV((List <ASC.CRM.Core.Entities.Cases>)_externalData);
            }
            else if (_externalData is List <RelationshipEvent> )
            {
                Status = ExportHistoryToCSV((List <RelationshipEvent>)_externalData);
            }
            else if (_externalData is List <Task> )
            {
                Status = ExportTasksToCSV((List <Task>)_externalData);
            }
            else if (_externalData is List <InvoiceItem> )
            {
                Status = ExportInvoiceItemsToCSV((List <InvoiceItem>)_externalData);
            }
            else
            {
                throw new ArgumentException();
            }

            Complete();
        }
コード例 #57
0
ファイル: widget.ascx.cs プロジェクト: rajgit31/RajBlog
    private string RenderComments(List<Comment> comments, StringDictionary settings)
    {
        if (comments.Count == 0)
        {
            //HttpRuntime.Cache.Insert("widget_recentcomments", "<p>" + Resources.labels.none + "</p>");
            return "<p>" + Resources.labels.none + "</p>";
        }

        HtmlGenericControl ul = new HtmlGenericControl("ul");
        ul.Attributes.Add("class", "recentComments");
        ul.ID = "recentComments";

        foreach (Comment comment in comments)
        {
            if (comment.IsApproved)
            {
                HtmlGenericControl li = new HtmlGenericControl("li");

                // The post title
                HtmlAnchor title = new HtmlAnchor();
                title.HRef = comment.Parent.RelativeLink.ToString();
                title.InnerText = comment.Parent.Title;
                title.Attributes.Add("class", "postTitle");
                li.Controls.Add(title);

                // The comment count on the post
                LiteralControl count = new LiteralControl(" (" + ((Post)comment.Parent).ApprovedComments.Count + ")<br />");
                li.Controls.Add(count);

                // The author
                if (comment.Website != null)
                {
                    HtmlAnchor author = new HtmlAnchor();
                    author.Attributes.Add("rel", "nofollow");
                    author.HRef = comment.Website.ToString();
                    author.InnerHtml = comment.Author;
                    li.Controls.Add(author);

                    LiteralControl wrote = new LiteralControl(" " + Resources.labels.wrote + ": ");
                    li.Controls.Add(wrote);
                }
                else
                {
                    LiteralControl author = new LiteralControl(comment.Author + " " + Resources.labels.wrote + ": ");
                    li.Controls.Add(author);
                }

                // The comment body
                string commentBody = Regex.Replace(comment.Content, @"\[(.*?)\]", "");
                int bodyLength = Math.Min(commentBody.Length, 50);

                commentBody = commentBody.Substring(0, bodyLength);
                if (commentBody.Length > 0)
                {
                    if (commentBody[commentBody.Length - 1] == '&')
                    {
                        commentBody = commentBody.Substring(0, commentBody.Length - 1);
                    }
                }
                commentBody += comment.Content.Length <= 50 ? " " : "... ";
                LiteralControl body = new LiteralControl(commentBody);
                li.Controls.Add(body);

                // The comment link
                HtmlAnchor link = new HtmlAnchor();
                link.HRef = comment.Parent.RelativeLink + "#id_" + comment.Id;
                link.InnerHtml = "[" + Resources.labels.more + "]";
                link.Attributes.Add("class", "moreLink");
                li.Controls.Add(link);

                ul.Controls.Add(li);
            }
        }

        StringWriter sw = new StringWriter();
        ul.RenderControl(new HtmlTextWriter(sw));

        string ahref = "<a href=\"{0}syndication.axd?comments=true\">Comment RSS <img src=\"{0}pics/rssButton.gif\" alt=\"\" /></a>";
        string rss = string.Format(ahref, Utils.RelativeWebRoot);
        sw.Write(rss);
        return sw.ToString();
        //HttpRuntime.Cache.Insert("widget_recentcomments", sw.ToString());
    }
コード例 #58
0
        private String ExportContactsToCSV(IEnumerable <Contact> contacts, StringDictionary contactInfos)
        {
            var listItemDao    = _daoFactory.GetListItemDao();
            var tagDao         = _daoFactory.GetTagDao();
            var customFieldDao = _daoFactory.GetCustomFieldDao();
            var contactDao     = _daoFactory.GetContactDao();

            var dataTable = new DataTable();

            dataTable.Columns.AddRange(new[]
            {
                new DataColumn
                {
                    Caption    = CRMCommonResource.TypeCompanyOrPerson,
                    ColumnName = "company/person"
                },
                new DataColumn
                {
                    Caption    = CRMContactResource.FirstName,
                    ColumnName = "firstname"
                },
                new DataColumn
                {
                    Caption    = CRMContactResource.LastName,
                    ColumnName = "lastname"
                },
                new DataColumn
                {
                    Caption    = CRMContactResource.CompanyName,
                    ColumnName = "companyname"
                },
                new DataColumn
                {
                    Caption    = CRMContactResource.JobTitle,
                    ColumnName = "jobtitle"
                },
                new DataColumn
                {
                    Caption    = CRMContactResource.About,
                    ColumnName = "about"
                },
                new DataColumn
                {
                    Caption    = CRMContactResource.ContactStage,
                    ColumnName = "contact_stage"
                },
                new DataColumn
                {
                    Caption    = CRMContactResource.ContactType,
                    ColumnName = "contact_type"
                },
                new DataColumn
                {
                    Caption    = CRMContactResource.ContactTagList,
                    ColumnName = "contact_tag_list"
                }
            });

            foreach (ContactInfoType infoTypeEnum in Enum.GetValues(typeof(ContactInfoType)))
            {
                foreach (Enum categoryEnum in Enum.GetValues(ContactInfo.GetCategory(infoTypeEnum)))
                {
                    var localTitle = String.Format("{1} ({0})", categoryEnum.ToLocalizedString().ToLower(), infoTypeEnum.ToLocalizedString());

                    if (infoTypeEnum == ContactInfoType.Address)
                    {
                        dataTable.Columns.AddRange((from AddressPart addressPartEnum in Enum.GetValues(typeof(AddressPart))
                                                    select new DataColumn
                        {
                            Caption = String.Format(localTitle + " {0}", addressPartEnum.ToLocalizedString().ToLower()),
                            ColumnName = String.Format("contactInfo_{0}_{1}_{2}", (int)infoTypeEnum, categoryEnum, (int)addressPartEnum)
                        }).ToArray());
                    }

                    else
                    {
                        dataTable.Columns.Add(new DataColumn
                        {
                            Caption    = localTitle,
                            ColumnName = String.Format("contactInfo_{0}_{1}", (int)infoTypeEnum, categoryEnum)
                        });
                    }
                }
            }

            var fieldsDescription = customFieldDao.GetFieldsDescription(EntityType.Company);

            customFieldDao.GetFieldsDescription(EntityType.Person).ForEach(item =>
            {
                var alreadyContains = fieldsDescription.Any(field => field.ID == item.ID);

                if (!alreadyContains)
                {
                    fieldsDescription.Add(item);
                }
            });

            fieldsDescription.ForEach(
                item =>
            {
                if (item.FieldType == CustomFieldType.Heading)
                {
                    return;
                }

                dataTable.Columns.Add(
                    new DataColumn
                {
                    Caption    = item.Label,
                    ColumnName = "customField_" + item.ID
                }
                    );
            });

            var customFieldEntity = new Dictionary <int, List <CustomField> >();

            var entityFields = customFieldDao.GetEnityFields(EntityType.Company, 0, false);

            customFieldDao.GetEnityFields(EntityType.Person, 0, false).ForEach(item =>
            {
                var alreadyContains = entityFields.Any(field => field.ID == item.ID && field.EntityID == item.EntityID);

                if (!alreadyContains)
                {
                    entityFields.Add(item);
                }
            });

            entityFields.ForEach(
                item =>
            {
                if (!customFieldEntity.ContainsKey(item.EntityID))
                {
                    customFieldEntity.Add(item.EntityID, new List <CustomField> {
                        item
                    });
                }
                else
                {
                    customFieldEntity[item.EntityID].Add(item);
                }
            });

            var tags = tagDao.GetEntitiesTags(EntityType.Contact);

            foreach (var contact in contacts)
            {
                Percentage += 1.0 * 100 / _totalCount;

                var isCompany = contact is Company;

                var compPersType = (isCompany) ? CRMContactResource.Company : CRMContactResource.Person;

                var contactTags = String.Empty;

                if (tags.ContainsKey(contact.ID))
                {
                    contactTags = String.Join(",", tags[contact.ID].ToArray());
                }

                String firstName;
                String lastName;

                String companyName;
                String title;

                if (contact is Company)
                {
                    firstName   = String.Empty;
                    lastName    = String.Empty;
                    title       = String.Empty;
                    companyName = ((Company)contact).CompanyName;
                }
                else
                {
                    var people = (Person)contact;

                    firstName = people.FirstName;
                    lastName  = people.LastName;
                    title     = people.JobTitle;

                    companyName = String.Empty;

                    if (people.CompanyID > 0)
                    {
                        var personCompany = contacts.SingleOrDefault(item => item.ID == people.CompanyID);

                        if (personCompany == null)
                        {
                            personCompany = contactDao.GetByID(people.CompanyID);
                        }

                        if (personCompany != null)
                        {
                            companyName = personCompany.GetTitle();
                        }
                    }
                }

                var contactStatus = String.Empty;

                if (contact.StatusID > 0)
                {
                    var listItem = listItemDao.GetByID(contact.StatusID);

                    if (listItem != null)
                    {
                        contactStatus = listItem.Title;
                    }
                }

                var contactType = String.Empty;

                if (contact.ContactTypeID > 0)
                {
                    var listItem = listItemDao.GetByID(contact.ContactTypeID);

                    if (listItem != null)
                    {
                        contactType = listItem.Title;
                    }
                }

                var dataRowItems = new List <String>
                {
                    compPersType,
                    firstName,
                    lastName,
                    companyName,
                    title,
                    contact.About,
                    contactStatus,
                    contactType,
                    contactTags
                };

                foreach (ContactInfoType infoTypeEnum in Enum.GetValues(typeof(ContactInfoType)))
                {
                    foreach (Enum categoryEnum in Enum.GetValues(ContactInfo.GetCategory(infoTypeEnum)))
                    {
                        var contactInfoKey = String.Format("{0}_{1}_{2}", contact.ID,
                                                           (int)infoTypeEnum,
                                                           Convert.ToInt32(categoryEnum));

                        var columnValue = "";

                        if (contactInfos.ContainsKey(contactInfoKey))
                        {
                            columnValue = contactInfos[contactInfoKey];
                        }

                        if (infoTypeEnum == ContactInfoType.Address)
                        {
                            if (!String.IsNullOrEmpty(columnValue))
                            {
                                var addresses = JArray.Parse(String.Concat("[", columnValue, "]"));

                                dataRowItems.AddRange((from AddressPart addressPartEnum in Enum.GetValues(typeof(AddressPart))
                                                       select String.Join(",", addresses.Select(item => (String)item.SelectToken(addressPartEnum.ToString().ToLower())).ToArray())).ToArray());
                            }
                            else
                            {
                                dataRowItems.AddRange(new[] { "", "", "", "", "" });
                            }
                        }
                        else
                        {
                            dataRowItems.Add(columnValue);
                        }
                    }
                }

                var dataRow = dataTable.Rows.Add(dataRowItems.ToArray());

                if (customFieldEntity.ContainsKey(contact.ID))
                {
                    customFieldEntity[contact.ID].ForEach(item => dataRow["customField_" + item.ID] = item.Value);
                }
            }

            return(DataTableToCSV(dataTable));
        }
コード例 #59
0
 public virtual bool runTest()
 {
     Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver: " + s_strDtTmVer);
     int iCountErrors = 0;
     int iCountTestcases = 0;
     IntlStrings intl;
     String strLoc = "Loc_000oo";
     StringDictionary sd; 
     string [] values = 
     {
         "",
         " ",
         "a",
         "aa",
         "text",
         "     spaces",
         "1",
         "$%^#",
         "2222222222222222222222222",
         System.DateTime.Today.ToString(),
         Int32.MaxValue.ToString()
     };
     string [] keys = 
     {
         "zero",
         "one",
         " ",
         "",
         "aa",
         "1",
         System.DateTime.Today.ToString(),
         "$%^#",
         Int32.MaxValue.ToString(),
         "     spaces",
         "2222222222222222222222222"
     };
     string itm;         
     try
     {
         intl = new IntlStrings(); 
         Console.WriteLine("--- create dictionary ---");
         strLoc = "Loc_001oo"; 
         iCountTestcases++;
         sd = new StringDictionary();
         Console.WriteLine("1. set Item on empty dictionary");
         iCountTestcases++;
         for (int i = 0; i < keys.Length; i++) 
         {
             if (sd.Count > 0)
                 sd.Clear();
             sd[keys[i]] = values[i];
             if (sd.Count != 1) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_0001a_{0}, didn't add item with {0} key", i);
             }
             if (String.Compare(sd[keys[i]], values[i], false) != 0) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_0001b_{0}, added wrong value", i);
             }
         }
         Console.WriteLine("2. set Item on filled dictionary");  
         strLoc = "Loc_002oo"; 
         int len = values.Length;
         iCountTestcases++;
         sd.Clear();
         for (int i = 0; i < len; i++) 
         {
             sd.Add(keys[i], values[i]);
         }
         if (sd.Count != len) 
         {
             iCountErrors++;
             Console.WriteLine("Err_0002a, count is {0} instead of {1}", sd.Count, len);
         } 
         for (int i = 0; i < len; i++) 
         {
             iCountTestcases++;
             itm = "item" + i;
             sd[keys[i]] = itm;
             if (String.Compare(sd[keys[i]], itm, false) != 0) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_0002b_{0}, returned {1} instead of {2}", i, sd[keys[i]], itm);
             } 
         }
         Console.WriteLine("3. set Item on dictionary with duplicate values ");
         strLoc = "Loc_003oo"; 
         iCountTestcases++;
         sd.Clear();
         string intlStr = intl.GetString(MAX_LEN, true, true, true);
         string intlStr1 = intl.GetString(MAX_LEN, true, true, true);
         sd.Add("keykey1", intlStr);        
         for (int i = 0; i < len; i++) 
         {
             sd.Add(keys[i], values[i]);
         }
         sd.Add("keykey2", intlStr);        
         if (sd.Count != len+2) 
         {
             iCountErrors++;
             Console.WriteLine("Err_0003a, count is {0} instead of {1}", sd.Count, len+2);
         } 
         iCountTestcases++;
         sd["keykey1"] = intlStr1;
         if (String.Compare(sd["keykey1"], intlStr1, false) != 0) 
         {
             iCountErrors++;
             Console.WriteLine("Err_0003b, returned {1} instead of {2}", sd["keykey1"],intlStr1);
         } 
         iCountTestcases++;
         sd["keykey2"] = intlStr1;
         if (String.Compare(sd["keykey2"], intlStr1, false) != 0) 
         {
             iCountErrors++;
             Console.WriteLine("Err_0003c, returned {1} instead of {2}", sd["keykey2"],intlStr1);
         } 
         Console.WriteLine("4. set Item on dictionary with intl strings");
         strLoc = "Loc_004oo"; 
         string [] intlValues = new string [len*2];
         string [] intlSets = new string [len];
         for (int i = 0; i < len*2; i++) 
         {
             string val = intl.GetString(MAX_LEN, true, true, true);
             while (Array.IndexOf(intlValues, val) != -1 )
                 val = intl.GetString(MAX_LEN, true, true, true);
             intlValues[i] = val;
         } 
         for (int i = 0; i < len; i++) 
         {
             intlSets[i] = intl.GetString(MAX_LEN, true, true, true);
         } 
         sd.Clear();
         for (int i = 0; i < len; i++) 
         {
             sd.Add(intlValues[i+len], intlValues[i]);
         }
         if (sd.Count != len) 
         {
             iCountErrors++;
             Console.WriteLine("Err_0004a, count is {0} instead of {1}", sd.Count, len);
         }
         for (int i = 0; i < len; i++) 
         {
             iCountTestcases++;
             sd[intlValues[i+len]] = intlSets[i];
             if (String.Compare(sd[intlValues[i+len]], intlSets[i], false) != 0) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_0002b_{0}, returned {1} instead of {2}", i, sd[intlValues[i+len]], intlSets[i]);
             } 
         }
         Console.WriteLine("5. Case sensitivity");
         strLoc = "Loc_005oo"; 
         iCountTestcases++;
         sd.Clear();
         string [] intlValuesUpper = new string [len];
         for (int i = 0; i < len * 2; i++) 
         {
             intlValues[i] = intlValues[i].ToLower();
         }
         for (int i = 0; i < len; i++) 
         {
             intlValuesUpper[i] = intlValues[i].ToUpper();
         } 
         sd.Clear();
         Console.WriteLine(" ... add Lowercased ...");
         for (int i = 0; i < len; i++) 
         {
             sd.Add(intlValues[i+len], intlValues[i]);     
         }
         if (sd.Count != len) 
         {
             iCountErrors++;
             Console.WriteLine("Err_0005a, count is {0} instead of {1}", sd.Count, len);
         } 
         Console.WriteLine(" ... set to Uppercased ..."); 
         for (int i = 0; i < len; i++) 
         {
             iCountTestcases++;
             sd[intlValues[i+len]] = intlValuesUpper[i];
             if (String.Compare(sd[intlValues[i+len]], intlValuesUpper[i], false) != 0) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_0005b_{0}, returned {1} instead of {2}", i, sd[intlValues[i+len]], intlValuesUpper[i]);
             } 
         }
         Console.WriteLine("6. set Item(null)");
         strLoc = "Loc_006oo"; 
         iCountTestcases++;
         try 
         {
             sd[null] = intlStr;
             iCountErrors++;
             Console.WriteLine("Err_0006a, no exception");
         }
         catch (ArgumentNullException ex) 
         {
             Console.WriteLine("  expected exception: " + ex.Message);
         }
         catch (Exception e) 
         {
             iCountErrors++;
             Console.WriteLine("Err_0006b, unexpected exception: {0}", e.ToString());
         }
         Console.WriteLine("7. set Item to null");
         strLoc = "Loc_007oo"; 
         iCountTestcases++;
         if (!sd.ContainsKey(keys[0]) ) 
         {
             sd.Add(keys[0], values[0]);
         }
         sd[keys[0]] = null;
         if ( sd[keys[0]] != null )
         {
             iCountErrors++;
             Console.WriteLine("Err_0007, returned non-null");
         }
     } 
     catch (Exception exc_general ) 
     {
         ++iCountErrors;
         Console.WriteLine (s_strTFAbbrev + " : Error Err_general!  strLoc=="+ strLoc +", exc_general==\n"+exc_general.ToString());
     }
     if ( iCountErrors == 0 )
     {
         Console.WriteLine( "Pass.   "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases);
         return true;
     }
     else
     {
         Console.WriteLine("Fail!   "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums );
         return false;
     }
 }
コード例 #60
0
        // Constructor
        public Arguments(IEnumerable <string> args)
        {
            _parameters = new StringDictionary();
            var spliter = new Regex(@"^-{1,2}|^/|=|:",
                                    RegexOptions.IgnoreCase | RegexOptions.Compiled);

            var remover = new Regex(@"^['""]?(.*?)['""]?$",
                                    RegexOptions.IgnoreCase | RegexOptions.Compiled);

            string parameter = null;

            // Valid parameters forms:
            // {-,/,--}param{ ,=,:}((",')value(",'))
            // Examples:
            // -param1 value1 --param2 /param3:"Test-:-work"
            //   /param4=happy -param5 '--=nice=--'
            foreach (var arg in args)
            {
                // Look for new parameters (-,/ or --) and a
                // possible enclosed value (=,:)
                var parts = spliter.Split(arg, 3);

                switch (parts.Length)
                {
                // Found a value (for the last parameter
                // found (space separator))
                case 1:
                    if (parameter != null)
                    {
                        if (!_parameters.ContainsKey(parameter))
                        {
                            parts[0] =
                                remover.Replace(parts[0], "$1");

                            _parameters.Add(parameter, parts[0]);
                        }
                        parameter = null;
                    }
                    // else Error: no parameter waiting for a value (skipped)
                    break;

                // Found just a parameter
                case 2:
                    // The last parameter is still waiting.
                    // With no value, set it to true.
                    if (parameter != null)
                    {
                        if (!_parameters.ContainsKey(parameter))
                        {
                            _parameters.Add(parameter, "true");
                        }
                    }
                    parameter = parts[1];
                    break;

                // Parameter with enclosed value
                case 3:
                    // The last parameter is still waiting.
                    // With no value, set it to true.
                    if (parameter != null)
                    {
                        if (!_parameters.ContainsKey(parameter))
                        {
                            _parameters.Add(parameter, "true");
                        }
                    }

                    parameter = parts[1];

                    // Remove possible enclosing characters (",')
                    if (!_parameters.ContainsKey(parameter))
                    {
                        parts[2] = remover.Replace(parts[2], "$1");
                        _parameters.Add(parameter, parts[2]);
                    }

                    parameter = null;
                    break;
                }
            }
            // In case a parameter is still waiting
            if (parameter == null)
            {
                return;
            }

            if (!_parameters.ContainsKey(parameter))
            {
                _parameters.Add(parameter, "true");
            }
        }