Add data at the end of existing data in resource file - c#

I want to add data at the end of existing data in resource file on the click of button in windows form.
I have a windows form with 3 text boxes -
text_box1: Name
text_box2: Value
text_box3: Comments
and a button named as Save.
code for button:
private void button1_Click(object sender, EventArgs e)
{
myMethod.Create(textBox1.Text, textBox2.Text, textBox3.Text);
}
Method to add data in resource file:
public class myMethod
{
public static void Create(string myName, string myValue, string myComment)
{
try
{
ResXResourceReader resxReader = new ResXResourceReader(#"D:\Validator_Tool\resx\resx\myres.resx");
resxReader.UseResXDataNodes = true;
IDictionaryEnumerator data = resxReader.GetEnumerator();
while (data.MoveNext())
{
ResXResourceWriter resxWriter = new ResXResourceWriter(#"D:\Validator_Tool\resx\resx\myres.resx");
var node = new ResXDataNode(myName, myValue);
node.Comment = myValue;
resxWriter.AddResource(node);
resxWriter.Close();
}
}
catch (FileNotFoundException caught)
{
MessageBox.Show("Source: " + caught.Source + " Message: " + caught.Message);
}
}
}
Please help me in this problem to add data in resource file because with this code my data is overwrite with existing data but I want my data should append at the end of the existing data.
This code giving me exception too while using IDictionaryEnumerator exception is:
System.InvalidOperationException

This is a snippet, to add a new line to your resx and keep the old records:
var reader = new ResXResourceReader("filename");
var node = reader.GetEnumerator();
var writer = new ResXResourceWriter("filename");
while (node.MoveNext())
{
writer.AddResource(node.Key.ToString(), node.Value.ToString());
}
var newNode = new ResXDataNode("name", "value");
writer.AddResource(newNode);
writer.Generate();
writer.Close();
This will re-write your old lines and add your new line.

Related

Checking to see if definition exists in Revit API

Running into an issue where I can't figure out how to tell this to check if the definition or shared parameter exists before adding. I've tried combinations of if else statements as well as coalescing. There is still a lot that I am learning so any help would be greatly appreciated. ` public Autodesk.Revit.UI.Result Execute(
ExternalCommandData commandData, ref string message, Autodesk.Revit.DB.ElementSet elements)
{
Transaction transaction = new Transaction(commandData.Application.ActiveUIDocument.Document, "External Tool");
try
{
transaction.Start();
//Create a clear file as parameter file.
String path = Assembly.GetExecutingAssembly().Location;
int index = path.LastIndexOf("\\");
String newPath = path.Substring(0, index);
newPath += "\\TPMechanicalRevitParameters.txt";
if (File.Exists(newPath))
{
File.Delete(newPath);
}
FileStream fs = File.Create(newPath);
fs.Close();
//cache application handle
Application revitApp = commandData.Application.Application;
//prepare shared parameter file
commandData.Application.Application.SharedParametersFilename = newPath;
//Open shared parameter file
DefinitionFile parafile = revitApp.OpenSharedParameterFile();
//get Fabricaation Pipe category
Category TpCat = commandData.Application.ActiveUIDocument.Document.Settings.Categories.get_Item(BuiltInCategory.OST_FabricationPipework);
CategorySet categories = revitApp.Create.NewCategorySet();
categories.Insert(TpCat);
InstanceBinding binding = revitApp.Create.NewInstanceBinding(categories);
//Create a group
DefinitionGroup apiGroup = parafile.Groups.Create("TpFabricationPipe");
//Create a visible "VisibleParam" of text type.
ExternalDefinitionCreationOptions ExternalDefinitionCreationOptions1 = new ExternalDefinitionCreationOptions("FullFabricationServiceName", ParameterType.Text);
Definition visibleParamDef = apiGroup.Definitions.Create
(ExternalDefinitionCreationOptions1);
BindingMap bindingMap = commandData.Application.ActiveUIDocument.Document.ParameterBindings;
bindingMap.Insert(visibleParamDef, binding);
//Create a invisible "InvisibleParam" of text type.
ExternalDefinitionCreationOptions ExternalDefinitionCreationOptions2 = new ExternalDefinitionCreationOptions("InvisibleParam", ParameterType.Text);
Definition invisibleParamDef = apiGroup.Definitions.Create
(ExternalDefinitionCreationOptions2);
bindingMap.Insert(invisibleParamDef, binding);
}
catch (Exception e)
{
transaction.RollBack();
message = e.ToString();
return Autodesk.Revit.UI.Result.Cancelled;
}
finally
{
transaction.Commit();
}
return Autodesk.Revit.UI.Result.Succeeded;
}`
Think I've found a solution. I just changed it to see if the file exists instead of the definition & it worked. If there is a better way to achieve this let me know.

How to retrieve data from firebase using firesharp c# library (unknown exact child path)?

I'm trying to make a database that stores dental records. I'm using firesharp library. I made a form called Register UI that registers details of new patients. Then another form called DatabaseUI where records could be retrieved from the database. Here is what my firebase structure looks like:
Firebase Parent/child structure (General Records>Patient Name>PatientDetails)
I used this code to connect to firebase:
{
IFirebaseConfig config = new FirebaseConfig {
AuthSecret = "\\mysecretcode",
BasePath = "\\firebase url"
};
IFirebaseClient client;
client = new FireSharp.FirebaseClient(config);
The Register Form code looks like this ("Data" is a class):
public async void subbtn_Click(object sender, EventArgs e) {
//For Gender Radio Buttons
string gender = "";
if (maleradio.Checked) {
gender = "Male";
} else {
gender = "Female";
}
//Data to be stored into Firebase
var data = new Data {
Name = lastnametbox.Text + ", " + firstnametbox.Text + " " + mitbox.Text,
Age = agetbox.Text,
Gender = gender,
Birthdate = dateTimePicker1.Value.Date.ToString("MM/dd/yyyy")
};
if (selectdbase.Text == "General") //Store in General Records Category
{
SetResponse response = await client.SetAsync("General Records/" + data.Name, data);
Data result = response.ResultAs < Data > ();
} else //Store in Orthodontics Records Category
{
SetResponse resp2 = await client.SetAsync("Orthodontics Records/" + data.Name, data);
Data result = resp2.ResultAs < Data > ();
};
MessageBox.Show("Registered!");
this.Close();
}
Here's the code for the database form:
private async void searchbtn_Click(object sender, EventArgs e) {
FirebaseResponse response = await client.GetAsync("General Records/" + data.Name); //'data' is unknown here
Data obj = response.ResultAs < Data > ();
searchtbox.Text = obj.Name;
}
Adding of records works fine. In retrieving from firebase, the error is at "data.Name" since that variable is in the RegistrationUI Form. The output on the textbox is always null. What path after the "General Records/" should I put since the nodes under this are varying (since they are names of patients)? Please please help.

An Error occured while parsing EntityName. Line 32, position 51

I've tried looking at several different methods revolving around using XDocument class to load my xml file. However, this error and other variations have been appearing. If I use the absolute path, it displays an error of it cannot find the file.
The issue is my xml file has a combination of both English and Japanese used in it. The link should allow for anyone to view the xml file.
Here is my code and xml file:
public partial class MainWindow : Window
{
private string URLSource = "https://www.dropbox.com/s/nh3bfzvhpj6e3x1/JapanseEnglish.xml?dl=0";
public MainWindow()
{
InitializeComponent();
XMLViewer();
}
private void XMLViewer()
{
try
{
XDocument Doc = XDocument.Load(URLSource);
var Kanji = from WordList in Doc.Descendants("Kanji")
select new
{
Word = WordList.Element("Kanji").Value
};
foreach (var Word in Kanji)
{
JpnTxt.ItemsSource = Word.ToString();
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}
}
The URL you use don't contain a XML document but an HTML page :
https://www.dropbox.com/s/nh3bfzvhpj6e3x1/JapanseEnglish.xml?dl=0
You need to change the value of dl to 1, so Dropbox will return your XML document:
https://www.dropbox.com/s/nh3bfzvhpj6e3x1/JapanseEnglish.xml?dl=1
As #Florian said you should use second link, but maybe you have problem to read unicode xml, so its better using Request and ResponseStream:
private string URLSource = "https://www.dropbox.com/s/nh3bfzvhpj6e3x1/JapanseEnglish.xml?dl=1";
private void XMLViewer()
{
try
{
var request = (HttpWebRequest)WebRequest.Create(URLSource);
var response = (HttpWebResponse)request.GetResponse();
using (var stream = response.GetResponseStream())
{
using (var sr = new StreamReader(stream, true))
{
XDocument Doc = XDocument.Load(sr);
var Kanji = from WordList in Doc.Descendants("Kanji")
select new
{
Word = WordList.Element("Kanji").Value
};
foreach (var Word in Kanji)
{
JpnTxt.ItemsSource = Word.ToString();
}
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}

Elency Solutions CSV Library Error C#

I am using the elency solutions CSV library for C# to save and load some data from a file.
My code saves and loads correctly, but when I load and then try to save an error occurs, saying that another process is using the file.
The load method is this:
private void loadfile(string name)
{
int key = 696969;
CsvReader read = new CsvReader("data.csv");
try
{
do
{
read.ReadNextRecord();
} while (name != read.Fields[0]);
int decAgain = int.Parse(read.Fields[1], System.Globalization.NumberStyles.HexNumber); //convert to int
int dec = decAgain ^ key;
MessageBox.Show(dec.ToString());
}
catch (Exception)
{
MessageBox.Show("Not Found");
}
read = null;
}
As you can see, I am sort of disposing the "read" object.
Here is the save method:
private void savefile(string encrypted, string name)
{
CsvFile file = new CsvFile();
CsvRecord rec = new CsvRecord();
CsvWriter write = new CsvWriter();
rec.Fields.Add(name);
rec.Fields.Add(encrypted);
file.Records.Add(rec);
write.AppendCsv(file, "data.csv");
file = null;
rec = null;
write = null;
}
It always gets stuck on append csv.
I do understand the problem. The reader is not being closed successfully. How can I correctly close the file?
NB: I have tried read.Dispose() but it is not working.
Can you please help me out?
Regards
Use using to automatically dispose object. It may solve your issue.
private void savefile(string encrypted, string name)
{
using(CsvFile file = new CsvFile())
{
using(CsvRecord rec = new CsvRecord())
{
using(CsvWriter write = new CsvWriter())
{
rec.Fields.Add(name);
rec.Fields.Add(encrypted);
file.Records.Add(rec);
write.AppendCsv(file, "data.csv");
}
}
}
}

Array class not rendering into datagrid

The following application is not rendering the information that I am getting back from a web service into the datagrid. I know I am being able to connect to the webservice because I am getting the count for the class array. I am being able to get a Response.Write but when I try to pull all the information from the array class I haven't been able to see the elements nor to render the whole class into the data grid. What might be my issue? I am stuck with this one.
void LoadABCPhoneInfo()
{
PhoneTypeInfo[] PhoneInfo = GetPhoneInfo();
DataSet quoteDataSet = XmlString2DataSet(PhoneInfo.ToString());
//Here is NOT doing the databinding.
grdABC.DataSource = quoteDataSet;
grdABC.DataBind();
grdABC.Visible = true;
}
private PhoneTypeInfo[] GetPhoneInfo()
{
//string strGetPhoneInfo = String.Empty;
PhoneTypeInfo[] strGetPhoneInfo; //
try
{
OwnerAndReservation ownerAndReservationWS = new OwnerAndReservation();
strGetPhoneInfo = ownerAndReservationWS.GetPhoneTypes();
//GetPhoneTypesAsync()
//Here I can get the count for the array
Response.Write("GetPhoneInfo Length "+ strGetPhoneInfo);
}
catch (Exception ex)
{
//raise the error
string errorMessage = String.Format("Error while trying to connect to the Web Service. {0}", ex.Message);
throw new Exception(errorMessage);
}
//return the quote information
return strGetPhoneInfo;
}
private DataSet XmlString2DataSet(string xmlString)
{
//create a new DataSet that will hold our values
DataSet quoteDataSet = null;
//check if the xmlString is not blank
if (String.IsNullOrEmpty(xmlString))
{
//stop the processing
return quoteDataSet;
}
try
{
//create a StringReader object to read our xml string
using (StringReader stringReader = new StringReader(xmlString))
{
//initialize our DataSet
quoteDataSet = new DataSet();
//load the StringReader to our DataSet
quoteDataSet.ReadXml(stringReader);
}
}
catch
{
//return null
quoteDataSet = null;
}
//return the DataSet containing the stock information
return quoteDataSet;
}

Categories