Esempio n. 1
0
 public void Titleize()
 {
     foreach (var pair in TestData)
     {
         Assert.AreEqual(Inflector.Titleize(pair.Key), pair.Value);
     }
 }
Esempio n. 2
0
        /// <summary>
        /// Get localized value of enum
        /// </summary>
        /// <typeparam name="T">Enum</typeparam>
        /// <param name="enumValue">Enum value</param>
        /// <param name="localizationService">Localization service</param>
        /// <param name="languageId">Language identifier</param>
        /// <param name="hint">Whether to load the hint.</param>
        /// <returns>Localized value</returns>
        public static string GetLocalizedEnum <T>(this T enumValue, ILocalizationService localizationService, int languageId = 0, bool hint = false)
            where T : struct
        {
            Guard.NotNull(localizationService, nameof(localizationService));

            if (!typeof(T).IsEnum)
            {
                throw new ArgumentException("T must be an enumerated type.");
            }

            var resourceName = string.Format("Enums.{0}.{1}",
                                             typeof(T).ToString(),
                                             enumValue.ToString());

            if (hint)
            {
                resourceName += ".Hint";
            }

            var result = localizationService.GetResource(resourceName, languageId, false, "", true);

            // Set default value if required.
            if (string.IsNullOrEmpty(result))
            {
                result = Inflector.Titleize(enumValue.ToString());
            }

            return(result);
        }
Esempio n. 3
0
        /// <summary>
        /// Get localized value of enum
        /// </summary>
        /// <typeparam name="T">Enum</typeparam>
        /// <param name="enumValue">Enum value</param>
        /// <param name="localizationService">Localization service</param>
        /// <param name="languageId">Language identifier</param>
        /// <returns>Localized value</returns>
        public static string GetLocalizedEnum <T>(this T enumValue, ILocalizationService localizationService, int languageId = 0)
            where T : struct
        {
            if (localizationService == null)
            {
                throw new ArgumentNullException(nameof(localizationService));
            }

            if (!typeof(T).IsEnum)
            {
                throw new ArgumentException("T must be an enumerated type");
            }

            //localized value
            string resourceName = string.Format("Enums.{0}.{1}",
                                                typeof(T).ToString(),
                                                //Convert.ToInt32(enumValue)
                                                enumValue.ToString());

            string result = localizationService.GetResource(resourceName, languageId, false, "", true);

            // Set default value if required
            if (String.IsNullOrEmpty(result))
            {
                result = Inflector.Titleize(enumValue.ToString());
            }

            return(result);
        }
Esempio n. 4
0
        private Tuple <string /*Name*/, string /*Description*/> GetFriendlyName(Type type, PluginDescriptor descriptor)
        {
            string name        = null;
            string description = name;

            var attr = type.GetAttribute <FriendlyNameAttribute>(false);

            if (attr != null)
            {
                name        = attr.Name;
                description = attr.Description;
            }
            else if (typeof(IPlugin).IsAssignableFrom(type) && descriptor != null)
            {
                name        = descriptor.FriendlyName;
                description = descriptor.Description;
            }
            else
            {
                name = Inflector.Titleize(type.Name);
                //throw Error.Application("The 'FriendlyNameAttribute' must be applied to a provider type if the provider does not implement 'IPlugin' (provider type: {0}, plugin: {1})".FormatInvariant(type.FullName, descriptor != null ? descriptor.SystemName : "-"));
            }

            return(new Tuple <string, string>(name, description));
        }
Esempio n. 5
0
        void FillCombos(bool refresh = false)
        {
            if (!refresh)
            {
                Audiences = WebsiteDataService.Audiences.Select(o => new SelectListItem {
                    Value = ((Audience)o.Value).ToString(), Text = o.Name, Model = o
                }).ToObservableCollection();
                Audiences.RemoveAt(0);
                Audiences.Insert(0, new SelectListItem {
                    Value = Audience.None.ToString(), Text = DEFAULT_AUDIENCE_SELECT_TEXT, Model = null
                });

                Years = BaseDataService.ReportingYears.Select(o => new SelectListItem {
                    Value = o, Text = o, Model = o
                }).ToObservableCollection();
                Years.RemoveAt(0);
                Years.Insert(0, new SelectListItem {
                    Value = string.Empty, Text = DEFAULT_YEAR_SELECT_TEXT, Model = null
                });

                Quarters = BaseDataService.ReportingQuarters.Select(o => new SelectListItem {
                    Value = o.Id, Text = o.Text, Model = o
                }).ToObservableCollection();
                Quarters.RemoveAt(0);
                Quarters.Insert(0, new SelectListItem {
                    Value = -1, Text = DEFAULT_QUARTER_SELECT_TEXT, Model = null
                });

                RegionContextItems = new ObservableCollection <SelectListItem>();
                // RegionContextItems.Insert( 0, new SelectListItem { Text= "Please Select Region", Value = null, Model = null } );
                RegionContextItems.Add(new SelectListItem {
                    Text = Inflector.Titleize(typeof(HospitalServiceArea).Name), Value = typeof(HospitalServiceArea).Name, Model = null
                });
                RegionContextItems.Add(new SelectListItem {
                    Text = Inflector.Titleize(typeof(HealthReferralRegion).Name), Value = typeof(HealthReferralRegion).Name, Model = null
                });
                RegionContextItems.Add(new SelectListItem {
                    Text = Inflector.Titleize(typeof(CustomRegion).Name), Value = typeof(CustomRegion).Name, Model = null
                });
            }

            StateContextItems = new ObservableCollection <SelectListItem>();
            // StateContextItems.Insert(0, new SelectListItem { Text = "Please Select State(s)", Value = null, Model = null });

            StateContextItems = WebsiteDataService.GetStates().ToObservableCollection();
            // else
            //    StateContextItems =
            //        WebsiteDataService.GetApplicableReportingStates(
            //            ManageViewModel.WebsiteViewModel.Website.StateContext.ToArray()).ToObservableCollection();
        }
        /// <summary>
        /// Processes the name of the property.
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        /// <returns></returns>
        private string ProcessPropertyName(string propertyName)
        {
            if (string.IsNullOrWhiteSpace(propertyName))
            {
                return(null);
            }

            if (propertyName.StartsWith("_") && propertyName.EndsWith("Xml"))
            {
                propertyName = Inflector.Titleize(propertyName.Replace("_", null).Replace("Xml", null));
            }

            return(propertyName);
        }
        public static MvcHtmlString ThemeVarLabel(this HtmlHelper html, ThemeVariableInfo info)
        {
            Guard.ArgumentNotNull(info, "info");

            var result     = new StringBuilder();
            var resKey     = "ThemeVar.{0}.{1}".FormatInvariant(info.Manifest.ThemeName, info.Name);
            var langId     = EngineContext.Current.Resolve <IWorkContext>().WorkingLanguage.Id;
            var locService = EngineContext.Current.Resolve <ILocalizationService>();

            var displayName = locService.GetResource(resKey, langId, false, Inflector.Titleize(info.Name));

            var hint = locService.GetResource(resKey + ".Hint", langId, false, "", true);

            hint = "@(var_){0}{1}".FormatInvariant(info.Name, hint.HasValue() ? "\n" + hint : "");

            result.Append("<div class='ctl-label'>");
            result.Append(html.Label(html.NameForThemeVar(info), displayName));
            result.Append(html.Hint(hint).ToHtmlString());
            result.Append("</div>");

            return(MvcHtmlString.Create(result.ToString()));
        }
Esempio n. 8
0
 public static string GetNamespaceName(this OdcmNamespace namespaceObject)
 {
     return(inflector.Titleize(namespaceObject.Name).Replace(" ", ""));
 }
 private static List <string> GetDBResponses <T>(NHibernate.ISession session, Expression <Func <T, bool> > clause)
     where T : EnumLookupEntity <int>
 {
     return
         (session.QueryOver <T>().OrderBy(x => x.Value).Asc.List().Select((x, index) =>
                                                                          String.Format("{0},{1},{2},{3}",
                                                                                        x.Id,
                                                                                        Inflector.Titleize(x.Name),
                                                                                        index + 1,
                                                                                        clause.Compile()(x) ? "Include" : "Exclude")).ToList());
 }
Esempio n. 10
0
 public static string Titlize(this string source)
 {
     return(Inflector.Titleize(source));
 }
Esempio n. 11
0
        private static string FormatPlayerSectionScore(string player)
        {
            var sb = new StringBuilder();
            var i  = 0;
            var ratingsAccumulator = new List <RatingChange>();

            //Console.WriteLine("{");
            sb.Append("{");

            foreach (var line in player.Split('\n'))
            {
                var y = 0;

                // score line
                if (i == 0)
                {
                    foreach (var item in line.Split('|'))
                    {
                        if (y == 0)
                        {
                            // place
                            //Console.WriteLine($"\"Rank\": {item.Trim()},");
                            sb.Append($"\"Rank\": {item.Trim()},");
                        }
                        else if (y == 1)
                        {
                            // name
                            //Console.WriteLine($"\"Name\": \"{Inflector.Titleize(item.Trim())}\",");
                            sb.Append($"\"Name\": \"{Inflector.Titleize(item.Trim())}\",");
                        }
                        else if (y == 2)
                        {
                            // total
                            //Console.WriteLine($"\"TotalPoints\": {item.Trim()},");
                            sb.Append($"\"TotalPoints\": {item.Trim()},");
                        }
                        else
                        {
                            if (y == 3)
                            {
                                //Console.WriteLine("\"Rounds\": [");
                                sb.Append("\"Rounds\": [");
                            }

                            if (string.IsNullOrWhiteSpace(item.Trim()))
                            {
                                continue;
                            }

                            // round
                            var split = item.Trim().ReduceWhitespace().Split(' ');

                            if (split.Length > 1)
                            {
                                //Console.WriteLine($"{{ \"Number\": {y - 2}, \"Outcome\": \"{split[0]}\", \"Versus\": \"{split[1]}\" }},");
                                sb.Append($"{{ \"Number\": {y - 2}, \"Outcome\": \"{split[0]}\", \"Versus\": \"{split[1]}\" }},");
                            }
                            else
                            {
                                //Console.WriteLine($"{{ \"Number\": {y - 2}, \"Outcome\": \"{split[0]}\", \"Versus\": \"{split[1]}\" }},");
                                sb.Append($"{{ \"Number\": {y - 2}, \"Outcome\": \"{split[0]}\", \"Versus\": \"0\" }},");
                            }
                        }

                        y++;
                    }

                    //Console.WriteLine("],");
                    sb.Append("],");
                }

                y = 0;

                // ratings line
                if (i == 1)
                {
                    foreach (var item in line.Split('|'))
                    {
                        if (string.IsNullOrWhiteSpace(item))
                        {
                            continue;
                        }

                        if (y == 0)
                        {
                            // state
                            //Console.WriteLine($"\"State\": \"{item.Trim()}\",");
                            sb.Append($"\"State\": \"{item.Trim()}\",");
                        }
                        else if (y == 1)
                        {
                            var split = item.Trim().Split('/');

                            // player ID + R
                            //Console.WriteLine($"\"PlayerId\": \"{split[0].Trim()}\",");
                            sb.Append($"\"PlayerId\": \"{split[0].Trim()}\",");

                            ratingsAccumulator.Add(split[1].FormatRatingChange());
                        }
                        else if (y == 2)
                        {
                            // N:1
                            //Console.WriteLine($"\"NValue\": \"{item.Trim()}\",");
                            sb.Append($"\"NValue\": \"{item.Trim()}\",");
                        }

                        y++;
                    }
                }

                if (i > 1)
                {
                    foreach (var item in line.Split('|'))
                    {
                        if (string.IsNullOrWhiteSpace(item))
                        {
                            continue;
                        }

                        ratingsAccumulator.Add(item.FormatRatingChange());
                    }
                }

                i++;

                //Console.WriteLine(line);
            }

            //Console.WriteLine($"\"Ratings\": {JsonConvert.SerializeObject(ratingsAccumulator)},");
            sb.Append($"\"Ratings\": {JsonConvert.SerializeObject(ratingsAccumulator)},");

            //Console.WriteLine("},");
            sb.Append("},");
            //Console.WriteLine(new string('+', 80));

            return(sb.ToString());
        }
Esempio n. 12
0
 public void TestTitleize()
 {
     Assert.AreEqual("Man From The Boondocks", Inflector.Titleize("man from the boondocks"));
     Assert.AreEqual("X Men: The Last Stand", Inflector.Titleize("x-men: the last stand"));
 }
Esempio n. 13
0
        public ActionResult Configure()
        {
            var model = new UPSModel();

            model.Url       = _upsSettings.Url;
            model.AccessKey = _upsSettings.AccessKey;
            model.Username  = _upsSettings.Username;
            model.Password  = _upsSettings.Password;
            model.AdditionalHandlingCharge = _upsSettings.AdditionalHandlingCharge;
            model.InsurePackage            = _upsSettings.InsurePackage;

            foreach (UPSCustomerClassification customerClassification in Enum.GetValues(typeof(UPSCustomerClassification)))
            {
                model.AvailableCustomerClassifications.Add(new SelectListItem()
                {
                    Text     = Inflector.Titleize(customerClassification.ToString()),
                    Value    = customerClassification.ToString(),
                    Selected = customerClassification == _upsSettings.CustomerClassification
                });
            }
            foreach (UPSPickupType pickupType in Enum.GetValues(typeof(UPSPickupType)))
            {
                model.AvailablePickupTypes.Add(new SelectListItem()
                {
                    Text     = Inflector.Titleize(pickupType.ToString()),
                    Value    = pickupType.ToString(),
                    Selected = pickupType == _upsSettings.PickupType
                });
            }
            foreach (UPSPackagingType packagingType in Enum.GetValues(typeof(UPSPackagingType)))
            {
                model.AvailablePackagingTypes.Add(new SelectListItem()
                {
                    Text     = Inflector.Titleize(packagingType.ToString()),
                    Value    = packagingType.ToString(),
                    Selected = packagingType == _upsSettings.PackagingType
                });
            }

            foreach (var country in _countryService.GetAllCountries(true))
            {
                model.AvailableCountries.Add(new SelectListItem()
                {
                    Text     = country.Name.ToString(),
                    Value    = country.Id.ToString(),
                    Selected = country.Id == _upsSettings.DefaultShippedFromCountryId
                });
            }
            model.DefaultShippedFromCountryId     = _upsSettings.DefaultShippedFromCountryId;
            model.DefaultShippedFromZipPostalCode = _upsSettings.DefaultShippedFromZipPostalCode;

            var services = new UPSServices();
            // Load Domestic service names
            string carrierServicesOfferedDomestic = _upsSettings.CarrierServicesOffered;

            foreach (string service in services.Services)
            {
                model.AvailableCarrierServices.Add(service);
            }

            if (!String.IsNullOrEmpty(carrierServicesOfferedDomestic))
            {
                foreach (string service in services.Services)
                {
                    string serviceId = UPSServices.GetServiceId(service);
                    if (!String.IsNullOrEmpty(serviceId) && !String.IsNullOrEmpty(carrierServicesOfferedDomestic))
                    {
                        // Add delimiters [] so that single digit IDs aren't found in multi-digit IDs
                        if (carrierServicesOfferedDomestic.Contains(String.Format("[{0}]", serviceId)))
                        {
                            model.CarrierServicesOffered.Add(service);
                        }
                    }
                }
            }

            return(View(model));
        }
        public static string GetNamespaceName(this OdcmNamespace namespaceObject)
        {
            var nameSpaceName = GetReservedNameSpaces().Contains(namespaceObject.Name) ? $"{namespaceObject.Name}Namespace" : namespaceObject.Name;

            return(inflector.Titleize(nameSpaceName).Replace(" ", ""));
        }
        /// <summary>
        /// Called when [delete all physicians].
        /// </summary>
        private async void OnDeleteAllPhysicians()
        {
            //bool noPhysicianDataSetCheck = true;

            var websiteDatasets  = new Dictionary <string, List <string> >();
            var contextualStates = ConfigurationService.HospitalRegion.DefaultStates.OfType <string>().ToList();

            using (var session = DataserviceProvider.SessionFactory.OpenSession())
            {
                foreach (var state in contextualStates)
                {
                    var query = string.Format(@"select distinct ds.[File], w.[Name] from [Wings_Datasets] ds
	inner join [Websites_WebsiteDatasets] wd on wd.[Dataset_Id] = ds.[Id]
    inner join [Websites] w on w.[Id] = wd.[Website_Id]
where ds.[ProviderStates] like '%{0}%' and ds.[ProviderUseRealtime]=0;", state);

                    var foundItems = session.CreateSQLQuery(query)
                                     .AddScalar("File", NHibernateUtil.String)
                                     .AddScalar("Name", NHibernateUtil.String)
                                     .DynamicList();

                    if (foundItems.Any())
                    {
                        foreach (var item in foundItems)
                        {
                            if (!websiteDatasets.ContainsKey(item.Name))
                            {
                                websiteDatasets.Add(item.Name, new List <string> {
                                    item.File
                                });
                            }
                            else
                            {
                                var datasets = websiteDatasets[item.Name];
                                if (!datasets.Contains(item.File))
                                {
                                    datasets.Add(item.File);
                                    websiteDatasets[item.Name] = datasets;
                                }
                            }
                        }
                    }
                }
            }

            if (websiteDatasets.Any())
            {
                var message = new StringBuilder();

                foreach (var wd in websiteDatasets)
                {
                    foreach (var ds in  wd.Value.ToList())
                    {
                        message.AppendLine(ds + " ( Website: " + wd.Key + " )");
                    }
                }

                MessageBox.Show(string.Format(@"Please remove the following dataset(s) from their corresponding website(s) before deleting physicians for the following states {1}:{0}{0}{2}", Environment.NewLine, string.Join(", ", contextualStates), message),
                                @"Delete Confirmation", MessageBoxButtons.OKCancel);
                return;
            }

            var result = MessageBox.Show(@"Are you sure want to delete the data for all physicians?", @"Delete Confirmation", MessageBoxButtons.OKCancel);

            if (result != DialogResult.OK)
            {
                return;
            }

            var deleteResult = await Task.Run(() =>
            {
                using (var session = DataserviceProvider.SessionFactory.OpenSession())
                {
                    using (var trans = session.BeginTransaction())
                    {
                        try
                        {
                            var deleteAllQuery = string.Format(
                                @"
truncate table [dbo].[Addresses];
truncate table [dbo].[Physicians_AffiliatedHospitals];
truncate table [dbo].[Physicians_Audits];
truncate table [dbo].[Physicians_MedicalPractices];
delete from [dbo].[MedicalPractices];
delete from [dbo].[Physicians];");

                            session.CreateSQLQuery(deleteAllQuery)
                            .SetTimeout(50000)
                            .ExecuteUpdate();

                            session.Flush();
                            trans.Commit();

                            return(new DeleteAllPhysiciansResult {
                                Status = true
                            });
                        }
                        catch (Exception exc)
                        {
                            trans.Rollback();

                            return(new DeleteAllPhysiciansResult {
                                Status = false, Exception = exc
                            });
                        }
                    }
                }
            });

            if (deleteResult.Status)
            {
                Notify(string.Format("All {0} have been successfully deleted.",
                                     Inflector.Pluralize(Inflector.Titleize(typeof(db.Physician).Name))));
                CollectionItems = new ListCollectionView(new List <db.Physician>());
            }

            if (!deleteResult.Status && deleteResult.Exception != null)
            {
                var fullMessage = new StringBuilder();
                fullMessage.AppendLine("An error occurred while deleting all physicans. Error Message: " + deleteResult.Exception.Message);
                fullMessage.AppendLine();
                fullMessage.AppendLine("Stack Trace: " + deleteResult.Exception.StackTrace);
                Logger.Write(deleteResult.Exception, "Error deleting all physicians");

                LogEntityError(deleteResult.Exception, typeof(db.Physician), "*");
            }

            //CollectionItems.Refresh();
            ForceLoad();
        }
        /// <summary>
        /// Called when [delete].
        /// </summary>
        /// <param name="entity">The entity.</param>
        protected override async void OnDelete(db.Physician entity)
        {
            if (entity == null)
            {
                return;
            }

            var result =
                MessageBox.Show(@"Are you sure want to delete the data for this physician, """ + entity.Name + @"""?", @"Delete Confirmation", MessageBoxButtons.OKCancel);

            if (result != DialogResult.OK)
            {
                return;
            }

            var       errorOccurred   = false;
            Exception errorException  = null;
            var       progressService = new ProgressService();

            progressService.SetProgress("Deleting physican", 0, false, true);

            //await Task.Delay(500);

            string entityName          = entity.Name;
            var    executedSuccessully = await progressService.Execute(() =>
            {
                using (var session = DataserviceProvider.SessionFactory.OpenSession())
                {
                    using (var trans = session.BeginTransaction())
                    {
                        try
                        {
                            var updateQuery = string.Format(@"UPDATE {0} SET IsDeleted = 1 WHERE Id = {1} AND IsDeleted = 0",
                                                            typeof(db.Physician).EntityTableName(),
                                                            entity.Id);
                            session.CreateSQLQuery(updateQuery).ExecuteUpdate();
                            session.Flush();
                            trans.Commit();
                        }
                        catch
                        {
                            trans.Rollback();
                            throw;
                        }
                    }
                }
            },
                                                                       opResult =>
            {
                if (!opResult.Status && opResult.Exception != null)
                {
                    errorOccurred  = true;
                    errorException = opResult.Exception;
                }
                else
                {
                    errorOccurred = true;
                }
            }, new CancellationToken());

            progressService.SetProgress("Completed", 100, true, false);

            if (errorOccurred && errorException != null)
            {
                Logger.Write(errorException, "Error deleting physician \"{0}\"", entity.Name);
                LogEntityError(errorException, typeof(db.Physician), entityName);
                return;
            }

            CollectionItems.Remove(entity);
            CollectionItems.Refresh();

            Notify(string.Format("{0} {1} has been deleted.", entityName,
                                 Inflector.Titleize(typeof(db.Physician).Name)));
        }
Esempio n. 17
0
        protected override void OnDelete(MedicalPractice entity)
        {
            if (entity == null)
            {
                return;
            }

            var associatedPhysicians = new List <string>();

            using (var session = DataserviceProvider.SessionFactory.OpenSession())
            {
                associatedPhysicians = session.Query <Monahrq.Infrastructure.Domain.Physicians.PhysicianMedicalPractice>()
                                       .Where(x => x.MedicalPractice.Id == entity.Id && !x.Physician.IsDeleted)
                                       .Select(x => string.Format(" - {0} {1} (NPI: {2})", x.Physician.FirstName, x.Physician.LastName, x.Physician.Npi))
                                       .ToList();
            }

            if (associatedPhysicians.Any())
            {
                // string physicianNames = string.Join(",", associatedPhysicians);
                var warningMessage = string.Format("Unable to delete medical practice \"{0}\" because it is associated with the following physicians:", entity.Name) + Environment.NewLine;
                associatedPhysicians.ForEach(x => warningMessage += Environment.NewLine + x);

                MessageBox.Show(warningMessage, "Dataset Deletion Warning", MessageBoxButtons.OK);
                return;
            }
            else if (MessageBox.Show(string.Format(@"Are you sure want to delete {0} ?", entity.Name), @"Delete Confirmation", MessageBoxButtons.OKCancel) != DialogResult.OK)
            {
                return;
            }

            using (var session = DataserviceProvider.SessionFactory.OpenSession())
            {
                using (var trans = session.BeginTransaction())
                {
                    var msg = string.Format("{0} {1} has been deleted.", entity.Name, Inflector.Titleize(entity.GetType().Name));

                    try
                    {
                        session.Evict(entity);
                        session.Delete(entity);
                        trans.Commit();
                        Notify(msg);
                    }
                    catch (Exception exc)
                    {
                        trans.Rollback();

                        var excToUse = exc;
                        LogEntityError(excToUse, entity.GetType(), entity.Name);
                    }
                }
            }

            CollectionItems.Remove(entity);
        }