Entity-Framework EntityConnection MetaData Problem - entity-framework

We are trying to build an EntityConnection dynamically so that different users are connecting to differnet databases determined at run-time. In order to do this we are testing the code found here: http://msdn.microsoft.com/en-us/library/bb738533.aspx. We have implemented this below:
' Specify the provider name, server and database.
Dim providerName As String = "System.Data.SqlClient"
Dim serverName As String = "OurDBServerName"
Dim databaseName As String = "OurDBName"
' Initialize the connection string builder for the
' underlying provider.
Dim sqlBuilder As New SqlConnectionStringBuilder
' Set the properties for the data source.
sqlBuilder.DataSource = serverName
sqlBuilder.InitialCatalog = databaseName
sqlBuilder.IntegratedSecurity = False
sqlBuilder.UserID = "OurAppUserName"
sqlBuilder.Password = "OurPassword"
' Build the SqlConnection connection string.
Dim providerString As String = sqlBuilder.ToString
' Initialize the EntityConnectionStringBuilder.
Dim entityBuilder As New EntityConnectionStringBuilder
'Set the provider name.
entityBuilder.Provider = providerName
' Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = providerString
' Set the Metadata location to the current directory.
entityBuilder.Metadata = "res://*/NotaModel.csdl|" & _
"res://*/NotaModel.ssdl|" & _
"res://*/NotaModel.msl"
Console.WriteLine(entityBuilder.ToString)
Using conn As EntityConnection = New EntityConnection(entityBuilder.ToString)
conn.Open()
Console.WriteLine("Just testing the connection.")
conn.Close()
End Using
When the conn.Open() is run an error is thrown: "Unable to load the specified metadata resource." It seems to indicate that one or more of the "res://*..." references is wrong. I have confirmed that the project does indeed contain these files (under the bin/debug folder). What are we missing here - any ideas?
Thanks

Yes, the res:// part is wrong. Look at the resource names in Reflector (inside the assembly), not on your local filesystem, to see what they should be.

Related

Passing value into your parameter (rs.exe) by stored procudure

I have a situation here where I have a deployed rdl file in the reporting server. The rdl file in question has a parameter.
I am using the rs.exec component to execute the report; whenever I remove the parameter from the rdl file, I successfully run the report from the stored procedure. When I add the parameter, all I keep getting is
\\server\R\subfolder\working\inputfile\example.batK00WE is not recognized as an internal or external operable program or batch file.
Here is what I did: I created a .rss file in VB (Please see code below)
Public Sub Main()
TRY
DIM historyID as string = Nothing
DIM deviceInfo as string = Nothing
DIM extension as string = Nothing
DIM encoding as string
DIM mimeType as string = "application/Excel"
DIM warnings() AS Warning = Nothing
DIM streamIDs() as string = Nothing
DIM results() as Byte
rs.Credentials = System.Net.CredentialCache.DefaultCredentials
rs.LoadReport(REPORTSERVER_FOLDER, historyID)
results = rs.Render(FORMAT, deviceInfo, extension, mimeType, encoding, warnings, streamIDs)
DIM stream As FileStream = File.OpenWrite(FILENAME)
stream.Write(results, 0, results.Length)
stream.Close()
Catch e As IOException
Console.WriteLine(e.Message)
End Try
End Sub
Afterwards... I wrote batch file that utilizes the rs.exec. Please see below:
"\\server\R\subfolder\working\app\rs.exe" -i \\server\R\subfolder\working\inputfile\coo.rss -s "http://server/ReportServer_MSSQLSERVER2" -v FILENAME="\\server\R\subfolder\working\inputfile\file.csv" -v REPORTSERVER_FOLDER="/FILE_REPORT/FILE" -t -v FORMAT="EXCEL" -e Exec2005
If you see the above script the rs.exec utilizes the path of the report server etc.
Finally I created a stored procedure that will run the report on the server and pass into the server the parameter value.
CREATE PROCEDURE [dbo].[test_sproc]
#ProcessID varchar(50)
AS
DECLARE #cmdsql varchar(1000)
Declare #id varchar(50)
Set #id=#SID
Set #cmdsql= '"\\server\R\subfolder\working\inputfile\example.bat"' + #id
exec master..xp_CMDShell #cmdsql
So here is my question is: How do I pass the parameter value from stored procedure to the report server? Where did I go wrong with my code?

Create User Defined Type In SMO

How Create User Defined Type (ex: Point(X int,Y int) With SMO?
I Am Use VB.NET (Or C#.NET) And Want Use SMO For Create?
I know must use "UserDefinedType" in SMO but i don't know How?!
Thanks.
By using following code sample you can create UserDefinedType using SMO:
Dim oServer As Microsoft.SqlServer.Management.Smo.Server
Dim oSMOServer As Microsoft.SqlServer.Management.Smo.Server
Dim oSMODatabase As Microsoft.SqlServer.Management.Smo.Database
Dim sUDT As String = "udt_RecordID"
Try
oServer = New Microsoft.SqlServer.Management.Smo.Server()
''Set ServerName
oServer.ConnectionContext.ServerInstance = pServerInstanceName
''Set is Windows Authentication
oServer.ConnectionContext.LoginSecure = pIsWinAuth
''Set Server UserName & Password, If not Windows Authentication
If pIsWinAuth = False Then
oServer.ConnectionContext.Login = pUsername
oServer.ConnectionContext.Password = pPassword
End If
Dim oUDTs = oSMOServer.Databases(pDatabaseName).UserDefinedTableTypes
''Add UserDefinedType if not exist
If Not oUDTs.Contains(sUDT) Then
oSMODatabase = oSMOServer.Databases(pDatabaseName)
Dim udtt As UserDefinedTableType
udtt = New UserDefinedTableType(oSMODatabase, sUDT)
''Add necessary columns
udtt.Columns.Add(New Microsoft.SqlServer.Management.Smo.Column(udtt, "RecordID", DataType.NVarChar(50)))
''Create UserDefinedType
udtt.Create()
End If
Catch ex As Exception
''Handle Exception
End Try
Feel free to ask if required.

Lotus Notes 7 - copy / move docs. ( parent & response docs ) without changing the UNID ?

I have 2 databases : let say dbA and dbB. Actually, dbB is a ''child'' database of dbA, because the forms/views/frameset/etc that it contains they all are also in dbA.
I want now, to copy from a view ( let say vwA ) from dbA some 8K docs to the same view ( vwA ) from dbB. THese 8k contains both parent and child docs, which in dbA are listing OK, with #Text(#UniqueDocumentID). I just made a test, copy one parent doc and its response, and pasted in the 2nd database, but unfortunately the connection between the 2 docs isn't made... I guess the UNID had changed...
Is there any solutions? Thanks for your time.
Yes, copying a document to another database always creates a new UniversalIDs for document in target database.
To avoid this, your LotusScript should work like this:
create new document in target database
CopyAllItems from source document to target document
set same UniversalID to target document targetDoc.UniversalID = sourceDoc.UniversalID
save the target document
This way the target document has the same UniversalID like the source document and links between document should work in target database too.
This is an example for an agent working on selected documents:
Dim session As New NotesSession
Dim dbSource As NotesDatabase
Dim dbTarget As NotesDatabase
Dim col As NotesDocumentCollection
Dim docSource As NotesDocument
Dim docTarget As NotesDocument
Set dbSource = session.Currentdatabase
Set dbTarget = session.Getdatabase(dbSource.Server, "YourTargetDatabase.nsf", false)
Set col = dbSource.Unprocesseddocuments
Set docSource = col.Getfirstdocument()
While Not docSource Is Nothing
Set docTarget = dbTarget.Createdocument()
Call docSource.Copyallitems(docTarget, true)
docTarget.UniversalID = docSource.UniversalID
Call docTarget.save(True, False)
Set docSource = col.Getnextdocument(docSource)
Wend
Or, you could let replication handle this for you by setting a replication formula, assuming that dbA and dbB are replicas.
I think the easiest way is creating a script and copiing the documents using the CopyToDatabase method of NotesDocument class.
The CopyToDatabase method retains the UniversalID of documents (for perfomance reasons). This is true at least for Versions up to R7.
More information can be found here:
IBM Technote: Documents copied using CopyToDatabase method reuse same UNID
A sample Script (copied and modified from Knut) would be:
Dim session As New NotesSession
Dim dbSource As NotesDatabase
Dim dbTarget As NotesDatabase
Dim col As NotesDocumentCollection
Dim docSource As NotesDocument
Dim docTarget As NotesDocument
Set dbSource = session.Currentdatabase
Set dbTarget = session.Getdatabase(dbSource.Server, "YourTargetDatabase.nsf", false)
Set col = dbSource.Unprocesseddocuments
Set docSource = col.Getfirstdocument()
While Not docSource Is Nothing
Set docTarget = docSource.Copytodatabase(dbTarget)
Set docSource = col.Getnextdocument(docSource)
Wend

How to INSERT into table using Entity Data Model (EDMX)

I am trying to write a button handler in VB.NET that will read rows from a gridview and write them to a DB if a checkbox is checked.
I setup this application to use EntityDataSource and added my .edmx file to a DAL folder. I have the button method written but I do not know enough about EF to know how to handle the data the data from the gridview. Here is my btn_click method:
Private Sub btnGetChecks_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGetChecks.Click
'********************************************
'* gets status of checkbox and writes to db *
'********************************************
Dim row As GridViewRow
Label6.Text = ""
For Each row In DvsGridView.Rows
Dim RowCheckBox As CheckBox = CType(row.FindControl("chkStatus"), CheckBox)
If RowCheckBox.Checked Then
Label6.Text += row.Cells(5).Text & " Checked "
' Need to write checked data to the db
' ******* WHAT GOES HERE? *******
Else
Label6.Text += row.Cells(5).Text & " Unchecked "
End If
Next
End Sub
I am fairly new to EDMX but understand VB.net. Any direction would be greatly appreciated.
Check this sample code and modify this to match your entities and objects
Using db As New DBEntities()
'set values here
Dim x As New TableNameE()
x.col1 = "value1"
x.col2 = "value2"
db.AddToTableNameE(x)
db.SaveChanges()
End Using
Thanks to #rs., I was able to figure out my issues. Referring to the accepted answer, for those wondering what .AddToTableNameE() should be in your proj, it's just going to be .Add(x). It's also somewhat a performance hit using .SaveChanges() for every row, you should create a Dim List(Of TableNameE()) and add the "x" to the list, then use .AddRange() like this:
//creating a data access class is one way to connect to your db by passing in db path
Dim context As New Namespace.YourContext(New DataAccessClass() With {.Path = aBrowsedForSDFFileTextBoxMaybe.Text})
Dim listOfTableObjects As List(Of Namespace.TableObject) = New List(Of Namespace.TableObject)
For n = 1 To SomethingRelatedToRows
Dim tableObject As New Namespace.TableObject() With {
.entityProp1 = TableObject(n).entityProp1,
.entityProp2 = TableObject(n).entityProp2,
.entityProp3 = TableObject(n).entityProp3,
.entityProp4 = TableObject(n).entityProp4,
.entityProp5 = TableObject(n).entityProp5,
.entityProp6 = TableObject(n).entityProp6
}
listOfTableObjects.Add(tableObject)
Next n
//.TableObjects being the DbSet from the ...Context.vb file
context.TableObjects.AddRange(listOfTableObjects)
context.SaveChanges()

How to OpenWebConfiguration with physical path?

I have a win form that creates a site in IIS7.
One function needs to open the web.config file and make a few updates. (connection string, smtp, impersonation)
However I do not have the virtual path, just the physical path.
Is there any way I can still use WebConfigurationManager?
I need to use it's ability to find section and read/write.
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration
You will have to map the physicalPath to a virtualPath. Here is how you would do that.
using System.Web.Configuration; //Reference the System.Web DLL (project needs to be using .Net 4.0 full, not client framework)
public static Configuration OpenConfigFile(string configPath)
{
var configFile = new FileInfo(configPath);
var vdm = new VirtualDirectoryMapping(configFile.DirectoryName, true, configFile.Name);
var wcfm = new WebConfigurationFileMap();
wcfm.VirtualDirectories.Add("/", vdm);
return WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");
}
Vadim's answer worked great on our dev server, but bombed out on our live server with the following message:
System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: site
To correct this, I found another overload for WebConfigurationManager.OpenMappedWebConfiguration that takes the IIS website name as the third parameter. The result is as follows:
public static Configuration OpenConfigFile(string configPath)
{
var configFile = new FileInfo(configPath);
var vdm = new VirtualDirectoryMapping(configFile.DirectoryName, true, configFile.Name);
var wcfm = new WebConfigurationFileMap();
wcfm.VirtualDirectories.Add("/", vdm);
return WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/", "iis_website_name");
}
Vadim's answer was exactly what I needed, but I came across the same issue as Kieth, and his solution did the trick!
I thought I'd add though, that the IIS Website name can be retrieved by calling:
System.Web.Hosting.HostingEnvironment.ApplicationHost.GetSiteName();
Also, cjbarth's code included a tidy solution for those testing in environments where the location of wwwroot and Web.config can vary:
System.Web.HttpContext.Current.Server.MapPath("~");
So with these in mind another slight improvement on Vadim's function would read:
public static Configuration GetWebConfig() {
var webConfigFile = new FileInfo("Web.config");
var wwwRootPath = HttpContext.Current.Server.MapPath("~");
var vdm = new VirtualDirectoryMapping(wwwRootPath, true, webConfigFile.Name);
var wcfm = new WebConfigurationFileMap();
wcfm.VirtualDirectories.Add("/", vdm);
var siteName = HostingEnvironment.ApplicationHost.GetSiteName();
return WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/", siteName);
}
I ended up using Powershell.
$file = "D:\Applications\XXX\Private\XXX\XXXX\web.config"
$configurationAssembly = "System.Configuration, Version=4.0.0.0, Culture=Neutral, PublicKeyToken=b03f5f7f11d50a3a"
[Void] [Reflection.Assembly]::Load($configurationAssembly)
$filepath = New-Object System.Configuration.ExeConfigurationFileMap
$filepath.ExeConfigFileName = $file
$configuration = [System.Configuration.ConfigurationManager]::OpenMappedExeConfiguration($filepath,0)
$section = $configuration.GetSection("appSettings")
Write-Host "Set the Protection Provider"
if (-not $section.SectionInformation.IsProtected)
{
$section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider")
$configuration.Save()
}
Building on Vadim's answer, I found what he wrote didn't exactly work for my situation, so I used this instead:
Dim connectionSettings As New ConnectionStringSettings("mySQLite", ConnectionStringHelper.MyConnectionString)
Dim dummyVirtualPath As String = "/MyApp"
Dim virtualDirMap = New VirtualDirectoryMapping(Server.MapPath("~"), True)
Dim webConfigFileMap = New WebConfigurationFileMap()
webConfigFileMap.VirtualDirectories.Add(dummyVirtualPath, virtualDirMap)
Dim mappedConfigFile = WebConfigurationManager.OpenMappedWebConfiguration(webConfigFileMap, dummyVirtualPath)
Dim config As System.Configuration.Configuration = mappedConfigFile WebConfigurationManager.OpenWebConfiguration(Server.MapPath("~") & "/")
Dim csSection As ConnectionStringsSection = config.ConnectionStrings
If csSection.ConnectionStrings("mySQLite") IsNot Nothing AndAlso csSection.ConnectionStrings("mySQLite").ConnectionString <> connectionSettings.ConnectionString Then
csSection.ConnectionStrings("mySQLite").ConnectionString = connectionSettings.ConnectionString
config.Save()
ConfigurationManager.RefreshSection(csSection.SectionInformation.Name)
End If
In case anyone else is trying what I'm trying and finds this, the purpose of my doing this was to get SimpleMembershipProvider, which inherits from ExtendedMembershipProvider, to work with SQLite. To do that, I created the tables manually per this link: SimpleMembershipProvider in MVC4, and then used this command in my Global.asax file's Application_Start routine:
WebSecurity.InitializeDatabaseConnection(ConnectionStringHelper.MyConnectionString, "System.Data.SQLite", "Users", "UserID", "Email", False)
Which it turns out didn't require me to actually re-write my web.config file at all. (There were also a lot of web.config changes I had to do, but that is even more out of the scope of this question.)