SubSonic Transactions - Inserting to a second table with the return identity from first table - subsonic

I am using the code below to update a second table (Info2) with the identity used from the first table (info2.Id = info.Id;). When the second save is carried out (info2.Save()) I get the error: "There is already an open DataReader associated with this Command which must be closed first.".
Can anyone see what I may be doing wrong.
SubSonic version 3.0.0.3 and SQL Server 2005
Thanks
using (SharedDbConnectionScope sharedConnectionScope = new SharedDbConnectionScope())
{
using (TransactionScope ts = new TransactionScope())
{
Info info = new Info();
info.Desc = "Some information";
info.Save();
Info2 info2 = new Info2();
info2.Id = info.Id;
info2.Desc = "More information";
info2.Save();
ts.Complete();
}
}

Looks like you've got the TransactionScope and the SharedDbConnectionScope the wrong way round, try:
using (TransactionScope ts = new TransactionScope())
{
using (SharedDbConnectionScope sharedConnectionScope = new SharedDbConnectionScope())
{
Info info = new Info();
info.Desc = "Some information";
info.Save();
Info2 info2 = new Info2();
info2.Id = info.Id;
info2.Desc = "More information";
info2.Save();
ts.Complete();
}
}

As per what I have written in the comments, the only way I can get this working is using TransactionScope first then SharedDbConnectionScope (thanks Adam) and to add MultipleActiveResultSets=True; (SQL Server 2005) to the connection string.
Anybody have any better solutions or other suggestions?
Thanks
try
{
using (TransactionScope ts = new TransactionScope())
{
using (SharedDbConnectionScope scs = new SharedDbConnectionScope())
{
Info info = new Info();
info.Desc = "Some information";
info.Save();
//Test for rollback
//throw new Exception("STOP");
Info2 info2 = new Info2();
info2.Id = info.Id;
info2.Desc = "More information";
info2.Save();
ts.Complete();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

Related

is it possible to connect to java jOOQ DB?

I discovered a new interesting service and I'm trying to understand how it works. Please explain how to connect to my jOOQ database from another program?
MockDataProvider provider = new MyProvider();
MockConnection connection = new MockConnection(provider);
DSLContext create = DSL.using(connection, SQLDialect.H2);
Field<Integer> id = field(name("BOOK", "ID"), SQLDataType.INTEGER);
Field<String> book = field(name("BOOK", "NAME"), SQLDataType.VARCHAR);
So, I create but can I connect to it?
Here I have added your code, Lukas.
try (Statement s = connection.createStatement();
ResultSet rs = s.executeQuery("SELECT ...")
) {
while (rs.next())
System.out.println(rs.getString(1));
}
This example was found here
https://www.jooq.org/doc/3.7/manual/tools/jdbc-mocking/
public class MyProvider implements MockDataProvider {
#Override
public MockResult[] execute(MockExecuteContext ctx) throws SQLException {
// You might need a DSLContext to create org.jooq.Result and org.jooq.Record objects
//DSLContext create = DSL.using(SQLDialect.ORACLE);
DSLContext create = DSL.using(SQLDialect.H2);
MockResult[] mock = new MockResult[1];
// The execute context contains SQL string(s), bind values, and other meta-data
String sql = ctx.sql();
// Dynamic field creation
Field<Integer> id = field(name("AUTHOR", "ID"), SQLDataType.INTEGER);
Field<String> lastName = field(name("AUTHOR", "LAST_NAME"), SQLDataType.VARCHAR);
// Exceptions are propagated through the JDBC and jOOQ APIs
if (sql.toUpperCase().startsWith("DROP")) {
throw new SQLException("Statement not supported: " + sql);
}
// You decide, whether any given statement returns results, and how many
else if (sql.toUpperCase().startsWith("SELECT")) {
// Always return one record
Result<Record2<Integer, String>> result = create.newResult(id, lastName);
result.add(create
.newRecord(id, lastName)
.values(1, "Orwell"));
mock[0] = new MockResult(1, result);
}
// You can detect batch statements easily
else if (ctx.batch()) {
// [...]
}
return mock;
}
}
I'm not sure what lines 3-5 of your example are supposed to do, but if you implement your MockDataProvider and put that into a MockConnection, you just use that like any other JDBC connection, e.g.
try (Statement s = connection.createStatement();
ResultSet rs = s.executeQuery("SELECT ...")
) {
while (rs.next())
System.out.println(rs.getString(1));
}

Netsuite Transaction search performance

I am using Netsuite API (version v2016_2) to search data. With below code, it seems that Netsuite taking much time to give response for the query. I am searching GL transaction of periticular period that has 149 MainLine record and 3941 LineItem (Journal Entries) record and Netsuite takes almost 22 minutes to give this data in response. Below is code snippet that I am using to search transaction.
public void GetTransactionData()
{
DataTable dtData = new DataTable();
string errorMsg = "";
LoginToService(ref errorMsg);
TransactionSearch objTransSearch = new TransactionSearch();
TransactionSearchBasic objTransSearchBasic = new TransactionSearchBasic();
SearchEnumMultiSelectField semsf = new SearchEnumMultiSelectField();
semsf.#operator = SearchEnumMultiSelectFieldOperator.anyOf;
semsf.operatorSpecified = true;
semsf.searchValue = new string[] { "Journal" };
objTransSearchBasic.type = semsf;
objTransSearchBasic.postingPeriod = new RecordRef() { internalId = "43" };
objTransSearch.basic = objTransSearchBasic;
//Set Search Preferences
SearchPreferences _searchPreferences = new SearchPreferences();
Preferences _prefs = new Preferences();
_serviceInstance.preferences = _prefs;
_serviceInstance.searchPreferences = _searchPreferences;
_searchPreferences.pageSize = 1000;
_searchPreferences.pageSizeSpecified = true;
_searchPreferences.bodyFieldsOnly = false;
//Set Search Preferences
try
{
SearchResult result = _serviceInstance.search(objTransSearch);
/*
Above line taking almost 22 minutes for below record count
result.recordList.Length = 149
Total JournalEntryLine = 3941
*/
List<JournalEntry> lstJEntry = new List<JournalEntry>();
List<JournalEntryLine> lstLineItems = new List<JournalEntryLine>();
if (result.status.isSuccess)
{
for (int i = 0; i <= result.recordList.Length - 1; i += 1)
{
JournalEntry JEntry = (JournalEntry)result.recordList[i];
lstJEntry.Add((JournalEntry)result.recordList[i]);
if (JEntry.lineList != null)
{
foreach (JournalEntryLine line in JEntry.lineList.line)
{
lstLineItems.Add(line);
}
}
}
}
try
{
_serviceInstance.logout();
}
catch (Exception ex)
{
}
}
catch (Exception ex)
{
throw ex;
}
}
I am unable to know that If I am missing something in my code or this is something about the data. Please suggest me some sort of solution for this.
Thanks.
You should set _searchPreferences.bodyFieldsOnly = true. It will improve the performance with searching because it doesn't return the related or sublist data
I think you are doing this search from the outside of the Netsuite to get journal entries data or lines. Instead of doing a direct search outside, do maintain RESTLET in NETSUITE and call that RESTLET. In the RESTLET DO that search you wanted and return results. Within the NETSUITE, search performance gives fast results.

early bound entity classes dynamics CRM 2011, Error while updating or deleting

i create the CrmProxy class using CrmScUtil now when i am trying to use it i got some problems.
Creating a contact works fine, but updating and deleting just throws this error:
{"An error occured while processing this request."}
at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.SaveChanges(SaveChangesOptions options)
at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.SaveChanges()
Could you please let me know what am i doing wrong?, the query works it returns the contact data that i am trying to update/delete.
OrganizationServiceProxy orgserv;
orgserv = new OrganizationServiceProxy(orgConfigInfo, clientCreds);
orgserv.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
//Create
using (var context = new XrmContext(orgserv))
{
Contact contact = new Contact()
{
FirstName = "fName",
LastName = "lName",
Address1_Line1 = "Address1_Line1",
Address1_City = "Address1_City",
Address1_StateOrProvince = "XX",
Address1_PostalCode = "00000",
Telephone1 = "(000) 000-0000",
JobTitle = "JobTitle",
Company = "Company",
EMailAddress1 = "test#test.com"
};
context.AddObject(contact);
context.SaveChanges();
}
//End Create
//Update
using (var contextUpdate = new XrmContext(orgserv))
{
try
{
Contact con = contextUpdate.ContactSet.FirstOrDefault(c => c.EMailAddress1 == "test#test.com");
if (con != null)
{
con.Fax = "Fax132456";
contextUpdate.UpdateObject(con);
contextUpdate.SaveChanges();
}
}
catch (Exception ex)
{
}
}
//End Update
//Delete
using (var contextDelete = new XrmContext(orgserv))
{
Contact con = contextDelete.ContactSet.FirstOrDefault(c => c.EMailAddress1 == "test#test.com");
if (con != null)
{
contextDelete.DeleteObject(con);
contextDelete.SaveChanges();
}
}
//End Delete
I was able to find the answer for this, i hope this helps:
it looks like there is a bug on the latest CoreAssamblies (7.1.0)
So the key is uninstall the NuGet package and install 7.0.0
Install-Package Microsoft.CrmSdk.CoreAssemblies -Version 7.0.0
After that works with no issues.

How to Insert/Update into Azure Table using Windows Azure SDK 2.0

I have multiple entities to be stored in the same physical Azure table. I'm trying to Insert/Merge the table entries from a file. I'm trying to find a way to do this w/o really serializing each property or for that matter creating a custom entities.
While trying the following code, I thought maybe I could use generic DynamicTableEntity. However, I'm not sure if it helps in an insert operation (most documentation is for replace/merge operations).
The error I get is
HResult=-2146233088
Message=Unexpected response code for operation : 0
Source=Microsoft.WindowsAzure.Storage
Any help is appreciated.
Here's an excerpt of my code
_tableClient = storageAccount.CreateCloudTableClient();
_table = _tableClient.GetTableReference("CloudlyPilot");
_table.CreateIfNotExists();
TableBatchOperation batch = new TableBatchOperation();
....
foreach (var pkGroup in result.Elements("PartitionGroup"))
{
foreach (var entity in pkGroup.Elements())
{
DynamicTableEntity tableEntity = new DynamicTableEntity();
string partitionKey = entity.Elements("PartitionKey").FirstOrDefault().Value;
string rowKey = entity.Elements("RowKey").FirstOrDefault().Value;
Dictionary<string, EntityProperty> props = new Dictionary<string, EntityProperty>();
//if (pkGroup.Attribute("name").Value == "CloudServices Page")
//{
// tableEntity = new CloudServicesGroupEntity (partitionKey, rowKey);
//}
//else
//{
// tableEntity = new CloudServiceDetailsEntity(partitionKey,rowKey);
//}
foreach (var element in entity.Elements())
{
tableEntity.Properties[element.Name.ToString()] = new EntityProperty(element.Value.ToString());
}
tableEntity.ETag = Guid.NewGuid().ToString();
tableEntity.Timestamp = new DateTimeOffset(DateTime.Now.ToUniversalTime());
//tableEntity.WriteEntity(/*WHERE TO GET AN OPERATION CONTEXT FROM?*/)
batch.InsertOrMerge(tableEntity);
}
_table.ExecuteBatch(batch);
batch.Clear();
}
Have you tried using DictionaryTableEntity? This class allows you to dynamically fill the entity as if it were a dictionary (similar to DynamicTableEntity). I tried something like your code and it works:
var batch = new TableBatchOperation();
var entity1 = new DictionaryTableEntity();
entity1.PartitionKey = "abc";
entity1.RowKey = Guid.NewGuid().ToString();
entity1.Add("name", "Steve");
batch.InsertOrMerge(entity1);
var entity2 = new DictionaryTableEntity();
entity2.PartitionKey = "abc";
entity2.RowKey = Guid.NewGuid().ToString();
entity2.Add("name", "Scott");
batch.InsertOrMerge(entity2);
table.ExecuteBatch(batch);
var entities = table.ExecuteQuery<DictionaryTableEntity>(new TableQuery<DictionaryTableEntity>());
One last thing, I see that you're setting the Timestamp and ETag yourself. Remove these two lines and try again.

Subsonic 3 transaction

I have DTC configured as outlined on MS website to support for remote transaction. I have the following code always giving me error.
using (TransactionScope ts = new TransactionScope())
{
Category c = new Category();
c.Name = "Cat1";
c.Save();
Product p = Product.SingleOrDefault(x=>x.ProductID==1);
p.Title = "new title";
p.Save();
ts.Close();
}
However if I move the second block of code out of the suing block it works just fine. What I want to do is bind those two block of code into one trascation. What could be the readon? Thanks,
You don't specify what error the code is giving you but the only thing wrong I can see is that you're not calling Complete on your TransactionScope. Try the following:
using (TransactionScope ts = new TransactionScope())
{
Category c = new Category();
c.Name = "Cat1";
c.Save();
Product p = Product.SingleOrDefault(x=>x.ProductID==1);
p.Title = "new title";
p.Save();
ts.Complete();
}
You shouldn't actually need DTC enabled, you can wrap this code in a transaction using SubSonic's SharedDbConnectionScope. Try the following:
using (TransactionScope ts = new TransactionScope())
using (SharedDbConnectionScope sharedConnectionScope = new SharedDbConnectionScope())
{
Category c = new Category();
c.Name = "Cat1";
c.Save();
Product p = Product.SingleOrDefault(x=>x.ProductID==1);
p.Title = "new title";
p.Save();
ts.Complete();
}

Resources