linq,linq-to-sql,dynamics-crm-2011,dynamics-crm,dynamics-crm-2013 , Pre Operation Concurrent Plugins Getting MAXIMUM Existing Field Value For An Entity Records

Pre Operation Concurrent Plugins Getting MAXIMUM Existing Field Value For An Entity Records


Tag: linq,linq-to-sql,dynamics-crm-2011,dynamics-crm,dynamics-crm-2013

I am trying to set a field (Record Number) on an entity in Pre-Operation plugin that triggers on create with an incremental number based on previous one. For example if the MAX Previous Record Number is 4 I will set the one being created to 5. I am using LINQ to get the MAX exiting number from entity records and then incremented by 1. My concern is that, what if 2 or more plugins execute at the same time and does the same thing. Does CRM has a sequential mechanism to force the plugins to run in sequential order and if NOT how can I avoid 2 plugins getting the same previous maximum record number?


The way CRM supports concurrence is: 1. The plug-in must be in the pre or post operation. 2. You need to update one field on the entity you need. (Whatever value you want). 3. You add your logic here.

The third step will grant you one plug-in execute that logic and the others will wait for it until it ends.

Edit: This is what you need:

Entity context = (Entity)executionContext.InputParameters["Target"];
Entity entity = new Entity { LogicalName = "salesorder", Id = context.Id };
entity["new_dummyfield"] = Guid.NewGuid().ToString();
service.Update(entity); // Lock

entity = service.Retrieve("salesorder", context.Id, new ColumnSet("new_autonumber"));
if (!entity.Contains("new_autonumber"))
int autonumber = (int)entity["new_autonumber"] + 1;
entity["new_autonumber"] = autonumber;


How to declare var datatype in public scope in c#?

I write simple query with linq to sql : var query = (from p in behzad.GAPERTitles select new {, p.gaptitle }).ToArray(); up code into the c# windows application ,windows form load event,and i want use up result into the button click event in this scope: private void button1_Click(object sender,...

Adding where clause to IEnumerable Select

I have the following line of code in my controller that selects the id's of the interests shown within a view (they are listed down the page). IEnumerable<int> interestIds = viewModel.ExistingInterests.Select(x => x.InterestId); However I want to be able to add a where clause to the select section. In ExisitingInterests...

how to parse a rgbColor using c#

I am having trouble parsing a RGB color. I need the int values in there own variable. here is a screenshot of what the object looks like I need to end up with this data [0] R = int value G = int value B = int value Name =...

Compare if the characters in a string are a subset of a second string in C#

I'm working on a game where I want to check if the characters of a string are contained in another string. Obviously a set would be my first choice but I want to account for duplicates. For example: "met".IsContainedWithin("meet"); => true "meet".IsContainedWithin("met"); => false A multi-set would be nice but...

LINQ to Entities Retrieving related Entities or T-SQL

I have these (simplified) models: class Vendor { public int Id { get; set; } public IEnumerable<Product> Products { get; set; } public IEnumerable<Booth> Booths { get; set; } } class Show { public int Id { get; set; } public IEnumerable<Booth> Booths { get; set; } } class Booth...

Difference between cast and as inside a select in LINQ

This code throws exception: var query = services .SomeQuery(bar).select(x => (Foo)x) .Where(x.PropertyOfFoo == FooState.SomeState); var result = query.ToList(); The exception: Unable to cast the type... LINQ to Entities only supports casting EDM primitive or enumeration types. This code works: var query = services .SomeQuery(bar).select(x => x as Foo) .Where(x.PropertyOfFoo ==...

ExecuteQuery returns empty collection when there is only a single result

I'm using a auto created Linq to SQL Classes dbml and I have created the model class by hand. It should select all Schemas from a SQL Server, which is working when there are more than one Schema in the Database, but when there is only a single result I...

LINQ pad is showing SUM at end of result

When i run the below query by LINQ PAD then saw it was showing sum at the end of result. here is the full code and it is working. void Main() { var csvlines = File.ReadAllLines(@"M:\smdr(backup08-06-2015).csv"); var csvLinesData = csvlines.Skip(1).Select(l => l.Split(',').ToArray()); // i am assuming that line[7] is the...

Passing conditional parameters to Database.SqlQuery

I have been doing the following to pass parameters with my sql query: var retval = context.MyObject.SqlQuery(sql.ToString(), new SqlParameter("@ProductId", productId), new SqlParameter("@CustomerId", customerId)).ToList(); I ran into a scenario where @CustomerId will not always be used in my sql string. Meaning I used an if statement to either add (Where p.CustomerId...

LINQ Group By and not contains usage issue

i like to eliminate those user data which start with VM & Voice Mail var csvlines = File.ReadAllLines(@"M:\smdr(backup08-06-2015).csv"); var csvLinesData = csvlines.Skip(1).Select(l => l.Split(',').ToArray()); var groupOfUser = from line in csvLinesData where !line[12].contains('VM') and !line[12].contains('Voice Mail') group line by line[12] into newGroup orderby newGroup.Key select newGroup; this line where !line[12].contains('VM')...

CSV File header part is coming parsing by LINQ

the below way i am parsing csv file by LINQ but i found header part is coming when i inspect user class data. what is wrong there in code. var csvlines = File.ReadAllLines(filename); // IEnumerable<string> var csvLinesData = csvlines.Select(l => l.Split(',').Skip(1).ToArray()); // IEnumerable<string[]> int flag = 0; var users =...

Group by day, time and id in one LINQ

I have a list of Example class elements: public class Example { public long Id { get; set; } public string Name { get; set; } public DateTime SomeDate { get; set; } } Now I want to group it using ONE LINQ to make the following hierarchy: public class...

joining two collections in C# or JavaScript

I have two objects of "pseudotype" Hash(int key, list values) that I need to combine into one based on the key. For example, [{1, {a, b, c}}, {2, {apple, pear}}, {3, {blue, red}}] and [{2, {tomato}}, {3, {pink, red}}, {4, {x, y, z}}] The result that I need is: [{1,...

Can't access any of Linq methods

I'm writing a simple ApiController for getting product stocks, but I'm having a strange issue. I get the data from a method that returns a System.Linq.IQueryable (In a library), but I can't apply any of the Linq methods, like Count or ToList(). The import directive is present and doesn't report...

Asp.Net Identity find users not in role,linq,entity-framework,
I need to find all users that DONT'T contain a certain role, using Asp.Net Identity. So far I have something like this but it is not working. (From role In context.Roles From userRoles In role.Users Join us In context.Users On us.Id Equals userRoles.UserId Where role.Name <> "SomeRole" Select us.UserName) This...

How to select rows from a DataTable where a Column value is within a List?,.net,,linq,datatable
Say you had a table in SQL and you wanted to find all the rows where a particular column could be one of 3 options. You could write something like this: SELECT * FROM MyTable WHERE uid IN (123, 456, 789) That's effectively what I want to do with a...

Finding an item in a list in c#

The code below contains a foreach loop that loops through a list of string collection which contains XML. While enumerating through the collection, it reads the question and answer elements and adds them to the list collection. I need to ensure that no repeated question is added to the list...

Issue displaying LINQ query results in a grid in C#

I received some help here with the following LINQ query, but am still struggling with it. The result I'm trying to obtain is to display some attributes and their values from an xml file in a DataGridView control. I'm calling my method from a button click and am trying to...

How does the Take() method work in LINQ

I have a question regarding LINQ's Take() Method. I have a somewhat large table I'm querying in my web app, and I only want to return say N number of rows from the table. I've read through the MSDN documentation, but I can't see where it states if Take() first...

How to write Nested LINQ for specific scenario

Apologized to post a problem for which i could not construct anything solid. it is very shameful for me to post like this kind of question even after having so high reputation for this web site. Most of the time i write sql in store procedure in sql server and...

sqlite query slow, how to optimize (using linq to entities)

I have used MS SQL server a few times and have yet to run into a speed issue when querying, using linq to entities. This time, I am using sqlite, as to ship the entire database with the application. I have a winforms app that contains 4 search fields. My...

How can I select items where there exists a reference between each item and all items in a list?

I have a list of objects called Keywords, each with an Id. In my database, I have a table of Forms and a table of KeywordReferences. Each KeywordReference has a FormId and a KeywordId. What I need to do is create a query that gets all Forms where there exists...

check if a list contains all the element in an array using linq,linq
I have a list of objects and I have an array of keywords. I need to check if all the elements of the array are present inside the list of objects. The user enters the data to be searched like this pain+fever+thirst+itching My code looks like: //i check if the...

WPF, DataGrid, clicked item/row does not highlight (blue background)

Here is the DataGrid XAML: <DataGrid CanUserAddRows="False" AutoGenerateColumns="False" Height="501" HorizontalAlignment="Left" Margin="6,6,0,0" Name="dataGridTrades" VerticalAlignment="Top" Width="574" SelectionChanged="dataGridTrades_SelectionChanged"> <DataGrid.Columns> <DataGridTextColumn Header="ID" Binding="{Binding TradeID}" IsReadOnly="true"/> <DataGridTextColumn Header="Account" Binding="{Binding AccountName}" IsReadOnly="true"/> <DataGridTextColumn Header="Card Name" Binding="{Binding...

Why does .Where() with a Func parameter executes the query?

Here's how my DataAccessLayer works : public Foo GetFooBy(Func<Foo, bool> filter) { var query = from item in this.DataService.FooSet select item; var where = query.Where(filter); var first = where.First(); return first; } I assumed the query would be run when First() is called but it's actually executed by the Where()....

Grabbing most recent transaction/record

I'm having trouble creating a linq statement that would grab the most recent transaction that happened before the startdate specified. Was wondering if anyone can help me. For example startdate is January 20st. Id LoanId TransactionDate InterestDate Balance 1 5 January 5 January 3 5000 1 5 January 30 January...

Get a single text value using linq

I am using this line to return a value, but instead its getting a True var valor = valoresCampoAdicionalesEmpresa.Select(p => p.Key == propiedad.Nombre).First(); This the view data passes from the controller var valoresCampoAdicionalesEmpresa = (Dictionary)ViewData["ValoresCampoAdicionalesEmpresa"]; public ActionResult Edit(int? id) { var listFields = from b in db.Propiedades where b.Entidad.Nombre ==...

Linq update with specific select of column being null

I wanted to select few columns from SQl and then update that table. I used var xyz_repl= from mfrepl in xyz_repl_alias where (mfrepl.RPT_ID == sched_data.NOTIF_RPT_ID) && (mfrepl.NOTIF_ID == "" || mfrepl.NOTIF_ID == null) select mfrepl; This did my job but then it does not work if any column is NULL.Then...

orderby () containing numbers and letters

I want to order an array containing numbers and letters in an ascending order the values are stored as a string in a DB. This is the list I have 4B 1A 1 1B 2 4C 4 and want them to order like this where numbers are ascending followed by...

Please help me convert this sql to LINQ

DECLARE @items table ( pfid varchar(8), timestart datetime, timeend datetime ) insert INTO @items(pfid,timestart,timeend) VALUES('123456','12:00 AM','3:00 AM') ,('987654', '2:00 AM', '4:00 PM') ,('492384', '3:00 PM', '9:00 PM') SELECT * FROM @items a INNER JOIN @items b ON a.timestart < b.timeend AND b.timestart < a.timeend AND a.pfid != b.pfid I need...

Listing directories by content size using C# [closed]

I'm trying to list all folders of my c drive excluding the document folder which i do not seem to have access to. This first seemed rather simple to me but i found myself still struggling with it despite the seemingly rich .net library. I can't post any code as...

Cannot get data using LINQ in MVC

I'm trying to get data in autocomplete from JsonResult Action Method in my controller. I cannot query data with LINQ, I'm sharing code please guide me. Action Method public class VehicleController : Controller { private readonly IService<Vehicle> _service; public VehicleController(IService<Vehicle> service) { _service = service; } public JsonResult AutoComplete(string term)...

Sort a LINQ with another LINQ in MVC

Using SQL Server Management Using MVC VS 2013 for Web Being in a Controller Here materialnumb it's a LINQ query that always return only one value. Being the following... var materialnumb = (from r in db.MaterialNumber where r.MaterialNumber == 80254842 select r.MaterialNumber); I have another LINQ query from a...

Linq to Sql with dynamic database

I'm now creating an application which creates database in runtime. For example: User 'A' registers to my server will be provided a database A.sdf. After that, I want to create a connection to the newly created database file using Linq to Sql. I'm wondering if I'll create that connection during...

Convert delimited string to array and group using LINQ in C#

I have a string that has a delimited format like this: orgname: firstname lastname, firstname lastname; (this can repeat with orgnames and variable number of names for each org) Example: **XXX University**: Martha Zander, Rick Anderson; **Albert School**: Nancy Vanderburg, Eric Towson, George Branson; **Hallowed Halls**: Jane Goodall, Ann Crabtree,...

Get List of Elements in Tree with specific Field Value,linq,properties,interface
I have an Interface like this: Public Interface TreeSelectorAttributes Property selectedInTreeSelector As Boolean Property Name As String ReadOnly Property childs As IEnumerable(Of TreeSelectorAttributes) End Interface and I have a TreeView which has a List of this TreeSelectorAttributes: Public Property rootList As IEnumerable(Of TreeSelectorAttributes) now after the User chooses which elements...

Updating entity framework model using Linq

I have a problem with updating data in an entity framework model. I have a few tables in the model (Users, UserActivity and Orders). I have added associations between the tables, one between Users and UserActivity and one between Users and Orders. The associations are through the column UserID. These...

how can I add a column to IQueryable object and modify its values

var packs = from r in new XPQuery<Roll>(session) select new { Number = r.number Selection = new bool() }; gcPack.DataSource = packs; I want to add another column to my grid control with: Selection = new bool(). It will be added to the grid but I can't change its...

How do I convert this tSQL statement to LINQ using group by in a sub query

I have the following MSSQL query I am trying to convert to LINQ. I am using entity framework with the following syntax to get at the data. var rv = (from i in DC.TableA select i).ToList(); This is the sql I want to write a C# LINQ query for but...

Sort Array by contains specific char count

I have an array and I want to sort this array by its element' specific character count. var myNewArray = myArray.ToList().Sort(u => u.Name.Split(' ').Length); but this does not work at all. How can I provide the LINQ code for this problem ? myArray[0] = "word1 word2" myArray[1] = "word1" myArray[2]...

Distinct() How to find unique elements in list of objects

There is a very simple class: public class LinkInformation { public LinkInformation(string link, string text, string group) { this.Link = link; this.Text = text; this.Group = group; } public string Link { get; set; } public string Text { get; set; } public string Group { get; set; } public...

Linq where clause with if condition

I have the following model: class Project{ bool IsDeleted {set;get;} ICollection<Document> Documents {set;get;} } class Document{ Project Project {set;get;} int? ProjectId {set;get;} } I am querying Document repository, I want to get all the documents and also the documents whose project is not deleted. var documents = _repository.Include(p=>p.Project) .Where(m =>...

Linq Conditional DefaultIfEmpty query filter

I have a query as below: bool variable = false//or true var query = from e in _repository.GetAll<Entity>() from u in e.Users where (e.AuditQuestionGroupId != null ? e.AuditQuestionGroupId : 0) == this.LoggedInEntity.AuditQuestionGroupId from p in e.PractitionerProfiles.DefaultIfEmpty() select new { entity = e, user = u, profile = p }; This...

How to select all objects that have a property value in list of values?

I have a table named Items. Items have a property named "locationId" Given a list of location Ids, how do I select all items? List example List<long> locationIds = new List<long> { 1, 2, 3 }; Essentially the query below, but for multiple locations at once: var sleectedItems= db.Items.Select(i =>...

Error when building an XDocument

Using the following example xml containing one duplicate: <Persons> <Person> <PersonID>7506</PersonID> <Forename>K</Forename> <Surname>Seddon</Surname> <ChosenName /> <MiddleName /> <LegalSurname /> <Gender>Male</Gender> </Person> <Person> <PersonID>6914</PersonID> <Forename>Clark</Forename> <Surname>Kent</Surname> <ChosenName>Clark</ChosenName> <MiddleName />...

Using LINQ to reference XML local Xelements

All, It's easy enough to do reference the LocalName of an Element when using a foreach. However, if I'm interested in a particular element name, perhaps because each element has an array of children elements and I want a LocalName of a parental element, how do I go about it,...

Distinct all columns in a datatable and store to another datatable with LINQ

I have a datatable with more than 10 columns and I would like to distinct all columns and then store a result to another datatable. Is there any way to distinct all columns in a datatable by using LINQ without naming all ones? I've tried as the code below but...

Update list of items in c#

I would like to know if you can suggest me an efficient way to update a list of items in c#. Here is a generic example: If CurrentList is [ {Id: 154, Name: "George", Salary: 10 000} {Id: 233, Name: "Alice", Salary: 10 000}] And NewList is [ {Id: 154,...

Load XML to list using LINQ [duplicate]

This question already has an answer here: XDocument to List of object 1 answer I have following XML: <?xml version="1.0" encoding="utf-8"?> <start> <Current CurrentID="5"> <GeoLocations> <GeoLocation id="1" x="78492.61" y="-80973.03" z="-4403.297"/> <GeoLocation id="2" x="78323.57" y="-81994.98" z="-4385.707"/> <GeoLocation id="3" x="78250.57" y="-81994.98" z="-4385.707"/> </GeoLocations> <Vendors> <Vendor id = "1" x="123456" y="456789" z="0234324"/>...