Data Is not being added to the database - sql

I finally got another issue I was having worked out. Now I am having an issue updating a database with my code.
The data gets put in just fine, and If I loop through the data, it shows that it is there. But when I open the DataSet Designer and "Preview Data" it doesn't show the new data. All this runs smoothly and I get no Errors or exceptions.
CUsersTableAdapter.Fill(MasterDataSet.CUsers)
Dim AddRow As MasterDataSet.CUsersRow
AddRow = MasterDataSet.CUsers.NewCUsersRow
AddRow.UserFirst = "New"
AddRow.UserLast = "User"
AddRow.UserEmail = "Test#Email.com"
AddRow.UserPhone = "555-555-5555"
AddRow.UserWorkCenter = 482126468
AddRow.UserRole = 908977894
AddRow.MergeID = 739809237
MasterDataSet.CUsers.Rows.Add(AddRow)
If I loop through Data Here, it shows the new row
For Each NewRow As DataRow In CUsersTableAdapter.GetData()
Logger.WriteLog(NewRow.Item("UserFirst"))
Next
Try
Validate()
CUsersTableAdapter.Update(MasterDataSet.CUsers)
Catch ex As Exception
Logger.WriteLog("Failed : " & ex.Message)
End Try

The issue the whole time is the connection string was pointed to the mdf file inside the program. So nothing gets saved when running the debugger. I copied the mdf file to the desktop and changed the connection string. Everything works now so I must remember to copy the mdf to users AppData folder when installing.

Related

Crystal Report formula field index changing on each new build

I've got a Crystal Report which I made in CR2008, which I'm printing from my vb.net application. In this report, I have an image and a formula field.
The image formula (Under Format Graphic > Picture > Graphic Location is set to be the formula field called #imgLocation.
In my vb.net code, I have the following block to select the saved file path from the database, then fill #imgLocation with this value, to set the image that is being shown.
Try
Dim logoPath As String = ds.Tables(0).Rows(0).Item("reportLogoPath") & ""
If logoPath = "" Then
MessageBox.Show("No logo path has been defined in the System Settings. Please set " & _
"one and try again.", "Load Report Failed", MessageBoxButtons.OK)
Exit Sub
Else
cReport.DataDefinition.FormulaFields.Item(2).Text = Chr(34) & logoPath & Chr(34)
End If
Catch ex As Exception
errorLog(ex)
End Try
I've seen this working twice. The image I want replaced the placeholder image when I had FormulaFields.Item(2), but then I resized the image and it didn't work. I then changed the value of the index, and it worked with FormulaFields.Item(4), but again stopped working when I resized the image.
Why is the index changing, and what is the way around it?
I tried using the named parameter option, but FormulaFields.Item("#imgLocation") gave me an error of
Invalid Index
EDIT
As per #Bugs request, this is the report showing the correct string and image
Then, after deleting and re-saving the image (But in a slightly bigger size), the parameter was passed correctly still, but the placeholder image was shown instead.
This makes me think now that it's to do with image size, however, re-sizing it back to the original size still didn't show it again.
EDIT 2
Could it be do to with the fact that I'm loading a new form which contains the report viewer, rather than opening it from the same form?
cReport.RecordSelectionFormula = selectionFormula
Me.Cursor = Cursors.Default
Dim f As New frmReportViewer(con, cReport, 0)
f.Show()
Private Sub frmReportViewer_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
setFormSizes(Me, con)
Me.Location = New Point((Screen.PrimaryScreen.WorkingArea.Width / 2) - (Me.Width / 2), 10)
Me.Text = "Report Viewer"
Dim logOnInfo As New TableLogOnInfo()
Dim i As Integer
For i = 0 To cReport.Database.Tables.Count - 1
logOnInfo.ConnectionInfo.DatabaseName = "comm_db"
logOnInfo.ConnectionInfo.Password = "Acplus2016!"
cReport.Database.Tables.Item(i).ApplyLogOnInfo(logOnInfo)
Next i
cReport.VerifyDatabase()
crViewer.ReportSource = cReport
crViewer.ToolPanelView = CrystalDecisions.Windows.Forms.ToolPanelViewType.None
crViewer.Zoom(87)
Catch ex As Exception
errorLog(ex)
End Try
End Sub
Please note my answer is addressing the part regarding adding parameters. For the moment the no image available placeholder is proving difficult to resolve on my side.
To add a parameter please follow these steps:
Add a parameter within Crystal Reports called imageLocation:
After pressing OK you should have a parameter in your list like this:
The following code will pass a value to the parameter:
Dim cReport As New ReportDocument
cReport.Load("C:\Report.rpt")
If cReport.ParameterFields.Item("imageLocation") IsNot Nothing Then
cReport.SetParameterValue("imageLocation", "\\SAGE200FS\Sage\StockImages\sc002.jpg")
End If
reportViewer.ReportSource = cReport
This is the output (I have added the parameter onto the report):
Note that if you are passing parameters and they are shown on the report, make sure you don't have cReport.VerifyDatabase() in place. This often throws up a dialog box asking for the parameter values.
Screenshot of dialog box:
By not calling cReport.VerifyDatabase() this will stop the dialog box from showing.
Now through Crystal Reports you can set the Graphic Location using a parameter. To do this, add the parameter to the report and suppress the field (as you don't want to see it). Then you can add the Report Field as the location.
Add parameter to report and suppress:
Add Report Field as the Graphic Location for the OLE Object:~=
Run the report and input the parameter. This will change the image accordingly. See both screenshots:
SC001::
INT4303:
This however does not seem to work through VB. The ReportViewer does not handle the change of images. Instead you are left with the default image. I'm unsure why this is the case and I'm guessing it's a bug with Crystal. If anyone knows of why this happens, feel free to comment.
EDIT
After discussing the smaller points in chat, we seem to have worked out that the issue arose because of the file path. Saving it to the database as \\server\...\...\image.png was not displaying, but after changing it to Z:\...\...\image.png it has worked fine every time. It was because of the file path, all along.

Cannot mark Excel workbook as Final

The situation is as follows:
We want to publish to a remote machine a locally edited file. This file could be of type Word, Excel, Powerpoint. Apparently, after the publishing to the remote machine, we would like the local document to be marked as final, in order to prevent the user from editing it again (, because the intented workflow is first downloading it from the remote server, editing the downloaded document and the publishing it back to the server).
So, there is a bunch of code like this:
Public Sub setDocFinal()
Select Case addin.HostType
Case ADXOfficeHostApp.ohaWord
Dim doc As Word.Document = Nothing
Try
doc = addin.WordApp.ActiveDocument
doc.Final = True
Catch ex As Exception
Throw New Exception(Me.addin.getLabel("cannotSaveCopy", "Cannot Save the document."))
Finally
Marshal.ReleaseComObject(doc)
End Try
Case ADXOfficeHostApp.ohaExcel
Dim doc As Excel.Workbook = Nothing
Try
doc = addin.ExcelApp.ActiveWorkbook
doc.Final = True
'doc.RefreshAll()
'doc.CalculateUntilAsyncQueriesDone()
'doc.Calculate()
Catch ex As Exception
Throw New Exception(Me.addin.getLabel("cannotSaveCopy", "Cannot Save the document."))
Finally
Marshal.ReleaseComObject(doc)
End Try
' Powerpoint case intentionally skipped as is has same format/code
End Select
End Sub
The above code works pretty well for the Word case, but when it comes to Excel, it stacks on the popup which informs the user for the publish action to the remote server:
EDIT
At that particular point, the execution freezes (or maybe gets into an infinite internal loop, because the only available buttons in debugging mode are pause and stop) at the line of setting the document as final and it never reaches the finally statement (where we release the object). It also seems like the execution tries to return control back to the excel document, but nothing more than this notification occurs :
Any idea of what is wrong in the above code, regarding the handling of Excel?
The lines in comments display some trials I have been going through, while trying to find a solution around the net.
In addition, here is also the popup's related code:
Private Sub doWork(ByVal action As String, ByVal e As System.ComponentModel.DoWorkEventArgs)
Dim myDoc As MyDocument
myDoc = DirectCast(e.Argument, MyDocument)
System.Diagnostics.Debug.WriteLine("Post in Thread")
Dim resultObject(3) As Object
resultObject(0) = True
resultObject(1) = myDoc
Dim saveDocumentResult As SaveDocumentResult = Nothing
Try
Select Case action
Case Constants.SAVE_DRAFT
saveDocumentResult = myDoc.getRequestService().saveDraft(myDoc.getSaveFile(), myDoc.getDocName(), myDoc)
Case Constants.PUBLISH
saveDocumentResult = myDoc.getRequestService().publishDocument(myDoc.getSaveFile(), myDoc.getDocName(), myDoc)
myDoc.setDocFinal() 'this line makes the call to the above code
End Select
myDoc.updateDocumentProperty(Constants.VERSION, saveDocumentResult.version)
myDoc.updateDocumentProperty(Constants.HASH, saveDocumentResult.hash)
myDoc.setSaved(True)
System.Threading.Thread.Sleep(1500)
Catch ex As Exception
resultObject(0) = False
resultObject(2) = ex.Message
Finally
e.Result = resultObject
End Try
End Sub

VB.net Terminal Server application

im working on an terminal service application for personal use that allows me to list and manage all my RDP sessions via tabs (I know these exists, but using it as a small learning project also). I was wondering if anyone could help with a few items. I am trying to dynamically create and add tabs and the RDP control onto each tab. This seems to be working OK for creating the first tab page and control but fails on the subsequent ones with the error below Code below:
Dim theNewTabPage As New DevExpress.XtraTab.XtraTabPage()
theNewTabPage.Text = txtserver.Text
theNewTabPage.Name = Minute(DateTime.Now) & Second(DateTime.Now)
Dim RDPCONTROL As New AxMSTSCLib.AxMsRdpClient9NotSafeForScripting
RDPCONTROL.Dock = DockStyle.Fill
'Just a test to ensure unique name
RDPCONTROL.Name = Minute(DateTime.Now) & Second(DateTime.Now)
XtraTabControl1.TabPages.Add(theNewTabPage)
theNewTabPage.Controls.Add(RDPCONTROL)
Try
RDPCONTROL.Server = txtserver.Text
RDPCONTROL.Domain = txtdomain.text
RDPCONTROL.UserName = txtusername.Text
Dim secured As MSTSCLib.IMsTscNonScriptable = DirectCast(RDPCONTROL.GetOcx(), MSTSCLib.IMsTscNonScriptable)
secured.ClearTextPassword = txtpassword.Text
RDPCONTROL.Connect()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try`
Error when creating the second connection:
Using ex.message: exception of type 'system.windows.forms.axhost+invalidactivexstateexception was thrown
Using ex.tostring: property set of 'Server' cannot be invoked at this time
The next item is how can i detect if the RDP session was disconnected on the tab and then pop-up a message and close the required tab
After a bit of playing around i was able to solve this by calling:
XtraTabControl1.SelectedTabPage = newTabPage
Just after i added the new tab page.
Hope this helps someone in the future

Prompting for a folder in SSIS 2008 Script Task

What I'm trying to do here would seem to be pretty simple. At the start of my SSIS package I want to set a variable to a directory that the user is prompted for. Here's my VB code:
Public Sub Main()
Dim fldDialog As FolderBrowserDialog = New FolderBrowserDialog
fldDialog.Description = "Select the folder..."
fldDialog.ShowNewFolderButton = False
fldDialog.RootFolder = Environment.SpecialFolder.MyDocuments
If fldDialog.ShowDialog() = DialogResult.OK Then
Dts.Variables("variable").Value = fldDialog.SelectedPath
Dts.TaskResult = ScriptResults.Success
Else
MsgBox("You need to select a folder!", MsgBoxStyle.Exclamation, "Error!")
Dts.TaskResult = ScriptResults.Failure
End If
End Sub
Of course, I've got "variable" set as a "ReadWriteVariables" in the Script Task Editor, and the "Imports System.Windows.Forms" at the top of my VB file.
When I run the task it just sits there yellow (as if it's running), but never shows the dialog. There's never even an error, it just sits there. I can run the same code within a standard windows application project no problem.
Not sure what's going on here. On know one quirk of showing an OpenFileDialog is you have to set the ShowHelp property to True, so I'm wondering if there's another quirk to getting this to run. Google only mostly shows me an old problem where the folder tree is blank, but I'm not even getting the prompt. Any help would be much appreciated.
I know it's a little bit late but I came across this Problem and found a fix for this. (Using C#)
You need to use the "OpenFileDialog" instead of the "FolderBrowserDialog" and you need to set a few adjustments. Here is a sample code which opens the explorer and lets you pick a folder:
public void Main()
{
string myPath="";
OpenFileDialog folderBrowser = new OpenFileDialog();
folderBrowser.ValidateNames = false;
folderBrowser.CheckFileExists = false;
folderBrowser.CheckPathExists = true;
folderBrowser.FileName = "Folder Selection.";
folderBrowser.ShowHelp = true;
if (folderBrowser.ShowDialog() == DialogResult.OK)
{
myPath = Path.GetDirectoryName(folderBrowser.FileName);
}
else
{
MessageBox.Show("Error selecting path");
}
Dts.Variables["User::varFolderPath"].Value = myPath;
Dts.TaskResult = (int)ScriptResults.Success;
}
The most important statement is the "folderBrowser.ShowHelp = true" statement. If this assignment isn't made you'll get the same problem as in your question.
You also need the statements above to "trick" the Dialog so you can select a Folder instead of a File.
I hope I can help you or people with the same problem but you should pass in the folder as a variable into the package as "N West" said.

How do I output to a text file without getting an IO exception?

I have this code.
Dim txtVern As String = String.Empty
Try
Using verSR As New StreamReader(appDataVersionLoc)
txtVern = verSR.ReadToEnd()
End Using
Catch ex As Exception
Dim verFile As System.IO.FileStream
verFile = System.IO.File.Create(appDataVersionLoc)
Dim wWFERes As DialogResult = MessageBox.Show("Version file missing/corrupt, created a new one.")
If My.Computer.FileSystem.FileExists(appDataVersionLoc) Then
My.Computer.FileSystem.WriteAllText(appDataVersionLoc, "0.0.0.0", True)
End If
End Try
But when it tries to execute My.Computer.FileSystem.WriteAllText(appDataVersionLoc, "0.0.0.0", True), I get this error:
The process cannot access the file 'C:\Users\Dubstaphone\AppData\Roaming\TheArena\version.txt' because it is being used by another process.
How to I avoid this? What I did was I made it create a text file called "version.txt" if it doesn't already exist. Now I'm trying to write "0.0.0.0" to it, but it's giving me that error. By the way, "appDataVersionLoc" equals GetFolderPath(SpecialFolder.ApplicationData) & "\TheArena\version.txt"
This variable works fine for everything else.
Thanks!
P.S.
I'm a complete noob.
System.IO.File.Create or My.Computer.FileSystem.WriteAllText may still hold a lock on the file. Use the System.IO.File WriteAllText and a Using statement.
If you use a Stream you should close/dispose of it. Better yet when dealing with files always use a Using statement.
Edit:
Example of creating a file
Using File.Create(path)
End Using
If File.Exists(appDataVersionLoc) Then
File.WriteAllText(appDataVersionLoc, "0.0.0.0")
End If
or
Dim appDataFile = File.Create(path)
appDataFile.Close