I have attempting to implement a file naming convention in my program. For example I have a configuration file such as below:
MyConfig.conf
# File naming convention for output-file
[Field1][Field3][Field2]
'FieldX' corresponds with string within the program - so for example a program would read the configuration file and format the strings as follows in the program:
Field1Value Field2Value Field3Value
Are there any preferred ways to do this kind of thing in C#?
Easiest way I can think of is to use app settings. The app settings contain the string format that you need. Then you just use that string format.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _16852548
{
class Program
{
static void Main(string[] args)
{
NameValueCollection appSettings = ConfigurationManager.AppSettings;
string field1Value = "Filename";
string field2Value = ".";
string field3Value = "txt";
string fileFormat = appSettings["FileNameFormat"];
Console.WriteLine(string.Format(fileFormat, field1Value, field2Value, field3Value));
}
}
}
Then the config file can be:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="FileNameFormat" value="{0}{2}{1}"/> <!-- follow string.Format syntax -->
</appSettings>
</configuration>
Related
I am new to the UFT API Test, and I need to extract certain values from the XML response to be included in an existing XLS, which will serve as input data for another test.
This is my XML Response:
<NS1:Body>
<NS3:BuscaSaldosCaptacionOut xmlns:NS3="http://www.portal.com/ws/esb/ConsultaCuentasSaldos">
<SaldosCaptacion>
<NumeroCliente>51844068</NumeroCliente>
<Cuenta>0201484326</Cuenta>
<ProductoCuenta>01</ProductoCuenta>
<SubProductoCuenta>0382</SubProductoCuenta>
<Divisa>MXP</Divisa>
<IdCuenta>0201484326</IdCuenta>
<SaldoInicialDia>7062.42</SaldoInicialDia>
<SaldoPromedio>30596.01</SaldoPromedio>
<SaldoActual>17062.42</SaldoActual>
<SaldoDisponible>17062.42</SaldoDisponible>
<EstatusCuenta>A</EstatusCuenta>
</SaldosCaptacion>
<SaldosCaptacion>
<NumeroCliente>51844068</NumeroCliente>
<Cuenta>0201484371</Cuenta>
<ProductoCuenta>01</ProductoCuenta>
<SubProductoCuenta>0340</SubProductoCuenta>
<Divisa>MXP</Divisa>
<SaldoInicialDia>6825.11</SaldoInicialDia>
<SaldoPromedio>8936.26</SaldoPromedio>
<SaldoActual>6825.11</SaldoActual>
<SaldoDisponible>6825.11</SaldoDisponible>
<SaldoRetenido>0.00</SaldoRetenido>
<EstatusCuenta>A</EstatusCuenta>
</SaldosCaptacion>
<SaldosCaptacion>
<NumeroCliente>51844068</NumeroCliente>
<Cuenta>0201533729</Cuenta>
<ProductoCuenta>01</ProductoCuenta>
<SubProductoCuenta>0363</SubProductoCuenta>
<Divisa>MXP</Divisa>
<SaldoInicialDia>28316.52</SaldoInicialDia>
<SaldoPromedio>6230.52</SaldoPromedio>
<SaldoActual>7374.52</SaldoActual>
<SaldoDisponible>7374.52</SaldoDisponible>
<SaldoRetenido>942.00</SaldoRetenido>
<EstatusCuenta>A</EstatusCuenta>
</SaldosCaptacion>
</NS3:BuscaSaldosCaptacionOut>
I need save "Cuenta" and "SaldoActual" values. (Everybody), and completely ignore how to parameterize them.
The "Write to file" option does not work for me.
Try following code. If it doesn't work then the namespace needs to be changed in code. I can't tell the correct namespace because you did post the beginning of the xml file. I'm using xml linq which is a Net Library.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
string xml = File.ReadAllText(FILENAME);
XElement doc = XElement.Parse(xml);
var results = doc.Descendants("SaldosCaptacion").Select(x => new {
Cuenta = (string)x.Element("Cuenta"),
SaldoActual = (decimal)x.Element("SaldoActual")
}).ToList();
}
}
}
I'm attempting to implement my first go-around of reading custom configuration elements from an ASP.NET web.config file. It seems pretty simple to me, yet I'm receiving a run-time `Property is not a ConfigurationElement' error. Here's my code:
The web.config file sections:
<?xml version="1.0" encoding="utf-8" ?>...
<configuration>
...
<section name="appConfig" type="ParticipationManagement.AppConfig" allowDefinition="Everywhere" allowLocation="true" requirePermission="false" />
</configSections>
...
<appConfig>
<startRecertVFC>2/15</startRecertVFC>
</appConfig>
</configuration>
The handler:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;
namespace ParticipationManagement
{
public class AppConfig : ConfigurationSection
{
[ConfigurationProperty("startRecertVFC", IsRequired = false)]
public DateTime RecertVFCStart
{
get
{
string start = (string)this["startRecertVFC"];
string year = DateTime.Now.Year.ToString();
DateTime start_date;
if (DateTime.TryParse(start + "/" + year, out start_date))
{
return start_date;
}
else
{
return DateTime.Today;
}
}
set
{
this["startRecertVFC"] = value;
}
}
}
}
And my invocation in page code:
protected void Page_Init(object sender, EventArgs e)
{
...
AppConfig config = (AppConfig)System.Configuration.ConfigurationManager.GetSection("appConfig");
RecertVFCStart = config.RecertVFCStart;
}
Seems very clean and straight-forward to me, but I'm getting that troubling error at runtime and I cannot narrow it down since I have no experience with this.
Sorry in advance: I see plenty of other posts about this but all seem to address more advanced/complex issues than what I'm trying to accomplish, which is nothing more than embedding a few app-specific values in an external file...
Change your config setting like an example shown below
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="appConfig" type="ParticipationManagement.AppConfig" allowDefinition="Everywhere" allowLocation="true" requirePermission="false"/>
</configSections>
<appConfig startRecertVFC="5/1/2015 8:30:52 AM" />
</configuration>
Try to make the following change in AppConfig file
string start = this["startRecertVFC"].ToString();
Let us know if this solves your problem
I created this class "XML_Toolbox" that could be used by any of my forms to perform any of the key XML actions that i am going to be using repeatedly. So with that being said, here is that class' code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;
namespace Personal_Finance_Manager
{
class XML_toolbox
{
public static void createFile (string filename, string filePath)
{
string createPath = filePath + #"\" + filename + ".txt";
if (file.exists(createPath))
{
StreamWriter outfile = new StreamWriter(createPath, true);
}
else
{
MessageBox.Show("This file already exists!!! Please choose another name!");
}
}
}
}
all the individual parts were working when called from another form up until i added the:
if (file.exists(createPath)) {}
IF statement.
Now i am getting the
The name "file" does not exist in the current context
error. I have the
using System.IO;
what else am i missing?
Thanks!
Class name is File not file, method name is Exists. C# is case-sensitive.
It's called File, not file.
File.Exists()
I have the xml file is following manner :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Conn" providerName="System.Data.SqlClient"
connectionString="Data Source=machine_name; Initial Catalog=database_name; User ID=id; Password=password" />
</connectionStrings>
</configuration>
In above xml file i want to change the value of password.
Code i have tried is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Configuration;
using System.Xml.Linq;
namespace ConsoleApplication85
{
class Program
{
static void Main(string[] args)
{
XDocument xdoc = XDocument.Load(#"filepath.xml");
var element = xdoc.Elements("Password").Single();
element.Value = "new password";
xdoc.Save(#"filepath.xml");
}
}
}
The best way to change the application configuration is through the methods of the ConfigurationManager class, not through XmlDocument methods..
See this question:
Change connection string & reload app.config at run time
I have a very large sql file I want to break up into batches for execution.
I want to make sure I'm parsing it the same way that SSMS and SQLCMD do.
Microsoft has a great mixed mode assembly named Microsoft.SqlServer.BatchParser with a class named Parser that seams like it would do the trick.
It wants an implementation of IBatchSource as an argument to SetBatchSource before calling Parse().
Where can I find an implementation of IBatchSource, and more information on how to make use of this functionality?
I found the assembly Microsoft.SqlServer.BatchParser in the GAC along with it's friend Microsoft.SqlServer.BatchParserClient that contains implementations the interface IBatchSource.
namespace Microsoft.SqlServer.Management.Common
{
internal class BatchSourceFile : IBatchSource
internal class BatchSourceString : IBatchSource
}
The following conversation then occurred.
Assembly: Hello! My name is
Microsoft.SqlServer.Management.Common.ExecuteBatch. Would you like to StringCollection GetStatements(string sqlCommand)?
Me: Yes, I would, BatchParserClient assembly. Thanks for asking!
Repeatable Instructions (Do try this at home!)
Install Microsoft SQL Server 2008 R2 Shared Management Objects
Copy Microsoft.SqlServer.BatchParser.dll and Microsoft.SqlServer.BatchParserClient.dll from the GAC to a folder in your solution.
Reference Microsoft.SqlServer.BatchParser & Microsoft.SqlServer.BatchParserClient
Program.cs
using System;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using Microsoft.SqlServer.Management.Common;
namespace ScriptParser
{
class Program
{
static void Main(string[] args)
{
ExecuteBatch batcher = new ExecuteBatch();
string text = File.ReadAllText(#"Path_To_My_Long_Sql_File.sql");
StringCollection statements = batcher.GetStatements(text);
foreach (string statement in statements)
{
Console.WriteLine(statement);
}
}
}
}
App.Config
<?xml version="1.0"?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
</startup>
</configuration>
Another option is to use the ScriptDom as described in this answer: https://stackoverflow.com/a/32529415/26877.
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.SqlServer.TransactSql.ScriptDom;
namespace ScriptDomDemo
{
class Program
{
static void Main(string[] args)
{
TSql120Parser parser = new TSql120Parser(false);
IList<ParseError> errors;
using (StringReader sr = new StringReader(#"create table t1 (c1 int primary key)
GO
create table t2 (c1 int primary key)"))
{
TSqlFragment fragment = parser.Parse(sr, out errors);
IEnumerable<string> batches = GetBatches(fragment);
foreach (var batch in batches)
{
Console.WriteLine(batch);
}
}
}
private static IEnumerable<string> GetBatches(TSqlFragment fragment)
{
Sql120ScriptGenerator sg = new Sql120ScriptGenerator();
TSqlScript script = fragment as TSqlScript;
if (script != null)
{
foreach (var batch in script.Batches)
{
yield return ScriptFragment(sg, batch);
}
}
else
{
// TSqlFragment is a TSqlBatch or a TSqlStatement
yield return ScriptFragment(sg, fragment);
}
}
private static string ScriptFragment(SqlScriptGenerator sg, TSqlFragment fragment)
{
string resultString;
sg.GenerateScript(fragment, out resultString);
return resultString;
}
}
}