Menu
  • HOME
  • TAGS

Asp.Net Identity find users not in role

Tag: asp.net,linq,entity-framework,asp.net-identity

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 give me a list of all users but it includes users in role "SomeRole".
It looks I need some type of not in sub query?

Here is the SQL code that works but I would still like the LINQ query if possible.

select distinct A.UserName from AspNetUsers A
inner join AspNetUserRoles UR on UR.UserId = A.Id
inner join AspNetRoles R on R.Id = UR.RoleId
where not exists(
    select AspNetUserRoles UR1 on UR1.UserId = A.Id
    inner join AspNetRoles R1 on R1.Id = UR1.RoleId 
    where R1.Name = 'SomeRole')

Well I have a working solution but it is not pretty and I'm sure it can be written better.

(From role In context.Roles
From userRole In role.Users
Join user In context.Users On us.Id Equals userRole.UserId
Where Not (
    From role1 In context.Roles
    From userRole1 In role1.Users
    Join user1 In context.Users On user1.Id Equals userRoles1.UserId
    Where role1.Name = "SomeRole"
    Select user1.Id).Contains(user.Id)
Select user.UserName).Distinct()

Best How To :

In c# you can get all users that are not in a certain role like this:

var role = context.Roles.SingleOrDefault(m => m.Name == "role");
var usersNotInRole = context.Users.Where(m => m.Roles.All(r => r.RoleId != role.Id));

onSuccess and onFailure doesn't get fired

javascript,c#,asp.net,webmethod,pagemethods

You PageMethod is looking like this PageMethods.LoginUser(onSuccess, onFailure, email, pass); And when you call it, it looks like this PageMethods.LoginUser(email, pass); Your arguments should be in the same order as the method. PageMethods.LoginUser(email, pass, onSuccess, onFailure); ...

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

c#,linq

Declare it as a known type (not an anonymous type), like this for example: Dictionary<int, string> results = new Dictionary<int, string>(); Then you could store the results in the Dictionary: results = behzad.GAPERTitles.ToDictionary(x => x.id, x => x.gaptitle); And reference it later: private void button1_Click(object sender, EventArgs e) { //...

Update list of items in c#

c#,linq,list,updates

I would do something like this: (for ordinairy lists) // the current list var currentList = new List<Employee>(); currentList.Add(new Employee { Id = 154, Name = "George", Salary = 10000 }); currentList.Add(new Employee { Id = 233, Name = "Alice", Salary = 10000 }); // new list var newList =...

SQL Server / C# : Filter for System.Date - results only entries at 00:00:00

c#,asp.net,sql-server,date,gridview-sorting

What happens if you change all of the filters to use 'LIKE': if (DropDownList1.SelectedValue.ToString().Equals("Start")) { FilterExpression = string.Format("Start LIKE '{0}%'", TextBox1.Text); } Then, you're not matching against an exact date (at midnight), but matching any date-times which start with that date. Update Or perhaps you could try this... if (DropDownList1.SelectedValue.ToString().Equals("Start"))...

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

c#,sql-server,linq,tsql

I think there is opportunity to rewrite your query, but for information purposes I rewrote your sql into linq verbatim. If you explain what you are trying to achieve we can provide alternative sql / linq var eqnums = new[] { "M0435", "Z0843" }; var testdate = "2008-06-01"; var query...

How IE setting affect authorization

asp.net,iis

If you set "Enable Integrated Windows Authentication" (which is the default), and the server requires integrated Windows authentication, then the user will be authenticated silently using current default credentials, if possible. If you disable Integrated Windows Authentication, the user will be prompted to supply credentials. See this KB article for...

Can't access any of Linq methods

linq,asp.net-web-api

The non-generic IQueryable interface doesn't have extension methods of Count and ToList(). Only the generic IQueryable<T> does. If you can modify the library to return a suitable IQueryable<T>, I suggest you do so. If you can't, you may need to call Cast<T>() or OfType<T>() to create an appropriate IQueryable<T> with...

System.net.http.formatting causing issues with Newtonsoft.json

c#,asp.net,asp.net-mvc,json.net

Does the assemblyBinding tag have proper xmlns schema? Check if the issue you are encountering is same as Assembly binding redirect does not work

Make uneven table layout

html,asp.net

You can solve this using the attribute colspan on the td tag: <table border = "1"> <tr> <td colspan="2"> Do you love peanuts? This is a very important question. </td> </tr> <tr> <td> Yes, I do. </td> <td> No, I don't. </td> </tr> </table> Check this link ...

Multiple Posted Types asp.net 5 MVC 6 API

c#,asp.net,asp.net-mvc,asp.net-5,asp.net-mvc-6

The best way is to create a composite wrapper: public class Wrapper { public ModelA A { get; set; } public ModelB B { get; set; } } Put Wrapper in the parameter list and mark that [FromBody]. You can't use that attribute more than once because all of the...

Problems With FOR XML AUTO

sql,asp.net,sql-server,subquery,sqlxml

Change XML PATH('') to XML PATH('tag')

Server side session in asp.net

asp.net,web-services,session

You've got a quotes problem, fix it like this: <% Session["path"] = "'" + vr_ + "'"; %> EDIT 1: Javascript and ASP.NET are not the same, so you cannot access the variables, so you can't do it on the client side. You must send something to the server like...

Access manager information from Active Directory

c#,asp.net,active-directory

try this: var loginName = @"loginNameOfInterestedUser"; var ldap = new DirectoryEntry("LDAP://domain.something.com"); var search = new DirectorySearcher(ldap) { Filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=" + loginName + "))" }; var result = search.FindOne(); if (result == null) return; var fullQuery = result.Path; var user = new DirectoryEntry(fullQuery); DirectoryEntry manager; if (user.Properties.PropertyNames.OfType<string>().Contains("manager")) { var managerPath...

How to make a website work only with https [duplicate]

asp.net,ssl,https

Sure, assuming you are using IIS to host your site, open IIS Manager and select your web site and then binding on the right: make sure you only have a binding for https not for http. This way IIS will only send https traffic to that web site. Edit: What...

Convert Double from String

asp.net,vb.net,visual-studio-2012,converter

The result isn't wrong, it only has lower precision than you expected. Floating point numbers have a limited precision by design, and you simply can't expect to get a result that is more precise than its limit. You can use a Decimal to get higher precision. In this case it...

Unable to find the auto created Database

c#,asp.net,asp.net-mvc,entity-framework

If you don't specify a database name then the connection will use the default database for the user, in this case it's integrated security so it's your Windows login. As you likely have full system admin on the server the default database will be master so you will find all...

How do ASP.NET Web APIs work once built with MSBUILD?

c#,asp.net,msbuild

The WebApi is a web project and on compiling it creates a dll. It is not a class library or a nuget package to consume and use it. I have practically implemented this in a real world application and below are my thoughts for your understanding. Your question is Once...

Show/hide tinymce with radio buttons

c#,asp.net,asp.net-mvc,tinymce

Your missing an @symbol for the id attribute: Modify your script as well like this: ***EDIT some thing seems off about the radio buttons only one should be checked and they should have the same name ** you can use the # to denote and ID in Jquery by the...

Load XML to list using LINQ [duplicate]

c#,xml,linq

Make a base class which will have id,x,y,z, and have Vendors,Bankers and Hospitals extend it. Then you can have a collection of the base class, and add to it the classes that inherit from it....

Linq update with specific select of column being null

c#,linq

The problem you have is that your model is not identical to you database, if you could select the row directly (you said Linq2SQL and not Linq2Entities) then you could update it again, which you do. If you select an anonymous type then you lose the context connection and cannot...

deployment of a site asp.net and iis

c#,asp.net,iis

There are several domain providers like: godaddy, name etc you can use to buy a domain name. These providers also provide you steps to map the domain name to your website. Check out this link for example. This link explains domain name configuration in details.

Retrieve data from one table and insert into another table

sql,asp.net,sql-server

INSERT INTO tbl2 ( Name ,parentId ) SELECT DISTINCT manager ,0 FROM tbl1 WHERE manager NOT IN ( SELECT employee FROM tbl1 ) INSERT INTO tbl2 SELECT DISTINCT employee ,0 FROM tbl1 UPDATE tbl2 SET parentid = parent.id FROM tbl2 INNER JOIN tbl1 ON tbl2.Name = tbl1.employee INNER JOIN tbl2...

asp.net background in 3 pieces to be stationary

html,css,asp.net

I would use a separate div and use fixed positioning on it. Example <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Layout Example</title> <link rel="stylesheet" type="text/css" href="./Layout Example_files/style.css"> <style type="text/css"> .fixed-background{ background: url( "images/SoapBubbles.jpg" ) no-repeat fixed top center; position:fixed; z-index:-1; top:0; right:0; left:0; bottom:0; } </style> </head> <body> <div...

Select @field From table as parameter

asp.net,sql-server,parameter-passing

If doing it from codebehind works then you can do something like sdsOrderErrors.SelectCommand = string.Format("SELECT {0} AS fld FROM [a_table]", colName); (OR) Have a stored procedure to accept a parameter and perform a dynamic query to achieve the same like create procedure usp_testSelect(@colname varchar(30)) as begin declare @sql varchar(200); set...

Adding where clause to IEnumerable Select

c#,asp.net-mvc,linq

Per Discosultan in the comments: IEnumerable<int> interestIds = viewModel.ExistingInterests.Where(x => x.selected == true).Select(x => x.InterestId); ...

Can I uniquely identify 2 check boxes so that I can add a different image to each?

html,css,asp.net,checkbox

Here is an example of what I meant: (Oh and, forgive the images please :) ) #field1,#field2{ display:none; } #field1 + label { padding:40px; padding-left:100px; background:url(http://www.clker.com/cliparts/M/F/B/9/z/O/nxt-checkbox-unchecked-md.png) no-repeat left center; background-size: 80px 80px; } #field1:checked + label { background:url(http://www.clker.com/cliparts/B/2/v/i/n/T/tick-check-box-md.png) no-repeat left center; background-size: 80px 80px; } #field2 + label { padding:40px;...

Sort Array by contains specific char count

c#,linq

Use: var myNewArray = myArray.OrderByDescending(u => u.Name.Split(' ').Length).ToList(); To count the number of words...

Gridview items not populating correctly

asp.net,vb.net

Try this vb code behind, then comment out my test Private Sub BindGrid() Dim dt_SQL_Results As New DataTable '' Commenting out to use test data as I have no access to your database 'Dim da As SqlClient.SqlDataAdapter 'Dim strSQL2 As String 'Dim Response As String = "" 'strSQL2 = "SELECT...

Error when building an XDocument

c#,xml,linq,xpath,linq-to-xml

You can ignore pretty much all your code, the issue is just this: XDocument people = new XDocument("Persons"); You can't create an XDocument containing a string, you need to add an element: XDocument people = new XDocument( new XElement("Persons", original.XPathSelectElements(xpathFilterDups))); ...

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

c#,.net,linq,grid,devexpress

Simple example for using a non-anonymous class. public class MyLovelyClass { public Int32 Number { get; set; } public bool Selection { get; set; } } var packs = from r in new XPQuery<Roll>(session) select new MyLovelyClass() { Number = r.number }; gcPack.DataSource = packs; ...

Creating a viewmodel on an existing project

c#,asp.net,asp.net-mvc

You are using a namespace, your full type name is Project.ViewModel.ViewModel (namespace is Project.ViewModel and class name is ViewModel) so use this using instead: @model Project.ViewModel.ViewModel ...

orderby () containing numbers and letters

c#,wpf,linq,linq-to-sql,sql-order-by

Given your example data where the first number is always a single digit: allScenes.OrderBy(x => x.SceneNumber).ToList() If you can possibly have multi-digit numbers, please provide them and where you want them in the sort order. This is one way to sort multiple digit numbers: var allScenes = new[]{ new {SceneNumber="4B"},...

Third-party security providers like Google, Twitter etc. in ASP.Net

asp.net,authentication

No, you cannot enter any string. You will need to register with each provider to get the parameters that you need. See http://www.asp.net/web-api/overview/security/external-authentication-services for instructions on how to do this....

WCF service architecture query

asp.net,architecture,wcfserviceclient

As long as you are able to use the exact same contract for all the versions the web application does not need to know which version of the WCF service it is accessing. In the configuration of the web application, you specify the URL and the contract. However, besides the...

why does the compiler complain about missing ctor of WebSocketHandler?

asp.net

protected member is accessible by derived class instances and there's nothing special about it. Nothing special in the class itself, either @ WebSocketHandler.cs. It just mens you need to pass in a nullable type, it does not mean it can't get any arguments. int? maxIncomingMessageSize = 0; var socket =...

check if file is image

c#,asp.net,asp.net-mvc

You can't do this: string.Contains(string array) Instead you have to rewrite that line of code to this: if (file == null || formats.Any(f => file.Contains(f))) And this can be shortened down to: if (file == null || formats.Any(file.Contains)) ...

check if a list contains all the element in an array using linq

vb.net,linq

You can use Enumerable.All: dim linqMeddata = From m In medicineDataList Where keys.All(Function(k) m.MedicineData.Contains(k)) Order By m.MedicineName Ascending Select m ...

Get List of Elements in Tree with specific Field Value

vb.net,linq,properties,interface

If i have understood it correctly you want to get all selected parents and all selected children. You could use a recursive method: Public ReadOnly Property checkedList As List(Of TreeSelectorAttributes) Get Return rootList.Where(Function(t) t.SelectedInTreeSelector). SelectMany(Function(root) GetSelectedChildren(root)). ToList() End Get End Property Function GetSelectedChildren(root As TreeSelectorAttributes, Optional includeRoot As Boolean =...

Why is my View not displaying value of ViewBag?

c#,asp.net,asp.net-mvc,asp.net-mvc-4,razor

ViewBag is used when returning a view, not when redirecting to another action. Basically it doesn't persist across separate requests. Try using TempData instead: TempData["Tag"] = post.SelectedTag.ToString(); and in the view: <p><strong>Tag: @TempData["Tag"]</strong></p> ...

.NET wep api won't accept %2E or . in api request uri

c#,jquery,asp.net,ajax,json

Have a look at this answer MVC4 project - cannot have dot in parameter value? Try changing the Web.Config file <system.web> <httpRuntime relaxedUrlToFileSystemMapping="true" /> </system.web> ...

Database object with different data

sql,asp.net,asp.net-mvc,database,entity-framework-6

Ideally what you want is a many-to-many relationship between your Shop and Product entities: public class Shop { public int ShopId {get; set;} public virtual ICollection<ShopProduct> ShopProducts {get; set;} } public class Product { public int ProductId {get; set;} public string Name {get; set;} public virtual ICollection<ShopProduct> ShopProducts {get; set;}...

Trigger a js function with parameter from code behind

c#,jquery,asp.net,scriptmanager,registerstartupscript

All you need to do is add a semi-colon to the end of your String.Format call. ScriptManager.RegisterStartupScript(this, this.GetType(), "ScriptManager1", String.Format(@"ShowHideMessageBlock('{0}');", @"#successMsg"), true); ...

Finding an item in a list in c#

c#,linq

You have your condition wrong, you are looking for questionanswers where the question does not match, you should be looking where they do match and checking that the result is null. (switch the != with ==) It should be if (questionnaire.QuestionAnswers.Find(a => a.Question == fataQuestionsAnswers.Question) == null) However I would...

Catch concurrency exception in EF6 to change message to be more user friendly

c#,asp.net,.net,entity-framework,entity-framework-6

You are executing an asynchronous method. This means that any exceptions will be thrown when you call await on the returned task or when you try to retrieve the results using await myTask; You never do so, which means that the exception is thrown and caught higher up your call...

Please help me convert this sql to LINQ

linq

something in the line of...i didn't test this but you may have to do Datetime.Parse etc if needed... (from r1 in dt.Rows.OfType<DataRow>() from r2 in dt.Rows.OfType<DataRow>() where r1["timestart"] < r2["timeend"] && r2["timestart"] < r1["timeend"] && r1["pfid"] != r2["pfid"] select new {R1=r1, R2=r2}) ...

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

c#,linq,entity-framework,sqlite

The biggest optimization would be changing the Contains to a StartsWith. Which would be equivalent to changing from name like '%search%' to name like 'search%'. Otherwise SQLite can't fully use the indexes you placed on the columns and you are basically searching the whole table. // First Name if (!string.IsNullOrEmpty(firstName))...

add BR between text in dynamically created control

c#,asp.net

You need to use InnerHtml property HtmlGenericControl li = new HtmlGenericControl("li"); li.ID = "liQuestions" + recordcount.ToString(); li.Attributes.Add("role", "Presentation"); ULRouting.Controls.Add(li); HtmlGenericControl anchor = new HtmlGenericControl("a"); li.Attributes.Add("myCustomIDAtribute", recordcount.ToString()); anchor.InnerHtml = "Test <br/> 12345"; li.Controls.Add(anchor); Or, like this: anchor.Controls.Add(new LiteralControl("Test")); //or new Literal("Test"); anchor.Controls.Add(new HtmlGenericControl("br"));...

Updating entity framework model using Linq

c#,sql,linq,entity-framework

You need to update your SQL server with the following columns: UserActivity_UserID, Orders_UserId. Or in the code remove this two columns(Map again your DB to the edmx file)....

Difference between application and module pipelines in Nancy?

c#,asp.net,nancy

The module- and application pipelines are explained in detail in the wiki. It's basically hooks which are executed before and after route execution on a global (application pipelines) and per-module basis. Here's an example: If a route is resolved to a module called FooModule, the pipelines will be invoked as...

How does the Take() method work in LINQ

c#,.net,linq,entity-framework

See Return Or Skip Elements in a Sequence. Take(N) will add TOP N to your SQL and only retrieve N records. For example (using my own SQL Server 2014 with EF 6.1): This LINQ: var query = await dbContext.Lookup .Where(w => w.LookupCd == '1') .Take(10) .ToListAsync(); Generates this SQL: SELECT...