I've been trying to write a simple financial app to manage my home spending's and while I was writing my Save button code I've encountered a situation where the code runs fine but inserts 0 rows to the local database.
Here's the code that calls saveIncome method:
if (comboBox1.SelectedIndex == 0)
{
try
{
saveIncome();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
And here's the code for the "Save" button:
public void saveIncome()
{
using (WalletEntities ctx = new WalletEntities())
{
var Income = new Income
{
ID = transID,
Name = tbName.Text,
Date = calDate.SelectionRange.Start,
Value = decimal.Parse(tbValue.Text),
Owner = tbOwner.Text,
Desc = tbDesc.Text,
};
ctx.Income.Add(Income);
ctx.SaveChanges();
MessageBox.Show("Added Income ID: " + transID.ToString());
}
}
When I've tried to debug this everything ran ok. Object Income was filled and the Message Box shows.
As I understand, I was using the "Model First" approach to make this.
Please be gentle - I'm a beginner in programming :) also sorry for my English - not my primary language.
Ok, so the problem is fixed and it was due to my lack of knowledge. So apparently #MilenPavlov was right. I did in fact inspect a different database. I had no idea that when built the project copies the *.sdf to DEBUG folder and places changes there - courtesy of Copy to Output Directory property on your *.sdf file. So as I was inspecting via Visual Studio, I've been viewing a different copy of the file.
Thanks #MilenPavlov for showing me the way :)
Related
I'm having a hard time with what appears to be a connection issue. I have scoured the web and sounds like this is not the way to go but if someone has any thoughts or ideas that would be great.
I have a hunch it's because these 4 pages are using the same .cs code file and all logic is happening OnLoad() so it is kicking the other off? These reports are for display only, no input required from user.
Please let me know if more information is needed, thank you!
Issue:
Page loads fine on its own but if multiple tabs are ran and one is still processing, it halts this and then displays missing data and formatting. Can sometimes be mimicked by pressing refresh (F5) twice quickly.
Environment:
IIS running on server
DB2Database (IBM)
Web Report:
4 asp.net pages that link to same Default.CS code file (ex. /dash/steel.aspx, /dash/steelnums.aspx)
On page load > read CSV files using StreamReader > run SQL query > format/display information into data grid view
Connection Example:
iDB2Connection BlueDB2Connection = new iDB2Connection(strConnectionString);
iDB2DataAdapter BlueDB2PartsDataAdapter = new iDB2DataAdapter();
iDB2Command SqlCmd = BlueDB2Connection.CreateCommand();
SqlCmd.CommandTimeout = 1000000000;
// select proper query based on page being loaded
if (curPage.Contains("amewood"))
{
SqlCmd.CommandText = sqlMainDataWood();
}
else if (curPage.Contains("amesteel"))
{
SqlCmd.CommandText = sqlMainDataSteel();
}
BlueDB2PartsDataAdapter.SelectCommand = SqlCmd;
try
{
BlueDB2PartsDataAdapter.Fill(dsParts);
}
catch (SqlException sqlEx)
{
DisplayError.Text = "Error:" + sqlEx.Message;
}
Reading CSV function:
using (StreamReader reader = new StreamReader(basePath + filePath + "daysStart.csv"))
{
var headerLine = reader.ReadLine();
var line = reader.ReadToEnd();
var values = line.Split(',');
DateTime dt;
DateTime today = DateTime.ParseExact(DateTime.Now.ToString("MMddyyyy"), "MMddyyyy", CultureInfo.InvariantCulture);
int i = 0;
if (values.Length != 0)
{
foreach (string item in values)
{
if (item != "")
{
dt = DateTime.ParseExact(item, "MMddyyyy", CultureInfo.InvariantCulture);
dateData.startDate = dt;
}
else
{
dateData.startDate = today;
}
i++;
}
}
else
{
dateData.startDate = today;
}
}
Troubleshooting:
Attempted multiple threading
Tried delays prior to code
Tested that the CSV's were not causing the issue
Not closing the DB connection (disposing it) would be the culprit. After running every command or query, you have to dispose of the connection (or at the end of the event handler function). As #Dai suggested if you're not limited to using DB2 and Web Forms you should use newer technologies such as ASP.net MVC and EntityFramework or other ORMs.
Update :
after reading your link:
Any public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Any instance members are not guaranteed to be thread-safe.
it is maybe from not sharing the same instance of DB2DataAdapter object. Share it with static modifier between pages and see if it helps.
Sorry for the delay, I don't get much time to work on this. The issue turned out to be related to a static variable that was being overwritten... face palm. I'm sure if I posted all of the code you would have noticed it immediately. Thank you for your time and effort.
I have a console application which tries to upload a document into a share point document library list.
I am successfully able to do it and also I am able to fill one of the custom Column(Column name is : "Category") value while uploading the file using C#.
I have tried to fill another custom column(Column name is : "Related Assets") value using the same procedure but i get the error stating the provided column name does not exist but when i see in actual share point portal it does exist.
So not able to solve this issue. Even i tried couple of methods as given below and i get same error message in terms of the column does not exist or it has been deleted or not able to recognize it.
Please find the screenshot of SharePoint showing the list of columns:
Please find the code i have till now which upload the document into SharePoint portal.
public static async Task<string> UploadReleaseNoteDocumentintoSpPortal(string releasenotefilepath, string releasenotefilename, string clientid, string clientsecret)
{
string status = string.Empty;
try
{
Console.WriteLine("Trying to Upload Release note file into Share Point Portal...");
string siteUrl = "<<Sp site URL>>";
Console.WriteLine("Connecting to Share Point Portal...");
var ClientContext = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl, clientid, clientsecret);
ClientContext.Load(ClientContext.Web, p => p.Title);
await ClientContext.ExecuteQueryAsync();
Console.WriteLine(ClientContext.Web.Title);
var web = ClientContext.Web;
Console.WriteLine("Connected successfully to Share Point Portal...");
List DocumentsList = web.Lists.GetByTitle("Accelerators Documents");
ClientContext.Load(DocumentsList.RootFolder);
await ClientContext.ExecuteQueryAsync();
Console.WriteLine("Reading and loading the list named : Accelerators Documents from SP");
Console.WriteLine("Converting the release note document into byte array");
byte[] bytes = System.IO.File.ReadAllBytes(releasenotefilepath);
MemoryStream stream = new MemoryStream(bytes);
Console.WriteLine("Storing the release note Data into File Create information object of SharePoint");
FileCreationInformation FileCreateInfo = new FileCreationInformation();
FileCreateInfo.Content = bytes;
FileCreateInfo.ContentStream = stream;
FileCreateInfo.Overwrite = true;
FileCreateInfo.Url = DocumentsList.RootFolder.ServerRelativeUrl + #"\" + releasenotefilename;
Console.WriteLine("Adding file to SharePoint");
var ReleaseNoteFiledata = DocumentsList.RootFolder.Files.Add(FileCreateInfo);
ReleaseNoteFiledata.Update();
ReleaseNoteFiledata.ListItemAllFields["Category"] = "Release Notes";
//ReleaseNoteFiledata.ListItemAllFields["Related Assets"] = "<<Desired Value>>";
//IN Above commented line i get the error stating Microsoft.SharePoint.Client.ServerException:
//'Column 'Related Assets' does not exist. It may have been deleted by another user.
//But in actual site if we see it exists as you can see in above screenshot
ReleaseNoteFiledata.ListItemAllFields.Update();
ClientContext.Load(ReleaseNoteFiledata);
await ClientContext.ExecuteQueryAsync();
Console.WriteLine("Adding file to SharePoint Completed Successfully...");
return status = "Successful";
}
catch (Exception ex)
{
Console.WriteLine("Exception occured while trying to upload Release note file into CoP Portal :" + ex.Message);
return status = "Error/Exception";
}
}
Please find the error message i get while trying to add value to another custom column present in SharePoint:
Microsoft.SharePoint.Client.ServerException: 'Column 'Related Assets' does not exist. It may have been deleted by another user.
Even if i use the ReleaseNoteFiledata.SetFileProperties() and pass the values as a dictionary key value pair containing the column name and its value then also i get the same error for the second custom column. If i keep only the category custom column then it works perfectly without any issue as you can see in the screenshot above.
If i select the record and see the details or properties in the SharePoint the Related assets column symbol is some like in below screenshot:
Please let me know if the supporting documents are fine or still if my issue is not understandable so that i can re frame it or provide more screenshots.
Please help me in solving the above issue or how to make this column recognizable or readable or identifiable in the code.
Thanks in Advance
Regards
ChaitanyaNG
You need to use the internal name of the column 'Related Assets' in your code. It should be Related_x0020_Assets.
You could check the internal name of the column by go to list settings-> click the column, you would see the internal name in the url.
I have a web form with 4 dropdownlists and a search button that obtains a list from the database using the values of the selected dropdownlist as filters, what I need is that if user A and B select the same values of the dropdownlist, only 1 of them can work with the list obtained from the database. What would be the best way to work this?
//Get employee list
List<Entity.Employee> lstEmployees = new List<Entity.Employee>();
lstEmployees = Logic.Employee.getEmployees(DropDownList1.SelectedValue, DropDownList2.SelectedValue, DropDownList3.SelectedValue, DropDownList4.SelectedValue);
foreach(Employee emp in lstEmployees)
{
//single process per user required
}
//release single process
Here are two options depending on the environment you are using
1) If you are hosting it on a single server
You can use the application pool Application[Key1 + Key2 + Key3] as a way to track if someone is already working on that combination if not, let them continue.
2) If you are hosting it on a web farm
Use a database (or a shared storage somewhere ex: network share) to track the locking of those parameter combination similar to #1
Obviously #1 is easier/faster
2 is scalable
//Get employee list
List<Entity.Employee> lstEmployees = new List<Entity.Employee>();
lstEmployees = Logic.Employee.getEmployees(DropDownList1.SelectedValue, DropDownList2.SelectedValue, DropDownList3.SelectedValue, DropDownList4.SelectedValue);
foreach(Employee emp in lstEmployees)
{
String MyKey = DropDownList1.SelectedValue + DropDownList2.SelectedValue + DropDownList3.SelectedValue + DropDownList4.SelectedValue;
if(Application[MyKey]==null || Application[MyKey]=""){
//single process per user required
}
}
//release single process
I'm assuming that Employee is a class that you have access to?
The simplest solution I can picture here would be to incorporate a boolean field titled something like "isCheckedOut" and simply check for this value before allowing any data modification.
This solution doesn't really mechanically "lock-down" the code, but depending on how you're accessing it, this sort of quick check could be a very simple fix.
I write the code like this
string sProcesoUnico = ddlCompania.SelectedValue + ddlNomina.SelectedValue + ddlPeriodo.SelectedValue + ddlClaveMovi.SelectedValue;
if (Application[sProcesoUnico].ToString() == "" || Application[sProcesoUnico] == null)
{
try
{
// Process
}
catch (Exception)
{
throw;
}
finally
{
Application[sProcesoUnico] = ""; //release process
}
}
It´s ok the way that I release the Application State?
I have an app that reads from text files to determine which reports should be generated. It works as it should most of the time, but once in awhile, the program deletes one of the text files it reads from/writes to. Then an exception is thrown ("Could not find file") and progress ceases.
Here is some pertinent code.
First, reading from the file:
List<String> delPerfRecords = ReadFileContents(DelPerfFile);
. . .
private static List<String> ReadFileContents(string fileName)
{
List<String> fileContents = new List<string>();
try
{
fileContents = File.ReadAllLines(fileName).ToList();
}
catch (Exception ex)
{
RoboReporterConstsAndUtils.HandleException(ex);
}
return fileContents;
}
Then, writing to the file -- it marks the record/line in that file as having been processed, so that the same report is not re-generated the next time the file is examined:
MarkAsProcessed(DelPerfFile, qrRecord);
. . .
private static void MarkAsProcessed(string fileToUpdate, string
qrRecord)
{
try
{
var fileContents = File.ReadAllLines(fileToUpdate).ToList();
for (int i = 0; i < fileContents.Count; i++)
{
if (fileContents[i] == qrRecord)
{
fileContents[i] = string.Format("{0}{1} {2}"
qrRecord, RoboReporterConstsAndUtils.COMPLETED_FLAG, DateTime.Now);
}
}
// Will this automatically overwrite the existing?
File.Delete(fileToUpdate);
File.WriteAllLines(fileToUpdate, fileContents);
}
catch (Exception ex)
{
RoboReporterConstsAndUtils.HandleException(ex);
}
}
So I do delete the file, but immediately replace it:
File.Delete(fileToUpdate);
File.WriteAllLines(fileToUpdate, fileContents);
The files being read have contents such as this:
Opas,20170110,20161127,20161231-COMPLETED 1/10/2017 12:33:27 AM
Opas,20170209,20170101,20170128-COMPLETED 2/9/2017 11:26:04 AM
Opas,20170309,20170129,20170225-COMPLETED
Opas,20170409,20170226,20170401
If "-COMPLETED" appears at the end of the record/row/line, it is ignored - will not be processed.
Also, if the second element (at index 1) is a date in the future, it will not be processed (yet).
So, for these examples shown above, the first three have already been done, and will be subsequently ignored. The fourth one will not be acted on until on or after April 9th, 2017 (at which time the data within the data range of the last two dates will be retrieved).
Why is the file sometimes deleted? What can I do to prevent it from ever happening?
If helpful, in more context, the logic is like so:
internal static string GenerateAndSaveDelPerfReports()
{
string allUnitsProcessed = String.Empty;
bool success = false;
try
{
List<String> delPerfRecords = ReadFileContents(DelPerfFile);
List<QueuedReports> qrList = new List<QueuedReports>();
foreach (string qrRecord in delPerfRecords)
{
var qr = ConvertCRVRecordToQueuedReport(qrRecord);
// Rows that have already been processed return null
if (null == qr) continue;
// If the report has not yet been run, and it is due, add i
to the list
if (qr.DateToGenerate <= DateTime.Today)
{
var unit = qr.Unit;
qrList.Add(qr);
MarkAsProcessed(DelPerfFile, qrRecord);
if (String.IsNullOrWhiteSpace(allUnitsProcessed))
{
allUnitsProcessed = unit;
}
else if (!allUnitsProcessed.Contains(unit))
{
allUnitsProcessed = allUnitsProcessed + " and "
unit;
}
}
}
foreach (QueuedReports qrs in qrList)
{
GenerateAndSaveDelPerfReport(qrs);
success = true;
}
}
catch
{
success = false;
}
if (success)
{
return String.Format("Delivery Performance report[s] generate
for {0} by RoboReporter2017", allUnitsProcessed);
}
return String.Empty;
}
How can I ironclad this code to prevent the files from being periodically trashed?
UPDATE
I can't really test this, because the problem occurs so infrequently, but I wonder if adding a "pause" between the File.Delete() and the File.WriteAllLines() would solve the problem?
UPDATE 2
I'm not absolutely sure what the answer to my question is, so I won't add this as an answer, but my guess is that the File.Delete() and File.WriteAllLines() were occurring too close together and so the delete was sometimes occurring on both the old and the new copy of the file.
If so, a pause between the two calls may have solved the problem 99.42% of the time, but from what I found here, it seems the File.Delete() is redundant/superfluous anyway, and so I tested with the File.Delete() commented out, and it worked fine; so, I'm just doing without that occasionally problematic call now. I expect that to solve the issue.
// Will this automatically overwrite the existing?
File.Delete(fileToUpdate);
File.WriteAllLines(fileToUpdate, fileContents);
I would simply add an extra parameter to WriteAllLines() (which could default to false) to tell the function to open the file in overwrite mode, and not call File.Delete() at all then.
Do you currently check the return value of the file open?
Update: ok, it looks like WriteAllLines() is a .Net Framework function and therefore cannot be changed, so I deleted this answer. However now this shows up in the comments, as a proposed solution on another forum:
"just use something like File.WriteAllText where if the file exists,
the data is just overwritten, if the file does not exist it will be
created."
And this was exactly what I meant (while thinking WriteAllLines() was a user defined function), because I've had similar problems in the past.
So, a solution like that could solve some tricky problems (instead of deleting/fast reopening, just overwriting the file) - also less work for the OS, and possibly less file/disk fragmentation.
BACKGROUND:
What I am trying to do is output a list of files which are unversioned or have had changes done to them and need to be commited.
WHAT IVE TRIED:
I am currently using the code below, the code runs but nothing is outputted to the console. The catch method isnt activated either as the message box doesnt appear.
using (SvnClient client = new SvnClient())
{
try
{
EventHandler<SvnStatusEventArgs> statusHandler = new EventHandler<SvnStatusEventArgs>(HandleStatusEvent);
client.Status(Properties.Settings.Default.LocalFolderPath + #"\" + project, statusHandler);
}
catch
{
MessageBox.Show("ERROR");
}
}
private void HandleStatusEvent(object sender, SvnStatusEventArgs args)
{
switch (args.LocalContentStatus)
{
case SvnStatus.NotVersioned: // Handle appropriately
Console.WriteLine(args.ChangeList);
break;
}
// review other properties of 'args'
}
Im not quite sure if this is the right code to get the list of files which need to be committed as the documentation is poor. Ive looked on this site and have found a few other methods (similar to this way) but I still cant get it working. can anyone help?