How to Change database name in Linq Vb.net - sql

I have a database Linq dbml
I need to change the database name before creating
Dim dt As New DataSchool()
dt.Connection.Open()
dt.CreateDatabase()

Use This Method
Sub CreatesqldatabaseMSQL()
Try
Using connect As New DataSchool(GetSQLConnectionString(True))
connect.CreateDatabase()
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
GetSQLConnectionString This Function Return SQLconnection string
Public Function GetSQLConnectionString(ByVal includeDatabase As Boolean) As String
Dim builder As New SqlConnectionStringBuilder()
'Build a connection string from the user input.'
builder.DataSource = Msql.datasource
builder.IntegratedSecurity = Msql.IntSec
If builder.IntegratedSecurity = False Then
builder.UserID = Msql.username
builder.Password = Msql.password
End If
If includeDatabase Then
builder.InitialCatalog = Msql.DatabaseName
End If
Return builder.ConnectionString
End Function
Msql.Server, Msql.DatabaseName and etc this is Structure, You can change database name From here
Public Structure Msql
Shared datasource As String
Shared IntSec As Boolean
Shared username As String
Shared password As String
Shared DatabaseName As String
End Structure

Related

VB.Net freezing when adding 10000+ rows to SQL from list

I am running a RESTful API service which gets data from a server as a JSON string. Around 20000 rows are being selected.
Dim js As New JavaScriptSerializer()
Dim prodlist As List(Of Product) = js.Deserialize(Of List(Of Product))(JSONreturn)
The 20000 rows are populated in the list prodlist. Checked the count and manually verified the list.
I need to insert these rows in a client machine. However, while inserting the rows, it freezes or stops after inserting around 600-700 rows. Below is the code I am using for inserting.
For Each item As Product In prodlist
Dim SPName As String = "someSPname"
With connectionstring
.Clear()
.Parameters("#itemnumber", SqlDbType.VarChar, ParameterDirection.Input, , item.itemnumber
.Parameters("#itemtype", SqlDbType.VarChar, ParameterDirection.Input, , item.itemtype)
.Parameters("#DESCRIPTION", SqlDbType.VarChar, ParameterDirection.Input, , item.DESCRIPTION)
.Execute(SPName)
End With
Next
No error is thrown. It just freezes after inserting roughly 600-700 rows everytime.
Bulk insert is not an option. How do I resolve this?
UPDATE : Adding connection class. Pretty sure there is no issue with this :
Public Class ConnectionClass
Public ReadOnly Property ConnectionString() As String
Get
Return GetConfiguration()
End Get
End Property
Public Sub Parameters(ByVal param_name As String, ByVal type As SqlDbType, ByVal direction As ParameterDirection, Optional param_size As Int32 = Nothing, Optional param_value As Object = Nothing)
Dim sqlParam As SqlParameter = Nothing
Try
sqlParam = New SqlParameter(param_name, type)
sqlParam.Size = param_size
sqlParam.Direction = direction
sqlParam.Value = param_value
Lstparam.Add(sqlParam)
Finally
If sqlParam IsNot Nothing Then
sqlParam = Nothing
End If
End Try
End Sub
Public Sub Execute(ByVal strSpName As String, Optional ByVal Type As CommandType = CommandType.StoredProcedure)
Try
sqlcmd = New SqlCommand()
sqlcmd.Connection = connection
''Setting the timeout to 50 mins as setup in the previous application
sqlcmd.CommandTimeout = 3000
If transaction IsNot Nothing Then
sqlcmd.Transaction = transaction
End If
sqlcmd.CommandType = Type
sqlcmd.CommandText = strSpName
For Each argument As SqlParameter In Lstparam
sqlcmd.Parameters.Add(argument)
Next
For introw As Integer = 0 To sqlcmd.Parameters.Count - 1
If sqlcmd.Parameters.Item(introw).ParameterName.Contains("Parameter") Then
sqlcmd.Parameters.Item(introw).ParameterName = String.Empty
End If
Next
sqlcmd.ExecuteNonQuery()
Catch ex As Exception
Throw
End Try
End Sub
Public Sub Clear()
ClearParameters()
Lstparam.Clear()
End Sub
Public Sub ClearParameters()
If Not sqlcmd Is Nothing Then
Do Until sqlcmd.Parameters.Count = 0
sqlcmd.Parameters.Clear()
Loop
End If
End Sub
Public Function GetConfiguration() As String
Dim sbConnectionString As New StringBuilder
With sbConnectionString
.Append("Data Source=")
.Append(ServerName)
.Append(";")
.Append("Initial Catalog =")
.Append(DatabaseName)
.Append(";")
.Append("User ID =")
.Append(UserName)
.Append(";")
.Append("Password =")
.Append(UserPassword)
End With
Return sbConnectionString.ToString()
End Function
Public Function CreateClientConnection() As SqlConnection
Dim connectionString As String
Try
connectionString = GetConfiguration()
Dim substrings() As String = connectionString.ToUpper.Split(";")
Dim substrings1() As String = connection.ConnectionString.ToUpper.Split(";")
If Not (connection.State = ConnectionState.Open) Then
connection.ConnectionString = connectionString
connection.Open()
ElseIf Not (Trim(substrings(0)) = Trim(substrings1(0))) Then
If connection IsNot Nothing Then
connection.Dispose()
End If
connection.ConnectionString = connectionString
connection.Open()
End If
Return connection
Catch ex As Exception
If connection IsNot Nothing Then
connection.Dispose()
End If
Throw ex
End Try
End Function
End Class

MongoDB Query in VB.Net

I can not get VB.net connect to a mongodb replicaset - it throws exceptions
dim mongo as MongoDBClient
dim mgDB as MongoDatabase
dim mgcol as MongoCollection(of Bob)
public class Bob
public property ID as ObjectID
public property Name as string
end class
sub Main()
try
mongo = New MongoClient("mongodb://ip:port,ip:port,ip:port/?replicaSet=Bob")
mgDB = mongo.GetDatabase("test")
mscol = mgDB.Collection(of Bob)("test.me")
mgDB.GetCollection("test.me").Find(MongoDB.Driver.Builders.Query.Exists("id"))
catch ex as Exception
console.writeline(ex)
end try
end sub
I don't know how I'm supposed to query via VB .Net?
I got this to work
Dim _client As IMongoClient
Dim _db As IMongoDatabase
Sub Main()
System.Console.WriteLine("Hi, Bob!!")
Try
_client = New MongoClient("mongodb://mongoone:27020,mongotwo:27021,mongothree:27020/?replicaSet=Bob")
_db = _client.GetDatabase("Test")
Dim mgCol = _db.GetCollection(Of Bob)("test.me")
Dim mybob As Bob
mybob = New Bob
mybob.Name = "Sam6"
mybob.ID = ObjectId.GenerateNewId
'mgCol.InsertOne(mybob)
getSomedata().Wait()
'getDataByFilterExtists().Wait()
'getMetaCardSpectrum().Wait()
getMetaCardSpectrumObj().Wait()
Catch ex As Exception
Console.WriteLine(ex)
End Try
End Sub

Database fields dont update when click event is triggered

the code I have runs without any errors but the database doesnt update its fields.
This runs with no errors but database doesnt update its fields
Sub UpdatePassword(ci As ClientInformation)
Try
Using con As New SqlCeConnection(GetConString)
If con.State = Data.ConnectionState.Closed Then con.Open()
Dim adapt As New SqlCeDataAdapter(String.Format("UPDATE AdminInformation
where ClientID='{0}' SET PWD='{1}'", ci.ClientID, ci.Password), con)
End Using
Catch ex As Exception
End Try
End Sub
my ClientInformation Class:
Public Class ClientInformation
Public Property ClientID As String
Public Property SubscriptionEndDate As Date
Property FirstName As String
Property Surname As String
Property Email As String
Property Company As String
Property PostalAdd As String
Property Country As String
Property Tel As String
Property Fax As String
Property Password As String
End Class
my event handler:
Protected Sub btnChangePass_Click(sender As Object, e As EventArgs) Handles
btnChangePass.Click
Dim ci As New ClientInformation
If txtBoxNewPass.Text = txtBoxConfirmNewPass.Text Then
ci.Password = txtBoxNewPass.Text
lblConfirmPasswordMsg.Visible = False
dh.UpdatePassword(ci)
lblPasswordChanged.Visible = True
txtBoxNewPass.Text = ""
txtBoxConfirmNewPass.Text = ""
Else
txtBoxNewPass.Text = ""
txtBoxConfirmNewPass.Text = ""
lblConfirmPasswordMsg.Visible = True
End If
End Sub
my connection string:
Private Function GetConString() As String
Return ConfigurationManager.ConnectionStrings("conStringLicenses").ConnectionString
End Function
any help will be appreciated, thanks in advance.
PS database is sql compact, visual studio 2012, windows 7
I think your query should be like this
UPDATE AdminInformation SET PWD='{1}' where ClientID='{0}'
You started your WHERE clause before your SET
UPDATE:
Try changing
Dim adapt As New SqlCeDataAdapter(String.Format("UPDATE AdminInformation where ClientID='{0}' SET PWD='{1}'", ci.ClientID, ci.Password), con)
into this
Dim cmd As New SqlCeCommand(String.Format("UPDATE AdminInformation SET PWD='{1}' where ClientID='{0}'", ci.ClientID, ci.Password), con)
cmd.ExecuteNonQuery()

vb.net return json object with multiple types?

I need to return some data from a web service that looks something like this:
data.page = 1
data.count = 12883
data.rows(0).id = 1
data.rows(0).name = "bob"
data.rows(1).id = 2
data.rows(1).name = "steve"
data.rows(2).id = 3
data.rows(2).name = "fred"
I have no idea how to do this. I've returend simple types and simple arrays, but never an object like this.
The data source is a sql Database. The target is a javascript/ajax function. I'm currently successfully returning the rows themselves as a dataset and it works, but I need to add the count and a couple other "parent level" variables.
For the sake of full disclosure, here is the code that is working:
<WebMethod()> _
Public Function rptPendingServerRequests() As DataSet
Dim connetionString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim sql As String
connetionString = "..."
sql = "SELECT usm_request.request_id, usm_request.status, usm_request.req_by_user_id " +
"FROM usm_request " +
"WHERE usm_request.request_id in " +
"(SELECT distinct(usm_request.request_id) from usm_request, usm_subscription_detail WHERE usm_request.request_id = usm_subscription_detail.request_id " +
"AND usm_subscription_detail.offering_id = 10307) ORDER BY usm_request.request_id DESC"
connection = New SqlConnection(connetionString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds)
adapter.Dispose()
command.Dispose()
connection.Close()
Return ds
Catch ex As Exception
End Try
End Function
And I'm trying to consume it with FlexiGrid. I've been working at it for a few hours with no luck. I basically need to convert the PHP at the following site to .net
http://code.google.com/p/flexigrid/wiki/TutorialPropertiesAndDocumentation
I think that you would be much better off just creating a couple of classes and moving the data from the database into these classes. For example:
Public Class MyDataClass
Public Property Page As Integer
Public ReadOnly Property Count As Integer
Get
If Me.Rows IsNot Nothing Then
Return Me.Rows.Count
Else
Return 0
End If
End Get
End Property
Public Property Rows As List(Of MyDataRow)
' Parameterless constructor to support serialization.
Public Sub New()
Me.Rows = New List(Of MyDataRow)
End Sub
Public Sub New(wPage As Integer, ds As DataSet)
Me.New()
Me.Page = wPage
For Each oRow As DataRow In ds.Tables(0).Rows
Dim oMyRow As New MyDataRow
oMyRow.Id = oRow("id")
oMyRow.Name = oRow("Name")
Me.Rows.Add(oMyRow)
Next
End Sub
End Class
Public Class MyDataRow
Public Property Id As Integer
Public Property Name As String
' Parameterless constructor to support serialization
Public Sub New()
End Sub
End Class
Then change the return type of the method to MyDataClass and change the return to:
Return New MyDataClass(1, ds)

Problem Understanding Access Modifiers in VB.Net with List( Of Object)

I've recently been updating a lot of my code to comply with proper n-tier architecture and OO programming, following examples from a book.
I'm starting to get problems now because I don't fully understand the access modifiers.
If I run the following code I get an error at the line
Dim clientFamilyDataAccessLayer As New ClientFamilyDAO
in the BLL at the point it creates an instance of the DAL. The full error message is: "The type initializer for 'ClientFamilyDAO' threw an exception. ---> System.NullReferenceException: Object reference not set to an instance of an object."
How do I use these function to create a list of ClientFamily objects that I can then work with?
On my UI layer I'm creating a list of objects; ClientFamilies
Dim listOfClientFamilies As List(Of ClientFamily) = ClientFamily.GetClientFamiliesByKRM(selectedEmployee.StaffNumber)
This is the function in the BLL
Public Shared Function GetClientFamiliesByKRM(ByVal krmStaffNumber As Integer) As List(Of ClientFamily)
Dim clientFamilyDataAccessLayer As New ClientFamilyDAO
Return clientFamilyDataAccessLayer.GetClientFamiliesByKRM(krmStaffNumber)
End Function
and this is function in the DAL
Public Function GetClientFamiliesByKRM(ByVal staffNumber As Integer) As List(Of ClientFamily)
Dim currentConnection As SqlConnection = New SqlConnection(_connectionString)
Dim currentCommand As New SqlCommand
currentCommand.CommandText = mainSelectStatement & " WHERE Key_Relationship_Manager = #StaffNumber ORDER BY Client_Family_Name"
currentCommand.Parameters.AddWithValue("#StaffNumber", staffNumber)
currentCommand.Connection = currentConnection
Dim listOfClientFamilies As New List(Of ClientFamily)
Using currentConnection
currentConnection.Open()
Dim currentDataReader As SqlDataReader = currentCommand.ExecuteReader()
Do While currentDataReader.Read
Dim newClientFamily As AECOM.ClientFamily = PopulateClientFamily(currentDataReader)
listOfClientFamilies.Add(newClientFamily)
Loop
End Using
Return listOfClientFamilies
End Function
Here's the full ClientFamilyDAO Class:
Public Class ClientFamilyDAO
Private Const mainSelectStatement As String = "SELECT Client_Family_ID, Client_Family_Name, Key_Relationship_Organisation, Key_Relationship_Manager, Obsolete, Market_Sector_ID FROM Client_Families"
Private Shared ReadOnly _connectionString As String = String.Empty
Shared Sub New()
_connectionString = WebConfigurationManager.ConnectionStrings("ClientFamilyManagementConnectionString").ConnectionString
End Sub
Public Function GetClientFamiliesByKRM(ByVal staffNumber As Integer) As List(Of ClientFamily)
Dim currentConnection As SqlConnection = New SqlConnection(_connectionString)
Dim currentCommand As New SqlCommand
currentCommand.CommandText = mainSelectStatement & " WHERE Key_Relationship_Manager = #StaffNumber ORDER BY Client_Family_Name"
currentCommand.Parameters.AddWithValue("#StaffNumber", staffNumber)
currentCommand.Connection = currentConnection
Dim listOfClientFamilies As New List(Of ClientFamily)
Using currentConnection
currentConnection.Open()
Dim currentDataReader As SqlDataReader = currentCommand.ExecuteReader()
Do While currentDataReader.Read
Dim newClientFamily As AECOM.ClientFamily = PopulateClientFamily(currentDataReader)
listOfClientFamilies.Add(newClientFamily)
Loop
End Using
Return listOfClientFamilies
End Function
Private Function PopulateClientFamily(ByVal currentDataReader As SqlDataReader) As AECOM.ClientFamily
Dim newClientFamily As New AECOM.ClientFamily
If Not (currentDataReader.IsDBNull(currentDataReader.GetOrdinal("Client_Family_ID"))) Then
newClientFamily.ClientFamilyID = currentDataReader("Client_Family_ID")
End If
If Not (currentDataReader.IsDBNull(currentDataReader.GetOrdinal("Client_Family_Name"))) Then
newClientFamily.ClientFamilyName = currentDataReader("Client_Family_Name")
End If
If Not (currentDataReader.IsDBNull(currentDataReader.GetOrdinal("Key_Relationship_Organisation"))) Then
Select Case currentDataReader("Key_Relationship_Organisation")
Case False
newClientFamily.IsKeyRelationshipOrganisation = False
Case True
newClientFamily.IsKeyRelationshipOrganisation = True
End Select
End If
If Not (currentDataReader.IsDBNull(currentDataReader.GetOrdinal("Key_Relationship_Manager"))) Then
newClientFamily.KeyRelationshipManagerStaffNumber = currentDataReader("Key_Relationship_Manager")
End If
If Not (currentDataReader.IsDBNull(currentDataReader.GetOrdinal("Obsolete"))) Then
Select Case currentDataReader("Obsolete")
Case False
newClientFamily.Obsolete = False
Case True
newClientFamily.Obsolete = True
End Select
End If
If Not (currentDataReader.IsDBNull(currentDataReader.GetOrdinal("Market_Sector_ID"))) Then
newClientFamily.MarketSectorID = currentDataReader("Market_Sector_ID")
End If
Return newClientFamily
End Function
End Class
The issue doesn't relate to access modifiers, rather it is more to do with the exception message you get. The following line within the constructor of ClientFamilyDAO would seem to be causing the issue:
_connectionString = WebConfigurationManager.ConnectionStrings("ClientFamilyManagementConnectionString").ConnectionString
Are you sure ClientFamilyManagementConnectionString exists in the configuration?