Using XML document as DataSource for DataTable - c#

I have a program which gets data from a database and uses that information to create a XML document.
The program works as intended, but there are issues when the program is used during the nightshift, as the database is usually under maintenance, so the program stops working as intended.
What I want to achieve here is, when the program cant connect to the database, to use a XML document (created with the same data as the database), so the program can work properly during the maintenance periods, basically, using a XML document to create another XML
Here is how the program is connected to the database:
namespace Cotas.Class
{
public class CData
{
static string S_Connection = "ConnectionString";
public static BDMINIAPPS.SP_MINIAPPS SPMINIAPPS = new BDMINIAPPS.SP_MINIAPPS(S_Connection);
public static BDMINIAPPS.D_CGeometricas CCGeometricos = new BDMINIAPPS.D_CGeometricas(S_Connection);
public static BDMINIAPPS.D_CGParametros CCGParametros = new BDMINIAPPS.D_CGParametros(S_Connection);
}
}
Method
private void LoadConfiguration()
{
DataTable DTCGeometricas = CData.SPMINIAPPS.SP_GetCGeometricas();
D_Tolerancia = decimal.Parse(CData.CCGParametros.SelectCGParametros("Tolerancia").Parametro);
S_Descripcion = CData.CCGParametros.SelectCGParametros("Descripcion").Parametro;
S_Encoding = CData.CCGParametros.SelectCGParametros("Encoding").Parametro;
S_PathOrigen = CData.CCGParametros.SelectCGParametros("PathOrigen").Parametro;
S_PathDestino = CData.CCGParametros.SelectCGParametros("PathDestino").Parametro;
S_PathProcesados = CData.CCGParametros.SelectCGParametros("PathProcesados").Parametro;
S_PathErrores = CData.CCGParametros.SelectCGParametros("PathErrores").Parametro;
S_ArchivoLOGs = CData.CCGParametros.SelectCGParametros("ArchivoLOGs").Parametro;
S_Operacion = CData.CCGParametros.SelectCGParametros("Operacion").Parametro;
foreach (DataRow DRCGeometrica in DTCGeometricas.Rows)
L_CGeometricas.Add(DRCGeometrica["CGeometrica"].ToString());
}
And this is the command I used to export the data from the Database to a XML document
SELECT ( SELECT * From CGeometricas
FOR
XML PATH('Row'), ROOT('CGeometricas'),
TYPE),
(SELECT * From CGParametros
FOR
XML PATH('Row'), ROOT('CGParametros'),
TYPE)
FOR XML PATH('') ,
ROOT('Root')

Related

Unit Testing class that requires file data?

I'm working on expanding our unit test suite, and I've come across a specific class that I'm attempting to figure out how to mock. I have a method that accepts a byte[] array as a parameter. In a perfect world, this byte array will always be a PDF file that contains a form of some sort. It then extracts all of the form fields from that pdf and returns them.
How can I potentially mock up logic that is dependent on file data? My only real ideas are to include the pdf in the project and use IO to read the test file, or to attempt to generate a pdf form on the fly and then extract those fields.
Here is the code for the PDF extractor:
public class PdfFormExtractor : IDisposable
{
private readonly PdfReader _pdfReader;
private readonly MemoryStream _newPdf;
private readonly PdfStamper _pdfStamper;
public PdfFormExtractor(byte[] pdf)
{
_pdfReader = new PdfReader(pdf);
_newPdf = new MemoryStream();
_pdfStamper = new PdfStamper(_pdfReader, _newPdf);
}
public FormDto ExtractForm()
{
var pdfFormFields = _pdfStamper.AcroFields;
var form = new FormDto()
{
Fields = pdfFormFields.Fields.Select(n => new FormFieldDto
{
Name = n.Key,
Label = n.Key
}).ToList()
};
return form;
}
#region IDisposable Support
// disposable implementation
#endregion
}
Use Resource files.
In Visual Studio, just create a resource file in your test project to contain all the files you want to use in your tests.
Open the resx and you will see the usual list of strings. But you're not limited to strings: you can select "Files" in the top-left dropdown and then drag and drop files INTO the resx file.
When you do, pay attention to the pasted file properties: you can select to interpret the file as binary (a byte[] is exposed, as in your use case) or text (with encoding, which exposes a string).
Then, in your test you can just reference the strongly typed Resource object and the strongly typed byte[] with the contents of your test file.
This strategy has a lot of applications when testing complex scenarios, especially when paired with a smart enough serializer/deserializer (like Json.NET).
You can serialize any complex data structure as Json, then in your tests reference it as a string (exposed directly by the Resource file's class), deserialize it with a simple JsonConvert.DeserializeObject and run your test on the business logic directly.
You can use Microsoft.Fakes to generate fake assembly for your *.dll. With Fakes, we can bend the outcome of any properties, methods,..
I faked Sqlconnection class which usually is hardened for mocking.
Right-click on your assembly (in my case, System.Data)
Create fakes assembly
It creates shims & stubs
We need to add scope by using (ShimsContext.Create()). Everything inside the scope will behave as you proposed.
public void ExtractFormTest()
{
using (ShimsContext.Create())
{
#region FakeIt
System.Data.SqlClient.Fakes.ShimSqlConnection.AllInstances.Open = (SqlConnection sqlConnection) =>
{
Console.WriteLine("Opened a session with Virtual Sql Server");
};
System.Data.SqlClient.Fakes.ShimSqlConnection.AllInstances.Close = (SqlConnection sqlConnection) =>
{
Console.WriteLine("Closed the session with Virtual Sql Server");
};
System.Data.SqlClient.Fakes.ShimSqlCommand.AllInstances.ExecuteNonQuery = (SqlCommand sqlCommand) =>
{
if (sqlCommand.CommandText.ToLower().Contains("truncate table"))
{
Console.WriteLine("Ran " + sqlCommand.CommandText + " at Virtual Sql Server");
return 1;
}
return 0;
};
System.Data.SqlClient.Fakes.ShimSqlBulkCopy.AllInstances.WriteToServerDataTable = (SqlBulkCopy sqlBulkCopy, DataTable datatable) =>
{
Console.WriteLine("Written #" + datatable.Rows.Count + " records to Virtual Sql Server");
};
System.Data.Common.Fakes.ShimDbDataAdapter.AllInstances.FillDataSet = (DbDataAdapter dbDataAdapter, DataSet dataSet) =>
{
var _dataSet = new DataSet();
var _dataTable = DataTableHelper.LoadFlatfileIntoDataTable(Path.Combine(dailyEmailFlatfilesDirectory, "Flatfile.txt"), flatfileDelimiter, flatfileDataTableFields, regexPatternMdmValidEmail, traceWriter);
if (dbDataAdapter.SelectCommand.CommandText.Equals(mdmSqlStorProcForSpFlatfileData))
{
while (_dataTable.Rows.Count > 1000)
_dataTable.Rows.RemoveAt(0);
}
else if (dbDataAdapter.SelectCommand.CommandText.Equals(mdmSqlStorProcForStFlatfileData))
{
while (_dataTable.Rows.Count > 72)
_dataTable.Rows.RemoveAt(0);
}
dataSet.Tables.Add(_dataTable);
dataSet = _dataSet;
return 1;
};
#endregion
#region Act
FormDto formDto = ExtractForm();
#endregion
#region Assert
// Upto the scope of your method and acceptance criteria
#endregion
}
}
Hope this helps!

How to delete table on Cassandra using C# Datastax driver?

var keyspace = "mydb";
var datacentersReplicationFactors = new Dictionary<string, int>(0);
var replication = ReplicationStrategies.CreateNetworkTopologyStrategyReplicationProperty(datacentersReplicationFactors);
using (var cluster = Cluster.Builder().AddContactPoints("my_ip").Build())
using (var session = cluster.Connect())
{
session.CreateKeyspaceIfNotExists(keyspace, replication, true);
session.ChangeKeyspace(keyspace);
var entityTable = new Table<Models.Entity>(session);
var attributeTable = new Table<Models.Attribute>(session);
entityTable.CreateIfNotExists(); // Worked
attributeTable.CreateIfNotExists(); // Worked
entityTable.Delete(); // Does nothing
attributeTable.Delete(); // Does nothing
}
EDIT: Without using raw queries session.Execute("DROP TABLE entities;"); working fine.
Delete() method is not intended for drop of the tables. It returns representation of a DELETE cql statement. If you call it, you just get {DELETE FROM entities}.
If you need to drop a table, the easiest way is just to execute DROP statement:
session.Execute("DROP TABLE entities;");
Unless there is already a method for dropping tables that I not aware of, you can use this extensions.
public static class DastaxTableExtensions
{
public static void Drop<T>(this Table<T> table)
{
table.GetSession().Execute($"DROP TABLE {table.Name};");
}
public static void DropIfExists<T>(this Table<T> table)
{
table.GetSession().Execute($"DROP TABLE IF EXISTS {table.Name};");
}
}
Then you can use it like this
entityTable.Drop();
attributeTable.DropIfExists();

Add data from XML to existing SQL Server Database with pre-set parameters

This is probably super simple, but I'm new to C# and SQL. So I have an XML generated by my program like this (it works perfectly).
namespace programName
{
class Program
{
static void Main(string[] args)
{
//Enumerate all .docx files
var enumerator = Directory.EnumerateFiles("[file path]"*.docx");
Xml.checklist xmlList = new Xml.checklist();
foreach (var entry in enumerator)
{
//XML is created
//name info
//birthday info
}
}
}
}
Now somewhere within this I want to grab the data from the XML and insert it into an SQL server database that already has these pre-existing parameters
#nvName (nvarchar(50), Input, Default)
#dteBirthday(datetime, Input, Default)
How would I go about doing this within the program? It seems simple, but I'm lost

Save data in a Visual Studio WPF aplication without a database

I'm developing a WPF app using C#.
The first thing my app does is trying to connect to the database, so I ask for some data to connect to the database like the name of the server (could be the IP too), the name of the database, the name of MySQL instance user and password, and the port (3306 for default). But I want to save this info in the app because I don't have the database yet to save there.
I want to save this strings in the application without using a database:
Computer Name
Name of the database backup
MySql Instance User
MySql Instance Pass
Port
I don't want to save this data in the database because I need this info for the first use of the application.
With first use I mean before the database backup is even restored to the server from the installer.
You can save file with registry. Try this :
Microsoft.Win32.RegistryKey RegistryKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("WPF APPLICATION");
RegistryKey.SetValue(SET THE VALUE);
RegistryKey.Close();
best practice is to store these values in configuration file. like a .ini file or xml file.
if your data is sensitive and you don't wish to see this details directly you can encrypt this data with any convenient encryption method.
so your ini file structure will look like this,
[port]=3306
[ip]=111.222.1.2
hope this will help.
Try using the app.Config.
The main benefit of the app.config is that It's directly attached to your executable. Once you build your solution, the app.config gets copied together with the executable.
From What is App.config in C#.NET? How to use it?:
At its simplest, the app.config is an XML file with many predefined configuration sections available and support for custom configuration sections. A "configuration section" is a snippet of XML with a schema meant to store some type of information.
Settings can be configured using built-in configuration sections such as connectionStrings or appSettings. You can add your own custom configuration sections; this is an advanced topic, but very powerful for building strongly-typed configuration files.
Source for app.config in msdn: How to: Add an Application Configuration File to a C# Project
.NET Applications are compiled with a .config file like "YourApp.exe.config" next to the .exe.
This file should be used for such purposes, and can be accessed in code with the ConfigurationManager.
/You can Save Data in XML file/
//You can Save and load time by this method but it's slow process,
it may crash if data is large and system is slow, it stores data runtime
so takes RAM, its ok to use for few rows without any problem
//use the collection for storing data runtime
List<Person> pers = new List<Person>();
public class Person
{
public string id { get; set; }//1
public string name { get; set; }//2
public string bilno { get; set; }//3
public string mob { get; set; }//4
public DateTime dt { get; set; }//5
}
string path=#"c:\.....";
void save()
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load(path + #"\data.xml");
XmlNode xnode = xdoc.SelectSingleNode("Items");
xnode.RemoveAll();
foreach (Person i in pers)
{
XmlNode xtop = xdoc.CreateElement("Item");
XmlNode x1 = xdoc.CreateElement("a");
XmlNode x2 = xdoc.CreateElement("b");
XmlNode x3 = xdoc.CreateElement("c");
XmlNode x4 = xdoc.CreateElement("d");
XmlNode x5 = xdoc.CreateElement("e");
x1.InnerText = i.id;
x2.InnerText = i.name;
x3.InnerText = i.bilno;
x4.InnerText = i.mob;
x5.InnerText = i.dt.ToFileTime().ToString();
xtop.AppendChild(x1);
xtop.AppendChild(x2);
xtop.AppendChild(x3);
xtop.AppendChild(x4);
xtop.AppendChild(x5);
xdoc.DocumentElement.AppendChild(xtop);
}
xdoc.Save(path + #"\data.xml");
}
void load()
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load(path + #"\data.xml");
foreach (XmlNode xnode in xdoc.SelectNodes("Items/Item"))
{
Person p = new Person();
p.id = xnode.SelectSingleNode("a").InnerText;
p.name = xnode.SelectSingleNode("b").InnerText;
p.bilno = xnode.SelectSingleNode("c").InnerText;
p.mob = xnode.SelectSingleNode("d").InnerText;
p.dt = DateTime.FromFileTime(Convert.ToInt64(xnode.SelectSingleNode("e").InnerText));
}
}

Read XML files in deployed app to Windows Store

I have a simple service which let me read XML file.
public class SetService : ISetService
{
private const string FilesPath = "Data/Sets.xml";
private string xmlPath = Path.Combine(Package.Current.InstalledLocation.Path, FilesPath);
public async Task<IList<Set>> GetAll()
{
XDocument loadedData = XDocument.Load(xmlPath);
var data = from query in loadedData.Descendants("set")
select new Set
{
Id = (int)query.Element("id"),
Name = (string)query.Element("name"),
IsActive = (bool)query.Element("isactive"),
IsPassed = (bool)query.Element("ispassed"),
};
return (IList<Set>)data.ToList();
}
}
Everything works fine when I am using this method, on my local machine or on emulator provided with Microsoft Visual Studio 2013 but after I published this app to the Windows Store I am not able to see these data from XML files.
What am I doing wrong?

Categories

Resources