Sunday 2 July 2017

ASP.NET MVC 5 Security And Creating User Role

https://code.msdn.microsoft.com/ASPNET-MVC-5-Security-And-44cbdb97

ASP.NET MVC - How to hide or Show a link/button based on logged in User's Role permission?

For example, you can do it in a way like this:
@if (ViewContext.HttpContext.User.IsInRole("Your role"))
{
    // Do something here
}

If statement and Html.ActionLink in Razor MVC 3

I think you forgot an @ which is used to output:
@if (item.hasTypes.Value) { 
    @Html.ActionLink(item.marketGroupName, "Index", new { id = item.marketGroupID });
}

The Role Manager feature has not been enabled

You can do this by reading from the boolean property at:
System.Web.Security.Roles.Enabled
This is a direct read from the enabled attribute of the roleManager element in the web.config:
<configuration>
  <system.web>
    <roleManager enabled="true" />
  </system.web>
</configuration>

Update:
For more information, check out this MSDN sample: https://msdn.microsoft.com/en-us/library/aa354509(v=vs.110).aspx

How to pass HttpContext.Current to function?

ou can either pass the context into the function or use HttpContext.Current to retrieve the current context.

Pass it in

public static List<SellsLive> SearchFunc(SellsLiveSearch Per, HttpContext context)
{
    context.Response.SetCookie(cookie);
}
And call it like this:
SearchFunc(Per, this.HttpContext);

Get Current context

public static List<SellsLive> SearchFunc(SellsLiveSearch Per)
{
    HttpContext context = HttpContext.Current;
    context.Response.SetCookie(cookie);
    //etc
}
Of course, this way will only work if the function is running on the correct thread.

Problems with SQL Server Express user instancing and ASP.net Web Application Projects

Symptoms

Web applications running on IIS 7.5 and that rely on SQL Server Express user instancing will fail to run using the default IIS 7.5 security configuration on both Windows 7 Client and Windows Server 2008 R2. Developers will encounter problems developing web applications using Visual Studio 2005 + SQL Server Express 2005, Visual Studio 2008 + SQL Server Express 2008, or Visual Studio 2010 + SQL Server Express 2008 on both Windows 7 Client and Windows Server 2008 R2.
Developers will encounter similar problems attempting to develop web application projects (WAP) or websites hosted under IIS6/IIS7/IIS7.5 that rely on SQL Server Express user instances where the WAP project structure or website folder structure exists in a user's Documents folder.  This issue exists for all versions of Visual Studio regardless of the underlying operating system version.  A web application that attempts to create a database or read/write to a database using SQL Server Express user instance mode can encounter any of the following errors:
An attempt to attach an auto-named database for file c:\Users\[YourUserAccountName]\Documents\Visual Studio 20XX\Projects\[YourSolutionName]\[YourProjectnName]\App_Data\aspnetdb.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

--or--

Failed to generate a user instance of SQL Server due to failure in retrieving the user's local application data path.  Please make sure the user has a local user profile on the computer. The connection will be closed.

 
NOTE: A web application relies on SQL Server Express' user instance mode if either of the following is true:
  •  The application relies on the default "LocalSQLServer" connection string defined in machine.config
  •  The application uses a connection string that contains the following attributes:

                "AttachDBFilename=|DataDirectory|xxxxxx.mdf;User Instance=true"


Cause

For Windows Server 2008 R2 and Windows 7
The default security configuration for IIS 7.5 sets application pools to run as the "application pool identity".  Running an application pool using this special identity was first introduced as an optional setting in Vista SP2 and Windows Server 2008 SP2.  On Windows 7 Client and Windows Server 2008 R2 this special identity is now the default.
  
Web applications built with Visual Studio 2005, Visual Studio 2008, or Visual Studio 2010 and that rely on user instancing with either SQL Server Express 2005 or SQL Server Express 2008 do not work with the new application pool identity.  These products were developed and tested against application pools running with the older NETWORK SERVICE account.

For Web Application Projects and Websites Located in a User's Documents Folder Hosted in IIS
Web application projects (WAP) exist in a folder structure under a user's "Documents\Visual Studio 20XX\Projects" folder.  Website projects exist in a folder structure under a user's "Documents\Visual Studio 20XX\Websites" folder.  SQL Server Express user instances require file access rights to the parent folders of the website or WAP project's directory structure.  Because the IIS service account (NETWORK SERVICE) by default does not have these rights within the Visual Studio project folder structure, WAP projects and websites located in a user's Documents folder and that are hosted in IIS will not be able to open SQL Server Express user instanced databases for read access. 
 
WAPs that were originally created within a user's Documents folder, but were subsequently changed to use IIS for a web server via the web tab of the project's properties will encounter this file permissions problem.  Websites hosted in IIS where the website directory structure is located within a user's Documents folder will also encounter the file permissions problem.  This behavior occurs for WAP projects and websites hosted with any IIS versions that run as NETWORK SERVICE (IIS6, IIS7 and IIS 7.5) where the project structure exists within a user's Documents folder.

Resolution

Resolution for Windows 7 and Windows Server 2008 R2
For all web applications running under IIS 7.5, regardless of their project type, carry out the following steps:
  1. Run the Internet Information Services (IIS) Manager tool.  This tool can be accessed either from the Administrative start menu, or by typing "inetmgr" in the Windows Start-->Search textbox and selecting the inetmgr tool.
  2. In the left-hand pane of the IIS Manager tool expand the machine node.
  3. Click on the "Application Pools" node so that the application pools display in the main window of the management tool.
  4. If you are troubleshooting an ASP.NET 2.0/3.0/3.5 application select the "DefaultAppPool" application pool.  For ASP.NET v4 select the "ASP.NET v4.0" application pool.
  5. Right-click on the selected application pool and choose "Advanced Settings"
  6. In the "Advanced Settings" dialog box find the category called "Process Model".  The first row in the category will be the "Identity" row.
  7. Click on the "Identity" row and then click on the small button that shows on the right-hand side of the value cell.  The button displays the text "…"
  8. A dialog box called "Application Pool Identity" will popup.  Within that dialog box there are two radio buttons.  Make sure the first radio button titled "Built-in Account" is selected.
  9. In the dropdown box below the radio button choose "Network Service" for the identity.
  10. Click "Ok" to close out the "Application Pool Identity" dialog box.
  11. Click "Ok" to close out the "Advanced Settings" dialog box.
  12. At this point the changes to the application pool identity will have been saved to IIS 7.5's configuration store.

Resolution for Web Application Projects and Websites
For web application projects (WAP) and websites located in a user's Documents Folder hosted under any version of IIS running as NETWORK SERVICE, carry out the following steps:
  1. First confirm that IIS has been configured to run as NETWORK SERVICE.  This is the default on IIS6 and IIS7.  However if you are running on Windows 7 or Window Server 2008 R2 you will first need to follow the steps above in "Resolution for Windows 7 and Windows Server 2008 R2" to make IIS application pools run as NETWORK SERVICE.
  2. From a command prompt, type net stop iisadmin /y .  This will cause any running ASP.NET WAP applications to shutdown.
  3. Exit out of all running Visual Studio instances.
  4. NETWORK SERVICE must be granted Read permission to the top-level Visual Studio folder located in your user's Documents folder.  The Visual Studio folder will have different names depending on the version:  "Visual Studio 2005", "Visual Studio 2008", or "Visual Studio 2010".
  5. NETWORK SERVICE must be granted both read and write permissions to your project's top-level project folder.  For example if your WAP project is called "MyCustomWebProject", then the folder "Documents\Visual Studio 20xx\Projects\MyCustomWebProject" needs to have read and write access enabled for NETWORK SERVICE.  Or, if your webiste project is called "MyCustomWebProject", then the folder "Documents\Visual Studio 20xx\Websites\MyCustomWebProject" needs to have read and write access enabled for NETWORK SERVICE.
  6. NETWORK SERVICE must be granted both read and write permissions to the App_Data folder located within your web project's directory structure.

Group by in LINQ

Let's suppose if we have a class like
class Person { 
    internal int PersonID; 
    internal string car  ; 
}
Now I have a list of this class: List<Person> persons;
Now this list can have instances multiple same PersonIDs, for ex.
persons[0] = new Person { PersonID = 1, car = "Ferrari" }; 
persons[1] = new Person { PersonID = 1, car = "BMW"     }; 
persons[2] = new Person { PersonID = 2, car = "Audi"    }; 
Is there a way I can group by personID and get the list of all the cars he has? For ex. expected result would be
class Result { 
   int PersonID;
   List<string> cars; 
}
So after grouping by I would get:
results[0].PersonID = 1; 
List<string> cars = results[0].cars; 

result[1].PersonID = 2; 
List<string> cars = result[1].cars;
From what I have done so far:
var results = from p in persons
              group p by p.PersonID into g
              select new { PersonID = g.Key, // this is where I am not sure what to do
Absolutely - you basically want:
var results = from p in persons
              group p.car by p.PersonId into g
              select new { PersonId = g.Key, Cars = g.ToList() };
Or as a non-query expression:
var results = persons.GroupBy(
    p => p.PersonId, 
    p => p.car,
    (key, g) => new { PersonId = key, Cars = g.ToList() });
Basically the contents of the group (when view as an IEnumerable<T>) is a sequence of whatever values were in the projection (p.car in this case) present for the given key.
For more on how GroupBy works, see my Edulinq post on the topic.
(I've renamed PersonID to PersonId in the above, to follow .NET naming conventions.)
Alternatively, you could use a Lookup:
var carsByPersonId = persons.ToLookup(p => p.PersonId, p => p.car);
You can then get the cars for each person very easily:
// This will be an empty sequence for any personId not in the lookup
var carsForPerson = carsByPersonId[personId];