Write to XML file using existing dataset created in Visual Basic - c#

Please bear with me. I don't have any knowledge of C# or Visual Basic but I've been tasked with a complex project that wasn't properly scoped. This is way outside the scope of my normal work but no one in the organization appears to have this knowledge so I'm trying to assist since this data is a state requirement. I have been googling, watching tutorials, and testing things out for weeks.
I have multiple tables that I've used to create a dataset using Visual Studio 2019. Now I need to write the data in that dataset to XML. Most of what I've seen online just has a few lines of code like:
private void WriteXmlToFile(DataSet thisDataSet)
{
if (thisDataSet == null) { return; }
// Create a file name to write to.
string filename = "XmlDoc.xml";
// Write to the file with the WriteXml method.
thisDataSet.WriteXml(filename);
}
or
string filePath = "ENTER A VALID FILEPATH";
northwindDataSet.WriteXml(filePath);
but doesn't really say where or how they should be utilized (there obviously has to be more to it). I did try this by replacing 'thisDataSet' with my existing dataset but got an error that the modifier private is not valid for this item. I think because it's inside of another private void for the button click.
I found a tutorial that helped me create a form and then code for creating and filling a dataset and then writing that to XML and I was able to do that successfully and I understand what is being done.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace NEMSIS_Project
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void BtnCreate_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataColumn dc1 = new DataColumn("Name");
DataColumn dc2 = new DataColumn("Age");
DataColumn dc3 = new DataColumn("Gender");
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
dt.Columns.Add(dc3);
dt.Rows.Add("Mourya", "25", "Male");
dt.Rows.Add("Steve", "40", "Male");
dt.Rows.Add("Jasmine", "19", "Female");
DataSet ds = new DataSet();
ds.Tables.Add(dt);
ds.WriteXml("Contacts.xml");
}
}
}
My disconnect is how to use my own dataset. I've tried piecing together code from around the internet but I keep getting different errors depending on the code. I've tried searching my issue/question different ways but have yet to come up with anything. I'm not sure if I need to write something to call my dataset or if I have to "write" a query to pull the data from my dataset into a new dataset and then write to XML. Any guidance would be greatly appreciated.

Related

My JSON API call won't refresh with new data in C#. How do I clear the cache so I get fresh data?

As many others here, I’m new to C# and Xamarin, but not programming in general.
I’m working on a proof of model concept where I can reach out and query stock/crypto price data and update elements in Xamarin with that data.
I have an API method called LoadData() which works right when the application launches. It updates a few Xamarin Label items with the data in their Text property.
I have a Xamarin Button object which has a Click event that triggers the same LoadData() method in the attempt that it will load in new JSON data and subsequently update the Labels with the new data.
Any subsequent LoadData() call will NOT work once it is called the first time. What I think is happening is that the original data it called gets cached, and the call doesn’t return brand NEW, fresh data.
I have spent two days looking up caching in C# trying to find the right code syntax to either clear out the JSON data before each LoadData() call, or to prevent it from caching. I have found quite a few conversations and code examples, but when I try them they either don’t work, or they appear with red underlines in Visual Studio and generate errors.
I’m going to be making a lot of these API calls and so I’m looking for the right syntax to use to solve this problem. Any help with clear code examples is greatly appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Xamarin.Forms;
namespace DataBindingTest2
{
[System.ComponentModel.DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
static string IEXTrading_API_PATH = "https://cloud.iexapis.com/v1/crypto/btcusdt/quote/1?token=TOKEN_GOES_HERE";
static List<string> FinalPriceQuote = new List<string>(); // The LIST object to hold the final JSON data
public string vLatestPrice = "";
public string vCompanyName = "";
public string vLatestVolume = "";
public MainPage()
{
InitializeComponent();
LoadData();
}
void Handle_Clicked(object sender, System.EventArgs e)
{
LoadData();
}
public async void LoadData()
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Cache-Control", "no-cache"); // <-- doesn't seem to have any effect
using (HttpResponseMessage response = await client.GetAsync(IEXTrading_API_PATH))
using (HttpContent content = response.Content)
{
string data = await content.ReadAsStringAsync();
if (data != null)
{
RootObject priceData = JsonConvert.DeserializeObject<RootObject>(data);
FinalPriceQuote.Add(priceData.symbol.ToString());
FinalPriceQuote.Add(priceData.latestPrice.ToString());
FinalPriceQuote.Add(priceData.latestVolume.ToString());
vCompanyName = FinalPriceQuote[0];
vLatestPrice = FinalPriceQuote[1];
vLatestVolume = FinalPriceQuote[2];
CompanyName.Text = vCompanyName; // <-- updates Label text in XAML
PriceLabel.Text = vLatestPrice; // <-- updates Label text in XAML
LatestVolume.Text = vLatestVolume; // <-- updates Label text in XAML
}
}
}
}
}
It looks like you're always appending to FinalPriceQuote and reading the first 3 values., but never clearing it. Try adding FinalPriceQuote.Clear() before your FinalPriceQuote.Add(...)

Error when add new detail row in Payments and Applications (AR302000) screen because of customization (in Acumatia ERP System)

I have already create some customization in screen Payment and Application of Acumatica ERP. I have created new Extension of ARPaymentEntryExtension.cs
The following is the source code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using PX.Data;
using PX.Objects.AR;
using PX.Objects.GL;
namespace SGLCustomizeProject
{
public class ARPaymentEntryExtension: PXGraphExtension<ARPaymentEntry>
{
#region Override Button Menu
public override void Initialize()
{
Base.report.AddMenuAction(ReceiptVoucher);
}
#endregion
#region Button Receipt Vocher
public PXAction<ARPayment> ReceiptVoucher;
[PXButton]
[PXUIField(DisplayName = "Receipt Voucher")]
public IEnumerable receiptVoucher(PXAdapter adapter)
{
var result = adapter.Get<ARPayment>();
foreach (ARPayment doc in result)
{
object FinPeriodID;
if (Base.Caches[typeof(ARPayment)].GetStatus(doc) == PXEntryStatus.Notchanged)
{
Base.Caches[typeof(ARPayment)].SetStatus(doc, PXEntryStatus.Updated);
}
Base.Save.Press();
var docPeriod = (FinPeriodID = Base.Caches[typeof(ARPayment)].GetValueExt<ARRegister.finPeriodID>(doc)) is PXFieldState ? (string)((PXFieldState)FinPeriodID).Value : (string)FinPeriodID;
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters["ReferenceNbr"] = doc.RefNbr;
throw new PXReportRequiredException(parameters, "AR909095", "Report");
}
return result;
}
#endregion
}
}
I used extensoin above to preview report from current screen and it works.
When user need to create new document and then add some detail document and then click on save button, it will work.
But, when user need to add another detail document and then click on save button, system will show the error message.
Please refer to the following screenshot.
Actually the error message appear after Acumatica was upgraded into version 2017 R2 - Build 17.207.0029.
In previous version (Version 5.3 - Build 5.30.4209) it work fine.
Does anyone know how to solve this issue ?
I have solve this problem by remove the following If Condition of the code:
if (Base.Caches[typeof(ARPayment)].GetStatus(doc) == PXEntryStatus.Notchanged)
{
Base.Caches[typeof(ARPayment)].SetStatus(doc, PXEntryStatus.Updated);
}
After remove code above, the customization is work and no error.

How to do a simple C# import?

Okay, this may seem silly. But, I don't know how to do an "import" in C#, in visual studio 2008. I know java, but not C#. Currently, I don't have the time to read a c# book. So, I need some help to get it right.
I was trying to use the code here - SSIS Getting Execute Sql Task result set object
DataTable dt = new DataTable();
OleDbDataAdapter oleDa = new OleDbDataAdapter();
oleDa.Fill(dt, Dts.Variables["User::objShipment"].Value);
And I get the error - The type or namespace name 'OledDbDataAdapter' could not be found (are you missing a using directive or an assembly reference?)
I tried to do a java style import. But it failed.
using System.Data.OleDb::OleDbDataAdapter
Full code given below -
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.Data.OleDb;
namespace ST_LongCodeGoesHere.csproj
{
[System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
#region VSTA generated code
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
//To see the comment here, look at beyond end of this code.
public void Main()
{
// TODO: Add your code here
DataTable table = new DataTable();
OledDbDataAdapter oleDbA = new OleDbDataAdapter();
Dts.TaskResult = (int)ScriptResults.Success;
}
}
}
The comment was -
/*
The execution engine calls this method when the task executes.
To access the object model, use the Dts property. Connections, variables, events,
and logging features are available as members of the Dts property as shown in the following examples.
To reference a variable, call Dts.Variables["MyCaseSensitiveVariableName"].Value;
To post a log entry, call Dts.Log("This is my log text", 999, null);
To fire an event, call Dts.Events.FireInformation(99, "test", "hit the help message", "", 0, true);
To use the connections collection use something like the following:
ConnectionManager cm = Dts.Connections.Add("OLEDB");
cm.ConnectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;Provider=SQLNCLI10;Integrated Security=SSPI;Auto Translate=False;";
Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
To open Help, press F1.
*/
In C#, you don't import individual types, you import whole namespaces. Something like this
should work:
using System.Data.OleDb;
...
OleDbDataAdapter oleDa = new OleDbDataAdapter();
Or you could create a type alias like this:
using OleDbDataAdapter = System.Data.OleDb.OleDbDataAdapter;
Further Reading
using Directive (C# Reference)
In Solution Explorer under your Solution find 'References' and add System.Data by right-clicking and 'Add reference'. You probably also want to type your import as: using System.Data.OleDb;
Have a look at this http://msdn.microsoft.com/en-us/library/vstudio/wkze6zky.aspx
You need to add the reference, before you can use it.

unable to connect to R from c#

I am trying to connect to R from c# using the following code. It looks like C# is not reading the R dll files. My R installation directory is this:
C:\Users\R-2-13\R-2.13.0\bin\i386
and I also downloaded and put the R.NET.dll in the same directory. In Visual Studio, I set the reference to R.NET.dll file. When I run the following code, the code goes the the catch section "unable to find the R Installation". Any ideas? Has anybody got this working?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RDotNet;
namespace RNet_Calculator
{
public partial class Form1 : Form
{
// set up basics and create RDotNet instance
// if anticipated install of R is not found, ask the user to find it.
public Form1()
{
InitializeComponent();
bool r_located = false;
while (r_located == false)
{
try
{
REngine.SetDllDirectory(#"C:\Users\R-2-13\R-2.13.0\bin\i386");
REngine.CreateInstance("RDotNet");
r_located = true;
}
catch { MessageBox.Show(#"Unable to find R installation's \bin\i386 folder. Press OK to attempt to locate it.");
MessageBox.Show("error");
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
This is http://rdotnet.codeplex.com/ (RDotNet) to develop Winform applications. While I know Shiny and all the other Web-like R-tools quite well, the combination of c# and R still is my preferred end-user combinations. Try simple things like disabling buttons with Shiny...
Too bad rdotnet is quite buggy; in the current version, it crashes on R exeptions, even in try-catched ones.
This said: please make absolutely sure that you use version 1.5, not the stupidly called "stable" (=early beta) version on the page. Best download it via NuGet. Also check if you did not mix 32bit R with 64 bit c#.
Using the Helper-functions of 1.5, initialization is:
Helper.SetEnvironmentVariables();
engine = REngine.CreateInstance(EngineName);
engine.Initialize();
# Assuming you want to catch the graphic window, use my RGraphAppHook
# on the rdotnet site http://rdotnet.codeplex.com/workitem/7
cbt = new RGraphAppHook { GraphControl = GraphPanelControl };

Is there a tool that allows easy exporting of messages from a message queue (MSMQ)?

I am currently working on batch processing application using MSMQ in C#. In the application design, I have an error queue containing XML messages using the ActiveXFormatter. I know that I can write an application to write these error messages to text files or database tables.
Are there other pre-built tools available allowing you to export messages to variety of formats (i.e. text files, database tables, etc.)? I am just looking for best practices.
Ok. I found the solution of writing code to be really easy. Here's my reference solution.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Messaging;
namespace ExportMSMQMessagesToFiles
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void btnExportTextFiles_Click(object sender, EventArgs e)
{
//Setup MSMQ using path from user...
MessageQueue q = new MessageQueue(txtMSMQ.Text);
//Setup formatter... Whatever you want!?
q.Formatter = new ActiveXMessageFormatter();
// Loop over all messages and write them to a file... (in this case XML)
MessageEnumerator msgEnum = q.GetMessageEnumerator2();
int k = 0;
while (msgEnum.MoveNext())
{
System.Messaging.Message msg = msgEnum.Current;
string fileName = this.txtFileLocation.Text + "\\" + k + ".xml";
System.IO.File.WriteAllText(fileName, msg.Body.ToString());
k++;
}
MessageBox.Show("All done!");
}
}
}

Categories

Resources