I created a new c# project and follwed the steps from this tutorial to create a LocalDataCache:
http://www.codeproject.com/KB/database/AdoSyncServicesArticalPKg.aspx?fid=1526739&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2794305&fr=1#xx0xx
I next added the following code:
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;
namespace TestLocalSync
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the table. You can move, or remove it, as needed.
this.databaseTableAdapter.Fill(this.testDataSet.myTable);
}
private void Sync_Click(object sender, EventArgs e)
{
dataGridView1.EndEdit();
// Call SyncAgent.Synchronize() to initiate the synchronization process.
// Synchronization only updates the local database, not your project’s data source.
LocalDataCache1SyncAgent syncAgent = new LocalDataCache1SyncAgent();
syncAgent.testTable.SyncDirection = Microsoft.Synchronization.Data.SyncDirection.Bidirectional;
Microsoft.Synchronization.Data.SyncStatistics syncStats = syncAgent.Synchronize();
MessageBox.Show("Changes downloaded: " +
syncStats.TotalChangesDownloaded.ToString() +
Environment.NewLine +
"Changes uploaded: " + syncStats.TotalChangesUploaded.ToString());
// TODO: Reload your project data source from the local database (for example, call the TableAdapter.Fill method).
databaseTableAdapter.Fill(testDataSet.myTable);
testDataSet.Merge(databaseTableAdapter.GetData());
databaseTableAdapter.Update(testDataSet);
}
private void Refresh_Click(object sender, EventArgs e)
{
databaseTableAdapter.Fill(testDataSet.myTable);
}
}
}
I make some changes to the database on the server and perform the sync and it appears update the client datagrid. When I re-load the application, the client (sdf database) is the same before the sync took place and no changes have been stored.
Now I am not sure what I am missing? Must be something simple! Any advice is greatfully accepted.
Thank you
This is solved now.
The problem is that the database.sdf is always copied to the data output directory and would overwrite the database I was working on (manually making changes to test the merge!).
This can be changed by clicking on the sdf file in visual studio and in properties change the value for "Copy to Output Directory" to "Do Not Copy". Then manage the connection string outside of the data directory. The default is Copy If newer which caused the problems!
Related
I'm creating an app in winforms c# using vs 2013.
In the app I have a textfile to which I'm saying the time in int format using a custom format from a time select dropdown list.
I then want to display what is in that text file on a selectable listview from where I can remove it from the textfile etc. I'm almost there however at the moment when I try to add the items into the listbox they do seem to add however they do not display correctly.
For example say in my text file there is
22102210
19101610
17182218
10272227
Then that is how it should be displayed in the listview as selectable ready to be deleted.
At the moment it isn't showing correctly, it's showing up as 1.. 2.. 1..
Could someone help me out and point me in the right direction as to why this might be happening? Any help much appreciated. This is my class.
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 Chronos
{
public partial class Interface : Form
{
private string[] getTimes = System.IO.File.ReadAllLines(#"G:\Dropbox\University\Chronos\Application\Chronos\Chronos\AdminAccount\Times.txt");
public Interface()
{
InitializeComponent();
}
private void Interface_Load(object sender, EventArgs e)
{
PopulateList();
}
private void PopulateList()
{
int size = getTimes.Length;
lstTime.Items.Clear();
GetTimes();
for (int i = 0; i < size; i++)
{
lstTime.Items.Add(getTimes[i]);
}
}
private void GetTimes()
{
string[] getTimes = System.IO.File.ReadAllLines(#"G:\Dropbox\University\Chronos\Application\Chronos\Chronos\AdminAccount\Times.txt");
}
private void btnAdd_Click(object sender, EventArgs e)
{
string time = pickerTimeStart.Value.Hour.ToString() + pickerTimeStart.Value.Minute.ToString() + pickerTimeEnd.Value.Hour.ToString() + pickerTimeEnd.Value.Minute.ToString();
System.IO.File.AppendAllText(#"G:\Dropbox\University\Chronos\Application\Chronos\Chronos\AdminAccount\Times.txt", time + Environment.NewLine);
PopulateList();
MessageBox.Show("Time added", "Ok");
//PopulateList();
}
}
}
As currently written, GetTimes does nothing except read the file:
private void GetTimes()
{
// "string[]" here overrides the outer scope
string[] getTimes = System.IO.File.ReadAllLines(#"G:\Dropbox\University\Chronos\Application\Chronos\Chronos\AdminAccount\Times.txt");
}
If you change it to this, it becomes more useful:
private string[] GetTimes()
{
return File.ReadAllLines(#"G:\Dropbox\University\Chronos\Application\Chronos\Chronos\AdminAccount\Times.txt");
}
... and then PopulateList can simply become:
lstTime.Items.Clear(); //so you aren't getting a bunch of dupes
lstTime.Items.AddRange(GetTimes().Select(t => new ListViewItem(t)).ToArray());
You can also remove this line because you don't need to keep a copy of the data in the class:
private string[] getTimes = ...
Note: If you decide to keep the data source local and not work solely against the file, much of this would change.
I am currently using Visual Studio 2012 and am completely new to ASP.NET programming. Nonetheless, despite searching Google and finding some things that looked like they might help, I eventually became stuck in this situation. Most people who get an error of the sort "name" does not exist in the current context do not seem to have very similar problems, and none of them seem relevant to me.
So far I have tried (a deleting and recreating the designer files, to no avail. This was recommended by some previous stackoverflow questions, and (b, this little workaround to be able to access the body tag from outside of the master page (that is essentially what I am trying to do here).
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace WebApplication1
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
HelloWorldLabel.Text = "Hello" + TextInput.Text;
if (Request.Cookies["BackgroundColor"] != null)
{
ColorSelector.SelectedValue = Request.Cookies["BackgroundColor"].Value;
BodyTag.Style["background-color"] = ColorSelector.SelectedValue;
}
}
protected void GreetList_SelectedIndexChanged(object sender, EventArgs e)
{
HelloWorldLabel.Text = "Hello, " + GreetList.SelectedValue;
}
protected void ColorSelector_IndexChanged(object sender, EventArgs e)
{
BodyTag.Style["background-color"] = ColorSelector.SelectedValue;
HttpCookie cookie = new HttpCookie("BackgroundColor");
cookie.Value = ColorSelector.SelectedValue;
cookie.Expires = DateTime.Now.AddHours(1);
Response.SetCookie(cookie);
}
}
}
BodyTag has been defined by this workaround here:
public HtmlGenericControl BodyTag
{
get
{
return MasterPageBodyTag;
}
set
{
MasterPageBodyTag = value;
}
}
Which appears to work with no difficulties, but ultimately did not fix the problem. I also imported the right classes etc.
Note that my master page has this:
<body id="MasterPageBodyTag" runat="server">
Just in case you thought that that might be the problem. Also note that this was created as a result of merging various pieces of code - I did not create this myself! I am only beginning out and working about with things as such.
In any case, all help big or small is very appreciated. Thanks in advance for your time!
Either you set
<body id="BodyTag" runat="server">
or you change BodyTag in your code to "MasterPageBodyTag"
im having a problem in visual studio it keeps saying i have defined a member with same parameter types. Im new to C# programming and i dont really know what to do. These are the errors that are occurring:
Error 1 Type 'Secret.AddPage' already defines a member called
'AddPage' with the same parameter types
Error 2 Type 'Secret.AddPage' already defines a member called
'PhoneApplicationPage_Loaded' with the same parameter types
Here is the code i have written so far any help is greatly appreciated.
enter code here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Device.Location;
namespace secret
{
public partial class AddPage : PhoneApplicationPage
{
private string location = "";
public AddPage()
{
InitializeComponent();
GeoCoordinateWatcher myWatcher = new GeoCoordinateWatcher();
var myPosition = myWatcher.Position;
// Eftersom koden körs i emulatorn kan den inte få tillgång till riktiga GPS-värden
// Därför hårdkodas koordinaterna till slottet i Gamla stan så att MSR MAPS Web Services
//kan testas.
double latitude = 40.717;
double longitude = -74;
if (!myPosition.Location.IsUnknown)
{
latitude = myPosition.Location.Latitude;
longitude = myPosition.Location.Longitude;
}
myTerraService.TerraServiceSoapClient client = new myTerraService.TerraServiceSoapClient();
client.ConvertLonLatPtToNearestPlaceCompleted += new EventHandler<myTerraService.ConvertLonLatPtToNearestPlaceCompletedEventArgs>(client_ConvertLonLatPtToNearestPlaceCompleted);
client.ConvertLonLatPtToNearestPlaceAsync(new myTerraService.LonLatPt { Lat = latitude, Lon = longitude });
}
void client_ConvertLonLatPtToNearestPlaceCompleted(object sender, myTerraService.ConvertLonLatPtToNearestPlaceCompletedEventArgs e)
{
location = e.Result;
//throw new NotImplementedException();
}
private void AppBar_Cancel_Click(object sender, EventArgs e)
{
navigateBack();
}
private void AppBar_Save_Click(object sender, EventArgs e)
{ // spara en ny anteckning
if (location.Trim().Length == 0)
{
location = "Okänd";
}
navigateBack();
}
private void navigateBack()
{
NavigationService.Navigate(new Uri("/secret;component/NotesMainPage.xaml", UriKind.Relative));
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
editTextBox.Focus();
}
}
}
You are creating a partial class, so you probably have these members defined in another source file for your partial class.
You may look at the solution explorer, find that source file and either remove it from there or you may remove these members from your current partial class.
You may see: Partial Classes and Methods (C# Programming Guide)
To search for the other source file containing the partial class, right click on the Class Name AddPage and select Go to Definition. You will see multiple results in Find Symbol result window in visual studio.
Check for another partial class in which you've already defined the AddPage() constructor or PhoneApplicationPage_Loaded() methods. You can achieve this by Ctrl+F and searching the solution for the method signatures:
public AddPage()
and
PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
I had something very similar recently, and it turned out that when importing existing code files I had imported the obj directory itself!
This directory contained, for example, the auto-generated (and automatically imported) MainWindow.g.i.cs file. So I was effectively including the same partial class definition twice, hence the "already defined" errors.
How this help someone else!
i had a project where i opened the main program.cs in notepad++, made some edits and did a "save as" to make a copy of the file in the same folder. i later opened the same project in visual studio and got this same error when trying to compile. i just had to exclude the files i created from making a copy from the project by right clicking on the problem file and selecting "exclude from project". did a build and viola! the copy was still in the folder just not being included in the build.
In my case the reason of this error was finally as simple as this. I added a new DB table to my EDMX in my DB project. I accidentally ticked the box for generation of class with methods (but these were already generated in the project). The EDMX file after this contained two similarly named classes AB.Context.tt and AB.xxx.Context.tt and both contained the same methods. As the classes were partial the mentioned error arose.
The solution was to remove accidentally and freshly added secondary AB.xxx.Contex.tt file and rebuild the project.
I have been learning from a tutorial on Home and Learn about setting up databases. Currently, I'm learning about finding records in a database. I'm trying to get my GO! button search for a ingredient in my data table, and I"ve followed the tutorial thoroughly and have no errors in my Error list, but this line of code:
returnRows = dataRecipe.Tables["CookBookRecipes"].Select("Ingredients = '" + searchOut + "'");
It stops my program, and brings up this message:
Object reference not set to an
instance of an object.
I've searched the meaning, and I guess it means my returnRows variable is null, but I can't be sure. Can someone help me fix this problem?
Here is my full code in my Search button:
System.Data.SqlClient.SqlConnection con;
System.Data.SqlClient.SqlDataAdapter dataAdapt;
DataSet dataRecipe;
private void btnSearch_Click(object sender, EventArgs e)
{
if (tbSearch.TextLength >= 1)
{
MessageBox.Show("This will work when you put it a word!");
// Search code //
string searchOut = tbSearch.Text;
int result = 0;
DataRow[] returnRows;
returnRows = dataRecipe.Tables["CookBookRecipes"].Select("Ingredients = '" + searchOut + "'");
result = returnRows.Length;
if (result > 0)
{
DataRow rowBack;
rowBack = returnRows[0];
MessageBox.Show(rowBack[3].ToString());
}
else
{
MessageBox.Show("No such record");
}
}
else
{
MessageBox.Show("Please enter an ingredient to search for!", "Search");
}
}
Here is the full code of my form:
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;
namespace Cookbook {
public partial class BrowseIngredients : Form {
public BrowseIngredients() { InitializeComponent(); }
private void exitToolStripMenuItem_Click(object sender, EventArgs e) {
if (MessageBox.Show("Exit Cook Book?", "Exit?", MessageBoxButtons.OKCanc
I am very much a beginner, so forgive me if I don't understand the real problem!
Looking at the tutorial you are using I think I can see where you have gone wrong (and I don't blame you the - tutorial is not entirely clear).
Based on this stage : http://www.homeandlearn.co.uk/csharp/csharp_s12p5.html
You will have in your Form Load method a statement something like:
string sql = "SELECT * From CookBookRecipes";
dataAdapt = new System.Data.SqlClient.SqlDataAdapter(sql, con);
However, the tutorial then tells you to add the following to get the data from the data adapter to into the dataset, but doesn't actually show the code in context - and I suspect this is where you have gone wrong.
Immediately after the above lines you need to add this:
dataAdapt.Fill( dataRecipe, "CookBookRecipes" );
Then when you attempt to get the rows from dataRecipe.Tables["CookBookRecipes"] you will not be returning a reference to a null object.
Looks like you might not be instantiating your data set. You declare it but you aren't instantiating it, unless you do it elsewhere in your code that you haven't shown us.
DataSet dataRecipe;
You could instatiate it in the page load event and that would be fine.
private void Form_Load(object sender, EventArgs e)
{
dataRecipe = new DataSet();
}
i am trying to make a basic IRC client...but my problem is getting the text to display in a RTF box without it lagging
i settled on using threading, and i want to update the RTF box in a thread, but i cant because it gives me errors about the RTF box element not being static?
any insight? i will paste code if you guys want it
ok here is the code (do edits bump?)
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.Net.Sockets;
using System.IO;
using System.Threading;
using System.Net;
namespace IrcClient
{
public partial class mainWindow : Form
{
static IRC client;
static string newLine, oldLine;
public mainWindow()
{
InitializeComponent();
}
private void main()
{
}
private void mainWindow_Load(object sender, EventArgs e)
{
client = new IRC("irc.freenode.net" ,6667, "jimi__hendrix");
new Thread(new ThreadStart(update)).Start();
}
private static void update()
{
newLine = client.sr.ReadLine();
Thread.Sleep(50);
}
private void btnSend_Click(object sender, EventArgs e)
{
client.privmsg(inputBox.Text);
messageBox.AppendText(inputBox.Text + "\n");
inputBox.Text = "";
}
private void timer1_Tick(object sender, EventArgs e)
{
if (newLine != oldLine)
{
messageBox.AppendText(newLine + "\n");
oldLine = newLine;
}
}
}
class IRC
{
TcpClient connection;
NetworkStream stream;
public StreamWriter sw;
public StreamReader sr;
string nick;
public IRC(string server, int port, string Nick)
{
try
{
connection = new TcpClient(server, port);
stream = connection.GetStream();
sr = new StreamReader(stream);
sw = new StreamWriter(stream);
nick = Nick;
sw.WriteLine("PASS " + "caruso11");
sw.Flush();
sw.WriteLine("NICK " + nick);
sw.Flush();
sw.WriteLine("USER Jimi__Hendrix 8 irc.freenode.net :Jimi__Hendrix");
sw.Flush();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
public void privmsg(string msg)
{
sw.WriteLine(msg);
sw.Flush();
}
public void parse(string msg)
{
}
}
}
some of the methods are blank and some code could be cleaned up, but i want to get this done first...also, theres the code generated by visual studios that sets up the window
In general, trying to update a Control from a thread other than the main thread will not work, due to limitations of Windows. If you need to call a method or set a property on the RTF box from your worker thread, you'll probably need to use Invoke or BeginInvoke. This might look like the following:
void MyThreadMethod()
{
// stuff
this.rtfBox.BeginInvoke( (MethodInvoker)(()=> this.rtfBox.Text = "foo") );
// stuff
}
Edit: As others point out, if this is actually failing to compile due to an error about the control not being static, you're probably trying to reference a member variable from a static function, which is illegal. Posting code will help narrow down the problem.
I believe you are using Windows Forms. Check out this text about it, there is some remarks that you have to take care before making a thread accessing forms elements directly.
If this is not exactly your problem, please elaborate more the question.
RULE: You should not access one window from another thread.
Use this technique:
from your thread raise an event to update the RTF (with required text etc data)
on the GUI thread use the following:
use the "InvokeRequired" property to verify call is from GUI thread or not
Use the Invoke method (you will need a delegate for this)
BeginInvoke also works but the only problem is it does not really guarantee immediate start (it uses threadpool). I prefer to use the Invoke method instead.
Others have already mentioned what the problem you are experienced is, and how to solve it.
Not that having a separate worker thread is a bad idea, it seems odd that you need multiple threads because of performance reasons. It seems that for as something as simple as an IRC client, you should be able to do everything on one thread without any UI sluggishness. Maybe you can post some code so that we can see what the root of the problem is?
The RichTextBox is on the UI thread so you're not going to be able to access the RichTextBox unless your on the UI thread. How are you loading the content? How big is the content? Is the lag coming from loading the content or the RTF box parsing it?
You're probably referencing a member variable of the form, instead of a static variable, thus the error.
Anyway this is quite a wrong approach, since UI elements can only be updated from the UI thread, otherwise you'll get a cross-thread operation exception. So you'll need to do Invoke() to the set-text method on the UI thread, which will eventually 'lag' too.
Not sure what you mean by 'lagging', you may try making your parent form double-buffered to reduce flicker.