/// <summary> /// 将value转换为目标类型 /// 并将转换所得的值放到result /// 如果不支持转换,则返回false /// </summary> /// <param name="converter">转换器实例</param> /// <param name="value">要转换的值</param> /// <param name="targetType">转换的目标类型</param> /// <param name="result">转换结果</param> /// <returns>如果不支持转换,则返回false</returns> public virtual bool Convert(Converter converter, object value, Type targetType, out object result) { var dynamicObject = value as DynamicObject; if (dynamicObject == null) { result = null; return false; } var instance = Activator.CreateInstance(targetType); var setters = PropertySetter.GetPropertySetters(targetType); foreach (var set in setters) { object targetValue; if (this.TryGetValue(dynamicObject, set.Name, out targetValue) == true) { targetValue = converter.Convert(targetValue, set.Type); set.SetValue(instance, targetValue); } } result = instance; return true; }
/// <summary> /// 将value转换为目标类型 /// 并将转换所得的值放到result /// 如果不支持转换,则返回false /// </summary> /// <param name="converter">转换器实例</param> /// <param name="value">要转换的值</param> /// <param name="targetType">转换的目标类型</param> /// <param name="result">转换结果</param> /// <returns>如果不支持转换,则返回false</returns> public virtual bool Convert(Converter converter, object value, Type targetType, out object result) { var dic = value as IDictionary<string, object>; if (dic == null) { result = null; return false; } var instance = Activator.CreateInstance(targetType); var setters = PropertySetter.GetPropertySetters(targetType); foreach (var set in setters) { var key = dic.Keys.FirstOrDefault(k => string.Equals(k, set.Name, StringComparison.OrdinalIgnoreCase)); if (key != null) { var targetValue = converter.Convert(dic[key], set.Type); set.SetValue(instance, targetValue); } } result = instance; return true; }
public object ProvideValue(IServiceProvider serviceProvider) { if (Text == null) { return(""); } ResourceManager resmgr = new ResourceManager(ResourceId, typeof(LocalizeExtension).GetTypeInfo().Assembly); var translation = resmgr.GetString(Text, ci); if (translation == null) { #if DEBUG throw new ArgumentException( String.Format("Key '{0}' was not found in resources '{1}' for culture '{2}'.", Text, ResourceId, ci.Name), "Text"); #else translation = Text; // HACK: returns the key, which GETS DISPLAYED TO THE USER #endif } var convertTranslation = Converter?.Convert(translation, typeof(string), ConverterParameter, ci); return(convertTranslation ?? translation); }
public void Converts() { Converter converter = new Converter(new MarkdownWriter()); string result = converter.Convert(Input); Approvals.Verify(result); }
public void CanConvert_Borek01_To_NiceHtml() { var source = TestResources.Borek01; var converter = new Converter(); var result = converter.Convert(source); Assert.Inconclusive(); }
public void CanConvert_Heading_And_Formating_To_NiceHtml() { var source = TestResources.Headings_And_Formating; var converter = new Converter(); var result = converter.Convert(source); Assert.Inconclusive(); }
public void CanConvert_JustHeading_To_NiceHtml() { var source = TestResources.JustHeadings; var converter = new Converter(); var result = converter.Convert(source); Assert.Inconclusive(); }
/// <summary> /// 将value转换为目标类型 /// 并将转换所得的值放到result /// 如果不支持转换,则返回false /// </summary> /// <param name="converter">转换器实例</param> /// <param name="value">要转换的值</param> /// <param name="targetType">转换的目标类型</param> /// <param name="result">转换结果</param> /// <returns>如果不支持转换,则返回false</returns> public virtual bool Convert(Converter converter, object value, Type targetType, out object result) { if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable<>)) { var genericArgument = targetType.GetGenericArguments().First(); result = converter.Convert(value, genericArgument); return true; } result = null; return false; }
// This gets called on every change of the dynamic resource, for every object it's been applied to // either when applied directly, or via a style private object?WrapperConvert(object?[] values, Type?targetType, object?parameter, CultureInfo?culture) { object?dynamicResourceBindingResult = values[0]; // This is the result of the DynamicResourceBinding** var bindingTargetObject = values[1]; // The ultimate target of the binding // We can ignore the bogus third value (in 'values[2]') as that's the dummy result // of the BindingTrigger's value which will always be 'null' // ** Note: This value has not yet been passed through the converter, nor been coalesced // against TargetNullValue, or, if applicable, formatted, both of which we have to do here. if (Converter != null) { // We pass in the TargetType we're handed here as that's the real target. Child bindings // would've normally been handed 'object' since their target is the MultiBinding. dynamicResourceBindingResult = Converter?.Convert(dynamicResourceBindingResult, targetType, ConverterParameter, ConverterCulture); } // Check the results for null. If so, assign it to TargetNullValue // Otherwise, check if the target type is a string, and that there's a StringFormat // if so, format the string. // Note: You can't simply put those properties on the MultiBinding as it handles things differently // than a single binding (i.e. StringFormat is always applied, even when null. if (dynamicResourceBindingResult is null) { dynamicResourceBindingResult = TargetNullValue; } else if (targetType == typeof(string) && StringFormat != null) { dynamicResourceBindingResult = String.Format(CultureInfo.InvariantCulture, StringFormat, dynamicResourceBindingResult); } // If the binding target object is a FrameworkElement, ensure the BindingSource is added // to its Resources collection so it will be part of the lookup relative to the FrameworkElement if (bindingTargetObject is FrameworkElement targetFrameworkElement && !targetFrameworkElement.Resources.Contains(_bindingSource)) { // Add the resource to the target object's Resources collection targetFrameworkElement.Resources[_bindingSource] = _bindingSource; // Since we just added the source to the visual tree, we have to re-evaluate the value // relative to where we are. However, since there's no way to get a binding expression, // to trigger the binding refresh, here's where we use that BindingTrigger created above // to trigger a change notification, thus having it refresh the binding with the (possibly) // new value. // Note: since we're currently in the Convert method from the current operation, // we must make the change via a 'Post' call or else we will get results returned // out of order and the UI won't refresh properly. SynchronizationContext.Current?.Post(_ => _bindingTrigger?.Refresh(), null); } // Return the now-properly-resolved result of the child binding return(dynamicResourceBindingResult); }
public void Convert_NestedObject_ShouldSucced(Converter sut) { //Setup var columns = new List<string>() { "id", "city.name", "city.country.isoCode" }; var matrix = new List<List<object>>() { new List<object>() { 1, "cityName1", "countryIsoCode1" }, new List<object>() { 2, "cityName2", "countryIsoCode2" } }; //Exercise var actual = sut.Convert(columns, matrix); //Verify actual.Should().NotBeEmpty() .And.HaveSameCount(matrix) .And.DeepContain(new Dictionary<string, object>() { { "id", 1 }, { "city", new Dictionary<string, object>() { { "name", "cityName1" }, { "country", new Dictionary<string, object>() { { "isoCode", "countryIsoCode1" } } } } } }) .And.DeepContain(new Dictionary<string, object>() { { "id", 2 }, { "city", new Dictionary<string, object>() { { "name", "cityName2" }, { "country", new Dictionary<string, object>() { { "isoCode", "countryIsoCode2" } } } } } }); }
/// <summary> /// 将value转换为目标类型 /// 并将转换所得的值放到result /// 如果不支持转换,则返回false /// </summary> /// <param name="converter">转换器实例</param> /// <param name="value">要转换的值</param> /// <param name="targetType">转换的目标类型</param> /// <param name="result">转换结果</param> /// <returns>如果不支持转换,则返回false</returns> public virtual bool Convert(Converter converter, object value, Type targetType, out object result) { if (targetType.IsArray == false) { result = null; return false; } var items = value as IEnumerable; var elementType = targetType.GetElementType(); if (items == null) { result = Array.CreateInstance(elementType, 0); return true; } var length = 0; var list = items as IList; if (list != null) { length = list.Count; } else { var enumerator = items.GetEnumerator(); while (enumerator.MoveNext()) { length = length + 1; } } var index = 0; var array = Array.CreateInstance(elementType, length); foreach (var item in items) { var itemCast = converter.Convert(item, elementType); array.SetValue(itemCast, index); index = index + 1; } result = array; return true; }
public static string Convert(string input) { Dictionary<string, Converter.Tag> tagDict = new Dictionary<string, Converter.Tag>(); tagDict.Add("stats", new Converter.NodeTag("stats", new Converter.Style(@"<Run FontWeight=""Bold"">", @"</Run>"))); tagDict.Add("unique", new Converter.NodeTag("unique", new Converter.Style(@"<Run FontWeight=""Bold"" Foreground=""DarkBlue"">", @"</Run>"))); tagDict.Add("i", new Converter.NodeTag("i", new Converter.Style(@"<Run FontStyle=""Italic"">", @"</Run>"))); tagDict.Add("consumable", new Converter.NodeTag("consumable", new Converter.Style(@"<Run FontWeight=""Bold"" Foreground=""DarkOrange"">", @"</Run>"))); tagDict.Add("active", new Converter.NodeTag("active", new Converter.Style(@"<Run FontWeight=""Bold"" Foreground=""DarkRed"">", @"</Run>"))); tagDict.Add("passive", new Converter.NodeTag("passive", new Converter.Style(@"<Run FontWeight=""Bold"" Foreground=""DarkBlue"">", @"</Run>"))); tagDict.Add("aura", new Converter.NodeTag("aura", new Converter.Style(@"<Run FontWeight=""Bold"" Foreground=""DarkGreen"">", @"</Run>"))); tagDict.Add("br", new Converter.SingleTag("br", new Converter.Style("<LineBreak/>"))); tagDict.Add("start", new Converter.SingleTag("start", new Converter.Style(@"<Paragraph FontFamily=""Global User Interface"">"))); tagDict.Add("end", new Converter.SingleTag("end", new Converter.Style(@"</Paragraph>"))); tagDict.Add("body", new Converter.NodeTag("body", new Converter.Style(@"<Run Text=""", @"""></Run>"))); Converter c = new Converter(tagDict); return c.Convert(input); }
private void button1_Click(object sender, EventArgs e) { Converter converter = new Converter(); // Authentication converter.Username = ""; converter.Password = ""; converter.Domain = ""; // Authentication string cType=""; if (this.comboBox1.SelectedIndex==0) { cType="ObjCFiles";} if (this.comboBox1.SelectedIndex==1) { cType="ObjCARCFiles";} if (this.comboBox1.SelectedIndex==2) { cType="Javascript";} if (this.comboBox1.SelectedIndex==3) { cType="ActionScript";} converter.Type = cType ; converter.WsdlPaths = textBox1.Text; converter.Convert(); FileInfo zf=converter.CreateArchive(); MessageBox.Show(zf.FullName,"Code Generated"); }
public void Convert_SimpleObject_ShouldSucced(Converter sut) { //Setup var columns = new List<string>() { "id", "name" }; var matrix = new List<List<object>>() { new List<object>() { 1, "name1" }, new List<object>() { 2, "name2" }, new List<object>() { 3, "name3" } }; //Exercise var actual = sut.Convert(columns, matrix); //Verify actual.Should().NotBeEmpty() .And.HaveSameCount(matrix) .And.DeepContain(new Dictionary<string, object>() { { "id", 1 }, { "name", "name1" } }) .And.DeepContain(new Dictionary<string, object>() { { "id", 2 }, { "name", "name2" } }) .And.DeepContain(new Dictionary<string, object>() { { "id", 3 }, { "name", "name3" } }); }
private static void CheckConversion(string html, string expected) { var converter = new Converter(); var result = converter.Convert(html); Assert.That(result, Is.EqualTo(expected)); }
public void ConvertFromSingle() { TestHelper.AreEqual(9223372000000000000, Converter.Convert <long>((float)long.MaxValue)); TestHelper.AreEqual(-9223372000000000000, Converter.Convert <long>((float)long.MinValue)); }
public void ConvertFromString() { TestHelper.AreEqual(2147483647, Converter.Convert <long>(int.MaxValue.ToString())); TestHelper.AreEqual(-2147483648, Converter.Convert <long>(int.MinValue.ToString())); }
public void ConvertCodeBlock() { var codeText = @" public function addItem($sku, $name, $price, $category = null, $quantity = 1) { $product = array(); foreach (array('sku', 'name', 'category', 'price', 'quantity') as $arg) { if ($$arg !== null) { $product[$arg] = $$arg; } } if (empty($this->transaction['transactionProducts'])) { $this->transaction['transactionProducts'] = array(); } $this->transaction['transactionProducts'][] = $product; return $this; } "; var wikiText = "<code php>" + codeText + "</code>"; Assert.AreEqual("<pre><code class=\"php\">" + codeText + "</code></pre>\n", Converter.Convert(wikiText)); }
// static kstatus_t KonohaSpace_eval(CTX, kKonohaSpace *ks, const char *script, kline_t uline) public dynamic Eval(string script) { var tokens = tokenize(script); var parser = new Parser(ctx, this); var converter = new Converter(ctx, this); var block = parser.CreateBlock(null, tokens, 0, tokens.Count(), ';'); dynamic ast = converter.Convert(block); string dbv = typeof(Expression).InvokeMember("DebugView", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetProperty, null, ast, null); Console.WriteLine("### DLR AST Dump ###"); Console.WriteLine(dbv); var f = ast.Compile(); return f(); }
public void VerifyComplete(Converter converter, Task<bool> res) { if (this.HandleFaultedTask(res)) { EnableUi = true; converter.Dispose(); return; } if (res.Result) { converter.Convert().ContinueWith(x => this.ConvertComplete(converter, x)); } }
public void Process(ISemanticProcessor proc, IMembrane membrane, Route route) { IAuthenticatingRouterService routerService = proc.ServiceManager.Get <IAuthenticatingRouterService>(); IContext context = route.Context; HttpVerb verb = context.Verb(); UriPath path = context.Path(); string searchRoute = GetSearchRoute(verb, path); string data = route.Data; RouteInfo routeInfo; IPAddress addr = context.Request.RemoteEndPoint.Address; string ip = addr.ToString(); // Handle localhost format. if (ip == "::1") { addr = new IPAddress(new byte[] { 127, 0, 0, 1 }); } Console.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss tt ") + "IP: " + addr.ToString() + " URL: " + route.Context.Request.Url); // TODO: Session manager may not exist. How do we handle services that are missing? IWebSessionService session = proc.ServiceManager.Get <IWebSessionService>(); // Semantic routes can be either public or authenticated. if (routerService.Routes.TryGetValue(searchRoute, out routeInfo)) { // Public routes always authenticate. bool authenticatedRoute = true; bool authorizedRoute = true; if (routeInfo.RouteType == RouteType.AuthenticatedRoute) { session.UpdateState(context); authenticatedRoute = session.IsAuthenticated(context); } if (routeInfo.RouteType == RouteType.RoleRoute) { session.UpdateState(context); authenticatedRoute = session.IsAuthenticated(context); // User must be authenticated and have the correct role setting. if (authenticatedRoute) { // Any bits that are set with a binary "and" of the route's role mask and the current role passes the authorization test. uint mask = session.GetSessionObject <uint>(context, "RoleMask"); authorizedRoute = (mask & routeInfo.RoleMask) != 0; } } if (authenticatedRoute) // user is authenticated { session.UpdateLastTransaction(context); } if (authenticatedRoute && authorizedRoute) { Type receptorSemanticType = routeInfo.ReceptorSemanticType; SemanticRoute semanticRoute = (SemanticRoute)Activator.CreateInstance(receptorSemanticType); semanticRoute.PostData = data; if (!String.IsNullOrEmpty(data)) { // Is it JSON? // NOTE: "JSON" is passed in as a string, not object. So this is what it looks like in the Javascript: // $.post("/geeks/createProfile", '{ "profileName": "foobar" }' // Note the surrounding ' marks if (data[0] == '{') { JsonConvert.PopulateObject(data, semanticRoute); SetUrlParameters(context.Request.Url.ToString(), semanticRoute, receptorSemanticType); } else if (MultiPartParser.IsMultiPart(data)) { MultiPartParser.ContentType ct = MultiPartParser.GetContentType(data); string content = MultiPartParser.GetContent(data); if (!(semanticRoute is IFileUpload)) { throw new RouterException("Semantic route class must implement IFileUpload"); } ((IFileUpload)semanticRoute).Content = content; } else { // Instead here, the data is passed in as an object, which comes in as params. The Javascript for this looks like: // $.post("/geeks/createProfile", { "profileName": profileName } // Note the lack of surrounding ' around the { } // Example: "username=sdfsf&password=sdfsdf&LoginButton=Login" // Use $.post(url, JSON.stringify(data) to convert to JSON string[] parms = data.Split('&'); foreach (string parm in parms) { string[] keyVal = parm.Split('='); PropertyInfo pi = receptorSemanticType.GetProperty(keyVal[0], BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); if (pi != null) { // TODO: Should handling of "+" be before or after the UnescapedDataString call? object valOfType = Converter.Convert(Uri.UnescapeDataString(keyVal[1].Replace('+', ' ')), pi.PropertyType); pi.SetValue(semanticRoute, valOfType); } } } } else if (verb.Value == "GET") { SetUrlParameters(context.Request.Url.ToString(), semanticRoute, receptorSemanticType); } // Must be done AFTER populating the object -- sometimes the json converter nulls the base class! semanticRoute.Context = context; // TODO: Why are we doing this on the caller thread, except for debugging??? proc.ProcessInstance <WebServerMembrane>(semanticRoute, true); } else { // Deal with expired or requires authentication. switch (session.GetState(context)) { case SessionState.New: // TODO: Oh man, this is application specific!!! session.SetSessionObject(context, "OneTimeBadAlert", "Please Sign In"); context.Redirect("/account/login"); //proc.ProcessInstance<WebServerMembrane, StringResponse>(r => //{ // r.Context = context; // r.Message = "authenticationRequired"; // used in clifton.spa.js to handle SPA error responses // r.StatusCode = 403; //}); break; case SessionState.Authenticated: proc.ProcessInstance <WebServerMembrane, StringResponse>(r => { r.Context = context; r.Message = "notAuthorized"; // used in clifton.spa.js to handle SPA error responses r.StatusCode = 401; }); break; case SessionState.Expired: session.SetSessionObject(context, "OneTimeBadAlert", "Session expired. Please sign in again."); context.Redirect("/account/login"); //proc.ProcessInstance<WebServerMembrane, StringResponse>(r => //{ // r.Context = context; // r.Message = "sessionExpired"; // used in clifton.spa.js to handle SPA error responses // r.StatusCode = 401; //}); break; } } } else { // proc.ProcessInstance<LoggerMembrane, ST_Log>(msg => msg.Message = "Using default handler: " + verb.Value + ": " + path.Value); // Put the context on the bus for some service to pick up. // All unhandled context are assumed to be public routes. proc.ProcessInstance <WebServerMembrane, UnhandledContext>(c => c.Context = context); } }
protected override void Upload(DicomFile data, int frame, IStorageLocation location) { location.Upload(System.Text.Encoding.UTF8.GetBytes(Converter.Convert(data.DataSet))); }
/// <summary> /// Main program. /// </summary> /// <param name="args">Command line arguments.</param> static void Main(string[] args) { Helper = new ConsolePrinter(); Helper.Name = "Font2Font"; Helper.Description = "Converts a Windows font to a Woopsi font."; Helper.Version = "V1.2"; Helper.AddArgument(new Argument("FONT", "string", "Name of the Windows font to convert", false)); Helper.AddArgument(new Argument("SIZE", "int", "Size of the font in pixels", false)); Argument arg = new Argument("STYLE", "int", "Style of the font. Options are:", true); arg.AddOption("regular", "Standard font"); arg.AddOption("bold", "Bold font"); arg.AddOption("italic", "Italic font"); Helper.AddArgument(arg); arg = new Argument("FONTTYPE", "string", "Type of font to produce. Options are:", true); arg.AddOption("packedfont1", "Monochrome packed proportional font"); arg.AddOption("packedfont16", "16-bit packed proportional font"); Helper.AddArgument(arg); Helper.AddArgument(new Argument("PATH", "string", "Output path", false)); Helper.AddArgument(new Argument("R", "int", "Red component of the text colour", true)); Helper.AddArgument(new Argument("G", "int", "Green component of the text colour", true)); Helper.AddArgument(new Argument("B", "int", "Blue component of the text colour", true)); Helper.AddArgument(new Argument("LIST", "int", "Lists all available Windows font names", true)); Helper.AddParagraph("If the text colour is not specified it defaults to black."); Helper.AddParagraph("If the style is not specified it defaults to regular."); Helper.AddParagraph("If the path is not specified it defaults to the current path."); Helper.AddParagraph("If the font type is not specified it defaults to packedfont1."); Console.WriteLine(Helper.Title); Console.WriteLine(Helper.HelpText); // Fetch arguments ParseArgs(args); // Use background colour that is opposite of text colour int backgroundR = (mTextR ^ 255) & 255; int backgroundG = (mTextG ^ 255) & 255; int backgroundB = (mTextB ^ 255) & 255; // Get the font Font font = GetFont(mFontName, mFontSize, mFontStyle); // Convert the font to a bitmap Bitmap bmp = BitmapCreator.CreateFontBitmap(font, backgroundR, backgroundG, backgroundB, mTextR, mTextG, mTextB); // Convert bitmap to Woopsi font WoopsiFont woopsiFont = Converter.Convert(mFontName, mFontName, mFontType, bmp, bmp.Width / CHARS_PER_ROW, bmp.Height / ROWS_PER_FONT, backgroundR, backgroundG, backgroundB); // Output files WriteFile(mOutputPath + "\\" + woopsiFont.HeaderFileName, woopsiFont.HeaderContent); WriteFile(mOutputPath + "\\" + woopsiFont.BodyFileName, woopsiFont.BodyContent); Console.WriteLine("All done!"); }
public static object Convert(object from, Type toType) { return(Converter.Convert(from, toType)); }
public static TTo Convert <TFrom, TTo>(TFrom from) { return(Converter.Convert <TFrom, TTo>(from)); }
static void Main(string[] args) { ParseArgs(args, ToolName); InitializeLogger(); PrintWelcome(ToolName, RevisionResource); if (CreateContextMenuEntry) { // create context menu entry try { TraceLogger.Info("Creating context menu entry for xls2x ..."); RegisterForContextMenu(GetContextMenuKey(ContextMenuInputExtension, ContextMenuText)); TraceLogger.Info("Succeeded."); } catch (Exception) { TraceLogger.Info("Failed. Sorry :("); } } else { try { //copy processing file ProcessingFile procFile = new ProcessingFile(InputFile); //make output file name if (ChoosenOutputFile == null) { if (InputFile.Contains(".")) { ChoosenOutputFile = InputFile.Remove(InputFile.LastIndexOf(".")) + ".xlsx"; } else { ChoosenOutputFile = InputFile + ".xlsx"; } } //parse the document using (StructuredStorageReader reader = new StructuredStorageReader(procFile.File.FullName)) { XlsDocument xlsDoc = new XlsDocument(reader); OpenXmlPackage.DocumentType outType = Converter.DetectOutputType(xlsDoc); string conformOutputFile = Converter.GetConformFilename(ChoosenOutputFile, outType); using (SpreadsheetDocument spreadx = SpreadsheetDocument.Create(conformOutputFile, outType)) { //start time DateTime start = DateTime.Now; TraceLogger.Info("Converting file {0} into {1}", InputFile, conformOutputFile); Converter.Convert(xlsDoc, spreadx); DateTime end = DateTime.Now; TimeSpan diff = end.Subtract(start); TraceLogger.Info("Conversion of file {0} finished in {1} seconds", InputFile, diff.TotalSeconds.ToString(CultureInfo.InvariantCulture)); } } } catch (ParseException ex) { TraceLogger.Error("Could not convert {0} because it was created by an unsupported application (Excel 95 or older).", InputFile); TraceLogger.Debug(ex.ToString()); } catch (DirectoryNotFoundException ex) { TraceLogger.Error(ex.Message); TraceLogger.Debug(ex.ToString()); } catch (FileNotFoundException ex) { TraceLogger.Error(ex.Message); TraceLogger.Debug(ex.ToString()); } catch (ZipCreationException ex) { TraceLogger.Error("Could not create output file {0}.", ChoosenOutputFile); TraceLogger.Debug(ex.ToString()); } catch (Exception ex) { TraceLogger.Error("Conversion of file {0} failed.", InputFile); TraceLogger.Debug(ex.ToString()); } } }
public static int Run(string project, string workspace, string msbuildPath, bool diffOnly, bool noBackup) { if (!string.IsNullOrWhiteSpace(project) && !string.IsNullOrWhiteSpace(workspace)) { Console.WriteLine("Cannot specify both a project and a workspace."); return(-1); } try { msbuildPath = MSBuildHelpers.HookAssemblyResolveForMSBuild(msbuildPath); if (string.IsNullOrWhiteSpace(msbuildPath)) { Console.WriteLine("Could not find an MSBuild."); return(-1); } var currentDirectory = Environment.CurrentDirectory; var workspacePath = string.Empty; MSBuildWorkspaceType workspaceType; if (!string.IsNullOrWhiteSpace(project)) { workspacePath = Path.GetFullPath(project, Environment.CurrentDirectory); workspaceType = MSBuildWorkspaceType.Project; } else if (!string.IsNullOrWhiteSpace(workspace)) { var(isSolution, workspaceFilePath) = MSBuildWorkspaceFinder.FindWorkspace(currentDirectory, workspace); workspaceType = isSolution ? MSBuildWorkspaceType.Solution : MSBuildWorkspaceType.Project; workspacePath = workspaceFilePath; } else { throw new ArgumentException("No valid arguments to fulfill a workspace are given."); } var workspaceLoader = new MSBuildWorkspaceLoader(workspacePath, workspaceType); var msbuildWorkspace = workspaceLoader.LoadWorkspace(workspacePath, noBackup); foreach (var item in msbuildWorkspace.WorkspaceItems) { if (diffOnly) { var differ = new Differ(item.UnconfiguredProject.FirstConfiguredProject, item.SdkBaselineProject.Project.FirstConfiguredProject); differ.GenerateReport(workspacePath); } else { var converter = new Converter(item.UnconfiguredProject, item.SdkBaselineProject, item.ProjectRootElement); converter.Convert(item.ProjectRootElement.FullPath); } } } catch (Exception e) { Console.WriteLine(e.ToString()); return(-1); } Console.WriteLine("Conversion complete!"); return(0); }
public void Convert_SimpleObjectWithRepeatedColumns_ShouldThrowRepeatedColumnException(Converter sut) { //Setup var repeatedColumnName = "id"; var columns = new List<string>() { repeatedColumnName, repeatedColumnName }; var matrix = new List<List<object>>() { new List<object>() { 1, "name1" } }; //Exercise Action exercise = () => sut.Convert(columns, matrix); //Verify exercise.ShouldThrow<ConverterRepeatedColumnException>() .Where(x => x.Message.Contains(repeatedColumnName)); }
public void It_should_convert_it_to_expected_value(int input, string expected) { var sut = new Converter(); string actual = sut.Convert(input); actual.Should().Be(expected); }
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return(Converter.Convert(value, convObj.GetType())); }
/// <summary> /// Translation In Xaml /// </summary> /// <param name="serviceProvider"></param> /// <returns></returns> public override object ProvideValue(IServiceProvider serviceProvider) { IProvideValueTarget service = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget; if (service == null) { return(this); } targetProperty = service.TargetProperty as DependencyProperty; targetObject = service.TargetObject as DependencyObject; if (targetObject == null || targetProperty == null) { return(this); } try { if (string.IsNullOrEmpty(TextId)) { if (targetObject != null && targetProperty != null) { string context = targetObject.GetContextByName(); string obj = targetObject.FormatForTextId(); string property = targetProperty.ToString(); TextId = $"{context}.{obj}.{property}"; } else if (!string.IsNullOrEmpty(DefaultText)) { TextId = DefaultText; } } } catch (InvalidCastException) { // For Xaml Design Time TextId = Guid.NewGuid().ToString(); } if (IsDynamic) { Binding binding = new Binding("TranslatedText") { Source = new TrData() { TextId = TextId, DefaultText = DefaultText, LanguageId = LanguageId, Prefix = Prefix, Suffix = Suffix } }; if (Converter != null) { binding.Converter = Converter; binding.ConverterParameter = ConverterParameter; binding.ConverterCulture = ConverterCulture; } BindingOperations.SetBinding(targetObject, targetProperty, binding); return(binding.ProvideValue(serviceProvider)); } else { object result = Prefix + TM.Tr(TextId, DefaultText, LanguageId) + Suffix; if (Converter != null) { result = Converter.Convert(result, targetProperty.PropertyType, ConverterParameter, ConverterCulture); } return(result); } }
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { return(Converter.Convert(convObj, destinationType)); }
/// <summary> /// This function returns the properly prepared output of the markup extension. /// </summary> public object FormatOutput() { object result = null; if (_targetInfo == null) { return(null); } var targetObject = _targetInfo.TargetObject as DependencyObject; // Get target type. Change ImageSource to BitmapSource in order to use our own converter. var targetType = _targetInfo.TargetPropertyType; if (targetType == typeof(ImageSource)) { targetType = typeof(BitmapSource); } // Try to get the localized input from the resource. string resourceKey = LocalizeDictionary.Instance.GetFullyQualifiedResourceKey(Key, targetObject); var ci = GetForcedCultureOrDefault(); // Extract the names of the endpoint object and property var epName = ""; var epProp = ""; var element = targetObject as FrameworkElement; if (element != null) { epName = element.GetValueSync <string>(NameProperty); } else if (targetObject is FrameworkContentElement) { epName = ((FrameworkContentElement)targetObject).GetValueSync <string>(FrameworkContentElement.NameProperty); } if (_targetInfo.TargetProperty is PropertyInfo) { epProp = ((PropertyInfo)_targetInfo.TargetProperty).Name; } else if (_targetInfo.TargetProperty is DependencyProperty) { epProp = ((DependencyProperty)_targetInfo.TargetProperty).Name; } // What are these names during design time good for? Any suggestions? if (epProp.Contains("FrameworkElementWidth5")) { epProp = "Height"; } else if (epProp.Contains("FrameworkElementWidth6")) { epProp = "Width"; } else if (epProp.Contains("FrameworkElementMargin12")) { epProp = "Margin"; } var resKeyBase = ci.Name + ":" + targetType.Name + ":"; string resKeyNameProp = LocalizeDictionary.Instance.GetFullyQualifiedResourceKey( epName + LocalizeDictionary.GetSeparation(targetObject) + epProp, targetObject); string resKeyName = LocalizeDictionary.Instance.GetFullyQualifiedResourceKey(epName, targetObject); // Check, if the key is already in our resource buffer. object input = null; if (!IsNullOrEmpty(resourceKey)) { // We've got a resource key. Try to look it up or get it from the dictionary. lock (ResourceBufferLock) { if (_resourceBuffer.ContainsKey(resKeyBase + resourceKey)) { result = _resourceBuffer[resKeyBase + resourceKey]; } else { input = LocalizeDictionary.Instance.GetLocalizedObject(resourceKey, targetObject, ci); resKeyBase += resourceKey; } } } else { // Try the automatic lookup function. // First, look for a resource entry named: [FrameworkElement name][Separator][Property name] lock (ResourceBufferLock) { if (_resourceBuffer.ContainsKey(resKeyBase + resKeyNameProp)) { result = _resourceBuffer[resKeyBase + resKeyNameProp]; } else { // It was not stored in the buffer - try to retrieve it from the dictionary. input = LocalizeDictionary.Instance.GetLocalizedObject(resKeyNameProp, targetObject, ci); if (input == null) { // Now, try to look for a resource entry named: [FrameworkElement name] // Note - this has to be nested here, as it would take precedence over the first step in the buffer lookup step. if (_resourceBuffer.ContainsKey(resKeyBase + resKeyName)) { result = _resourceBuffer[resKeyBase + resKeyName]; } else { input = LocalizeDictionary.Instance.GetLocalizedObject(resKeyName, targetObject, ci); resKeyBase += resKeyName; } } else { resKeyBase += resKeyNameProp; } } } } // If no result was found, convert the input and add it to the buffer. if (result == null && input != null) { result = Converter.Convert(input, targetType, ConverterParameter, ci); SafeAddItemToResourceBuffer(resKeyBase, result); } return(result); }
/// <inheritdoc /> public T Execute <T>(IDictionary <string, object> variables) { return(Converter.Convert <T>(Execute(variables))); }
public void ConvertFromTimeSpan() { TestHelper.AreEqual(9223372036854775807, Converter.Convert <long>(TimeSpan.MaxValue)); TestHelper.AreEqual(-9223372036854775808, Converter.Convert <long>(TimeSpan.MinValue)); }
/// <inheritdoc /> public T Execute <T>(IVariableProvider variables = null) { return(Converter.Convert <T>(Execute(variables))); }
public bool DoTest(string sfmFileName, string mapFileName, string phase4KeyFileName, string locationOfFinalFile) { m_sfmName = sfmFileName; m_mapName = mapFileName; m_keyName = phase4KeyFileName; m_Phase5Output = locationOfFinalFile; Converter conv = new Converter(); // read in the Lex Import Fields LexImportFields autoFields = new LexImportFields(); autoFields.ReadLexImportFields(@"C:\fw\DistFiles\Language Explorer\Import\ImportFields.xml"); // if there are auto fields in the xml file, pass them on to the converter Hashtable htAutoFields = autoFields.GetAutoFields(); foreach (DictionaryEntry laf in htAutoFields) { string entryClass = laf.Key as String; LexImportField lexField = laf.Value as LexImportField; string fwDest = lexField.ID; conv.AddPossibleAutoField(entryClass, fwDest); } //// here the Auto import fields needs to be added to the converter as it is in the actual import process //conv.AddPossibleAutoField("Entry", "eires"); //conv.AddPossibleAutoField("Sense", "sires"); //conv.AddPossibleAutoField("Subentry", "seires"); //conv.AddPossibleAutoField("Variant", "veires"); conv.Convert(m_sfmName, m_mapName, m_phase1output); ProcessPhase1Errors(); DoTransform(m_BuildPhase2XSLT, m_phase1output, m_Phase2XSLT); DoTransform(m_Phase2XSLT, m_phase1output, m_Phase2Output); DoTransform(m_Phase3XSLT, m_Phase2Output, m_Phase3Output); #if true // put the phase4output in to the 'phase 5' file for comparing as there is no phase 5 now. DoTransform(m_Phase4XSLT, m_Phase3Output, m_Phase5Output); Microsoft.XmlDiffPatch.XmlDiff diff = new Microsoft.XmlDiffPatch.XmlDiff( Microsoft.XmlDiffPatch.XmlDiffOptions.IgnoreChildOrder | Microsoft.XmlDiffPatch.XmlDiffOptions.IgnoreComments | Microsoft.XmlDiffPatch.XmlDiffOptions.IgnoreWhitespace); bool same = diff.Compare(m_keyName, m_Phase5Output, false); #else DoTransform(m_Phase4XSLT, m_Phase3Output, m_Phase4Output); // strip out the id and target attributes as the guids WILL be different DoTransform(m_Phase5XSLT, m_Phase4Output, m_Phase5Output); DoTransform(m_Phase5XSLT, m_keyName, m_KeyOutput); Microsoft.XmlDiffPatch.XmlDiff diff = new Microsoft.XmlDiffPatch.XmlDiff( Microsoft.XmlDiffPatch.XmlDiffOptions.IgnoreChildOrder | Microsoft.XmlDiffPatch.XmlDiffOptions.IgnoreComments | Microsoft.XmlDiffPatch.XmlDiffOptions.IgnoreWhitespace ); bool same = diff.Compare(m_KeyOutput, m_Phase5Output, false); #endif return same; }
public override int Run(InterpretedFrame frame) { frame.Push(Converter.Convert(frame.Pop(), _type)); return(+1); }
protected override Visual GetVisualChild(int index) { if ((Property == null) || (Objects == null)) { MultiChecked = null; } else { var property = typeof(TextEditor).GetProperty(Property); var match = Objects.Where(obj => obj.Active).Select(obj => property.GetValue(obj)).Select(value => Converter?.Convert(value, MultiValue.GetType(), null, CultureInfo.DefaultThreadCurrentCulture) ?? value).Select(value => value.Equals(MultiValue)).Distinct().ToList(); MultiChecked = match.Count == 1 ? match.First() : default(bool?); } return(base.GetVisualChild(index)); }
/// <inheritdoc /> public async Task <T> ExecuteAsync <T>(IVariableProvider variables = null, CancellationToken cancellationtoken = new CancellationToken()) { return(Converter.Convert <T>(await ExecuteAsync(variables, cancellationtoken))); }
public void Convert_SimpleObjectWithInvalidColumnName_ShouldThrowInvalidColumnException(Converter sut) { var invalidColumnName = "address..zipCode"; //Setup var columns = new List<string>() { "id", invalidColumnName }; var matrix = new List<List<object>>() { new List<object>() { 1, 2605 } }; //Exercise Action exercise = () => sut.Convert(columns, matrix); //Verify exercise.ShouldThrow<ConverterInvalidColumnNameException>() .Where(x => x.Message.Contains(invalidColumnName)); }
/// <summary> /// selects a value from the json structure /// </summary> /// <typeparam name="T">type of value to select</typeparam> /// <param name="path">path to node to select</param> /// <returns>typed value</returns> public T SelectSingle <T>(string path) { return(Converter.Convert <T>(SelectSingle(path))); }
public void ConvertFromSByte() { TestHelper.AreEqual(127, Converter.Convert <long>(sbyte.MaxValue)); TestHelper.AreEqual(-128, Converter.Convert <long>(sbyte.MinValue)); }
/// <summary> /// selects nodes using a path from a json node /// </summary> /// <param name="path">path to nodes to select</param> /// <returns>enumeration of nodes matching path</returns> public IEnumerable <T> Select <T>(string path) { return(Select(path).Select(n => Converter.Convert <T>(n))); }
private static void CheckConversion(string html, string expected) { var converter = new Converter(); var result = converter.Convert(html); Assert.Equal<string>(expected, result); }
public ActionResult SaveRecipe(PostedRecipeViewModel postedRecipeViewModel) { // NOTE: This action handles saving for both new recipes // and edited recipes. New Recipes post to this action while // edits post to this action via Ajax. var isNewRecipe = false; // Hydrate JSON ReceipeViewModel var recipeViewModel = postedRecipeViewModel.HydrateRecipeJson(); isNewRecipe = recipeViewModel.IsNewRecipe(); // Validation (client validates also ... this to ensure data consistency) var validator = new RecipeViewModelValidator(); var validationResult = validator.Validate(recipeViewModel); if (!validationResult.IsValid) { if (isNewRecipe) { this.AppendMessage(new ErrorMessage { Text = "Did you leave something blank? Please check your entries and try again." }); ViewBag.RecipeCreationOptions = this.RecipeService.GetRecipeCreationOptions(); return(this.View("NewRecipe", recipeViewModel)); } // Signals Invalid return(this.Content("0")); } using (var unitOfWork = this.UnitOfWorkFactory.NewUnitOfWork()) { try { var recipe = recipeViewModel.IsNewRecipe() ? new Recipe() : this.RecipeService.GetRecipeById(recipeViewModel.RecipeId); // Issue 404 if recipe does not exists or not owned by user if (!isNewRecipe && !recipe.WasCreatedBy(this.ActiveUser.UserId)) { return(this.Issue404()); } // Map Recipe Mapper.Map(recipeViewModel, recipe); #region INGREDIENT DELETIONS if (!isNewRecipe) { // Delete Fermentables that were removed var fermentablesForDeletion = recipe.Fermentables.Except(recipe.Fermentables.Join(recipeViewModel.Fermentables ?? new List <RecipeFermentableViewModel>(), x => x.RecipeFermentableId, y => Converter.Convert <int>(y.Id), (x, y) => x)).ToList(); this.RecipeService.MarkRecipeIngredientsForDeletion <RecipeFermentable>(fermentablesForDeletion); // Delete Hops that were removed var hopsForDeletion = recipe.Hops.Except(recipe.Hops.Join(recipeViewModel.Hops ?? new List <RecipeHopViewModel>(), x => x.RecipeHopId, y => Converter.Convert <int>(y.Id), (x, y) => x)).ToList(); this.RecipeService.MarkRecipeIngredientsForDeletion <RecipeHop>(hopsForDeletion); // Delete Yeasts that were removed var yeastsForDeletion = recipe.Yeasts.Except(recipe.Yeasts.Join(recipeViewModel.Yeasts ?? new List <RecipeYeastViewModel>(), x => x.RecipeYeastId, y => Converter.Convert <int>(y.Id), (x, y) => x)).ToList(); this.RecipeService.MarkRecipeIngredientsForDeletion <RecipeYeast>(yeastsForDeletion); // Delete Adjuncts that were removed var adjunctsForDeletion = recipe.Adjuncts.Except(recipe.Adjuncts.Join(recipeViewModel.Others ?? new List <RecipeOtherViewModel>(), x => x.RecipeAdjunctId, y => Converter.Convert <int>(y.Id), (x, y) => x)).ToList(); this.RecipeService.MarkRecipeIngredientsForDeletion <RecipeAdjunct>(adjunctsForDeletion); // Delete MashSteps that were removed var mashStepsForDeletion = recipe.MashSteps.Except(recipe.MashSteps.Join(recipeViewModel.MashSteps ?? new List <RecipeMashStepViewModel>(), x => x.RecipeMashStepId, y => Converter.Convert <int>(y.Id), (x, y) => x)).ToList(); this.RecipeService.MarkRecipeIngredientsForDeletion <RecipeMashStep>(mashStepsForDeletion); } #endregion #region INGREDIENT ADDITIONS // Add Fermentables if (recipeViewModel.Fermentables != null) { recipeViewModel.Fermentables.Where(x => Converter.Convert <int>(x.Id) == 0) .ForEach(x => recipe.Fermentables.Add(Mapper.Map(x, new RecipeFermentable()))); } // Add Hops if (recipeViewModel.Hops != null) { recipeViewModel.Hops.Where(x => Converter.Convert <int>(x.Id) == 0) .ForEach(x => recipe.Hops.Add(Mapper.Map(x, new RecipeHop()))); } // Add Yeasts if (recipeViewModel.Yeasts != null) { recipeViewModel.Yeasts.Where(x => Converter.Convert <int>(x.Id) == 0) .ForEach(x => recipe.Yeasts.Add(Mapper.Map(x, new RecipeYeast()))); } // Add Adjuncts if (recipeViewModel.Others != null) { recipeViewModel.Others.Where(x => Converter.Convert <int>(x.Id) == 0) .ForEach(x => recipe.Adjuncts.Add(Mapper.Map(x, new RecipeAdjunct()))); } // Add MashStep if (recipeViewModel.MashSteps != null) { recipeViewModel.MashSteps.Where(x => Converter.Convert <int>(x.Id) == 0) .ForEach(x => recipe.MashSteps.Add(Mapper.Map(x, new RecipeMashStep()))); } #endregion #region INGREDIENT UPDATES if (!isNewRecipe) { // Update Fermentables if (recipeViewModel.Fermentables != null) { foreach (var recipeFermentableViewModel in recipeViewModel.Fermentables.Where(x => Converter.Convert <int>(x.Id) > 0)) { var match = recipe.Fermentables.FirstOrDefault(x => x.RecipeFermentableId == Converter.Convert <int>(recipeFermentableViewModel.Id)); if (match == null) { throw new InvalidOperationException("Unable to find matching fermentable"); } Mapper.Map(recipeFermentableViewModel, match); } } // Update Hops if (recipeViewModel.Hops != null) { foreach (var recipeHopViewModel in recipeViewModel.Hops.Where(x => Converter.Convert <int>(x.Id) > 0)) { var match = recipe.Hops.FirstOrDefault(x => x.RecipeHopId == Converter.Convert <int>(recipeHopViewModel.Id)); if (match == null) { throw new InvalidOperationException("Unable to find matching Hop"); } Mapper.Map(recipeHopViewModel, match); } } // Update Yeasts if (recipeViewModel.Yeasts != null) { foreach (var recipeYeastViewModel in recipeViewModel.Yeasts.Where(x => Converter.Convert <int>(x.Id) > 0)) { var match = recipe.Yeasts.FirstOrDefault(x => x.RecipeYeastId == Converter.Convert <int>(recipeYeastViewModel.Id)); if (match == null) { throw new InvalidOperationException("Unable to find matching Yeast"); } Mapper.Map(recipeYeastViewModel, match); } } // Update Adjuncts if (recipeViewModel.Others != null) { foreach (var recipeAdjunctViewModel in recipeViewModel.Others.Where(x => Converter.Convert <int>(x.Id) > 0)) { var match = recipe.Adjuncts.FirstOrDefault(x => x.RecipeAdjunctId == Converter.Convert <int>(recipeAdjunctViewModel.Id)); if (match == null) { throw new InvalidOperationException("Unable to find matching Adjunct"); } Mapper.Map(recipeAdjunctViewModel, match); } } // Update MashSteps if (recipeViewModel.MashSteps != null) { foreach (var recipeMashStepViewModel in recipeViewModel.MashSteps.Where(x => Converter.Convert <int>(x.Id) > 0)) { var match = recipe.MashSteps.FirstOrDefault(x => x.RecipeMashStepId == Converter.Convert <int>(recipeMashStepViewModel.Id)); if (match == null) { throw new InvalidOperationException("Unable to find matching MashStep"); } Mapper.Map(recipeMashStepViewModel, match); } } } #endregion #region STEP DELETIONS / ADDITIONS / UPDATES // Deletions if (!isNewRecipe) { var stepsForDeletion = recipe.Steps.Except(recipe.Steps.Join(recipeViewModel.Steps ?? new List <RecipeStepViewModel>(), x => x.RecipeStepId, y => Converter.Convert <int>(y.Id), (x, y) => x)).ToList(); this.RecipeService.MarkRecipeStepsForDeletion(stepsForDeletion); } // Additions if (recipeViewModel.Steps != null) { if (recipe.Steps == null) { recipe.Steps = new List <RecipeStep>(); } recipeViewModel.GetSteps() .Where(x => Converter.Convert <int>(x.Id) == 0) .Where(x => !string.IsNullOrWhiteSpace(x.Text)) .ForEach(x => recipe.Steps.Add(Mapper.Map(x, new RecipeStep { DateCreated = DateTime.Now }))); } // Updates if (!isNewRecipe) { if (recipeViewModel.Steps != null) { foreach (var recipeStep in recipeViewModel.GetSteps() .Where(x => Converter.Convert <int>(x.Id) > 0) .Where(x => !string.IsNullOrWhiteSpace(x.Text))) { var match = recipe.Steps.FirstOrDefault(x => x.RecipeStepId == Converter.Convert <int>(recipeStep.Id)); if (match == null) { throw new InvalidOperationException("Unable to find matching step"); } match = Mapper.Map(recipeStep, match); match.DateModified = DateTime.Now; } } } #endregion // Save the Image if (isNewRecipe) { if (recipeViewModel.PhotoForUpload != null) { // Save the New Image recipe.ImageUrlRoot = this.StaticContentService.SaveRecipeImage(recipeViewModel.PhotoForUpload.InputStream, this.WebSettings.MediaPhysicalRoot); } } // Finalize Recipe this.RecipeService.FinalizeRecipe(recipe); unitOfWork.Commit(); if (isNewRecipe) { this.ForwardMessage(new SuccessMessage { Text = BrewgrMessages.RecipeSaved }); return(Redirect(Url.RecipeEditUrl(recipe.RecipeId))); } else { // Signals Success return(Content("1")); } } catch (Exception ex) { this.LogHandledException(ex); unitOfWork.Rollback(); if (isNewRecipe) { ViewBag.RecipeCreationOptions = this.RecipeService.GetRecipeCreationOptions(); this.AppendMessage(new ErrorMessage { Text = GenericMessages.ErrorMessage }); return(View("NewRecipe", recipeViewModel)); } else { // Signals Failure return(Content("-1")); } } } }
public void TransitiveConversion() { string targetValue = (string)Converter.Convert(42, typeof(string)); Assert.AreEqual("42", targetValue); }
// CUIモード static int CUIExec(bool q, List <string> files) { IOutputController Output = new CUIOutput(q); if (files.Count == 0) { Console.WriteLine(Properties.Resources.NOINPUTFILE); return(-5); } try { Directory.CreateDirectory(Path.GetTempPath()); } catch (Exception) { Console.WriteLine(String.Format(Properties.Resources.FAIL_TMPFOLDER, Path.GetTempPath())); return(-7); } int failnum = 0; var outFiles = new System.Collections.Specialized.StringCollection(); for (int i = 0; i < files.Count / 2; ++i) { string file = Path.GetFullPath(files[2 * i]); string dir; if (Properties.Settings.Default.workingDirectory == "file") { dir = Path.GetDirectoryName(file); } else if (Properties.Settings.Default.workingDirectory == "current") { dir = Directory.GetCurrentDirectory(); } else { dir = Path.GetTempPath(); } string tmpTeXFileName = TempFilesDeleter.GetTempFileName(Path.GetExtension(file), dir); if (tmpTeXFileName == null) { Console.WriteLine(String.Format(Properties.Resources.FAIL_TMPFILE, Path.GetTempPath())); return(-6); } tmpTeXFileName = Path.Combine(dir, tmpTeXFileName); // 一時フォルダにコピー File.Copy(file, tmpTeXFileName, true); (new FileInfo(tmpTeXFileName)).Attributes = FileAttributes.Normal; var output = Path.GetFullPath(files[2 * i + 1]); // 変換! try { using (var converter = new Converter(Output, tmpTeXFileName, output)) { converter.AddInputPath(Path.GetDirectoryName(file)); if (!converter.Convert()) { ++failnum; } else { outFiles.AddRange(converter.OutputFileNames.ToArray()); } } if (Properties.Settings.Default.setFileToClipBoard) { Clipboard.SetFileDropList(outFiles); } } catch (Exception e) { Console.WriteLine(e.Message); } } return(failnum); }
/// <inheritdoc /> public async Task <T> ExecuteAsync <T>(IDictionary <string, object> variables, CancellationToken cancellationtoken = new CancellationToken()) { return(Converter.Convert <T>(await ExecuteAsync(variables, cancellationtoken))); }
internal static TTo Convert <TFrom, TTo>(TFrom value) { return(Converter <TFrom, TTo> .Convert(value)); }