I have multiple SQL server tables from which I want to pull data and write to XML. I want my XML to be formed like this:
<Data>
<Query1Table>
<Table>
<Column1>Data</Column1>
<Column2>Data</Column2>
...
</Table>
</Query1Table>
<Query2Table>
<Table>
<Column1>Data</Column1>
<Column2>Data</Column2>
...
</Table>
</Query2Table>
</Data>
I'm using datasets to write the xml, but the code I'm working with doesn't append the data, it overwrites:
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim directory As String
Dim ds As New DataSet
Dim sql As String
connection = New SqlConnection(connetionString)
sql = "select * from scheduledata"
connection.Open()
adapter = New SqlDataAdapter(sql, connection)
adapter.Fill(ds)
ds.DataSetName = "Schedule"
ds.WriteXml(directory)
ds.Clear()
sql = "select * from costdata"
adapter = New SqlDataAdapter(sql, connection)
adapter.Fill(ds)
ds.WriteXml(directory)
I have tried adding it all to the same data set by calling the SQL queries at once, but that doesn't help to separate them in the XML -- it groups them in the same node.
I'm open to a different method if anyone has a good suggestion.
You've defined directory as a string, so ds.WriteXml will (create and) write to a file by that name.
Use a FileStream or XmlTextWriter instead.
The way that I write to .xml files (which works) is as follows
Private Sub AuthenticationContinuebtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AuthenticationContinuebtn.Click
On Error GoTo PasswordHandler
GlobalVariables.Username = Usernametxtbx.Text
GlobalVariables.Password = Passwordtxtbx.Text
GetUsernamePassword()
Close()
Exit Sub
PasswordHandler:
MsgBox("Incorrect password or username.")
End Sub
Private Sub UserAuthenticationWindow_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim FileName4 As String = "C:\Forte\UsernamePassword.xml"
Dim FileRead4 As XmlTextReader = New XmlTextReader("C:\Forte\UsernamePassword.xml")
'If statement to see if file exists.
If System.IO.File.Exists(FileName4) = True Then
Do While (FileRead4.Read)
Select Case FileRead4.NodeType
Case XmlNodeType.Text, XmlNodeType.Element
If FileRead4.Name = "Username" Then
FileRead4.Read()
Usernametxtbx.Text = FileRead4.Value
GlobalVariables.Username = Usernametxtbx.Text
End If
If FileRead4.Name = "Password" Then
FileRead4.Read()
Passwordtxtbx.Text = FileRead4.Value
GlobalVariables.Password = Passwordtxtbx.Text
End If
End Select
Loop
Else
MainBox.MainTextBox.AppendText(FileName4 & " could not be found. Settings are restored to defaults.")
MainBox.Logging(Date.Now & FileName4 & " could not be found. Settings are restored to defaults.")
End If
FileRead4.Close()
End Sub
Public Sub createNode3(ByVal Username As String, ByVal Password As String, ByVal writer As XmlTextWriter)
'On Error Resume Next
writer.WriteStartElement("Username_Password")
writer.WriteStartElement("Username")
writer.WriteString(Username)
writer.WriteEndElement()
writer.WriteStartElement("Password")
writer.WriteString(Password)
writer.WriteEndElement()
writer.WriteEndElement()
End Sub
Related
I'm currently trying to write code for a form that has text boxes for a user to input the required data into which then with the use of button the data in the text boxes will be sent to an access table.
If you need any more information to help solve the problem I'm willing to provide it if you ask (I would upload pictures/screenshots but I need "10 reputation" apparently.
You can do this
Imports System.Data.OleDb
Public Class Form1
Dim AccessConection As OleDbConnection
Private Sub btSave_Click(sender As Object, e As EventArgs) Handles btSave.Click
Dim cmd As New OleDbCommand
Dim mySql As String
mySql = "INSERT INTO Customs (CustomName,Address) VALUES(#Name,#Address)"
Try
cmd.Parameters.AddWithValue("#Name", txName.Text)
cmd.Parameters.AddWithValue("#Address", txAddress.Text)
cmd.Connection = AccessConection
cmd.CommandType = CommandType.Text
cmd.CommandText = mySql
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Whatever you want to say..." & vbCrLf & ex.Message)
End Try
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim myDataBasePath As String = "C:\Users\user\Source\Workspaces\......\SOF003\Data.accdb" 'Here you put the full name of the database file (including path)
'The next line is for Access 2003 .mdb files
'Dim CadenaConection As String = String.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}", myDataBasePath)
Dim CadenaConection As String = String.Format("Provider=Microsoft.ACE.OLEDB.12.0; Data Source={0}", myDataBasePath)
AccessConection = New OleDbConnection(CadenaConection)
AccessConection.open()
End Sub
End Class
btSave is the command button.
Customs is the table's name.
CustomName and Address are two fields.
txName and txAddress are two TextBox Control.
Obviously you should be careful with the data types (here I use only strings), validation, etc, etc... But, this is a starting point. If you search, you'll find another ways, more elaborated.
Please I'm using vb.net 2008 and Sql 2008 and I have to save a picture in to the database. When I run the code initially it was saving and later i realized it was giving me NullReferenceException was caught. Object reference not set to an instance of an object. I' just confused!
The code below
Imports System.Data.SqlClient
Imports System.IO
Private Sub btnImage1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImage1.Click
'Code to load picture
Dim OpenFileDialog1 As New OpenFileDialog
OpenFileDialog1.Filter = "JPG|*.jpg|BITMAP|*.bmp|GIF|*.gif"
OpenFileDialog1.ShowDialog()
If OpenFileDialog1.FileName <> "" AndAlso IO.File.Exists(OpenFileDialog1.FileName) Then
Dim Extention As String = New IO.FileInfo(OpenFileDialog1.FileName).Extension
Select Case Extention.ToLower
Case Is = ".jpg", Is = ".bmp", Is = ".gif"
Case Else
MsgBox("Only JPG, BMP and GIF files are allowed. Thank you")
Exit Sub
End Select
Me.Pic1.Image = Image.FromFile(OpenFileDialog1.FileName)
End If
End Sub
'Code to save picture (I stepped into the code and the frmAllottee.Pic1 is there)
Public Sub Save_Picture()
Dim sql_command As SqlCommand
Dim mStream As MemoryStream = New MemoryStream()
'Dim mstream As New MemoryStream()
frmAllottee.Pic1.BackgroundImage.Save(mstream, frmAllottee.Pic1.BackgroundImage.RawFormat) - This line gives the error
Dim arrImage() As Byte = mstream.GetBuffer()
mstream.Close()
Dim Sql As String = "Insert into Alloc(Pic) VALUES(#Pic)"
sql_command = New SqlClient.SqlCommand(Sql, Con)
sql_command.Connection.Open()
sql_command.Parameters.AddWithValue("#Pic1", arrImage)
sql_command.ExecuteNonQuery()
sql_command.Connection.Close()
End Sub
This would happen if frmAllottee.Pic1.BackgroundImage is null.
Image and BackgroundImage are not the same.
Me.Pic1.Image = Image.FromFile(OpenFileDialog1.FileName)
This line of code here doesnt correspond to this code :
frmAllottee.Pic1.BackgroundImage.Save(mstream, frmAllottee.Pic1.BackgroundImage.RawFormat)
You have inserted an Image in your Pic1 in the Image while you are saving it and you chose BackgroundImage instead of Image
Also
Dim Sql As String = "Insert into Alloc(Pic) VALUES(#Pic)"
sql_command = New SqlClient.SqlCommand(Sql, Con)
sql_command.Connection.Open()
sql_command.Parameters.AddWithValue("#Pic1", arrImage)
sql_command.ExecuteNonQuery()
sql_command.Connection.Close()
#Pic from inserting to database should be the same as your #Pic1 when addingwithvalue i.e. (both should be #Pic or whichever you like)
Ive tried it and it works
I need your help.
I'm writing code for a shop program and I am using vb.net 2008 with Crystal Report version 10.5.37xxxx
The problem is when I'm trying to install my program on the client computer, everything works but not in my Crystal Report. It always asks for the database login and I did not code my program to ask for the database login.
I just wrote it in simple code like this:
Public Class Form16
Private Sub Form16_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim view As New CrystalReport4
view.SetParameterValue("p_1", Form5.no_faktur_tb_immanuel)
CrystalReportViewer1.ReportSource = view
End Sub
End Class
Can anyone help me with this?
You should be able to manually code the login credentials.
Public Class Form16
Private Sub Form16_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim view As New CrystalReport4
Dim user as string = "Username"
Dim pwd as string = "Password"
view.SetDatabaseLogon(user, pwd)
view.SetParameterValue("p_1", Form5.no_faktur_tb_immanuel)
CrystalReportViewer1.ReportSource = view
End Sub
End Class
Make Sure your Report DataSource Provider is set to Microsoft OLE DB provider for SQL Server and not SQL Server Native Client 10.0
try that open field explorer---> database field --->Right Click -->current Data source --->reports connection----->report ----->property ---->
set Property as---
Data Source: .\Databasename.accdb
and code on viewer form load as
Dim cryRpt As New ReportDocument
Dim Report1 As New rptItemWise
Dim strServerName As String
strServerName = Application.StartupPath
rptItemWise.SetDatabaseLogon("admin", "", strServerName, "dastabasename.accdb", True)
cryRpt.Load(Application.StartupPath + "\rptItemWise.rpt")
also change the report connection same as data source
i think that code work for you ....
This will work for you!
C# Code :
ConnectionInfo boconnectioninfo = new ConnectionInfo ();
boconnectioninfo.ServerName= "D-2818-w2k";
boconnectioninfo.DatabaseName ="NW";
boconnectioninfo.UserID ="sa";
boconnectioninfo.Password ="sa";
CrystalReportViewer1 .ReportSource = Server.MapPath("CrystalReport1.rpt");
TableLogOnInfos botableInfo= CrystalReportViewer1 .LogOnInfo;
foreach (TableLogOnInfo obj2 in botableInfo)
{
obj2.ConnectionInfo =boconnectioninfo;
}
Vb.net Code :
Dim boconnectioninfo As New ConnectionInfo
boconnectioninfo.ServerName = "sa"
boconnectioninfo.DatabaseName = "sa"
boconnectioninfo.UserID = "sa"
boconnectioninfo.Password = "sa"
Me.rptViewer.ReportSource = _ReportPath
Me.rptViewer.SelectionFormula = _SelectionFormula
If Not _ParameterFields Is Nothing Then
Me.rptViewer.ParameterFieldInfo = _ParameterFields
End If
Dim a As TableLogOnInfos = Me.rptViewer.LogOnInfo
' Iterate through the list.
For Each aa As TableLogOnInfo In a
aa.ConnectionInfo = boconnectioninfo
Next
Me.Cursor = Cursors.Default
rptViewer.Refresh()
.hi everyone I have this code:
Private Sub EditPage_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'InventorySysDataSet.tb_master_products' table. You can move, or remove it, as needed.
Me.Tb_master_productsTableAdapter.Fill(Me.InventorySysDataSet.tb_master_products)
sqlCnn = New SqlConnection("Data Source=ZEREY\SQLEXPRESS2008;Initial Catalog=InventorySys;Integrated Security=SSPI")
Me.txtRowId.Text = Form1.txtRowId.Text
'MsgBox(Me.txtRowId.Text)
sql = "Select * from tb_master_inventory_per_day where Inventory_Date = " & txtRowId.Text & ""
Dim upcmd As New SqlCommand("Select * from tb_master_inventory_per_day where Row_Id = #Row_Id", sqlCnn)
upcmd.Parameters.Add(New SqlParameter("#Row_Id", Me.txtRowId.Text))
upcmd.Connection.Open()
Try
Dim dr As SqlDataReader = upcmd.ExecuteReader()
If dr.Read Then
txtInventoryDate.Text = dr.Item("Inventory_Date")
cboProductCode.DisplayMember = dr.Item("Product_Code")
txtQty.Text = dr.Item("Product_Count")
Else
MessageBox.Show("Error!")
End If
Catch ex As SqlException
If ex.Number <> 0 Then
'ErrorProvider1.SetError(Me.txtuseridprofile, "Login Id: " &
'Me.txtuseridprofile.Text & " :Not Found!")
upcmd.Connection.Close()
Exit Sub
End If
End Try
upcmd.Connection.Close()
End Sub
what i want to do is to automatically change the selected option of the cboProductCode on page load depending on the result of a query executed onload also.
help pls! TIA!
.Haha! it's funny that i have tried so many ways but not tried using cboProductCode.Text instead of cboProductCode.DisplayMember. It now works! :D
Dim de As New System.DirectoryServices.DirectoryEntry()
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
de.Path = "WinNT://*****".Replace("*****", ActiveDirectory.Domain.GetCurrentDomain.Name)
Dim Mystream As Object
MsgBox("Please choose the place you want the file")
If savefileDialog1.ShowDialog() = DialogResult.OK Then Mystream = savefileDialog1.FileName
Dim UserFile As String = savefileDialog1.FileName & ".txt"
Dim fileExists As Boolean = File.Exists(UserFile)
Using sw As New StreamWriter(File.Open(UserFile, FileMode.OpenOrCreate))
For Each d As DirectoryEntry In de.Children()
sw.WriteLine(d.Name)
Next
End Using
End Sub
I am getting a large number of entries written out to the text file. The bottom half of the file is all that I really need. The bottom half seems to be the list of all machine names on the domain and the first half is filled with names or printers, and other names that i cannot "pushd \" into.
I am unable to figure out what will cut down this user list and give me only the machine names.
You might find something here...look at "Enumerate Objects in an OU"
Public Function EnumerateOU(OuDn As String) As ArrayList
Dim alObjects As New ArrayList()
Try
Dim directoryObject As New DirectoryEntry("LDAP://" + OuDn)
For Each child As DirectoryEntry In directoryObject.Children
Dim childPath As String = child.Path.ToString()
alObjects.Add(childPath.Remove(0, 7))
'remove the LDAP prefix from the path
child.Close()
child.Dispose()
Next
directoryObject.Close()
directoryObject.Dispose()
Catch e As DirectoryServicesCOMException
Console.WriteLine("An Error Occurred: " + e.Message.ToString())
End Try
Return alObjects
End Function
I'm not sure if there is much difference in our active directory setups, but I ran the following code in a console application and it only output the AD Names (as expected):
Module Module1
Sub Main()
Using de As New System.DirectoryServices.DirectoryEntry
de.Path = "WinNT://*****".Replace("*****", System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain.Name)
For Each d As System.DirectoryServices.DirectoryEntry In de.Children()
If d.SchemaEntry.Name = "User" Then
Console.WriteLine(d.Name)
End If
Next
Console.ReadKey()
End Using
End Sub
End Module
EDIT:
Code change to only output members with the SchemaType of "User"