EF6 code-first: access to database before update database - entity-framework

I'm trying to create a project with EF6.1 with code-first. All works fine I have migration is enabled, create and update DB works too. Now my Problem:
I have create a table "VersionHistory" and a CompanyInfo table.
I'm writing an "Upgrade Wizzard" for update the database. Is it possible to get data from this tables to Display Information (e.g. YourCompanyName and Update from Program Version 1.x to 1.y) before I start the database update?
Should I use classic SQLConnection for this?
Many thanks

You can use a SQL Connection (it can be the same of EF) or you can disable EF database structure checking.
System.Data.Entity.Database.SetInitializer<MyModel>(null);
EDIT
If you access to an entity that is not updated on the database, you can receive Ado exceptions from EF (i.e. missing columns, missing tables and so on).

In compliance with "bubi" I will use a SQLConnection based on my Context e.g.
using (var ctx = new AppContext()) {
ctx.Database.Connection.Open();
var cmd = ctx.Database.Connection.CreateCommand();
cmd.CommandText = "Select * From CompanyInfo";
var rdr = cmd.ExecuteReader();
var infos = (from row in rdr.Cast<System.Data.Common.DbDataRecord>()
let entityId = (int)row["EntityId"] //internal key
let entityKey = (string)row["EntityKey"] //visible key
let displayname = (string)row["DisplayName"] //company name
// some more stuff (version, etc.)
select new NOCompanyInfo {
EntityId = entityId,
EntityKey = entityKey,
DisplayName = displayname,
DBName = dbName,
...
}).ToList();
return new ObservableCollection<NOCompanyInfo>(infos);
}
Thanks

Related

How to set the Provider for CrystalDecisions.Enterprise.Desktop.Report?

For our reporting environment, we allow users to run reports "online" (the code for this is based on CrystalDecisions.ReportAppServer.ClientDoc.ReportClientDocument) or "offline" which is to schedule them on the Business Objects server directly. This code is based on CrystalDecisions.Enterprise.Desktop.Report.
For the online report, we're able to programmatically set the provider with this code:
If crTableNew.ConnectionInfo.Kind = CrConnectionInfoKindEnum.crConnectionInfoKindCRQE Then
crLogonInfo = CType(crAttributes("QE_LogonProperties"), PropertyBag)
crLogonInfo("Data Source") = serverName
crLogonInfo("Initial Catalog") = databaseName
crLogonInfo("Provider") = "SQLNCLI11"
End If
However, the equivalent code for offline doesn't seem to expose the "Provider" property. The equivalent object is roughly this:
CrystalDecisions.Enterprise.Desktop.Report.ReportLogons.Item(tableIndex) but none of the properties there seem to be the Provider.
Anyone able to help?
The closest corresponding ReportLogon property to the LoginInfo Provider property is the ServerType property. However, I don't think you need this in order to set the database credentials.
You can probably do something like this
foreach(ReportLogon reportLogon in reportLogons)
{
reportLogon.UseOriginalDataSource = false;
reportLogon.CustomServerName = serverName;
reportLogon.CustomUserName = userId;
reportLogon.CustomPassword = password;
reportLogon.CustomDatabaseName = databaseName;
foreach(TablePrefix tablePrefix in reportLogon.TableLocationPrefixes)
{
tablePrefix.MappedTablePrefix = databaseName + ".dbo.";
tablePrefix.UseMappedTablePrefix = true;
}
}
Looping through the TableLocationPrefixes ensures that all referenced tables or sprocs are associated to the database specified in the logon credentials.

Chef: Ohai attribute persistence

Chef Server 12.2.0-1.
I'm trying to find a way to query Ohai node attributes from the PostgreSQL database. Having browsed through the table schemas and data, I'm not seeing any tables that would contain those attributes.
Are these attributes stored on Chef server? Is there a way to view them remotely via a database query or a REST call?
List of opscode_chef tables:
checksums
clients
containers
cookbook_artifact_version_checksums
cookbook_artifact_versions
cookbook_artifacts
cookbook_version_checksums
cookbook_versions
cookbooks
data_bag_items
data_bags
environments
groups
keys
node_policy
nodes
opc_customers
opc_users
org_migration_state
org_user_associations
org_user_invites
orgs
policies
policy_groups
policy_revisions
policy_revisions_policy_groups_association
roles
sandboxed_checksums
users
UPDATE 1: Thanks to #Tensibai.
Attributes are stored in table nodes, column serialized_object. The column serialized_object is gzip encoded.
Java code to fetch attributes in json:
String query = "SELECT name, serialized_object FROM nodes";
PreparedStatement st = conn.prepareStatement(query);
ResultSet rs = st.executeQuery();
while (rs.next()) {
String name = rs.getString("name");
byte[] arr = rs.getBytes("serialized_object");
byte[] out = unzip(arr);
System.out.println(name + " : " + new String(out));
}
public static byte[] unzip(byte[] in) throws IOException{
ByteArrayOutputStream out = new ByteArrayOutputStream();
FileUtils.copy(new GZIPInputStream(new ByteArrayInputStream(in)), out);
return out.toByteArray();
}
Sample attributes: https://gist.github.com/rodionos/cb744155539699b5c348
I'm not an expert in PostgreSQL. A better solution would probably be to enable a native decompression function as described here: https://github.com/chef/chef-server/issues/8#issuecomment-99152808

iDB2Commands in Visual Studio 2010

These are the basic things I know about iDB2Commands to be used in Visual Studio 2010. Could you please help me how could I extract data from DB2? I know INSERT, DELETE and Record Count. But SELECT or Extract Data and UPDATE I don't know.
Imports IBM.Data.DB2
Imports IBM.Data.DB2.iSeries
Public conn As New iDB2Connection
Public str As String = "Datasource=10.0.1.11;UserID=edith;password=edith;DefaultCollection=impexplib"
Dim cmdUpdate As New iDB2Command
Dim sqlUpdate As String
conn = New iDB2Connection(str)
conn.Open()
'*****Delete Records and working fine
sqlUpdate = "DELETE FROM expusers WHERE username<>#username"
cmdUpdate.Parameters.Add("username", iDB2DbType.iDB2Date)
cmdUpdate.Parameters("username").Value = ""
'*****Insert Records and working fine
sqlUpdate = "INSERT INTO expusers (username, password, fullname) VALUES (#username, #password, #fullname)"
cmdUpdate.Parameters.Add("username", iDB2DbType.iDB2VarChar)
cmdUpdate.Parameters.Add("password", iDB2DbType.iDB2VarChar)
cmdUpdate.Parameters.Add("fullname", iDB2DbType.iDB2VarChar)
cmdUpdate.Parameters("username").Value = txtUsername.Text
cmdUpdate.Parameters("password").Value = txtPassword.Text
cmdUpdate.Parameters("fullname").Value = "Editha D. Gacusana"
'*****Count Total Records and working fine
Dim sqlCount As String
Dim cmd As New iDB2Command
sqlCount = "SELECT COUNT(*) AS count FROM import"
cmd = New iDB2Command(Sql, conn)
Dim count As Integer
count = Convert.ToInt32(cmd.ExecuteScalar)
'*****Update Records and IT IS NOT WORKING AT ALL
sqlUpdate = "UPDATE expusers SET password = #password WHERE RECNO = #recno"
cmdUpdate.Parameters.Add("recno", iDB2DbType.iDB2Integer)
cmdUpdate.Parameters.Add("password", iDB2DbType.iDB2VarChar)
cmdUpdate.Parameters("recno").Value = 61
cmdUpdate.Parameters("password").Value = txtPassword.Text
cmdUpdate.Connection = conn
cmdUpdate.CommandText = sqlUpdate
cmdUpdate.ExecuteNonQuery()
conn.Close()
Please help me how to code the SELECT query wherein I could extract/fetch data from DB2 Database. Also, how could i update the records in the database.
Thanks!
Instead of ExecuteNonQuery(), look at ExecuteReader(). I don't have VS2010 installed, but try something like this:
iDB2Command cmdSelect = new iDB2Command("SELECT username, password, fullname FROM expusers", conn);
cmdSelect.CommandTimeout = 0;
iDB2DataAdapter da = new iDB2DataAdapter(cmdSelect);
DataSet ds = new DataSet();
da.Fill(ds, "item_master");
GridView1.DataSource = ds.Tables["expusers"];
GridView1.DataBind();
Session["TaskTable"] = ds.Tables["expusers"];
da.Dispose();
cmdSelect.Dispose();
cn.Close();
See: http://gugiaji.wordpress.com/2011/12/29/connect-asp-net-to-db2-udb-for-iseries/
If you aren't trying to bind to a grid, look at iDB2Command.ExecuteReader() and iDB2DataReader()
The DELETE is working fine? The code has the parameter type for "username" set to iDB2Date. The INSERT has "username" set to iDB2VarChar. How is the column defined in the table? Char, Varchar or Date?
On the UPDATE, you reference RECNO, but that does not seem to be a column in the table. Updating a relational database table by row number is a bad idea - the row numbers are not guaranteed to stay constant. If you are just testing, as I think you are, don't use RECNO, use RRN(). The DB2 for i syntax is WHERE rrn(expusers) = #recno
To help your testing, do a SELECT without a WHERE clause and list out all the rows. Make sure the name stored in the username column matches the name you are trying to update. Pay particular attention to the case of the data. If the name in expusers looks like "EDITHA D. GACUSANA", and #username is "Editha D. Gacusana" then it will not match on the WHERE clause.

Strange behaviour of Grails' application connected to PostgreSQL

I'm trying to switch my grails application from h2 to PostgreSQL.
Steps I've done to reach my goal:
Download JDBC from http://jdbc.postgresql.org/download.html (JDBC4 Postgresql Driver, Version 9.3-1100)
Attach JDBC to /lib folder
Change DataSource. Now it looks like:
dataSource {
pooled = true
driverClassName = "org.postgresql.Driver"
dialect="org.hibernate.dialect.PostgreSQLDialect"
username = "postgres"
password = "admin"
}
hibernate {
cache.use_second_level_cache = true
cache.use_query_cache = false
cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory'
}
// environment specific settings
environments {
development {
dataSource {
dbCreate = "update" // one of 'create', 'create-drop', 'update', 'validate', ''
//url = "jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000"
url = "jdbc:postgresql://localhost:5432/admin_panel"
}
}
test {
dataSource {
dbCreate = "update"
url = "jdbc:postgresql://localhost:5432/admin_panel"
}
}
production {
dataSource {
dbCreate = "update"
url = "jdbc:postgresql://localhost:5432/admin_panel"
pooled = true
properties {
maxActive = -1
minEvictableIdleTimeMillis=1800000
timeBetweenEvictionRunsMillis=1800000
numTestsPerEvictionRun=3
testOnBorrow=true
testWhileIdle=true
testOnReturn=true
validationQuery="SELECT 1"
}
}
}
}
And now the game starts. I type 'run-app' in GGTS and I get an error. Objects I'm trying to create using BootStrap cannot be initialized because of Validation: Error initializing the application: Validation Error(s) occurred during save() .
It is really strange because the message says that reference to previously created object is null: Field error in object 'adminpanel.component.Text' on field 'subpage': rejected value [null];.
There should be no possibility that "subpage" is null in this line, so I go to the pgAdmin III to check if this record is created and there I notice that no table is created at all.
Everetyhing works if application is connected to H2, but starts to freak out when I switch it to postgres. Additionally, when I remove everything from BootStrap, application starts and I can create objects normally, but I still cannot see them into pgAdmin. Do you have any advice what else can I check or why GORM does not create tables in my app when I use PostgreSQL ?
Thanks in advance.
EDIT:
I found the source of the problem after few tests more...
PostgreSQL gives a strange value for 'id' column in every table. When I was using H2, I had values from 1..x in every table, in PostgreSQL I have something like this:
table1
id:
1
2
3
-
7
8
9
table2
id:
4
5
6
-
10
11
As you probably noticed, values are given interchangeably for all rows in different tables, so I cannot have e.g. object table1 with id 1 and object table2 with id 1. Do you have idea why?
Grails/Hibernate uses Sequence for object ID for databases like Postgres (or Oracle, etc). By default, Grails uses a shared sequence (hibernate_sequence). So all object will have uniq id, but unique per whole database, not per table.
You can configure domain to use a different Sequence for a domain, like:
static mapping = {
id generator: 'sequence', params: [sequence: 'my_own_sequence']
}
See also
http://www.postgresql.org/docs/9.1/static/sql-createsequence.html
http://grails.org/doc/2.3.4/ref/Database%20Mapping/id.html

Entity Framework Stored Procedure with Multiple Record Set not accepting my parameter

I'm using Microsofts suggested solution for using Entity Framework to read multiple record sets from a stored procedure but added a small snippet to use parameters and it's not working. I've had a co-worker look at the code and tell me it looks like it should work so I thought I'd ask here.
Using the 4.5 framework is not an option. I'm stuck with 4.0 and etity framework 4.4.
App MyApp = (App)Application.Current;
EnterpriseEntities EE = new EnterpriseEntities();
EE.Database.Connection.ConnectionString = MyApp.EnterpriseEntityConnectionString;
var cmd = EE.Database.Connection.CreateCommand();
cmd.CommandText = "[dbo].[spSelectWaterUsesByRightID]";
var param = cmd.CreateParameter();
param.Direction = ParameterDirection.Input;
param.DbType = DbType.Int32;
param.ParameterName = "#RightID";
param.Value = this.RightID;
cmd.Parameters.Add(param);
EE.Database.Connection.Open();
var reader = cmd.ExecuteReader();
List<WaterUses> ListOfWaterUses = (((System.Data.Entity.Infrastructure.IObjectContextAdapter)EE)
.ObjectContext
.Translate<WaterUses>(reader, "WaterUses",System.Data.Objects.MergeOption.AppendOnly)).ToList();
When I get to the ExecuteReader line I get an error message that the stored procedure requires Parameter #RightID but that's what I'm passing. I checked the parameter count right before it executes and it's at 1.
You have to add
cmd.CommandType = CommandType.StoredProcedure;
somewhere before cmd.ExecuteReader().