public void UnsupportedCulture()
 {
     Assert.Catch<NotSupportedException>(() =>
                                         {
                                             var inflector = new Inflector(new CultureInfo("fr"));
                                             var hommes = inflector.Pluralize("homme");
                                         });
 }
Esempio n. 2
0
 public void TestInitialize()
 {
     inflector = new Inflector();
 }
 public static string Pluralize(string input)
 {
     return(Inflector.Pluralize(input.EmptyNull()));
 }
Esempio n. 4
0
        public frmMain()
        {
            Predictor  = new Predictor(Settings.Default.PredictorKey);
            Dictionary = new Dictionary(Settings.Default.DictionaryKey);
            Translator = new Translator(Settings.Default.TranslatorKey);
            Speller    = new Speller();
            Inflector  = new Inflector();

            PredictorTimer  = new System.Threading.Timer(_ => UpdatePredictorResult(), null, Timeout.Infinite, Timeout.Infinite);
            DictionaryTimer = new System.Threading.Timer(_ => UpdateDictionaryResult(), null, Timeout.Infinite, Timeout.Infinite);
            TranslatorTimer = new System.Threading.Timer(_ => UpdateTranslatorResult(), null, Timeout.Infinite, Timeout.Infinite);
            SpellerTimer    = new System.Threading.Timer(_ => UpdateSpellerResult(), null, Timeout.Infinite, Timeout.Infinite);
            InflectorTimer  = new System.Threading.Timer(_ => UpdateInflectorResult(), null, Timeout.Infinite, Timeout.Infinite);

            InitializeComponent();

            tcServices.SelectedIndex = Settings.Default.SelectedTabIndex;

            cmbPredictorLangs.Items.AddRange(Predictor.GetLangs().Select(lang => (object)lang).ToArray());
            cmbDictionaryLangPairs.Items.AddRange(Dictionary.GetLangs().Select(lang => (object)lang).ToArray());
            cmbDictionaryLangUi.Items.Add("");
            cmbDictionaryLangUi.Items.AddRange(Predictor.GetLangs().Select(lang => (object)lang).ToArray());

            cmbPredictorLangs.SelectedItem = Enum.Parse(typeof(Lang), Settings.Default.PredictorLanguage);
            nudMaxHintCount.Value          = Settings.Default.PredictorMaxHintCount;
            nudPredictorDelay.Value        = Settings.Default.PredictorHintDelay;
            tbPredictorInput.Text          = Settings.Default.PredictorInput;

            cmbDictionaryLangPairs.SelectedItem = new LangPair(Settings.Default.DictionaryLangPair);
            cmbDictionaryLangUi.SelectedIndex   = 0;

            cbFamily.Checked               = Settings.Default.DictionaryFamily;
            cbMorpho.Checked               = Settings.Default.DictionaryMorpho;
            cbPartOfSpeech.Checked         = Settings.Default.DictionaryPartOfSpeech;
            nudPredictorDelay.Value        = Settings.Default.DictionaryHintDelay;
            tbDictionaryInput.Text         = Settings.Default.DictionaryInput;
            cbDictionaryFormatting.Checked = Settings.Default.DictionaryFormatting;
            rbDictionaryOutput.Text        = Settings.Default.DictionaryOutputIndent;

            var langArray = ((Lang[])Enum.GetValues(typeof(Lang))).Select(lang => (object)lang).ToArray();

            cmbTranslatorInputLang.Items.AddRange(langArray);
            cmbTranslatorOutputLang.Items.AddRange(langArray);
            cmbTranslatorInputLang.SelectedItem  = (Lang)Enum.Parse(typeof(Lang), Settings.Default.TranslatorInputLang);
            cmbTranslatorOutputLang.SelectedItem = (Lang)Enum.Parse(typeof(Lang), Settings.Default.TranslatorOutputLang);
            nudTranslatorDelay.Value             = Settings.Default.TranslatorHintDelay;
            cbTranslatorDetectInputLang.Checked  = Settings.Default.TranslatorDetectInputLang;
            tbTranslatorInput.Text = Settings.Default.TranslatorInput;

            cbSpellerRu.Checked = Settings.Default.SpellerRuLang;
            cbSpellerEn.Checked = Settings.Default.SpellerEnLang;
            cbSpellerUk.Checked = Settings.Default.SpellerUkLang;
            SpellerOptions options = (SpellerOptions)Settings.Default.SpellerOptions;

            cbIgnoreUppercase.Checked      = options.HasFlag(SpellerOptions.IgnoreUppercase);
            cbIgnoreDigits.Checked         = options.HasFlag(SpellerOptions.IgnoreDigits);
            cbIgnoreUrls.Checked           = options.HasFlag(SpellerOptions.IgnoreUrls);
            cbFindRepeatWords.Checked      = options.HasFlag(SpellerOptions.FindRepeatWords);
            cbIgnoreLatin.Checked          = options.HasFlag(SpellerOptions.IgnoreLatin);
            cbNoSuggest.Checked            = options.HasFlag(SpellerOptions.NoSuggest);
            cbFlagLatin.Checked            = options.HasFlag(SpellerOptions.FlagLatin);
            cbByWords.Checked              = options.HasFlag(SpellerOptions.ByWords);
            cbIgnoreCapitalization.Checked = options.HasFlag(SpellerOptions.IgnoreCapitalization);
            nudSpellerDelay.Value          = Settings.Default.SpellerHintDelay;
            tbSpellerInput.Text            = Settings.Default.SpellerInput;
            cbIncludeErrorWords.Checked    = Settings.Default.SpellerIncludeErrorWords;

            tbInflectorInput.Text = Settings.Default.InflectorInput;

            tbPredictorKey.Text      = Settings.Default.PredictorKey;
            tbDictionaryKey.Text     = Settings.Default.DictionaryKey;
            tbTranslatorKey.Text     = Settings.Default.TranslatorKey;
            tbPredictorBaseUrl.Text  = Settings.Default.PredictorBaseUrl;
            tbDictionaryBaseUrl.Text = Settings.Default.DictionaryBaseUrl;
            tbTranslatorBaseUrl.Text = Settings.Default.TranslatorBaseUrl;
            tbSpellerBaseUrl.Text    = Settings.Default.SpellerBaseUrl;
            tbInflectorBaseUrl.Text  = Settings.Default.InflectorBaseUrl;
        }
Esempio n. 5
0
        public HospitalMap()
        {
            var indexName = string.Format("IDX_{0}", EntityTableName);

            Map(x => x.CCR).Scale(4).Nullable();

            Map(x => x.CmsProviderID).Length(10).Index(indexName);
            Map(x => x.LocalHospitalId).Length(20).Index(indexName);

            Map(x => x.Description).Length(1000);
            Map(x => x.Employees);
            Map(x => x.TotalBeds);
            Map(x => x.HospitalOwnership).Length(100);
            Map(x => x.PhoneNumber).Length(50);
            Map(x => x.FaxNumber).Length(50);
            Map(x => x.MedicareMedicaidProvider).Default("0");
            Map(x => x.EmergencyService).Default("0");
            Map(x => x.TraumaService).Default("0");
            Map(x => x.UrgentCareService).Default("0");
            Map(x => x.PediatricService).Default("0");
            Map(x => x.PediatricICUService).Default("0");
            Map(x => x.CardiacCatherizationService).Default("0");
            Map(x => x.PharmacyService).Default("0");
            Map(x => x.DiagnosticXRayService).Default("0");
            Map(x => x.ForceLocalHospitalIdValidation).Default("0");

            Map(x => x.IsDeleted).Default("0").Index(indexName);
            Map(x => x.IsArchived).Default("0").Index(indexName);
            Map(x => x.ArchiveDate);
            Map(x => x.LinkedHospitalId);

            Map(x => x.Address).Length(100);
            Map(x => x.City).Length(100);
            Map(x => x.State).Length(10);
            Map(x => x.County).Length(10);
            Map(x => x.Zip).Length(12).Index(indexName);
            Map(x => x.Latitude);
            Map(x => x.Longitude);

            References(x => x.HospitalServiceArea, "HospitalServiceArea_Id")
            .Not.LazyLoad()
            .Cascade.None()
            .ForeignKey(string.Format("FK_Hospitals_{0}", typeof(HospitalServiceArea).Name));

            References(x => x.HealthReferralRegion, "HealthReferralRegion_Id")
            .Not.LazyLoad()
            .Cascade.None()
            .ForeignKey(string.Format("FK_Hospital_{0}", typeof(HealthReferralRegion).Name));

            References(x => x.CustomRegion, "CustomRegion_Id")
            .Not.LazyLoad()
            .Cascade.None()
            .ForeignKey(string.Format("FK_Hospitals_{0}", typeof(CustomRegion).Name));

            HasManyToMany(x => x.Categories)
            .Table("Hospitals_" + Inflector.Pluralize(typeof(HospitalCategory).Name))
            .ParentKeyColumn("Hospital_Id")
            .ChildKeyColumn("Category_Id")
            .AsBag()
            .NotFound.Ignore()
            .Not.LazyLoad()
            .Not.Inverse()
            .Cascade.SaveUpdate();
        }
        public List <Enumeration> ReadEnums(List <EnumerationSettings> enums)
        {
            var result = new List <Enumeration>();

            using (var conn = _factory.CreateConnection())
            {
                if (conn == null)
                {
                    return(result);
                }

                conn.ConnectionString = Settings.ConnectionString;
                conn.Open();

                var cmd = GetCmd(conn);
                if (cmd == null)
                {
                    return(result);
                }

                foreach (var e in enums)
                {
                    var sql = EnumSQL(e.Table, e.NameField, e.ValueField);
                    if (string.IsNullOrEmpty(sql))
                    {
                        continue;
                    }

                    cmd.CommandText = sql;

                    try
                    {
                        using (var rdr = cmd.ExecuteReader())
                        {
                            var items = new List <KeyValuePair <string, string> >();
                            while (rdr.Read())
                            {
                                var name = rdr["NameField"].ToString().Trim();
                                if (string.IsNullOrEmpty(name))
                                {
                                    continue;
                                }

                                name = RemoveNonAlphanumerics.Replace(name, string.Empty);
                                name = Inflector.ToTitleCase(name).Replace(" ", "").Trim();
                                if (string.IsNullOrEmpty(name))
                                {
                                    continue;
                                }

                                var value = rdr["ValueField"].ToString().Trim();
                                if (string.IsNullOrEmpty(value))
                                {
                                    continue;
                                }

                                items.Add(new KeyValuePair <string, string>(name, value));
                            }

                            if (items.Any())
                            {
                                result.Add(new Enumeration(e.Name, items));
                            }
                        }
                    }
                    catch (Exception)
                    {
                        // Enum table does not exist in database, skip
                    }
                }
            }
            return(result);
        }
Esempio n. 7
0
 public string Underscore() => Inflector.Underscore("aaaBbbCccDdd");
 public override string ClassName(string tableName)
 {
     return(Inflector.Singular(MemberName(tableName).FirstUpper()));
 }
 public TableTemplateData(Table table)
 {
     Table            = table;
     DbSetName        = table.NameHumanCaseWithSuffix();
     DbSetConfigName  = table.NameHumanCaseWithSuffix() + Settings.ConfigurationClassName;
     PluralTableName  = !string.IsNullOrWhiteSpace(table.PluralNameOverride) ? table.PluralNameOverride :  Inflector.MakePlural(table.NameHumanCase);
     DbSetModifier    = table.DbSetModifier;
     Comment          = Settings.IncludeComments == CommentsStyle.None ? string.Empty : " // " + table.DbName;
     DbSetPrimaryKeys = string.Join(", ", table.PrimaryKeys.Select(x => "\"" + x.NameHumanCase + "\""));
 }
Esempio n. 10
0
 private static string GenerateDefaultDataDirectory(string template, ResourceType type, string name)
 {
     return(template.Replace("{pluralizedResourceType}", Inflector.Pluralize(type.ToString()))
            .Replace("{name}", name));
 }
Esempio n. 11
0
        public static string GetDataDirectoryPath(CoreConfiguration coreConfiguration, string name, ResourceType type)
        {
            var dataDirectory     = coreConfiguration.DataDirectory;
            var dataDirectoryPath = dataDirectory != null?coreConfiguration.DataDirectory.Combine(Inflector.Pluralize(type.ToString())).Combine(name).ToFullPath() :
                                        GenerateDefaultDataDirectory(coreConfiguration.GetDefaultValue <CoreConfiguration>(v => v.DataDirectory).ToString(), type, name);

            return(dataDirectoryPath);
        }
        public void Apply(IPropertyInstance instance)
        {
            var propName = Inflector.Underscore(instance.Name.ToLower());

            instance.Column(propName);
        }
Esempio n. 13
0
        public async Task <HttpResponseMessage> LoadCsvFile()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new Exception(); // divided by zero
            }
            var provider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);

            foreach (var file in provider.Contents)
            {
                var filename = file.Headers.ContentDisposition.FileName.Trim('\"');

                var stream = await file.ReadAsStreamAsync();

                using (var csvReader = new TextFieldParser(stream))
                {
                    csvReader.SetDelimiters(",");
                    var headers = csvReader.ReadFields();
                    var entity  =
                        Inflector.Pluralize(CSharpClassName.ConvertToValidClassName(Path.GetFileNameWithoutExtension(filename)));
                    if (entity.Length > 0 && char.IsLower(entity[0]))
                    {
                        entity = char.ToUpper(entity[0]) + entity.Substring(1);
                    }

                    var totalCount = 0;
                    var batch      = new List <RavenJObject>();
                    var columns    = headers.Where(x => x.StartsWith("@") == false).ToArray();

                    batch.Clear();
                    while (csvReader.EndOfData == false)
                    {
                        var          record   = csvReader.ReadFields();
                        var          document = new RavenJObject();
                        string       id       = null;
                        RavenJObject metadata = null;
                        for (int index = 0; index < columns.Length; index++)
                        {
                            var column = columns[index];
                            if (string.IsNullOrEmpty(column))
                            {
                                continue;
                            }

                            if (string.Equals("id", column, StringComparison.OrdinalIgnoreCase))
                            {
                                id = record[index];
                            }
                            else if (string.Equals(Constants.RavenEntityName, column, StringComparison.OrdinalIgnoreCase))
                            {
                                metadata = metadata ?? new RavenJObject();
                                metadata[Constants.RavenEntityName] = record[index];
                                id = id ?? record[index] + "/";
                            }
                            else if (string.Equals(Constants.RavenClrType, column, StringComparison.OrdinalIgnoreCase))
                            {
                                metadata = metadata ?? new RavenJObject();
                                metadata[Constants.RavenClrType] = record[index];
                                id = id ?? record[index] + "/";
                            }
                            else
                            {
                                document[column] = SetValueInDocument(record[index]);
                            }
                        }

                        metadata = metadata ?? new RavenJObject {
                            { "Raven-Entity-Name", entity }
                        };
                        document.Add("@metadata", metadata);
                        metadata.Add("@id", id ?? Guid.NewGuid().ToString());

                        batch.Add(document);
                        totalCount++;

                        if (batch.Count >= csvImportBatchSize)
                        {
                            await FlushBatch(batch);

                            batch.Clear();
                        }
                    }

                    if (batch.Count > 0)
                    {
                        await FlushBatch(batch);
                    }
                }
            }

            return(GetEmptyMessage());
        }
Esempio n. 14
0
        internal string GenerateActions(string baseNamespace, string namespacePostfix, string classNamespace,
                                        IList <IEntityNavigation> excludeCircularReferenceNavigationProperties, IEntityType entity,
                                        bool InludeRelatedObjects, bool prependSchemaNameIndicator)
        {
            var    sb         = new StringBuilder();
            string entityName = Inflector.Humanize(entity.ClrType.Name);

            sb.AppendLine($"using System;");
            sb.AppendLine($"using System.Collections.Generic;");
            sb.AppendLine($"using System.Text;");
            sb.AppendLine($"using Csla; //https://github.com/MarimerLLC/csla");
            sb.AppendLine(string.IsNullOrWhiteSpace(namespacePostfix) ? $"using {baseNamespace}.DataAccess;" : $"using {baseNamespace}.DataAccess.{namespacePostfix};");
            sb.AppendLine($"");
            sb.AppendLine(string.IsNullOrWhiteSpace(namespacePostfix) ? $"namespace {baseNamespace}.Shared" : $"namespace {baseNamespace}.Shared.{namespacePostfix}");

            sb.AppendLine($"{{");
            sb.AppendLine("\t[Serializable]");
            sb.AppendLine($"\tpublic class {entityName}Edit : BusinessBase<{entityName}Edit>");
            sb.AppendLine($"\t{{");

            var primaryKeyList   = GetPrimaryKeys(entity);
            var entityProperties = entity.GetProperties();

            //////////////////Properties
            foreach (var property in entityProperties)
            {
                string ctype        = GetCType(property);
                var    simpleType   = ConvertToSimpleType(ctype);
                string propertyName = property.Name;

                sb.AppendLine($"\t\tpublic static readonly PropertyInfo<{simpleType}> {propertyName}Property = RegisterProperty<{simpleType}>(nameof({propertyName}));");

                sb.AppendLine($"\t\tpublic {simpleType} {propertyName}");
                sb.AppendLine("\t\t{");
                sb.AppendLine($"\t\t\tget {{return GetProperty({propertyName}Property);}}");
                sb.AppendLine($"\t\t\tprivate set {{ LoadProperty({propertyName}Property, value);}}");
                sb.AppendLine("\t\t}");
                sb.AppendLine(string.Empty);
            }

            //////////////////AddBusinessRules
            sb.AppendLine("\t\tprotected override void AddBusinessRules()");
            sb.AppendLine("\t\t{");
            sb.AppendLine("\t\t\tbase.AddBusinessRules();");
            sb.AppendLine("\t\t}");

            //////////////////Create
            var k           = entity.FindPrimaryKey();
            var kctype      = k.Properties[0].ClrType;
            var ksimpleType = ConvertToSimpleType(kctype.Name);

            sb.AppendLine("");
            sb.AppendLine("\t\t[Create]");
            sb.AppendLine("\t\tprivate void Create()");
            sb.AppendLine("\t\t{");

            sb.AppendLine($"\t\t\t{k.Properties[0].Name} = -1;");
            sb.AppendLine("\t\t\tbase.DataPortal_Create();");
            sb.AppendLine("\t\t}");

            //////////////////Fetch
            sb.AppendLine("");
            sb.AppendLine("\t\t[Fetch]");
            sb.AppendLine($"\t\tprivate void Fetch({ksimpleType} {k.Properties[0].Name}, [Inject]I{entityName}Dal dal)");
            sb.AppendLine("\t\t{");
            sb.AppendLine($"\t\t\tvar data = dal.Get({k.Properties[0].Name});");
            sb.AppendLine("\t\t\tusing (BypassPropertyChecks)");
            sb.AppendLine("\t\t\t{");
            sb.AppendLine("\t\t\t\tCsla.Data.DataMapper.Map(data, this);");
            sb.AppendLine("\t\t\t}");
            sb.AppendLine("\t\t\tBusinessRules.CheckRules();");
            sb.AppendLine("\t\t}");

            //////////////////Insert
            sb.AppendLine("");
            sb.AppendLine("\t\t[Insert]");
            sb.AppendLine($"\t\tprivate void Insert([Inject]I{entityName}Dal dal)");
            sb.AppendLine("\t\t{");

            sb.AppendLine("\t\t\tusing (BypassPropertyChecks)");
            sb.AppendLine("\t\t\t{");
            sb.AppendLine("\t\t\t\tvar data = new PersonEntity");
            sb.AppendLine("\t\t\t\t{");
            foreach (var property in entityProperties)
            {
                string ctype        = GetCType(property);
                var    simpleType   = ConvertToSimpleType(ctype);
                string propertyName = property.Name;

                if (propertyName != k.Properties[0].Name) //don't assign the key inside this, it is assigned to the return of insert data below
                {
                    sb.AppendLine($"\t\t\t\t\t{propertyName} = {propertyName},");
                }
            }
            sb.AppendLine("\t\t\t\t};");
            sb.AppendLine("\t\t\tvar result = dal.Insert(data);");
            sb.AppendLine($"\t\t\t{k.Properties[0].Name} = result.{k.Properties[0].Name};");

            sb.AppendLine("\t\t\t}");
            sb.AppendLine("\t\t}");

            //////////////////Update
            sb.AppendLine("");
            sb.AppendLine("\t\t[Update]");
            sb.AppendLine($"\t\tprivate void Update([Inject]I{entityName}Dal dal)");
            sb.AppendLine("\t\t{");

            sb.AppendLine("\t\t\tusing (BypassPropertyChecks)");
            sb.AppendLine("\t\t\t{");
            sb.AppendLine("\t\t\t\tvar data = new PersonEntity");
            sb.AppendLine("\t\t\t\t{");
            foreach (var property in entityProperties)
            {
                string ctype        = GetCType(property);
                var    simpleType   = ConvertToSimpleType(ctype);
                string propertyName = property.Name;

                if (propertyName != k.Properties[0].Name) //don't assign the key inside this, it is assigned to the return of insert data below
                {
                    sb.AppendLine($"\t\t\t\t\t{propertyName} = {propertyName},");
                }
            }
            sb.AppendLine("\t\t\t\t};");
            sb.AppendLine("\t\t\tvar result = dal.Update(data);");
            sb.AppendLine($"\t\t\t{k.Properties[0].Name} = result.{k.Properties[0].Name};");

            sb.AppendLine("\t\t\t}");
            sb.AppendLine("\t\t}");

            //////////////////Delete Self
            sb.AppendLine("");
            sb.AppendLine("\t\t[DeleteSelf]");
            sb.AppendLine($"\t\tprivate void DeleteSelf([Inject]I{entityName}Dal dal)");
            sb.AppendLine("\t\t{");
            sb.AppendLine($"\t\t\tDelete(ReadProperty({k.Properties[0].Name}Property), dal);");

            sb.AppendLine("\t\t}");

            //////////////////Delete
            sb.AppendLine("");
            sb.AppendLine("\t\t[Delete]");
            sb.AppendLine($"\t\tprivate void Delete({ksimpleType} {k.Properties[0].Name}, [Inject]I{entityName}Dal dal)");
            sb.AppendLine("\t\t{");
            sb.AppendLine($"\t\t\tdal.Delete({k.Properties[0].Name});");
            sb.AppendLine("\t\t}");
            sb.AppendLine($"\t}}");
            sb.AppendLine($"}}");
            return(sb.ToString());
        }
 public string QueryableName(string tableName)
 {
     return(Inflector.Plural(MemberName(tableName).FirstUpper()));
 }
Esempio n. 16
0
		public frmMain()
		{
			Predictor = new Predictor(Settings.Default.PredictorKey);
			Dictionary = new Dictionary(Settings.Default.DictionaryKey);
			Translator = new Translator(Settings.Default.TranslatorKey);
			Speller = new Speller();
			Inflector = new Inflector();

			PredictorTimer = new System.Threading.Timer(_ => UpdatePredictorResult(), null, Timeout.Infinite, Timeout.Infinite);
			DictionaryTimer = new System.Threading.Timer(_ => UpdateDictionaryResult(), null, Timeout.Infinite, Timeout.Infinite);
			TranslatorTimer = new System.Threading.Timer(_ => UpdateTranslatorResult(), null, Timeout.Infinite, Timeout.Infinite);
			SpellerTimer = new System.Threading.Timer(_ => UpdateSpellerResult(), null, Timeout.Infinite, Timeout.Infinite);
			InflectorTimer = new System.Threading.Timer(_ => UpdateInflectorResult(), null, Timeout.Infinite, Timeout.Infinite);

			InitializeComponent();

			tcServices.SelectedIndex = Settings.Default.SelectedTabIndex;

			cmbPredictorLangs.Items.AddRange(Predictor.GetLangs().Select(lang => (object)lang).ToArray());
			cmbDictionaryLangPairs.Items.AddRange(Dictionary.GetLangs().Select(lang => (object)lang).ToArray());
			cmbDictionaryLangUi.Items.Add("");
			cmbDictionaryLangUi.Items.AddRange(Predictor.GetLangs().Select(lang => (object)lang).ToArray());

			cmbPredictorLangs.SelectedItem = Enum.Parse(typeof(Lang), Settings.Default.PredictorLanguage);
			nudMaxHintCount.Value = Settings.Default.PredictorMaxHintCount;
			nudPredictorDelay.Value = Settings.Default.PredictorHintDelay;
			tbPredictorInput.Text = Settings.Default.PredictorInput;

			cmbDictionaryLangPairs.SelectedItem = new LangPair(Settings.Default.DictionaryLangPair);
			cmbDictionaryLangUi.SelectedIndex = 0;
			
			cbFamily.Checked = Settings.Default.DictionaryFamily;
			cbMorpho.Checked = Settings.Default.DictionaryMorpho;
			cbPartOfSpeech.Checked = Settings.Default.DictionaryPartOfSpeech;
			nudPredictorDelay.Value = Settings.Default.DictionaryHintDelay;
			tbDictionaryInput.Text = Settings.Default.DictionaryInput;
			cbDictionaryFormatting.Checked = Settings.Default.DictionaryFormatting;
			rbDictionaryOutput.Text = Settings.Default.DictionaryOutputIndent;

			var langArray = ((Lang[])Enum.GetValues(typeof(Lang))).Select(lang => (object)lang).ToArray();
			cmbTranslatorInputLang.Items.AddRange(langArray);
			cmbTranslatorOutputLang.Items.AddRange(langArray);
			cmbTranslatorInputLang.SelectedItem = (Lang)Enum.Parse(typeof(Lang), Settings.Default.TranslatorInputLang);
			cmbTranslatorOutputLang.SelectedItem = (Lang)Enum.Parse(typeof(Lang), Settings.Default.TranslatorOutputLang);
			nudTranslatorDelay.Value = Settings.Default.TranslatorHintDelay;
			cbTranslatorDetectInputLang.Checked = Settings.Default.TranslatorDetectInputLang;
			tbTranslatorInput.Text = Settings.Default.TranslatorInput;

			cbSpellerRu.Checked = Settings.Default.SpellerRuLang;
			cbSpellerEn.Checked = Settings.Default.SpellerEnLang;
			cbSpellerUk.Checked = Settings.Default.SpellerUkLang;
			SpellerOptions options = (SpellerOptions)Settings.Default.SpellerOptions;
			cbIgnoreUppercase.Checked = options.HasFlag(SpellerOptions.IgnoreUppercase);
			cbIgnoreDigits.Checked = options.HasFlag(SpellerOptions.IgnoreDigits);
			cbIgnoreUrls.Checked = options.HasFlag(SpellerOptions.IgnoreUrls);
			cbFindRepeatWords.Checked = options.HasFlag(SpellerOptions.FindRepeatWords);
			cbIgnoreLatin.Checked = options.HasFlag(SpellerOptions.IgnoreLatin);
			cbNoSuggest.Checked = options.HasFlag(SpellerOptions.NoSuggest);
			cbFlagLatin.Checked = options.HasFlag(SpellerOptions.FlagLatin);
			cbByWords.Checked = options.HasFlag(SpellerOptions.ByWords);
			cbIgnoreCapitalization.Checked = options.HasFlag(SpellerOptions.IgnoreCapitalization);
			nudSpellerDelay.Value = Settings.Default.SpellerHintDelay;
			tbSpellerInput.Text = Settings.Default.SpellerInput;
			cbIncludeErrorWords.Checked = Settings.Default.SpellerIncludeErrorWords;

			tbInflectorInput.Text = Settings.Default.InflectorInput;

			tbPredictorKey.Text = Settings.Default.PredictorKey;
			tbDictionaryKey.Text = Settings.Default.DictionaryKey;
			tbTranslatorKey.Text = Settings.Default.TranslatorKey;
			tbPredictorBaseUrl.Text = Settings.Default.PredictorBaseUrl;
			tbDictionaryBaseUrl.Text = Settings.Default.DictionaryBaseUrl;
			tbTranslatorBaseUrl.Text = Settings.Default.TranslatorBaseUrl;
			tbSpellerBaseUrl.Text = Settings.Default.SpellerBaseUrl;
			tbInflectorBaseUrl.Text = Settings.Default.InflectorBaseUrl;
		}
Esempio n. 17
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;
            model.PrimaryStoreCurrencyCode = Services.StoreContext.CurrentStore.PrimaryStoreCurrency.CurrencyCode;

            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;

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

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

            if (!String.IsNullOrEmpty(carrierServicesOfferedDomestic))
            {
                foreach (string service in services.Services)
                {
                    var 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));
        }
Esempio n. 18
0
        internal string GenerateRazor(string baseNamespace, string namespacePostfix, IEntityType entity, string AuthorizeRoles)
        {
            var    sb          = new StringBuilder();
            string entityName  = Inflector.Humanize(entity.ClrType.Name);
            var    k           = entity.FindPrimaryKey();
            var    kctype      = k.Properties[0].ClrType;
            var    primaryKey  = entity.FindPrimaryKey();
            var    ksimpleType = ConvertToSimpleType(kctype.Name);

            // Header area directives

            #region HeaderDirectives

            sb.AppendLine($"@page \"/Edit{entityName}\"");
            sb.AppendLine($"@page \"/EditPerson/{{{primaryKey.Properties[0].Name}}}\"");
            sb.AppendLine(string.IsNullOrWhiteSpace(namespacePostfix) ? $"@using {baseNamespace}.Shared" : $"@using {baseNamespace}.Shared.{namespacePostfix}");

            sb.AppendLine($"@inject Csla.Blazor.ViewModel<{entityName}Edit> vm");
            sb.AppendLine($"@inject NavigationManager NavigationManager");
            if (AuthorizeRoles != null && AuthorizeRoles.Any())
            {
                sb.AppendLine($"@attribute [Authorize(Roles = \"{AuthorizeRoles}\")]");
            }

            #endregion HeaderDirectives

            // Begin page body

            #region PageBody

            sb.AppendLine($"<h1>Edit {entityName}</h1>");
            sb.AppendLine($"");
            sb.AppendLine($"<p>This component demonstrates editing a BusinessBase-derived object.</p>");
            sb.AppendLine($"");
            sb.AppendLine($"<p style=\"background-color:red; color: white\">@vm.ViewModelErrorText</p>");
            sb.AppendLine($"");

            // Loading
            sb.AppendLine($"@if (vm.Model == null)");
            sb.AppendLine($"{{");
            sb.AppendLine($"\t\t<p>Loading {entityName}...</p>");
            sb.AppendLine($"}}");

            sb.AppendLine($"else");
            // Beginning of loading else
            sb.AppendLine($"{{");

            // Link back to index
            sb.AppendLine($"\t<p>");
            sb.AppendLine($"\t<a href=\"list{Inflector.Pluralize(entityName)}\">List of {Inflector.Pluralize(entityName)}</a>");
            sb.AppendLine($"\t</p>");
            sb.AppendLine($"");

            // Edit Table
            sb.AppendLine($"\t<table class=\"table\">");
            sb.AppendLine($"\t<thead>");
            sb.AppendLine($"\t\t<tr>");
            sb.AppendLine($"\t\t\t<th></th>");
            sb.AppendLine($"\t\t\t<th></th>");
            sb.AppendLine($"\t\t</tr>");
            sb.AppendLine($"\t</thead>");
            sb.AppendLine($"\t<tbody>");

            // begin iterate through properties for table
            var entityProperties = entity.GetProperties();
            foreach (var property in entityProperties)
            {
                string ctype        = GetCType(property);
                var    simpleType   = ConvertToSimpleType(ctype);
                string propertyName = property.Name;

                if (propertyName == k.Properties[0].Name)
                {
                    //key
                    sb.AppendLine($"\t\t<tr>");
                    sb.AppendLine($"\t\t<td>{k.Properties[0].Name}</td>");
                    sb.AppendLine($"\t\t<td>@vm.Model.{k.Properties[0].Name}</td>");
                    sb.AppendLine($"\t\t</tr>");
                    sb.AppendLine($"\t\t");
                }
                else
                {
                    //non key
                    sb.AppendLine($"\t@if(vm.GetPropertyInfo(nameof(vm.Model.{propertyName})).CanRead)");
                    sb.AppendLine($"\t{{");
                    sb.AppendLine($"\t\t<tr>");
                    sb.AppendLine("\t\t<td>@(vm.GetPropertyInfo(nameof(vm.Model.Name)).FriendlyName)</td>");
                    sb.AppendLine($"\t\t<td>");
                    sb.AppendLine($"\t\t<TextInput Property = \"@(vm.GetPropertyInfo(nameof(vm.Model.{propertyName})))\"/>");
                    sb.AppendLine($"\t\t</td>");
                    sb.AppendLine($"\t\t</tr>");
                    sb.AppendLine($"");
                    sb.AppendLine($"\t}}");
                }
            }

            sb.AppendLine($"");

            // Is new
            sb.AppendLine($"\t<tr>");
            sb.AppendLine($"\t\t<td>Is New</td>");
            sb.AppendLine($"\t\t<td>@vm.Model.IsNew</td>");
            sb.AppendLine($"\t</tr>");
            sb.AppendLine($"");

            // Is savable
            sb.AppendLine($"\t<tr>");
            sb.AppendLine($"\t\t<td>Is Savable</td>");
            sb.AppendLine($"\t\t<td>@vm.Model.IsSavable</td>");
            sb.AppendLine($"\t</tr>");
            sb.AppendLine($"");

            sb.AppendLine($"\t</tbody>");
            sb.AppendLine($"\t</table>");

            // Save buuton
            sb.AppendLine($"");
            sb.AppendLine($"\t<button @onclick=\"vm.SaveAsync\" disabled=\"@(!vm.Model.IsSavable)\">Save {entityName}</button>");

            // End of loading else
            sb.AppendLine($"}}");

            #endregion PageBody

            GenerateRazorCodeSection(sb, entity);
            return(sb.ToString());
        }
Esempio n. 19
0
 public string Camelize() => Inflector.Camelize("aaa_bbb_ccc_ddd");
Esempio n. 20
0
        private void GenerateRazorCodeSection(StringBuilder sb, IEntityType entity)
        {
            var primaryKey           = entity.FindPrimaryKey();
            var primaryKeyCType      = primaryKey.Properties[0].ClrType;
            var primatyKeySimpleType = ConvertToSimpleType(primaryKeyCType.Name);

            // Beginning code section declaration
            sb.AppendLine($"@code {{");

            // Parameter
            sb.AppendLine("\t[Parameter]");

            // In the original razor page, the parameter was declared as a string even though the key type was int
            // May want to revisit this
            sb.AppendLine($"\tpublic string {primaryKey.Properties[0].Name} {{ get; set; }}");

            // OnInitialized
            sb.AppendLine($"\tprotected override void OnInitialized()");
            sb.AppendLine("\t{");
            sb.AppendLine($"\t\tvm.Saved += () => NavigationManager.NavigateTo(\"list{ Inflector.Pluralize(entity.ClrType.Name) }\");");
            sb.AppendLine("\t\tvm.ModelChanging += (o, n) =>");
            sb.AppendLine($"\t\t{{");
            sb.AppendLine("\t\t\tif (o != null)");
            sb.AppendLine("\t\t\t\to.PropertyChanged -= async (s, e) => await InvokeAsync(() => StateHasChanged());");
            sb.AppendLine("\t\t\tif (n != null)");
            sb.AppendLine("\t\t\t\tn.PropertyChanged += async (s, e) => await InvokeAsync(() => StateHasChanged());");

            sb.AppendLine("");
            sb.AppendLine($"\t\t}};");

            sb.AppendLine($"\t}}");

            // OnParametersSetAsync
            sb.AppendLine($"\tprotected override async Task OnParametersSetAsync()");
            sb.AppendLine("\t{");
            sb.AppendLine($"\t\tif (string.IsNullOrWhiteSpace({primaryKey.Properties[0].Name}))");
            sb.AppendLine("\t\t\tawait vm.RefreshAsync();");
            sb.AppendLine("\t\telse");
            sb.AppendLine($"\t\t\tawait vm.RefreshAsync(int.Parse({primaryKey.Properties[0].Name}));");
            sb.AppendLine("");

            sb.AppendLine($"\t}}");

            // End code section declaration
            sb.AppendLine($"}}");
        }
        public List <RawStoredProcedure> ReadStoredProcs(bool includeSynonyms)
        {
            if (DatabaseReaderPlugin != null)
            {
                return(DatabaseReaderPlugin.ReadStoredProcs());
            }

            var result = new List <RawStoredProcedure>();

            using (var conn = _factory.CreateConnection())
            {
                if (conn == null)
                {
                    return(result);
                }

                conn.ConnectionString = Settings.ConnectionString;
                conn.Open();

                var storedProcedureSQL = StoredProcedureSQL();
                if (string.IsNullOrEmpty(storedProcedureSQL))
                {
                    return(result);
                }

                var cmd = GetCmd(conn);
                if (cmd == null)
                {
                    return(result);
                }

                if (includeSynonyms)
                {
                    cmd.CommandText = SynonymStoredProcedureSQLSetup() + storedProcedureSQL + SynonymStoredProcedureSQL() + SpecialQueryFlags();
                }
                else
                {
                    cmd.CommandText = storedProcedureSQL + SpecialQueryFlags();
                }

                using (var rdr = cmd.ExecuteReader())
                {
                    while (rdr.Read())
                    {
                        var schema         = rdr["SPECIFIC_SCHEMA"].ToString().Trim();
                        var name           = rdr["SPECIFIC_NAME"].ToString().Trim();
                        var routineType    = rdr["ROUTINE_TYPE"].ToString().Trim().ToLower();
                        var returnDataType = rdr["RETURN_DATA_TYPE"].ToString().Trim().ToLower();
                        var dataType       = rdr["DATA_TYPE"].ToString().Trim().ToLower();
                        var parameterMode  = rdr["PARAMETER_MODE"].ToString().Trim().ToLower();

                        var isTableValuedFunction  = (routineType == "function" && returnDataType == "table");
                        var isScalarValuedFunction = (routineType == "function" && returnDataType != "table");
                        var isStoredProcedure      = (routineType == "procedure");

                        StoredProcedureParameter parameter = null;
                        if (rdr["DATA_TYPE"] != null && rdr["DATA_TYPE"] != DBNull.Value)
                        {
                            parameter = new StoredProcedureParameter
                            {
                                Ordinal             = (int)rdr["ORDINAL_POSITION"],
                                Name                = rdr["PARAMETER_NAME"].ToString().Trim(),
                                SqlDbType           = GetStoredProcedureParameterDbType(dataType),
                                ReturnSqlDbType     = GetStoredProcedureParameterDbType(returnDataType),
                                PropertyType        = GetPropertyType(dataType),
                                ReturnPropertyType  = GetPropertyType(returnDataType),
                                DateTimePrecision   = (short)rdr["DATETIME_PRECISION"],
                                MaxLength           = (int)rdr["CHARACTER_MAXIMUM_LENGTH"],
                                Precision           = (byte)rdr["NUMERIC_PRECISION"],
                                Scale               = (int)rdr["NUMERIC_SCALE"],
                                UserDefinedTypeName = rdr["USER_DEFINED_TYPE"].ToString().Trim(),
                                IsSpatial           = SpatialTypes.Contains(dataType)
                            };

                            switch (parameterMode)
                            {
                            case "in":
                                parameter.Mode = StoredProcedureParameterMode.In;
                                break;

                            case "out":
                                parameter.Mode = StoredProcedureParameterMode.Out;
                                break;

                            default:
                                parameter.Mode = StoredProcedureParameterMode.InOut;
                                break;
                            }

                            var clean = CleanUp(parameter.Name.Replace("@", string.Empty));
                            if (!string.IsNullOrEmpty(clean))
                            {
                                parameter.NameHumanCase = Inflector.MakeInitialLower((Settings.UsePascalCase ? Inflector.ToTitleCase(clean) : clean).Replace(" ", ""));

                                if (ReservedKeywords.Contains(parameter.NameHumanCase))
                                {
                                    parameter.NameHumanCase = "@" + parameter.NameHumanCase;
                                }
                            }
                        }

                        var rsp = new RawStoredProcedure(schema, name, isTableValuedFunction, isScalarValuedFunction, isStoredProcedure, parameter);
                        result.Add(rsp);
                    }
                }
            }
            return(result);
        }
Esempio n. 22
0
 /// <summary>
 /// 把单数单词转化为复数单词
 /// </summary>
 /// <param name="str"></param>
 /// <returns></returns>
 public static string Plural(string str)
 {
     return(Inflector.Plural(str));
 }
        public Column CreateColumn(RawTable rt, Table table, IDbContextFilter filter)
        {
            var col = new Column
            {
                Scale               = rt.Scale,
                PropertyType        = GetPropertyType(rt.TypeName),
                SqlPropertyType     = rt.TypeName,
                IsNullable          = rt.IsNullable,
                MaxLength           = rt.MaxLength,
                DateTimePrecision   = rt.DateTimePrecision,
                Precision           = rt.Precision,
                IsIdentity          = rt.IsIdentity,
                IsComputed          = rt.IsComputed,
                IsRowGuid           = rt.IsRowGuid,
                GeneratedAlwaysType = (ColumnGeneratedAlwaysType)rt.GeneratedAlwaysType,
                IsStoreGenerated    = rt.IsStoreGenerated,
                PrimaryKeyOrdinal   = rt.PrimaryKeyOrdinal,
                IsPrimaryKey        = rt.PrimaryKey,
                IsForeignKey        = rt.IsForeignKey,
                IsSpatial           = rt.TypeName == "geography" || rt.TypeName == "geometry",
                Ordinal             = rt.Ordinal,
                DbName              = rt.ColumnName,
                Default             = rt.Default,
                ParentTable         = table,
                ExistsInBaseClass   = false
            };

            if (col.MaxLength == -1 && (col.SqlPropertyType.EndsWith("varchar", StringComparison.InvariantCultureIgnoreCase) ||
                                        col.SqlPropertyType.EndsWith("varbinary", StringComparison.InvariantCultureIgnoreCase)))
            {
                col.SqlPropertyType += "(max)";
            }

            if (col.IsPrimaryKey && !col.IsIdentity && col.IsStoreGenerated && rt.TypeName == "uniqueidentifier")
            {
                col.IsStoreGenerated = false;
                col.IsIdentity       = true;
            }

            if (!col.IsPrimaryKey && filter.IsExcluded(col))
            {
                col.Hidden = true;
            }

            col.IsFixedLength = (rt.TypeName == "char" || rt.TypeName == "nchar");
            col.IsUnicode     = !(rt.TypeName == "char" || rt.TypeName == "varchar" || rt.TypeName == "text");
            col.IsMaxLength   = (rt.TypeName == "ntext");

            col.IsRowVersion = col.IsStoreGenerated && !col.IsNullable && rt.TypeName == "timestamp";
            if (col.IsRowVersion)
            {
                col.MaxLength = 8;
            }

            if (rt.TypeName == "hierarchyid")
            {
                col.MaxLength = 0;
            }

            col.CleanUpDefault();
            col.NameHumanCase = CleanUp(col.DbName);
            if (string.IsNullOrWhiteSpace(col.NameHumanCase))
            {
                col.NameHumanCase = "Unknown";
                col.Hidden        = true;
            }
            col.NameHumanCase = ReservedColumnNames.Replace(col.NameHumanCase, "_$1");

            if (ReservedKeywords.Contains(col.NameHumanCase))
            {
                col.NameHumanCase = "@" + col.NameHumanCase;
            }

            col.DisplayName = Column.ToDisplayName(col.DbName);

            var titleCase = (Settings.UsePascalCase ? Inflector.ToTitleCase(col.NameHumanCase) : col.NameHumanCase).Replace(" ", string.Empty);

            if (titleCase != string.Empty)
            {
                col.NameHumanCase = titleCase;
            }

            // Make sure property name doesn't clash with class name
            if (col.NameHumanCase == table.NameHumanCase)
            {
                col.NameHumanCase += "_";
            }

            if (char.IsDigit(col.NameHumanCase[0]))
            {
                col.NameHumanCase = "_" + col.NameHumanCase;
            }

            table.HasNullableColumns = col.IsColumnNullable();

            // If PropertyType is empty, return null. Most likely ignoring a column due to legacy (such as OData not supporting spatial types)
            if (string.IsNullOrEmpty(col.PropertyType))
            {
                return(null);
            }

            return(col);
        }
Esempio n. 24
0
 /// <summary>
 /// 把复数单词转换为单数单词
 /// </summary>
 /// <param name="str"></param>
 /// <returns></returns>
 public static string Singular(string str)
 {
     return(Inflector.Singular(str));
 }
Esempio n. 25
0
 private void tbInflectorBaseUrl_TextChanged(object sender, EventArgs e)
 {
     Inflector = new Inflector(tbInflectorBaseUrl.Text);
     tbInflectorInput_TextChanged(sender, e);
 }
        /// <summary>
        /// Checks the pascal case.
        /// </summary>
        /// <param name="evalString">The eval string.</param>
        /// <param name="correctString">The correct string.</param>
        /// <param name="removeUnderscores">if set to <c>true</c> [remove underscores].</param>
        private static void CheckPascalCase(string evalString, string correctString, bool removeUnderscores)
        {
            string transform = Inflector.ToPascalCase(evalString, removeUnderscores);

            Assert.IsTrue(transform == correctString, evalString + " (remove underscores: " + removeUnderscores + ") - Should be: " + correctString + " - Actually is: " + transform);
        }
 public static string Handleize(string input)
 {
     return(Inflector.Handleize(input.EmptyNull()));
 }
 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. 29
0
        public void SetUp()
        {
            var types     = new[] { typeof(User), typeof(ExtraUserInfo), typeof(UserWithExtraInfo), typeof(Usersss), typeof(House), typeof(Supervisor) };
            var dbFactory = new DatabaseFactory();
            //DatabaseFactory.ColumnSerializer = new JsonNetColumnSerializer();
            var config = FluentMappingConfiguration.Scan(s =>
            {
                s.Assembly(typeof(User).GetTypeInfo().Assembly);
                s.IncludeTypes(types.Contains);
                s.PrimaryKeysNamed(y => ToLowerIf(y.Name + "Id", false));
                s.TablesNamed(y => ToLowerIf(Inflector.MakePlural(y.Name), false));
                s.Columns.Named(x => ToLowerIf(x.Name, false));
                s.Columns.ForceDateTimesToUtcWhere(x => x.GetMemberInfoType() == typeof(DateTime) || x.GetMemberInfoType() == typeof(DateTime?));
                s.Columns.ResultWhere(y => ColumnInfo.FromMemberInfo(y).ResultColumn);
                s.OverrideMappingsWith(new FluentMappingOverrides());
                s.OverrideMappingsWith(new OneToManyMappings());
            });

            dbFactory.Config().WithFluentConfig(config);

            var configuration = new ConfigurationBuilder()
                                .AddJsonFile("config.json")
                                .Build();

            var testDBType = Convert.ToInt32(configuration.GetSection("TestDBType").Value);

            switch (testDBType)
            {
            case 1:     // SQLite In-Memory
                TestDatabase = new InMemoryDatabase();
                Database     = dbFactory.Build(new Database(TestDatabase.Connection));
                break;

            case 2:     // SQL Local DB
            case 3:     // SQL Server
                var dataSource = configuration.GetSection("TestDbDataSource").Value;
                TestDatabase = new SQLLocalDatabase(dataSource);
                Database     = dbFactory.Build(new Database(TestDatabase.Connection, new SqlServer2008DatabaseType()));
                break;

            case 4:     // SQL CE
            case 5:     // MySQL
            case 6:     // Oracle
            case 7:     // Postgres
                Assert.Fail("Database platform not supported for unit testing");
                return;

#if !DNXCORE50
            case 8:     // Firebird
                TestDatabase = new FirebirdDatabase();
                var db = new Database(TestDatabase.Connection, new FirebirdDatabaseType());
                db.Mappers.Insert(0, new FirebirdDefaultMapper());
                Database = dbFactory.Build(db);
                break;
#endif

            default:
                Assert.Fail("Unknown database platform specified");
                return;
            }

            InsertData();
        }
        public override TemplateOutput Generate()
        {
            TemplateOutput retVal = new TemplateOutput();

            try
            {
                foreach (var entity in ProcessModel.MetadataSourceModel.EntityTypes)
                {
                    string outputfile = TemplateVariablesManager.GetOutputFile(templateIdentity: ProcessModel.TemplateIdentity,
                                                                               fileName: Consts.OUT_webApiController);
                    outputfile = outputfile.Replace("[tablename]", Inflector.Humanize(entity.ClrType.Name)).Replace("[tablepluralname]", Inflector.Pluralize(entity.ClrType.Name));
                    string filepath = outputfile;

                    var maxRequestPerPageOverrides =
                        DeserializeJsonObject <List <NameValue> >(MaxRequestPerPageOverrideByTableName);

                    if (maxRequestPerPageOverrides == null)
                    {
                        maxRequestPerPageOverrides = new List <NameValue>();
                    }

                    string baseControllerName = $"{NamespacePostfix}BaseApiController";

                    if (UseAuthorizedBaseController) //!string.IsNullOrEmpty(UseAuthorizedBaseController) && UseAuthorizedBaseController.ToLowerInvariant() == "true")
                    {
                        baseControllerName = $"{NamespacePostfix}BaseApiControllerAuthorized";
                    }

                    WebApiControllerGenerator webApiControllerGenerator = new WebApiControllerGenerator(inflector: Inflector);
                    string generatedCode = webApiControllerGenerator.GenerateWebApiController(
                        baseNamespace: BaseNamespace,
                        namespacePostfix: NamespacePostfix,
                        classNamespace: WebApiControllerNamespace,
                        baseControllerName: baseControllerName,
                        apiHelpersNamespace: ApiHelpersNamespace,
                        iLoggingServiceNamespace: ILoggingServiceNamespace,
                        repositoryNamespace: RepositoryNamespace,
                        factoryNamespace: FactoryNamespace,
                        efEntityNamespacePrefix: $"ent{NamespacePostfix}",
                        efEntityNamespace: RepositoryEntitiesNamespace,
                        dtoNamespacePrefix: $"dto{NamespacePostfix}",
                        dtoNamespace: DtoNamespace,
                        enumNamespace: EnumNamespace,
                        repositoryInterfaceName: $"I{NamespacePostfix}Repository",
                        dbContextName: DbContextName,
                        maxRequestPerPageOverrides: maxRequestPerPageOverrides,
                        prependSchemaNameIndicator: PrependSchemaNameIndicator,
                        entity: entity,
                        excludedNavigationProperties: ProcessModel.ExcludedNavigationProperties
                        );

                    retVal.Files.Add(new OutputFile()
                    {
                        Content = generatedCode,
                        Name    = filepath
                    });
                }
            }
            catch (Exception ex)
            {
                base.AddError(ref retVal, ex, Enums.LogLevel.Error);
            }

            AddTemplateVariablesManagerErrorsToRetVal(ref retVal, Enums.LogLevel.Error);
            return(retVal);
        }
Esempio n. 31
0
		private void tbInflectorBaseUrl_TextChanged(object sender, EventArgs e)
		{
			Inflector = new Inflector(tbInflectorBaseUrl.Text);
			tbInflectorInput_TextChanged(sender, e);
		}
Esempio n. 32
0
        /// <summary>
        /// Deletes the subtopic.
        /// </summary>
        /// <param name="subtopic">The subtopic.</param>
        public void DeleteSubtopic(object subtopic)
        {
            var vm = subtopic as SubTopicViewModel;

            if (vm == null)
            {
                return;
            }
            var count    = 0;
            var measures = new List <MeasureTopic>();

            // query to find out if this subtopic is assigned to any measures
            var dataServiceProvider = ServiceLocator.Current.GetInstance <IDomainSessionFactoryProvider>();

            using (var session = dataServiceProvider.SessionFactory.OpenSession())
            {
                measures = session.Query <MeasureTopic>().Where(m => m.Measure != null && m.Measure.Id == vm.Entity.Id).ToList();
                count    = session.Query <MeasureTopic>().Count(m => m.Measure != null && m.Measure.Id == vm.Entity.Id);
                //measures = session.Query<Measure>().Where(m => m.Topics.Any(t => t.Id == vm.Entity.Id)).ToList();
            }

            var warningMessage = count > 0
                ? string.Format(
                "Are you sure you want to delete this subtopic:\n\n{0} \n\nDeleting it will also remove it from the {1} measure(s) in which it is used.",
                vm.SubtopicName, count)
                : string.Format(
                "Are you sure you want to delete this subtopic:\n\n{0} \n\nThis subtopic is not currently used by any measures, it is safe to delete.",
                vm.SubtopicName);

            // Prompt user to confirm delete
            //TODO add normal pop-up
            if (
                MessageBox.Show(warningMessage, @"Delete Subtopic?", MessageBoxButton.YesNo, MessageBoxImage.Question) !=
                MessageBoxResult.Yes)
            {
                return;
            }

            var deleteStatement =
                string.Format("Delete from {0}_MeasureTopics Where Measure_Id in ({1}) and Topic_Id = {2}",
                              Inflector.Pluralize(typeof(Measure).Name), string.Join(",", measures.Select(x => x.Id)),
                              vm.Entity.Id);
            var name = vm.SubtopicName;

            try
            {
                using (var session = dataServiceProvider.SessionFactory.OpenSession())
                {
                    using (var trx = session.BeginTransaction())
                    {
                        if (count > 0)
                        {
                            session.CreateSQLQuery(deleteStatement).ExecuteUpdate();
                        }
                        session.Delete(vm.Entity);
                        trx.Commit();
                    }
                }
                EventAggregator.GetEvent <GenericNotificationEvent>().Publish(string.Format("{0} has been deleted.", name));
            }
            catch (Exception exec)
            {
                Logger.Write(exec);
            }

            RaiseErrorsChanged(() => SubtopicName);
            Events.GetEvent <TopicsUpdatedEvent>().Publish(1);
        }
Esempio n. 33
0
        public void EnglishCulture()
        {
            var inflector = new Inflector(new CultureInfo("en"));

            Assert.AreEqual("cats", inflector.Pluralize("cat"));
        }
Esempio n. 34
0
 public string Pascalize() => Inflector.Pascalize("aaa_bbb_ccc_ddd");
		public void Init()
		{
			Inflector = new Inflector();
		}
 public string Singularize(string identifier)
 {
     return(Inflector.Singularize(identifier) ?? identifier);
 }