I'm try to using a TransactionScope with isolation level snapshot on Entity framework 4 in asp.net web proyect and sql server 2012 standard edition. I'm getting this error Transactions with IsolationLevel Snapshot cannot be promoted.
using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew,
new TransactionOptions { IsolationLevel = IsolationLevel.Snapshot })) {
using (var db = new Datos.TestDBDataContext(System.Configuration
.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString))
{
Datos.Contacto newUser = new Datos.Contacto
{
name = user.name,
lastName = user.lastName,
type = user.type,
userId = user.userId,
email = user.Email,
password = Password(),
jobCode = user.JobCode,
DateCreated = user.DateCreated,
cityCode = user.cityCode,
numberPass = user.numberPass,
place = user.place,
estate = false
};
db.Contacts.InsertOnSubmit(newUser);
db.SubmitChanges();
}
scope.Complete();
}
What I'm doing wrong ?
Please try as shown below.Set the IsolationLevel.Serializable.
Serializable : Volatile data can be read but not modified, and no new
data can be added during the transaction.
IsolationLevel Enumeration
var scope = new TransactionScope(TransactionScopeOption.RequiresNew,
new TransactionOptions {
IsolationLevel = IsolationLevel.Snapshot,
IsolationLevel = IsolationLevel.Serializable,
})
Related
I have a dynamoDB table with a schema as follows:
var request = new CreateTableRequest
{
TableName = tableName,
KeySchema = new List<KeySchemaElement>
{
new KeySchemaElement("CompanyId", KeyType.HASH),
new KeySchemaElement("Timestamp", KeyType.RANGE)
},
AttributeDefinitions = new List<AttributeDefinition>
{
new AttributeDefinition("CompanyId", ScalarAttributeType.S),
new AttributeDefinition("Timestamp", ScalarAttributeType.N),
new AttributeDefinition("UserId", ScalarAttributeType.S)
},
GlobalSecondaryIndexes = new List<GlobalSecondaryIndex>
{
new GlobalSecondaryIndex
{
IndexName = "UserIndex",
KeySchema = new List<KeySchemaElement>
{
new KeySchemaElement("UserId", KeyType.HASH),
new KeySchemaElement("Timestamp", KeyType.RANGE)
},
Projection = new Projection {ProjectionType = "ALL"},
ProvisionedThroughput = new ProvisionedThroughput(5, 6)
}
},
ProvisionedThroughput = new ProvisionedThroughput(5, 6)
};
I can query the primary key successfully as follows:
var client = new AmazonDynamoDBClient();
using (var context = new DynamoDBContext(client))
{
var sortKeyValues = new List<object>{minTimestamp};
result = await context.QueryAsync<AuditLogEntry>(companyId, QueryOperator.GreaterThanOrEqual, sortKeyValues,
new DynamoDBOperationConfig {OverrideTableName = TableName}).GetRemainingAsync();
}
And I can query the global secondary index without any constraint on the range key as follows:
var client = new AmazonDynamoDBClient();
using (var context = new DynamoDBContext(client))
{
result = await context.QueryAsync<AuditLogEntry>(userId, new DynamoDBOperationConfig {OverrideTableName = TableName, IndexName = indexName})
.GetRemainingAsync();
}
But when I try to query the index with a range key constraint:
var client = new AmazonDynamoDBClient();
using (var context = new DynamoDBContext(client))
{
var sortKeyValues = new List<object> {minTimestamp};
result = await context.QueryAsync<AuditLogEntry>(userId, QueryOperator.GreaterThan, sortKeyValues, new DynamoDBOperationConfig {OverrideTableName = TableName, IndexName = indexName}).GetRemainingAsync();
}
I get the following error:
Exception thrown: 'System.InvalidOperationException' in AWSSDK.DynamoDBv2.dll
Additional information: Local Secondary Index range key conditions are used but no index could be inferred from model. Specified index name = UserIndex
Googling this error hasn't thrown any light on the issue. The reference to Local Secondary Index has me confused because I'm using a Global index, but I just can't see what's wrong with my code.
I've been able to get the query working by querying directly on the AmazonDynamoDBClient rather than using DynamoDBContext, but I'd really like to understand what I'm doing wrong and be able to use DynamoDBContext.
Any ideas would be appreciated.
In your model definition for AuditLogEntry you need to decorate properties that are part of the global secondary index with attributes - [DynamoDBGlobalSecondaryIndexRangeKey] and or [DynamoDBGlobalSecondaryIndexHashKey]. Example below.
public class AuditLogEntry {
// other properties ...
[DynamoDBProperty("UserId")]
[DynamoDBGlobalSecondaryIndexHashKey("UserIndex")]
public string UserId { get; set; }
}
`loadconfig.SourceUris.Add(#"gs:\\planar-fulcrum-837\leadload-ip\01-
02-2013");`
Null object reference set to instance of an object
Here is the working sample for loading CSV file from cloud storage into Google Big Query.
Update variables such as "ServiceAccountEmail, KeyFileName, KeySecret, ProjectID, Dataset name and etc..
Add your table schema into this variable
TableSchema Schema = new TableSchema();
Here i am using single file loading, you can add N number of CSV file into this variable
System.Collections.Generic.IList<string> URIs = newSystem.Collections.Generic.List<string>();
URIs.Add(filePath);
Use this below code modify & work with it. Have a great day. (This solution i have found working more than 3 days).
using Google.Apis.Auth.OAuth2;
using System.IO;
using System.Threading;
using Google.Apis.Bigquery.v2;
using Google.Apis.Bigquery.v2.Data;
using System.Data;
using Google.Apis.Services;
using System;
using System.Security.Cryptography.X509Certificates;
namespace GoogleBigQuery
{
public class Class1
{
private static void Main()
{
try
{
String serviceAccountEmail = "SERVICE ACCOUNT EMAIL";
var certificate = new X509Certificate2(#"KEY FILE NAME & PATH", "KEY SECRET", X509KeyStorageFlags.Exportable);
// SYNTAX: var certificate=new X509Certificate2(KEY FILE PATH+NAME (Here it resides in Bin\Debug folder so only name is enough), SECRET KEY, X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { BigqueryService.Scope.Bigquery, BigqueryService.Scope.BigqueryInsertdata, BigqueryService.Scope.CloudPlatform, BigqueryService.Scope.DevstorageFullControl }
}.FromCertificate(certificate));
// Create and initialize the Bigquery service. Use the Project Name value
// from the New Project window for the ApplicationName variable.
BigqueryService Service = new BigqueryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "APPLICATION NAME"
});
TableSchema Schema = new TableSchema();
TableFieldSchema F1 = new TableFieldSchema();
F1.Name = "COLUMN NAME";
F1.Type = "STRING";
F1.Mode = "REQUIRED";
TableFieldSchema F2 = new TableFieldSchema();
F1.Name = "COLUMN NAME";
F1.Type = "INTEGER";
F1.Mode = "NULLABLE";
//Add N number of fields as per your needs
System.Collections.Generic.IList<TableFieldSchema> FS = new System.Collections.Generic.List<TableFieldSchema>();
FS.Add(F1);
FS.Add(F2);
Schema.Fields = FS;
JobReference JR = JobUpload("PROJECT ID", "DATASET NAME", "TABLE NAME", #"gs://BUCKET NAME/FILENAME", Schema, "CREATE_IF_NEEDED", "WRITE_APPEND", '|', Service);
//SYNTAX JobReference JR = JobUpload(PROJECT ID, DATASET NAME, TABLE NAME, FULL PATH OF CSV FILE,FILENAME IN CLOUD STORAGE, TABLE SCHEMA, CREATE DISPOSITION, DELIMITER, BIGQUERY SERVICE);
while (true)
{
var PollJob = Service.Jobs.Get(JR.ProjectId, JR.JobId).Execute();
Console.WriteLine("Job status" + JR.JobId + ": " + PollJob.Status.State);
if (PollJob.Status.State.Equals("DONE"))
{
Console.WriteLine("JOB Completed");
Console.ReadLine();
return;
}
}
}
catch (Exception e)
{
Console.WriteLine("Error Occurred: " + e.Message);
}
Console.ReadLine();
}
public static JobReference JobUpload(string project, string dataset, string tableId, string filePath, TableSchema schema, string createDisposition, string writeDisposition, char delimiter, BigqueryService BigQueryService)
{
TableReference DestTable = new TableReference();
DestTable.ProjectId = project;
DestTable.DatasetId = dataset;
DestTable.TableId = tableId;
Job Job = new Job();
JobConfiguration Config = new JobConfiguration();
JobConfigurationLoad ConfigLoad = new JobConfigurationLoad();
ConfigLoad.Schema = schema;
ConfigLoad.DestinationTable = DestTable;
ConfigLoad.Encoding = "ISO-8859-1";
ConfigLoad.CreateDisposition = createDisposition;
ConfigLoad.WriteDisposition = writeDisposition;
ConfigLoad.FieldDelimiter = delimiter.ToString();
ConfigLoad.AllowJaggedRows = true;
ConfigLoad.SourceFormat = "CSV";
ConfigLoad.SkipLeadingRows = 1;
ConfigLoad.MaxBadRecords = 100000;
System.Collections.Generic.IList<string> URIs = new System.Collections.Generic.List<string>();
URIs.Add(filePath);
//You can add N number of CSV Files here
ConfigLoad.SourceUris = URIs;
Config.Load = ConfigLoad;
Job.Configuration = Config;
//set job reference (mainly job id)
JobReference JobRef = new JobReference();
Random r = new Random();
var JobNo = r.Next();
JobRef.JobId = "Job" + JobNo.ToString();
JobRef.ProjectId = project;
Job.JobReference = JobRef;
JobsResource.InsertRequest InsertMediaUpload = new JobsResource.InsertRequest(BigQueryService, Job, Job.JobReference.ProjectId);
var JobInfo = InsertMediaUpload.Execute();
return JobRef;
}
}
}
I'm trying to retrieve all phone calls related to opportunity, which statecode isn't equal 1. Tried QueryByAttribute, QueryExpression and RetrieveMultipleRequest, but still has no solution.
Here some code i wrote.
IContextService contextService = (IContextService)executionContext.GetService(typeof(IContextService));
IWorkflowContext context = contextService.Context;
ICrmService crmService = context.CreateCrmService(true);
if (crmService != null)
{
QueryByAttribute query = new Microsoft.Crm.Sdk.Query.QueryByAttribute();
query.ColumnSet = new Microsoft.Crm.Sdk.Query.AllColumns();
query.EntityName = EntityName.phonecall.ToString();
query.Attributes = new string[] { "regardingobjectid" };
query.Values = new string[] { context.PrimaryEntityId.ToString() };
RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();
retrieve.Query = query;
retrieve.ReturnDynamicEntities = true;
RetrieveMultipleResponse retrieved = (RetrieveMultipleResponse)crmService.Execute(retrieve);
}
return ActivityExecutionStatus.Closed;
}
And almost same for QueryExpression
QueryExpression phCallsQuery = new QueryExpression();
ColumnSet cols = new ColumnSet(new string[] { "activityid", "regardingobjectid" });
phCallsQuery.EntityName = EntityName.phonecall.ToString();
phCallsQuery.ColumnSet = cols;
phCallsQuery.Criteria = new FilterExpression();
phCallsQuery.Criteria.FilterOperator = LogicalOperator.And;
phCallsQuery.Criteria.AddCondition("statuscode", ConditionOperator.NotEqual, "1");
phCallsQuery.Criteria.AddCondition("regardingobjectid", ConditionOperator.Equal, context.PrimaryEntityId.ToString();
I always get something like Soap exception or "Server was unable to proceed the request" when debugging.
To get exception details try to use following code:
RetrieveMultipleResponse retrieved = null;
try
{
retrieved = (RetrieveMultipleResponse)crmService.Execute(retrieve);
}
catch(SoapException se)
{
throw new Exception(se.Detail.InnerXml);
}
Am new to DNN Module development and using MVC and Linq. Have built a class and controller that allows me to create a record in a table on the database. Can anyone tell me the best way to retrieve the id of the newly created record? The part of the controller for creating the record is below.
class BlockController
{
public void CreateBlock(Block b)
{
using (IDataContext ctx = DataContext.Instance())
{
var rep = ctx.GetRepository<Block>();
rep.Insert(b);
}
}
}
Call to the controller from the code
var bC = new BlockController();
var b = new Block()
{
SectionId = int.Parse(ddlPickSection.SelectedValue),
PlanId = int.Parse(ddlPickPlan.SelectedValue),
BlockName = bId,
BlockDesc = "",
xPos = bX,
yPos = bY,
width = arrBWidths[i],
ModuleId = ModuleId,
CreatedOnDate = DateTime.Now,
CreatedByUserId = UserId,
LastModifiedOnDate = DateTime.Now,
LastModifiedByUserId = UserId,
};
bC.CreateBlock(b);
Thanks
When you submit changes (insert the record in DB) the ID would available in b object:
...
rep.InsertOnSubmit(b);
ctx.SubmitChanges();
int desireID = b.id;
Hi guys,
I'm learning to climb with EF ,I do have basic understanding of CRUD with EF ,but now I have a table which have a navigation property (Which I suspect is the bridge table) ,so I need to add value into the bridge table ,I think I can do it with navigational property.
Problem Explained:
Original partial DB Diagram
Partial EF Model Diagram
Code I Wrote:
protected void BtnAddUser_Click(object sender, EventArgs e)
{
DBEntities entities = new DBEntities();
var usr = new User();
//I thought I would add an Roles object into usr.UserRoles.Add(usrRoles);
//but UserRoles have only two fields ,RoleTypeId and UserId
//var usrRoles = new Roles()
//{Id=0,RoleDescription="dfdfdf",RoleType="WebSite Admin"};
usr.UserName = TxtbxUserName.Text;
usr.Password = TxtBxPassword.Text;
usr.Email = TxtbxEmail.Text;
usr.CreateDate = DateTime.Now;
usr.LastActivityDate = DateTime.Now;
usr.IsEnabled = true;
//What to Add in the .Add method
usr.UserRoles.Add(
entities.User.AddObject(usr);
int result = entities.SaveChanges();
LblMsg.Text = result == 1 ? "User created successfully." : "An error occured ,please try later.";
entities.Dispose();
}
Update (What I have tried so far):
I fetch "Website Admin" role from roles table and put it into ObjectContext.UserRoles.Add(UserRoleWebsiteAdmin);
So that what I did in the code,
//Fetch WebsiteAdmin from Roles
var userRole = from usrRole in entities.Roles
where usrRole.Id == 1
select usrRole;
usr.UserName = TxtbxUserName.Text;
//same old code of usr.Property = someTextBox
//I have tried to type cast it LinqtoEntities result into Roles
usr.UserRoles.Add((Roles)userRole);
Exception generated
P.S: Let me know if you need more clarification.
Maybe you can use using http://msdn.microsoft.com/en-us/library/yh598w02.aspx and object initializer http://msdn.microsoft.com/en-us/library/bb384062.aspx for better readability so:
using(DBEntities entities = new DBEntities())
{
//Make user object
var user = new User{
UserName = TxtbxUserName.Text,
Password = TxtBxPassword.Text,
Email = TxtbxEmail.Text,
CreateDate = DateTime.Now,
LastActivityDate = DateTime.Now,
IsEnabled = true
};
//Fetch type of Role from Roles table
var userRole = entities.Roles.Where(x=>x.usrRole.Id ==1).Single();
user.UserRoles.Add(userRole);
entities.User.AddObject(user);
int result = entities.SaveChanges();
LblMsg.Text = result == 2 ? "User created succesfully." : "An error occured ,please try later.";
}
Regards
Well thanks guys...
Here what I have done and it works,
DBEntities entities = new DBEntities();
//Make user object
var usr = new User();
//Fetch type of Role from Roles table
var userRole = (from usrRole in entities.Roles
where usrRole.Id == 1
select usrRole).Single();
//copy user related info from textboxes
usr.UserName = TxtbxUserName.Text;
usr.Password = TxtBxPassword.Text;
usr.Email = TxtbxEmail.Text;
usr.CreateDate = DateTime.Now;
usr.LastActivityDate = DateTime.Now;
usr.IsEnabled = true;
usr.UserRoles.Add(userRole as Roles);
entities.User.AddObject(usr);
int result = entities.SaveChanges();
LblMsg.Text = result == 2 ? "User created succesfully." : "An error occured ,please try later.";
entities.Dispose();