protected override void GetReport(StringBuilder r) { if (Smart.IsValid) { Kernel32.SMART_ATTRIBUTE[] values = Smart.ReadSmartData(); Kernel32.SMART_THRESHOLD[] thresholds = Smart.ReadSmartThresholds(); if (values.Length > 0) { r.AppendFormat(CultureInfo.InvariantCulture, " {0}{1}{2}{3}{4}{5}{6}{7}", "Id".PadRight(3), "Description".PadRight(35), "Raw Value".PadRight(13), "Worst".PadRight(6), "Value".PadRight(6), "Threshold".PadRight(6), "Physical".PadRight(8), Environment.NewLine); foreach (Kernel32.SMART_ATTRIBUTE value in values) { if (value.Id == 0x00) { break; } byte?threshold = null; foreach (Kernel32.SMART_THRESHOLD t in thresholds) { if (t.Id == value.Id) { threshold = t.Threshold; } } string description = "Unknown"; float? physical = null; foreach (SmartAttribute a in SmartAttributes) { if (a.Id == value.Id) { description = a.Name; if (a.HasRawValueConversion | a.SensorType.HasValue) { physical = a.ConvertValue(value, null); } else { physical = null; } } } string raw = BitConverter.ToString(value.RawValue); r.AppendFormat(CultureInfo.InvariantCulture, " {0}{1}{2}{3}{4}{5}{6}{7}", value.Id.ToString("X2").PadRight(3), description.PadRight(35), raw.Replace("-", string.Empty).PadRight(13), value.WorstValue.ToString(CultureInfo.InvariantCulture).PadRight(6), value.CurrentValue.ToString(CultureInfo.InvariantCulture).PadRight(6), (threshold.HasValue ? threshold.Value.ToString(CultureInfo.InvariantCulture) : "-").PadRight(6), (physical.HasValue ? physical.Value.ToString(CultureInfo.InvariantCulture) : "-").PadRight(8), Environment.NewLine); } r.AppendLine(); } } }
public virtual string GetPredicate(IEnumerable <IProperty> properties) { return(Smart.Format("x => {0:x.{Name} == {Name:fctl()}| && }", properties)); }
public virtual void ProcessEntityCollection(IScriptContext scriptContext, IEnumerable <IEntityType> entityTypes, string collectionName) { IEnumerable <IEntityType> enumerable = entityTypes as IList <IEntityType> ?? entityTypes.ToList(); scriptContext.Logger.WriteDebug( $"Processing entity collection '{string.Join(", ", enumerable.Select(x => x.Name))}'."); scriptContext.Output.CurrentGeneratedFileName.FileNameWithoutExtension = collectionName; IFileWriter fileWriter = scriptContext.Output.Current; fileWriter.WriteLine(Header).WriteLine(); using (fileWriter.WriteScope($"namespace {Namespace}")) { fileWriter.WriteLine("using System;").WriteLine("using System.Linq;") .WriteLine("using System.Linq.Expressions;") .WriteLine("using System.Collections.Generic;"); foreach (string entityTypeNamespace in enumerable.Select(x => x.ClrType.Namespace).Distinct()) { fileWriter.WriteLine($"using {entityTypeNamespace};"); } fileWriter.WriteLine(); ISet <IEnumerable <IProperty> > addedFunctions = new HashSet <IEnumerable <IProperty> >(); using (fileWriter.WriteScope(Smart.Format(RepositoryClassHeader, new { Name = collectionName }))) { using (fileWriter.WriteScope(Smart.Format(RepositoryConstructorHeader, new { Name = collectionName }))) { fileWriter.WriteLine(Smart.Format(RepositoryConstructorBody, new { Name = collectionName })); } foreach (IEntityType entityType in enumerable) { WriteBasicFunctions(fileWriter, entityType, true); IKey primaryKey = entityType.FindPrimaryKey(); ProcessPrimaryKey(addedFunctions, fileWriter, entityType, primaryKey, true); foreach (IIndex index in entityType.GetIndexes()) { ProcessIndex(addedFunctions, fileWriter, entityType, index, true); } foreach (IForeignKey foreignKey in entityType.GetForeignKeys()) { ProcessForeignKey(addedFunctions, fileWriter, entityType, foreignKey, true); } foreach (IProperty property in entityType.GetProperties()) { ProcessProperty(addedFunctions, fileWriter, entityType, property, true); } } } } }
public virtual string GetEntityType(IEntityType entityType) { return(Smart.Format("{ClrType.Name}", entityType)); }
public virtual string GetFunctionNameParameter(IEnumerable <IProperty> properties, bool pluralize = false) { return(Smart.Format(!pluralize ? "{0:{Name}|And}" : "{0:{Name:pluralize()}|And}", properties)); }
public void Choose_should_work_with_enums(string format, object arg0, string expectedResult) { Assert.AreEqual(expectedResult, Smart.Format(format, arg0)); }
public void Choose_throws_when_choice_is_invalid(string format, object arg0) { Smart.Default.Settings.FormatErrorAction = ErrorAction.ThrowError; Assert.Throws <FormattingException>(() => Smart.Format(format, arg0)); }
public void NamedFormatter_should_use_specific_language(string format, object arg0, string expectedResult) { var actualResult = Smart.Format(format, arg0); Assert.AreEqual(expectedResult, actualResult); }
public void Error(string message, params object[] args) { log.Error(args.Length == 0 ? message : Smart.Format(message, args)); }
public void Syntax_should_not_be_confused_with_named_formatters(string format, object arg0, string expectedOutput) { var actualOutput = Smart.Format(format, arg0); Assert.AreEqual(expectedOutput, actualOutput); }
public void SetupSmart() { this.smart = Smart.CreateDefaultSmartFormat(); RegisterTemplates(this.smart); }
private void EntityTypeCreator(IEntityType entityType) { string file = null; using (StreamReader sr = new StreamReader("./CodeTemplates/EntityTypeTemplate.txt")) { file = sr.ReadToEnd(); } var entityClassName = EntityListFormatter.GetNakedNameOfIEntityType(entityType); var filePath = $"{filePathRoot}/{entityClassName}"; var className = EntityListFormatter.GetNameOfIEntityType(entityType); var classNameNameSpace = entityType.ClrType.Namespace; var primaryKey = entityType.FindPrimaryKey(); Directory.CreateDirectory(filePath); foreach (var property in entityType.GetProperties()) { PropertyCreator(property, filePath, className, classNameNameSpace, entityClassName); } foreach (var key in entityType.GetKeys()) { KeyCreator(key, filePath, entityClassName); } foreach (var index in entityType.GetIndexes()) { CreateIndex(index, filePath, entityClassName); } foreach (var serviceProperty in entityType.GetServiceProperties()) { ServicePropertyCreator(serviceProperty, filePath, entityClassName); } foreach (var foreignKey in entityType.GetForeignKeys()) { ForeignKeyCreator(foreignKey, filePath, entityClassName); } foreach (var navigation in entityType.GetNavigations()) { NavigationCreator(navigation, filePath, entityClassName); } var fileText = Smart.Format(file, new { Namespace = namespaceString, ClassName = className, ClassNamespace = classNameNameSpace, EntityName = entityType.Name, Annotations = entityType.GetAnnotations(), Keys = entityType.GetKeys(), ServiceProperties = entityType.GetServiceProperties(), ForeignKeys = entityType.GetForeignKeys(), Properties = entityType.GetProperties(), Indexes = entityType.GetIndexes(), ConfigurationSource = ((Key)primaryKey).GetConfigurationSource(), PrimaryKeyProperties = primaryKey.Properties, EntityClassName = entityClassName, QueryFilter = entityType.QueryFilter, DefiningQuery = entityType.DefiningQuery, DefiningNavigationName = entityType.DefiningNavigationName ?? "null", DefiningEntityType = entityType.DefiningEntityType == null ?"null":string.Format("{0}.GetInstance()", EntityListFormatter.GetNameOfIEntityType(entityType.DefiningEntityType)), IsQueryType = entityType.IsQueryType?"true":"false", BaseType = entityType.BaseType != null? string.Format("{0}.GetInstance()", EntityListFormatter.GetNameOfIEntityType(entityType.BaseType)):"null" } ); File.WriteAllText($"{filePath}/{className}.cs", fileText); }
private void PropertyCreator(IProperty propertyType, string filePath, string entityType, string classNameNameSpace, string entityClassName) { string file = null; using (StreamReader sr = new StreamReader("./CodeTemplates/PropertyTypeTemplate.txt")) { file = sr.ReadToEnd(); } var className = String.Format("{0}PropertyType", propertyType.Name); if (className == "TourSubcategoryIdPropertyType") { } string PropertyClrType1FullName; if (propertyType.ClrType.IsEnum) { PropertyClrType1FullName = string.Format("typeof({0})", propertyType.ClrType.FullName); } else { PropertyClrType1FullName = string.Format("Type.GetType(\"{0}\")", propertyType.ClrType.FullName); } string PropertyClrTypeFullName; if (((IPropertyBase)propertyType).ClrType.IsEnum) { PropertyClrTypeFullName = string.Format("typeof({0})", ((IPropertyBase)propertyType).ClrType.FullName); } else { PropertyClrTypeFullName = string.Format("Type.GetType(\"{0}\")", ((IPropertyBase)propertyType).ClrType.FullName); } var fileText = Smart.Format(file, new { Name = propertyType.Name, IsNullable = propertyType.IsNullable, IsReadOnlyBeforeSave = propertyType.IsReadOnlyBeforeSave, IsReadOnlyAfterSave = propertyType.IsReadOnlyAfterSave, IsStoreGeneratedAlways = propertyType.IsStoreGeneratedAlways, IsConcurrencyToken = propertyType.IsConcurrencyToken, AfterSaveBehavior = propertyType.AfterSaveBehavior, BeforeSaveBehavior = propertyType.BeforeSaveBehavior, ValueGenerated = propertyType.ValueGenerated, Namespace = namespaceString, ClassName = className, ClassNamespace = classNameNameSpace, EntityType = entityType, DeclaringType = propertyType.DeclaringType, DeclaringTypeAnnotations = propertyType.GetAnnotations(), PropertyClrType1FullName = PropertyClrType1FullName, IsShadowProperty1 = propertyType.IsShadowProperty, PropertyClrTypeFullName = PropertyClrTypeFullName, IsShadowProperty = ((IPropertyBase)propertyType).IsShadowProperty, EntityClassName = entityClassName, }); File.WriteAllText($"{filePath}/{className}.cs", fileText); }
public override void Close() { Smart.Close(); base.Close(); }
public void Choose_should_be_case_sensitive(string format, object arg0, string expectedResult) { Assert.AreEqual(expectedResult, Smart.Format(format, arg0)); }
public void Error(Exception e, string message, params object[] args) { log.Error(args.Length == 0 ? message : Smart.Format(message, args) + $"\n{e.Message}\n{e.StackTrace}"); }
public void Choose_should_default_to_the_last_item(string format, object arg0, string expectedResult) { Assert.AreEqual(expectedResult, Smart.Format(format, arg0)); }
public static string GetNYearsAgoText(int value) { return(Smart.Format(AppSettings.CurrentCultureInfo, Instance._yearsAgo.Text, value, Math.Abs(value))); }
public void Choose_has_a_special_case_for_null(string format, object arg0, string expectedResult) { Assert.AreEqual(expectedResult, Smart.Format(format, arg0)); }
public bool TryEvaluateFormat(IFormattingInfo formattingInfo) { var iCanHandleThisInput = formattingInfo.CurrentValue is int || formattingInfo.CurrentValue is long || formattingInfo.CurrentValue is double || formattingInfo.CurrentValue is float; if (!iCanHandleThisInput) { return(false); } double val = Convert.ToInt64(formattingInfo.CurrentValue); var opts = formattingInfo.FormatterOptions != null ? formattingInfo.FormatterOptions.Split(',') : new string[0]; var currencyOptions = opts.Length > 0 && opts[0] != null ? opts[0] : null; var multiplyOptions = opts.Length > 1 && opts[1] != null?tryParseDouble(opts[1]) : 1; var positiveOptions = opts.Length > 2 && opts[2] != null && tryParseBool(opts[2]); var numerologyStep = opts.Length > 3 && opts[3] != null?tryParseInt(opts[3]) : 1000; var numerologyZeroPadding = opts.Length > 4 && opts[4] != null?tryParseInt(opts[4]) : 2; val = (val * multiplyOptions); if (positiveOptions) { val = Math.Abs(val); } switch (currencyOptions) { default: return(false); case "": case null: case "null": case "val": formattingInfo.Write(val.ToString()); return(true); case "int": formattingInfo.Write(Smart.Format("{0:0}", val)); return(true); case "cur": formattingInfo.Write(Smart.Format("{0:0.00}", val)); return(true); case "rom": formattingInfo.Write(ToRoman((int)val)); return(true); case "num": formattingInfo.Write(val.GetNumerology(numerologyStep, numerologyZeroPadding)); return(true); } }
public void Choose_throws_when_choices_are_too_few_or_too_many(string format, object arg0) { Smart.Default.Settings.FormatErrorAction = ErrorAction.ThrowError; Assert.Throws <FormattingException>(() => Smart.Format(format, arg0)); }
public TemplateFormatterTests() { _smart = Smart.CreateDefaultSmartFormat(); }
public virtual string GetEntityTypeCollection(IEntityType entityType) { return(Smart.Format("ICollection<{ClrType.Name}>", entityType)); }
public string Format(string format, Dictionary <string, object> arguments) { return(Smart.Format(format, arguments)); }
public virtual string GetParameterList(IEnumerable <IProperty> properties) { return(Smart.Format("{0:{ClrType.Namespace}.{ClrType.Name} {Name:fctl()}|, }", properties)); }
public async override Task <Message> HandleMessage(Message msg) { MessageContext context = new MessageContext(msg, this); string dbName = Database != null ? await Database.SelectStringAsync(context) : null; string dsTable = Table != null ? await Table?.SelectStringAsync(context) : null; string dsColumn = Column != null ? await Column?.SelectStringAsync(context) : null; string dsFrom = From != null ? await From?.SelectStringAsync(context) : null; string dsQueryName = Query != null ? await Query?.SelectStringAsync(context) : null; string sfSql = null; bool hasRows = false; Semaphore accessSemaphore = null; if (AccessSemaphore.ContainsKey(dbName)) { accessSemaphore = AccessSemaphore[dbName]; } try { string[] paramValues; var namedQuery = dsQueryName != null?Queries?.Where(x => x.Name.Equals(dsQueryName)).FirstOrDefault() : null; if (namedQuery != null) { string[] parameterised = namedQuery.Content.Value.ToSmartParameterised("@arg{0}"); sfSql = parameterised[0]; var selectors = (from p in parameterised.Skip(1) select new DataSelector(p)).ToArray(); paramValues = new string[parameterised.Length - 1]; for (int i = 0; i < paramValues.Length; i++) { paramValues[i] = await selectors[i].SelectStringAsync(context); } } else { sfSql = Smart.Format("SELECT 1 FROM {0} WHERE {1} = @arg1", dsTable, dsColumn); paramValues = new string[1]; paramValues[0] = dsFrom; } accessSemaphore?.WaitOne(); using (DbConnection connection = await NewConnection(context)) { connection.Open(); DbCommand cmd = connection.CreateCommand(); cmd.CommandText = sfSql; cmd.CommandType = CommandType.Text; for (int i = 0; i < paramValues.Length; i++) { var param = cmd.CreateParameter(); param.ParameterName = String.Format("arg{0}", i + 1); param.Value = paramValues[i]; cmd.Parameters.Add(param); } var result = await cmd.ExecuteReaderAsync(); hasRows = result.HasRows; result.Close(); } } catch (Exception ex) { logger.Error(ex, $"{ex.GetType().Name} thrown for \"{this.Name}\": {ex.Message}"); return(null); } finally { accessSemaphore?.Release(); } // Wait to get out of the try/using/finally block for lock sensitive databases like SQLite if (hasRows) { return(ThisPassedTheTest(msg)); } else { return(ThisFailedTheTest(msg)); } }
public virtual string GetSetAccessor(IEntityType entityType) { return(Smart.Format("UnitOfWork.Set<{ClrType.Name}>()", entityType)); }
public void Choose_should_work_with_numbers_strings_and_booleans(string format, object arg0, string expectedResult) { Assert.AreEqual(expectedResult, Smart.Format(format, arg0)); }
public virtual void WriteFunctionBasicLoadReference(IFileWriter fileWriter, IEntityType entityType) { string functionSignature = Smart.Format(FunctionSignatureBasicLoadReference, entityType); WriteFunction(fileWriter, functionSignature, GetFunctionBodyBasicLoadReference(entityType)); }
public bool Export(ExportItem item, FileItem fileItem, Profile profile) { ExportItem = item; IMagickImage magickImage = null; Smart.Default.Settings.ConvertCharacterStringLiterals = false; string outFilename = Smart.Format(FileNameTemplate, GetFormatValues(item, fileItem, profile)); if (string.IsNullOrWhiteSpace(Path.GetExtension(outFilename))) { outFilename += ".jpg"; } string outFolder = Smart.Format(FtpFolder, GetFormatValues(item, fileItem, profile)); // check if the file is safe for open // not used by any other application Utils.WaitForFile(fileItem.TempFile); try { var tempFile = Path.Combine(Settings.Instance.CacheFolder, Path.GetRandomFileName() + Path.GetExtension(outFilename)); if (ImageSource == 0 && !Resize) { File.Copy(fileItem.TempFile, tempFile); } else { magickImage = GetImage(item, fileItem, profile); magickImage.Write(tempFile); } using (FtpClient conn = new FtpClient()) { conn.Host = FtpServer; conn.Credentials = new NetworkCredential(FtpUser, FtpPass); if (!string.IsNullOrWhiteSpace(outFolder)) { conn.CreateDirectory(outFolder, true); conn.SetWorkingDirectory(outFolder); } using (Stream ostream = conn.OpenWrite(outFilename, FtpDataType.Binary)) { try { var data = File.ReadAllBytes(tempFile); ostream.Write(data, 0, data.Length); } finally { ostream.Close(); } } } } catch (Exception e) { Log.Debug("Export error ", e); return(false); } return(true); }