replace linebreak with \r\n when sending back to database - c#

Newbie here again.
I have a form in c# that retrieves by calling a Web Service information from a database. One field it gets is just "notes" regarding this client.
The form i have allows multiple lines in the Notes field, but when i save it (send it via webservice to the database back) it doesn't recognize line breaks. How can i tell it to replace line breaks with the /r/n/ (is that right?) code, so when it retrieves it next time from the database it will know how to display it in the notes field?
This is the code i am using now which doesn't work.
if (MasterRecord.Customer.Notes.Trim().Length < 1)
{
string s = "";
foreach (object o in txtNotes.Text)
{
s += o.ToString() + ("\r\n");
}
}

Just do:
var stringToInsert = txtNotes.Text.Replace("\n", "\r\n");

When you are saving multiline text in sql server then replace carriage return with your Custom NewLine specifier for example : %NL%
txtNote.Text.Replace(Environment.NewLine, "%NL%");
and when you retrieving from database field then follow the reveres approach:
MasterRecord.Customer.Notes.Replace("%NL%", Environment.NewLine);
if you access this on .net platform then all ok.. i am not confirm about the the another platforms which acess this webserivce..
it works but it is trick to process data through application it saves %NL% in the field value.

Related

Database First with Windows Form

Hi I have a windows Form Application and using Database First Approach. When I am trying to save data using following code its not showing any error but not saving data into my .mdf database.
Models.NorthwoodRetreatsDBEntities db = new Models.NorthwoodRetreatsDBEntities();
db.Treatments.Add(new Models.Treatment() {
Name=_name,
address=_address,
phone=_phoneNo,
Email=_emailAddress
});
db.SaveChanges();
Not showing error I am also trying see is it inserted using the following line of code
bool a = db.ChangeTracker.HasChanges(); //double check if there was any change detected by EF or not?
it is returning true and
int UserID = db.Treatments.Max(item => item.AccommodationID);
Always returning 1 but when I explore database table showing nothing there and also when I am adding second item "int UserID" again 1. Now I am just wondering that can I use Database First EF with Windows Form. Could you please advice.

How Can I Make a Test Method on Coded UI Data Driven If that Data file doesn't exist at run time since data source doesn't exist yet

I know that for me to create a data driven test that i need to use a datasource with the test method, and that the datasource had to have already existed.
My question is how about if you want to make a test method data driven but you don't have the datasource file at run time.
Edit
What i mean is I want to basically iterate over the same test X number of times. The reason I dont have the data is because i have to first fetch the data first and then iterate over it.
below i created a test that ran for each of my hyperlink but after the test pass i only get results Passed Once instead for each iteration of my hyperlink. I also tried to launch something in the "[TestInitialize()]" section and assign my data file to it but since the data file has to be constant(or already exist), i cant do it. Any help with this would be great
[TestMethod]
public void Verify_Rates_Links()
{
HomePage getLinks = new HomePage(GlobalVariable.Browser);
int PicCount = 0;
// To generate code for this test, select "Generate Code for Coded UI Test" from the shortcut menu and select one of the menu items.
PageObjects.Shared.SharedBetweenPage StarTest = new PageObjects.Shared.SharedBetweenPage(GlobalVariable.Browser);
getLinks.GetAllHeaderLinks("Rates", "3", GlobalVariable.Rates_Links);
foreach ( HtmlHyperlink links in GlobalVariable.Rates_Links)
{
Assert.IsTrue(
StarTest.LetsGoToHomePage()
.LetsclickLink(links)
.VerifyLocationPage("Rates","Rates", "Rates", "VerifyRateslinkBreadcrumb" + PicCount.ToString() + ".jpg", "VerifyRatesHeader" + PicCount.ToString() + ".jpg"),
"There is an issue with Rates to create new membership APP one or more of the work flows is not work");
//Playback.Cleanup();
//testcl
PicCount++;
}
}
~Will

How to display contents of a listbox as soon as an item is added?

I have an application where i need to display a list of string outputs from a function in a System.Web.UI.ListBox. To get one string output (executing the function) it takes some time .I am adding the string output to the listbox after it is produced.Whats is my problem is that the application waits the entire time (till all items are calculated and added to listbox) and finally displays the entire listbox in one go (after waiting for quite a while due to the time required for generating large number of output string). Kindly someone help me to show the listox item on the page as soon as it is added.Thank you.
public void add_to_list_box()
{
int b;
for (b = 0; b <= 20; b++)
{
string message = demo(b);
ListBox1.Items.Add(message);
}
Button2.Text = "completed";
}
You have to understand that your code that is filling the ListBox is running on the web server, and it generates html / css / etc. After whole page is generated, it's send to the client. In your case client is Web browser, and after page is generated, send to the client only then is displayed.
In order to achieve your that instant display you have to use Ajax
Use Ajax. In the url put the add_to_list_box() function, and then in the success part of the Ajax, do this:
Button2.Text = "completed";

Issue with MySqlBulkLoader from C# app

I am writing an app to export some data from MSSQL to a MySQL server on a nightly basis. I use a simple query to grab all the data for the previous day and have then tried a few different approaches for getting it to MySQL. The fastest approach is using MySqlBulkLoader but for some reason it isn't moving all the data. After I do the insert, I am comparing the records in the text file that was generated to the number of records that are in MySQL and the counts are off from 1 in some cases all the way up to 10.
If I do the same approach for getting the data to the text file but loop through each row of the text file rather than bulk upload and do insert statements, all the records get imported.
Here is the bulk upload code I am currently using. I recently added the FieldQuotationCharacter to see if that would help and it didn't (when I added that, I made the text generation script enclose fields in quotes).
uploader.TableName = "testtable";
uploader.FieldTerminator = "\t";
uploader.LineTerminator = "\r\n";
uploader.NumberOfLinesToSkip = 0;
uploader.FileName = updateFile; //this is a variable pointing to the current file
uploader.Timeout = 120;
uploader.FieldQuotationCharacter = '"';
int totalExported = uploader.Load();
Any ideas?
Seems a little strange but on a whim I decided to write my output file with a blank line at the top and then set NumberOfLinesToSkip = 1. After doing this, everything worked and no records went missing. Kinda strange. Seems that setting it to 0 didn't work and may not be supported.
I was having a similar problem where it was loading about 2/3 of the rows in my file and the problem turned out to be the behavior of the local keyword in the load data sql that is generated by MySqlBulkLoader.
By default, it seems that MySqlBulkLoader.Local == true, this allows it to use a local file, but also affects the error handling for invalid rows. Instead of throwing an error when a row is invalid, it will give you "warnings". You can verify this and view the warning by running an actual sql command for load data (which is what MySqlBulkLoader uses):
load data local infile '/Temp/bb7dd81c-c79f-49c7-9ae4-fdc8e48df6d5.csv'
ignore into table my_staging_tbl
fields terminated by ',' enclosed by '"' escaped by '\\'
lines terminated by '\n'
This outputs the count of affected rows and a list of all warnings
In my case, I had the LineTerminator as "\n" instead of "\r\n" and after the warnings were suppressed it still ended up importing most of the rows.
You can override this behavior by setting MySqlBulkLoader.ConflictOption to MySqlBulkLoaderConflictOption.Replace instead of Ignore which is the default. Note that this also affects the way it handles duplicate keys.
More on the load data stuff for mysql: http://dev.mysql.com/doc/refman/5.7/en/load-data.html
If you stumble upon this post looking for a solution to trap those warnings, here it is. You actually need to add an event handler on the underlying connection to grab them. Like this:
connection.InfoMessage += new MySqlInfoMessageEventHandler(OnInfoMessage);
connection.Open();
MySqlBulkLoader bulkLoader = new MySqlBulkLoader(connection);
void OnInfoMessage(object sender, MySqlInfoMessageEventArgs e) {
MySqlCommand myCommand = new MySqlCommand("SHOW WARNINGS", (MySqlConnection)sender);
MySqlDataReader reader = myCommand.ExecuteReader();
while (reader.Read()) {
Console.WriteLine(reader[0].ToString() + " " + reader[1].ToString() + " " + reader[2].ToString());
}
}

WCF RIA service return data not matching on the 2 sides of the service

I originally thought this was a INotifyPropertyChanged/Binding issue because I'm not sure how to debug the silverlight part. So I had to put a messagebox in a foreach loop and view the values after the data returned that way. It turns out that I'm having trouble getting the updated data from the service. I use the service to do some updates to data on the server and when it gets back call to reload the data. This part of the service is returning the correct data (I verified using a breakpoint so I could look at the data result was holding). But the silverlight side is not getting the right data. Here is the relevant code.
public IQueryable<OurClass> GetItems(string condition)
{
var result = from items in context.OurClass
where item.value == condition
select item;
return result; //had my breakpoint here and the values were the correct updated values
}
/
Context.Load<OurClass>(Context.GetItemsQuery(condition)).Completed += new EventHandler(Context_LoadCompleted);
/
private void Context_LoadCompleted(object sender, EventArgs e)
{
IEnumerable<OurClass> result = ((LoadOperation<OurClass>)sender).Entities;
//This is where I put a MessageBox to view the returned results and the data was different
//than what was contained in the other result
}
Any ideas what could cause this? What should I look at next?
EDIT:
Some example data is OurClass.OurProperty will equal "Test" on the server side but once it is received on the client it will equal "Development" which was the old value. The IEnumerable will hold the newly added records and not have the deleted ones. Any that previously existed will contain the old property values and not the new values.
The solution was that I needed to add the parameter LoadBehavior.RefreshCurrent to the query call. So this:
Context.Load<OurClass>(Context.GetItemsQuery(condition)).Completed += new EventHandler(Context_LoadCompleted);
Needed to be this:
Context.Load<OurClass>(Context.GetItemsQuery(condition), LoadBehavior.RefreshCurrent, true).Completed += new EventHandler(Context_LoadCompleted);
How is the data different on each side of the service? can you show us some example data. You can have a look at data using something like wireshark (will need to be on the server, or on your client where you are running your silverlight applet from.)
Have you tried debugging your silverlight properly, ie attach to the process as shown here: http://www.michaelsnow.com/2010/04/22/silverlight-tip-of-the-day-2-attach-to-process-debugging/
I would also recommend turning on WCF tracing as detailed here: http://msdn.microsoft.com/en-us/library/ms733025.aspx

Categories