Search Results

Search found 111 results on 5 pages for 'northwind'.

Page 1/5 | 1 2 3 4 5  | Next Page >

  • Northwind now available on SQL Azure

    - by jamiet
    Two weeks ago I made available a copy of [AdventureWorks2012] on SQL Azure and published credentials so that anyone from the SQL community could connect up and experience SQL Azure, probably for the first time. One of the (somewhat) popular requests thereafter was to make the venerable Northwind database available too so I am pleased to say that as of right now, Northwind is up there too. You will notice immediately that all of the Northwind tables (and the stored procedures and views too) have been moved into a schema called [Northwind] – this was so that they could be easily differentiated from the existing [AdventureWorks2012] objects. I used an SQL Server Data Tools (SSDT) project to publish the schema and data up to this SQL Azure database; if you are at all interested in poking around that SSDT project then I have made it available on Codeplex for your convenience under the MS-PL license – go and get it from https://northwindssdt.codeplex.com/. Using SSDT proved particularly useful as it alerted me to some aspects of Northwind that were not compatible with SQL Azure, namely that five of the tables did not have clustered indexes: The beauty of using SSDT is that I am alerted to these issues before I even attempt a connection to SQL Azure. Pretty cool, no? Fixing this situation was of course very easy, I simply changed the following primary keys from being nonclustered to clustered: [PK_Region] [PK_CustomerDemographics] [PK_EmployeeTerritories] [PK_Territories] [PK_CustomerCustomerDemo]   If you want to connect up then here are the credentials that you will need: Server mhknbn2kdz.database.windows.net Database AdventureWorks2012 User sqlfamily Password sqlf@m1ly You will need SQL Server Management Studio (SSMS) 2008R2 installed in order to connect or alternatively simply use this handy website: https://mhknbn2kdz.database.windows.net which provides a web interface to a SQL Azure server. Do remember that hosting this database is not free so if you find that you are making use of it please help to keep it available by visiting Paypal and donating any amount at all to [email protected]. To make this easy you can simply hit this link and the details will be completed for you – all you have to do is login and hit the “Send” button. If you are already a PayPal member then it should take you all of about 20 seconds! I hope this is useful to some of you folks out there. Don’t forget that we also have more data up there than in the conventional [AdventureWorks2012], read more at Big AdventureWorks2012. @Jamiet  AdventureWorks on Azure - Provided by the SQL Server community, for the SQL Server community!

    Read the article

  • ASP.net DAL DatasSet and Table Adapter not in namespace - Northwind Tutorial

    - by Alan
    I've been attempting to walk through the "Creating a Data Access Layer" tutorial found http://www.asp.net/learn/data-access/tutorial-01-cs.aspx I create the DB connection, create the typed dataset and table adapter, specify the sql, etc. When I add the code to the presentation layer (in this case a page called AllProducts.aspx) I am unable to find the NorthwindTableAdapters.ProductsTableAdapter class. I tried to import the NorthwindTableAdapters namespace, but it is not showing up. Looking in the solution explorer Class View confirms that there is a Northwind class, but not the namespace I'm looking for. I've tried several online tutorials that all have essentially the same steps, and I'm getting the same results. Can anyone give me a push in the right direction? I'm getting error: Namespace or type specified in the Imports 'NorthwindTableAdapters' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. I think I might need to add a reference OR they may be creating a separate class and importing it into their main project. If that's the case, the tutorials do not mention this. SuppliersTest2.aspx.vb: Imports NorthwindTableAdapters Partial Class SuppliersTest2 Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim suppliersAdapter As New SuppliersTableAdapter GridView1.DataSource = suppliersAdapter.GetAllSuppliers() GridView1.DataBind() End Sub End Class

    Read the article

  • Can't get Sum() working in Northwind example

    - by Vince
    Hi, The following code is generating a runtime error and I have no idea why. from o in Orders group o by o.Employee into employeeOrders select new { employeeOrders.Key.EmployeeID, employeeOrders.Key.FirstName, Orders = from eord in employeeOrders orderby eord.OrderID select new { eord.OrderID, eord.OrderDate, OrderTotal=eord.OrderDetails.Sum (od => od.UnitPrice) } } The error is Member access 'System.Decimal UnitPrice' of 'LINQPad.User.OrderDetails' not legal on type 'LINQPad.User.Orders I've also tried this in VS2010 with a standard drag and drop data context and same thing. Thanks in advance

    Read the article

  • Order objects for Northwind Access database

    - by Artem Shnayder
    I need to build two objects: an OrderList and an Order. Using those two objects, I have to populate a DataGridView with a history of the orders. However, I am instructed not to use binding sources for the connection or other drag and drop controls. Unfortunately, from Google it seems like those are the most popular options for this type of problem. Can anyone point me in the right direction? I don't have much experience with C#. Thanks.

    Read the article

  • Can get Sum() working in Northwind example

    - by Vince
    Hi, The following code is generating a runtime error and I have no idea why. from o in Orders group o by o.Employee into employeeOrders select new { employeeOrders.Key.EmployeeID, employeeOrders.Key.FirstName, Orders = from eord in employeeOrders orderby eord.OrderID select new { eord.OrderID, eord.OrderDate, OrderTotal=eord.OrderDetails.Sum (od => od.UnitPrice) } } The error is Member access 'System.Decimal UnitPrice' of 'LINQPad.User.OrderDetails' not legal on type 'LINQPad.User.Orders Thanks in advance

    Read the article

  • What is Northwind.EmployeesRow

    - by Anthony
    I am doing a tutorial where you use a templatefield in the gridview control to call a function. I don't understand the code for the function. What is the object Northwind.EmployeesRow? This is the tutorial I am doing. http://msdn.microsoft.com/en-us/library/bb288032%28v=MSDN.10%29.aspx#aspnett12ustmpfldsvb_topic5 And this is the code for the function. Protected Function DisplayDaysOnJob(ByVal employee As Northwind.EmployeesRow) As String If employee.IsHireDateNull() Then Return "Unknown" Else ' Returns the number of days between the current ' date/time and HireDate Dim ts As TimeSpan = DateTime.Now.Subtract(employee.HireDate) Return ts.Days.ToString("#,##0") End If End Function

    Read the article

  • Looking for exercises to learn SQL, using the Northwind database

    - by MedicineMan
    I am trying to become more familiar with SQL by writing queries against the Northwind database. I am looking for some exercises that would help me to learn SQL and features of SQL Server. It is important that the exercises have solutions, and in complicated cases, it would be great if there was an explanation for the query. Thanks for the answers so far but I still have not found what I am looking for: Is there any free resource, available online, without registration, that I can find a list of these exercises?

    Read the article

  • Save VM properties with EF code first

    - by Julien
    I thought this would be simple but can't find any good examples. public Class BookVm : ImplementsPropertyChanged { public int BookId {get;set;} private bool _favorite; public bool Favorite { get { return _favorite; } set { _favorite = value; OnPropertyChanged("Favorite"); MyDbContext.SaveChanges() // this does not work } } Then in my XAML bound to Book <CheckBox Content="Favorite" IsChecked="{Binding Favorite}" /> How and when do I call SaveChanges() on my DatabaseContext? I don't want to implement a save button. If I intercept the PropertyChange event and call SaveChanges, nothing seems to happen. My object is modified in memory but the database does not see a change. My BookVm class is created on application startup like so: foreach (var book in MyDbContext.Books) Books.Add(book); Where Books is an ObservableCollection<Book> in my MainWindowVm

    Read the article

  • Announcing Entity Framework Code-First (CTP5 release)

    - by ScottGu
    This week the data team released the CTP5 build of the new Entity Framework Code-First library.  EF Code-First enables a pretty sweet code-centric development workflow for working with data.  It enables you to: Develop without ever having to open a designer or define an XML mapping file Define model objects by simply writing “plain old classes” with no base classes required Use a “convention over configuration” approach that enables database persistence without explicitly configuring anything Optionally override the convention-based persistence and use a fluent code API to fully customize the persistence mapping I’m a big fan of the EF Code-First approach, and wrote several blog posts about it this summer: Code-First Development with Entity Framework 4 (July 16th) EF Code-First: Custom Database Schema Mapping (July 23rd) Using EF Code-First with an Existing Database (August 3rd) Today’s new CTP5 release delivers several nice improvements over the CTP4 build, and will be the last preview build of Code First before the final release of it.  We will ship the final EF Code First release in the first quarter of next year (Q1 of 2011).  It works with all .NET application types (including both ASP.NET Web Forms and ASP.NET MVC projects). Installing EF Code First You can install and use EF Code First CTP5 using one of two ways: Approach 1) By downloading and running a setup program.  Once installed you can reference the EntityFramework.dll assembly it provides within your projects.      or: Approach 2) By using the NuGet Package Manager within Visual Studio to download and install EF Code First within a project.  To do this, simply bring up the NuGet Package Manager Console within Visual Studio (View->Other Windows->Package Manager Console) and type “Install-Package EFCodeFirst”: Typing “Install-Package EFCodeFirst” within the Package Manager Console will cause NuGet to download the EF Code First package, and add it to your current project: Doing this will automatically add a reference to the EntityFramework.dll assembly to your project:   NuGet enables you to have EF Code First setup and ready to use within seconds.  When the final release of EF Code First ships you’ll also be able to just type “Update-Package EFCodeFirst” to update your existing projects to use the final release. EF Code First Assembly and Namespace The CTP5 release of EF Code First has an updated assembly name, and new .NET namespace: Assembly Name: EntityFramework.dll Namespace: System.Data.Entity These names match what we plan to use for the final release of the library. Nice New CTP5 Improvements The new CTP5 release of EF Code First contains a bunch of nice improvements and refinements. Some of the highlights include: Better support for Existing Databases Built-in Model-Level Validation and DataAnnotation Support Fluent API Improvements Pluggable Conventions Support New Change Tracking API Improved Concurrency Conflict Resolution Raw SQL Query/Command Support The rest of this blog post contains some more details about a few of the above changes. Better Support for Existing Databases EF Code First makes it really easy to create model layers that work against existing databases.  CTP5 includes some refinements that further streamline the developer workflow for this scenario. Below are the steps to use EF Code First to create a model layer for the Northwind sample database: Step 1: Create Model Classes and a DbContext class Below is all of the code necessary to implement a simple model layer using EF Code First that goes against the Northwind database: EF Code First enables you to use “POCO” – Plain Old CLR Objects – to represent entities within a database.  This means that you do not need to derive model classes from a base class, nor implement any interfaces or data persistence attributes on them.  This enables the model classes to be kept clean, easily testable, and “persistence ignorant”.  The Product and Category classes above are examples of POCO model classes. EF Code First enables you to easily connect your POCO model classes to a database by creating a “DbContext” class that exposes public properties that map to the tables within a database.  The Northwind class above illustrates how this can be done.  It is mapping our Product and Category classes to the “Products” and “Categories” tables within the database.  The properties within the Product and Category classes in turn map to the columns within the Products and Categories tables – and each instance of a Product/Category object maps to a row within the tables. The above code is all of the code required to create our model and data access layer!  Previous CTPs of EF Code First required an additional step to work against existing databases (a call to Database.Initializer<Northwind>(null) to tell EF Code First to not create the database) – this step is no longer required with the CTP5 release.  Step 2: Configure the Database Connection String We’ve written all of the code we need to write to define our model layer.  Our last step before we use it will be to setup a connection-string that connects it with our database.  To do this we’ll add a “Northwind” connection-string to our web.config file (or App.Config for client apps) like so:   <connectionStrings>          <add name="Northwind"          connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\northwind.mdf;User Instance=true"          providerName="System.Data.SqlClient" />   </connectionStrings> EF “code first” uses a convention where DbContext classes by default look for a connection-string that has the same name as the context class.  Because our DbContext class is called “Northwind” it by default looks for a “Northwind” connection-string to use.  Above our Northwind connection-string is configured to use a local SQL Express database (stored within the \App_Data directory of our project).  You can alternatively point it at a remote SQL Server. Step 3: Using our Northwind Model Layer We can now easily query and update our database using the strongly-typed model layer we just built with EF Code First. The code example below demonstrates how to use LINQ to query for products within a specific product category.  This query returns back a sequence of strongly-typed Product objects that match the search criteria: The code example below demonstrates how we can retrieve a specific Product object, update two of its properties, and then save the changes back to the database: EF Code First handles all of the change-tracking and data persistence work for us, and allows us to focus on our application and business logic as opposed to having to worry about data access plumbing. Built-in Model Validation EF Code First allows you to use any validation approach you want when implementing business rules with your model layer.  This enables a great deal of flexibility and power. Starting with this week’s CTP5 release, EF Code First also now includes built-in support for both the DataAnnotation and IValidatorObject validation support built-into .NET 4.  This enables you to easily implement validation rules on your models, and have these rules automatically be enforced by EF Code First whenever you save your model layer.  It provides a very convenient “out of the box” way to enable validation within your applications. Applying DataAnnotations to our Northwind Model The code example below demonstrates how we could add some declarative validation rules to two of the properties of our “Product” model: We are using the [Required] and [Range] attributes above.  These validation attributes live within the System.ComponentModel.DataAnnotations namespace that is built-into .NET 4, and can be used independently of EF.  The error messages specified on them can either be explicitly defined (like above) – or retrieved from resource files (which makes localizing applications easy). Validation Enforcement on SaveChanges() EF Code-First (starting with CTP5) now automatically applies and enforces DataAnnotation rules when a model object is updated or saved.  You do not need to write any code to enforce this – this support is now enabled by default.  This new support means that the below code – which violates our above rules – will automatically throw an exception when we call the “SaveChanges()” method on our Northwind DbContext: The DbEntityValidationException that is raised when the SaveChanges() method is invoked contains a “EntityValidationErrors” property that you can use to retrieve the list of all validation errors that occurred when the model was trying to save.  This enables you to easily guide the user on how to fix them.  Note that EF Code-First will abort the entire transaction of changes if a validation rule is violated – ensuring that our database is always kept in a valid, consistent state. EF Code First’s validation enforcement works both for the built-in .NET DataAnnotation attributes (like Required, Range, RegularExpression, StringLength, etc), as well as for any custom validation rule you create by sub-classing the System.ComponentModel.DataAnnotations.ValidationAttribute base class. UI Validation Support A lot of our UI frameworks in .NET also provide support for DataAnnotation-based validation rules. For example, ASP.NET MVC, ASP.NET Dynamic Data, and Silverlight (via WCF RIA Services) all provide support for displaying client-side validation UI that honor the DataAnnotation rules applied to model objects. The screen-shot below demonstrates how using the default “Add-View” scaffold template within an ASP.NET MVC 3 application will cause appropriate validation error messages to be displayed if appropriate values are not provided: ASP.NET MVC 3 supports both client-side and server-side enforcement of these validation rules.  The error messages displayed are automatically picked up from the declarative validation attributes – eliminating the need for you to write any custom code to display them. Keeping things DRY The “DRY Principle” stands for “Do Not Repeat Yourself”, and is a best practice that recommends that you avoid duplicating logic/configuration/code in multiple places across your application, and instead specify it only once and have it apply everywhere. EF Code First CTP5 now enables you to apply declarative DataAnnotation validations on your model classes (and specify them only once) and then have the validation logic be enforced (and corresponding error messages displayed) across all applications scenarios – including within controllers, views, client-side scripts, and for any custom code that updates and manipulates model classes. This makes it much easier to build good applications with clean code, and to build applications that can rapidly iterate and evolve. Other EF Code First Improvements New to CTP5 EF Code First CTP5 includes a bunch of other improvements as well.  Below are a few short descriptions of some of them: Fluent API Improvements EF Code First allows you to override an “OnModelCreating()” method on the DbContext class to further refine/override the schema mapping rules used to map model classes to underlying database schema.  CTP5 includes some refinements to the ModelBuilder class that is passed to this method which can make defining mapping rules cleaner and more concise.  The ADO.NET Team blogged some samples of how to do this here. Pluggable Conventions Support EF Code First CTP5 provides new support that allows you to override the “default conventions” that EF Code First honors, and optionally replace them with your own set of conventions. New Change Tracking API EF Code First CTP5 exposes a new set of change tracking information that enables you to access Original, Current & Stored values, and State (e.g. Added, Unchanged, Modified, Deleted).  This support is useful in a variety of scenarios. Improved Concurrency Conflict Resolution EF Code First CTP5 provides better exception messages that allow access to the affected object instance and the ability to resolve conflicts using current, original and database values.  Raw SQL Query/Command Support EF Code First CTP5 now allows raw SQL queries and commands (including SPROCs) to be executed via the SqlQuery and SqlCommand methods exposed off of the DbContext.Database property.  The results of these method calls can be materialized into object instances that can be optionally change-tracked by the DbContext.  This is useful for a variety of advanced scenarios. Full Data Annotations Support EF Code First CTP5 now supports all standard DataAnnotations within .NET, and can use them both to perform validation as well as to automatically create the appropriate database schema when EF Code First is used in a database creation scenario.  Summary EF Code First provides an elegant and powerful way to work with data.  I really like it because it is extremely clean and supports best practices, while also enabling solutions to be implemented very, very rapidly.  The code-only approach of the library means that model layers end up being flexible and easy to customize. This week’s CTP5 release further refines EF Code First and helps ensure that it will be really sweet when it ships early next year.  I recommend using NuGet to install and give it a try today.  I think you’ll be pleasantly surprised by how awesome it is. Hope this helps, Scott

    Read the article

  • Using Enterprise Library DAAB in C# Console Project

    - by Kayes
    How can I prepare the configuration settings (App.config, maybe?) I need to use Enterprise Library Data Access Application Block in a C# console project? Following is what I currently trying with an App.config in the console project. When I call DatabaseFactory.CreateDatabase(), it throws an exception which says: "Configuration system failed to initialize" <configuration> <dataConfiguration> <xmlSerializerSection type="Microsoft.Practices.EnterpriseLibrary.Data. Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"> <enterpriseLibrary.databaseSettings xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" defaultInstance="Northwind" xmlns="http://www.microsoft.com/practices/enterpriselibrary/08-31-2004/data"> <databaseTypes> <databaseType name="Sql Server" type="Microsoft.Practices.EnterpriseLibrary.Data.Sql.SqlDatabase, Microsoft.Practices.EnterpriseLibrary.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" /> </databaseTypes> <instances> <instance name="Northwind" type="Sql Server" connectionString="Northwind" /> </instances> <connectionStrings> <connectionString name="Northwind"> <parameters> <parameter name="Database" value="Northwind" isSensitive="false" /> <parameter name="Integrated Security" value="True" isSensitive="false" /> <parameter name="Server" value="local" isSensitive="false" /> <parameter name="User ID" value="sa" isSensitive="false" /> <parameter name="Password" value="sa1234" isSensitive="true" /> </parameters> </connectionString> </connectionStrings> </enterpriseLibrary.databaseSettings> </xmlSerializerSection> </dataConfiguration> </configuration>

    Read the article

  • Linq 2 SQL Store inherited classes - not mapped to tables in the database

    - by user348672
    Hi. I'm trying to introduce the Linq2SQL technique into the project and have encountered the following issue: I've created ORM classes based on the Northwind database. In some other application I create several classes derived from the Linq2SQL classes. I'm able to add such a class to EntitySet but the application fails to submit changes. Is there any way around this? Sample code(MyClass is derived from the Order): DataClasses1DataContext northwind = new DataClasses1DataContext(); Product chai = northwind.Products.Single(p => p.ProductName == "Chai"); Product tofu = northwind.Products.Single(p => p.ProductName == "Tofu"); Order myOrder = new Order(); myOrder.OrderDate = DateTime.Now; myOrder.RequiredDate = DateTime.Now.AddDays(1); myOrder.Freight = 34; Order_Detail myItem1 = new Order_Detail(); myItem1.Product = chai; myItem1.Quantity = 12345; Order_Detail myItem2 = new Order_Detail(); myItem2.Product = tofu; myItem2.Quantity = 3; myOrder.Order_Details.Add(myItem1); myOrder.Order_Details.Add(myItem2); Customer myCustomer = northwind.Customers.Single(c => c.CompanyName == "B's Beverages"); MyClass newOrder = new MyClass(); newOrder.OrderDate = DateTime.Now; newOrder.RequiredDate = DateTime.Now.AddDays(31); newOrder.Freight = 35; Order_Detail myItem3 = new Order_Detail(); myItem3.Product = tofu; myItem3.Quantity = 3; newOrder.Order_Details.Add(myItem3); myCustomer.Orders.Add(myOrder); myCustomer.Orders.Add(newOrder); As I said I'm able to add the newOrder object but unable to submit into the database.

    Read the article

  • Socket : can an asynchronous Receive returns without reading all the bytes I asked for?

    - by NorthWind
    Hi; I was reading an article on Vadym Stetsiak's blog about how to transfer variable length messages with async sockets (url: http://vadmyst.blogspot.com/2008/03/part-2-how-to-transfer-fixed-sized-data.html). He says : What to expect when multiple messages arrive at the server? While dealing with multiple messages one has to remember that receive operation can return arbitrary number of bytes being read from the net. Typically that size is from 0 to specified buffer length in the Receive or BeginReceive methods. So, even if I tell BeginReceive to read 100 bytes, it may read less than that and returns??? I am developing a network-enabled software (TCP/IP), and I always receive the same exact number of bytes I asked for. I don't even understand the logic : why would Receive completes asynchronously if it didn't get every byte I asked for ... just keep waiting. Maybe it has something to do with IP vs TCP? Thank you for your help.

    Read the article

  • Securing an ASP.NET MVC 2 Application

    - by rajbk
    This post attempts to look at some of the methods that can be used to secure an ASP.NET MVC 2 Application called Northwind Traders Human Resources.  The sample code for the project is attached at the bottom of this post. We are going to use a slightly modified Northwind database. The screen capture from SQL server management studio shows the change. I added a new column called Salary, inserted some random salaries for the employees and then turned off AllowNulls.   The reporting relationship for Northwind Employees is shown below.   The requirements for our application are as follows: Employees can see their LastName, FirstName, Title, Address and Salary Employees are allowed to edit only their Address information Employees can see the LastName, FirstName, Title, Address and Salary of their immediate reports Employees cannot see records of non immediate reports.  Employees are allowed to edit only the Salary and Title information of their immediate reports. Employees are not allowed to edit the Address of an immediate report Employees should be authenticated into the system. Employees by default get the “Employee” role. If a user has direct reports, they will also get assigned a “Manager” role. We use a very basic empId/pwd scheme of EmployeeID (1-9) and password test$1. You should never do this in an actual application. The application should protect from Cross Site Request Forgery (CSRF). For example, Michael could trick Steven, who is already logged on to the HR website, to load a page which contains a malicious request. where without Steven’s knowledge, a form on the site posts information back to the Northwind HR website using Steven’s credentials. Michael could use this technique to give himself a raise :-) UI Notes The layout of our app looks like so: When Nancy (EmpID 1) signs on, she sees the default page with her details and is allowed to edit her address. If Nancy attempts to view the record of employee Andrew who has an employeeID of 2 (Employees/Edit/2), she will get a “Not Authorized” error page. When Andrew (EmpID 2) signs on, he can edit the address field of his record and change the title and salary of employees that directly report to him. Implementation Notes All controllers inherit from a BaseController. The BaseController currently only has error handling code. When a user signs on, we check to see if they are in a Manager role. We then create a FormsAuthenticationTicket, encrypt it (including the roles that the employee belongs to) and add it to a cookie. private void SetAuthenticationCookie(int employeeID, List<string> roles) { HttpCookiesSection cookieSection = (HttpCookiesSection) ConfigurationManager.GetSection("system.web/httpCookies"); AuthenticationSection authenticationSection = (AuthenticationSection) ConfigurationManager.GetSection("system.web/authentication"); FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket( 1, employeeID.ToString(), DateTime.Now, DateTime.Now.AddMinutes(authenticationSection.Forms.Timeout.TotalMinutes), false, string.Join("|", roles.ToArray())); String encryptedTicket = FormsAuthentication.Encrypt(authTicket); HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); if (cookieSection.RequireSSL || authenticationSection.Forms.RequireSSL) { authCookie.Secure = true; } HttpContext.Current.Response.Cookies.Add(authCookie); } We read this cookie back in Global.asax and set the Context.User to be a new GenericPrincipal with the roles we assigned earlier. protected void Application_AuthenticateRequest(Object sender, EventArgs e){ if (Context.User != null) { string cookieName = FormsAuthentication.FormsCookieName; HttpCookie authCookie = Context.Request.Cookies[cookieName]; if (authCookie == null) return; FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); string[] roles = authTicket.UserData.Split(new char[] { '|' }); FormsIdentity fi = (FormsIdentity)(Context.User.Identity); Context.User = new System.Security.Principal.GenericPrincipal(fi, roles); }} We ensure that a user has permissions to view a record by creating a custom attribute AuthorizeToViewID that inherits from ActionFilterAttribute. public class AuthorizeToViewIDAttribute : ActionFilterAttribute{ IEmployeeRepository employeeRepository = new EmployeeRepository(); public override void OnActionExecuting(ActionExecutingContext filterContext) { if (filterContext.ActionParameters.ContainsKey("id") && filterContext.ActionParameters["id"] != null) { if (employeeRepository.IsAuthorizedToView((int)filterContext.ActionParameters["id"])) { return; } } throw new UnauthorizedAccessException("The record does not exist or you do not have permission to access it"); }} We add the AuthorizeToView attribute to any Action method that requires authorization. [HttpPost][Authorize(Order = 1)]//To prevent CSRF[ValidateAntiForgeryToken(Salt = Globals.EditSalt, Order = 2)]//See AuthorizeToViewIDAttribute class[AuthorizeToViewID(Order = 3)] [ActionName("Edit")]public ActionResult Update(int id){ var employeeToEdit = employeeRepository.GetEmployee(id); if (employeeToEdit != null) { //Employees can edit only their address //A manager can edit the title and salary of their subordinate string[] whiteList = (employeeToEdit.IsSubordinate) ? new string[] { "Title", "Salary" } : new string[] { "Address" }; if (TryUpdateModel(employeeToEdit, whiteList)) { employeeRepository.Save(employeeToEdit); return RedirectToAction("Details", new { id = id }); } else { ModelState.AddModelError("", "Please correct the following errors."); } } return View(employeeToEdit);} The Authorize attribute is added to ensure that only authorized users can execute that Action. We use the TryUpdateModel with a white list to ensure that (a) an employee is able to edit only their Address and (b) that a manager is able to edit only the Title and Salary of a subordinate. This works in conjunction with the AuthorizeToViewIDAttribute. The ValidateAntiForgeryToken attribute is added (with a salt) to avoid CSRF. The Order on the attributes specify the order in which the attributes are executed. The Edit View uses the AntiForgeryToken helper to render the hidden token: ......<% using (Html.BeginForm()) {%><%=Html.AntiForgeryToken(NorthwindHR.Models.Globals.EditSalt)%><%= Html.ValidationSummary(true, "Please correct the errors and try again.") %><div class="editor-label"> <%= Html.LabelFor(model => model.LastName) %></div><div class="editor-field">...... The application uses View specific models for ease of model binding. public class EmployeeViewModel{ public int EmployeeID; [Required] [DisplayName("Last Name")] public string LastName { get; set; } [Required] [DisplayName("First Name")] public string FirstName { get; set; } [Required] [DisplayName("Title")] public string Title { get; set; } [Required] [DisplayName("Address")] public string Address { get; set; } [Required] [DisplayName("Salary")] [Range(500, double.MaxValue)] public decimal Salary { get; set; } public bool IsSubordinate { get; set; }} To help with displaying readonly/editable fields, we use a helper method. //Simple extension method to display a TextboxFor or DisplayFor based on the isEditable variablepublic static MvcHtmlString TextBoxOrLabelFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, bool isEditable){ if (isEditable) { return htmlHelper.TextBoxFor(expression); } else { return htmlHelper.DisplayFor(expression); }} The helper method is used in the view like so: <%=Html.TextBoxOrLabelFor(model => model.Title, Model.IsSubordinate)%> As mentioned in this post, there is a much easier way to update properties on an object. Download Demo Project VS 2008, ASP.NET MVC 2 RTM Remember to change the connectionString to point to your Northwind DB NorthwindHR.zip Feedback and bugs are always welcome :-)

    Read the article

  • xpath: determining if the customer has orders

    - by deostroll
    There is an xml dump of the Northwind database here. Document structure is something like: <NorthWind> <Customers></Customers> <Customers></Customers> . . . <Orders></Orders> <Orders></Orders> . . . </NorthWind> Each Customers tag will hold one customer information. Now while I select all Customers how do I furnish a field such that it indicates whether the customer has orders or not; something like a boolean field

    Read the article

  • Mass Delete Using Gridview with Checkboxes

    This sample shows how to use a Gridview to delete multiple records all at once, having marked them with a Checkbox, and clicking one button, external to the Gridview, to delete them all As usual, here, we're using the Northwind Database. If you want to try this on your own Northwind database, adhere to this word of caution - "BACK IT UP FIRST". You will be making multiple deletes, so in order to get it back to the original state, you must make a backup and then restore afterwards. Remember too, that you will need to substitute your own Web.Config connectionstring entry for "YourNorthwindString" in the sample code

    Read the article

  • How does LinqPad support WCF Data Services?

    - by user341127
    LinqPad supports WCF Data Services. If you assign an URL, such as http://services.odata.org/Northwind/Northwind.svc/. It will list all available data objects and you can query them. I guess LinqPad generates all available data classes at run time by reflection.Emit. I am wondering who can show me to how to do so. Or maybe someone has done it before. Any feedback are appreciated. Ying

    Read the article

  • missing a using directive or an assembly reference

    - by cire1507
    I'm in the process of writing a small asp.net mvc application that is using the northwind.mdf. When building the solution I get this error: Error 1 The type or namespace name 'Order' could not be found (are you missing a using directive or an assembly reference?) Order is a table in the northwind database. any help is most appreciated.

    Read the article

  • CodePlex Daily Summary for Wednesday, April 11, 2012

    CodePlex Daily Summary for Wednesday, April 11, 2012Popular ReleasesCommand-Line Database Builder: 1.0.2012.0411: Utility now supports arbitrary key:value pairs on the command-line for performing replacements in the .pp.sql files. Removed the usage of '-' to prefix key:value arguments. AspNetAssemblyPath is no longer a known key:value pair but can still be used because the tool now supports arbitrary key:value pairs for replacements. This was provided previously to support setting up ASP.NET Membership and Roles in a database. I've added a .pp.sql file to the Examples archive that demonstrates this usage.Supporting Guidance and Whitepapers: v1 - Team Foundation Service Whitepapers: Welcome to the BETA release of the Team Foundation Service Whitepapers preview As this is a BETA release and the quality bar for the final Release has not been achieved, we value your candid feedback and recommend that you do not use or deploy these BETA artifacts in a production environment. Quality-Bar Details Documentation has been reviewed by Visual Studio ALM Rangers Documentation has been through an independent technical review All critical bugs have been resolved Known Issue...Scrum Task Board Card Creator: TaskCardCreator 3.2.0.0: What's New: New report template added: Microsoft Visual Studio Scrum 1.0 Detailed Report Supported Templates: Microsoft Visual Studio Scrum 1.0 MSF for Agile Software Development v5.0Microsoft .NET Gadgeteer: .NET Gadgeteer Core 2.42.550 (BETA): Microsoft .NET Gadgeteer Core RELEASE NOTES Version 2.42.550 11 April 2012 BETA VERSION WARNING: This is a beta version! Please note: - API changes may be made before the next version (2.42.600) - The designer will not show modules/mainboards for NETMF 4.2 until you get upgraded libraries from the module/mainboard vendors - Install NETMF 4.2 (see link below) to use the new features of this release That warning aside, this version should continue to sup...DISM GUI: DISM GUI 3.1.1: Fixes - Fixed a bug in the Delete Driver function - The Index field is not auto populated with the number 1LINQ to Twitter: LINQ to Twitter Beta v2.0.24: Supports .NET 3.5, .NET 4.0, Silverlight 4.0, Windows Phone 7.1, and Client Profile. 100% Twitter API coverage. Also available via NuGet.Kendo UI ASP.NET Sample Applications: Sample Applications (2012-04-11): Sample application(s) demonstrating the use of Kendo UI in ASP.NET applications.Json.NET: Json.NET 4.5 Release 2: New feature - Added support for the SerializableAttribute and serializing a type's internal fields New feature - Added MaxDepth to JsonReader/JsonSerializer/JsonSerializerSettings New feature - Added support for ignoring properties with the NonSerializableAttribute Fix - Fixed deserializing a null string throwing a NullReferenceException Fix - Fixed JsonTextReader reading from a slow stream Fix - Fixed CultureInfo not being overridden on JsonSerializerProxy Fix - Fixed full trust ...SCCM Client Actions Tool: SCCM Client Actions Tool v1.12: SCCM Client Actions Tool v1.12 is the latest version. It comes with following changes since last version: Improved WMI date conversion to be aware of timezone differences and DST. Fixed new version check. The tool is downloadable as a ZIP file that contains four files: ClientActionsTool.hta – The tool itself. Cmdkey.exe – command line tool for managing cached credentials. This is needed for alternate credentials feature when running the HTA on Windows XP. Cmdkey.exe is natively availab...Dual Browsing: Dual Browser: Please note the following: I setup the address bar temporarily to only accepts http:// .com addresses. Just type in the name of the website excluding: http://, www., and .com; (Ex: for www.youtube.com just type: youtube then click OK). The page splitter can be grabbed by holding down your left mouse button and move left or right. By right clicking on the page background, you can choose to refresh, go back a page and so on. Demo video: http://youtu.be/L7NTFVM3JUYMultiwfn: Multiwfn 2.3.3: Multiwfn 2.3.3Liberty: v3.2.0.1 Release 9th April 2012: Change Log-Fixed -Reach Fixed a bug where the object editor did not work on non-English operating systemsPath Copy Copy: 10.1: This release addresses the following work items: 11357 11358 11359 This release is a recommended upgrade, especially for users who didn't install the 10.0.1 version.ExtAspNet: ExtAspNet v3.1.3: ExtAspNet - ?? ExtJS ??? ASP.NET 2.0 ???,????? AJAX ?????????? ExtAspNet ????? ExtJS ??? ASP.NET 2.0 ???,????? AJAX ??????????。 ExtAspNet ??????? JavaScript,?? CSS,?? UpdatePanel,?? ViewState,?? WebServices ???????。 ??????: IE 7.0, Firefox 3.6, Chrome 3.0, Opera 10.5, Safari 3.0+ ????:Apache License 2.0 (Apache) ??:http://extasp.net/ ??:http://bbs.extasp.net/ ??:http://extaspnet.codeplex.com/ ??:http://sanshi.cnblogs.com/ ????: +2012-04-08 v3.1.3 -??Language="zh_TW"?JS???BUG(??)。 +?D...Coding4Fun Tools: Coding4Fun.Phone.Toolkit v1.5.5: New Controls ChatBubble ChatBubbleTextBox OpacityToggleButton New Stuff TimeSpan languages added: RU, SK, CS Expose the physics math from TimeSpanPicker Image Stretch now on buttons Bug Fixes Layout fix so RoundToggleButton and RoundButton are exactly the same Fix for ColorPicker when set via code behind ToastPrompt bug fix with OnNavigatedTo Toast now adjusts its layout if the SIP is up Fixed some issues with Expression Blend supportHarness - Internet Explorer Automation: Harness 2.0.3: support the operation fo frameset, frame and iframe Add commands SwitchFrame GetUrl GoBack GoForward Refresh SetTimeout GetTimeout Rename commands GetActiveWindow to GetActiveBrowser SetActiveWindow to SetActiveBrowser FindWindowAll to FindBrowser NewWindow to NewBrowser GetMajorVersion to GetVersionBetter Explorer: Better Explorer 2.0.0.861 Alpha: - fixed new folder button operation not work well in some situations - removed some unnecessary code like subclassing that is not needed anymore - Added option to make Better Exlorer default (at least for WIN+E operations) - Added option to enable file operation replacements (like Terracopy) to work with Better Explorer - Added some basic usability to "Share" button - Other fixesLightFarsiDictionary - ??????? ??? ?????/???????: LightFarsiDictionary - v1: LightFarsiDictionary - v1WPF Application Framework (WAF): WPF Application Framework (WAF) 2.5.0.3: Version: 2.5.0.3 (Milestone 3): This release contains the source code of the WPF Application Framework (WAF) and the sample applications. Requirements .NET Framework 4.0 (The package contains a solution file for Visual Studio 2010) The unit test projects require Visual Studio 2010 Professional Changelog Legend: [B] Breaking change; [O] Marked member as obsolete [O] WAF: Mark the StringBuilderExtensions class as obsolete because the AppendInNewLine method can be replaced with string.Jo...ClosedXML - The easy way to OpenXML: ClosedXML 0.65.2: Aside from many bug fixes we now have Conditional Formatting The conditional formatting was sponsored by http://www.bewing.nl (big thanks) New on v0.65.1 Fixed issue when loading conditional formatting with default values for icon sets New on v0.65.2 Fixed issue loading conditional formatting Improved inserts performanceNew Projects0x10c Tools: Tools for the 0x10c-CPU: Assembler, emulator and (maybe in the future) a small compiler. Just for fun and exercise.AzureWiki: AzureWiki is the Wiki developed using Windows Azure platform which would be similar to dotnetwikiCommand-Line Database Builder: A command-line tool for interacting with a DBMS command-line interface (e.g., sqlcmd.exe) to execute a sequential list of SQL scripts against the DBMS. Tool allows for expression replacement in the SQL scripts during execution.copydata: The CopyData command-line utility enables you to easily transfer sets of data from an Oracle or SQL server data source directly to a target SQL Server database. It is developed in C#.DinoDoc: The little friendly batch-upload tool designed for SharePoint Server and Windows SharePoint Services, enabling you to easily upload multiple files and folders with a single click! For more information about DinoDoc and about SharePoint development: http://spdino.wordpress.comDiscovery House: This is a project demonstrating a green home.DocShare: DocShare illustrates the CQRS pattern on Windows Azure and also uses MVC4 Web API. DocShare uses two web roles, one for queries (reads) and one for command (writes). Each has a UI and a Web API service.EnderTecLauncher: EnderTecLauncherEntityFilter: This library provides a way to store filtering metadata, and reassemble it into dynamic lambda expressions. It allows for groups of filters to be created. Two implementations of IFilterRepository are in development:Database and XML. It's developed in C# for EntityFramework 4.1 and above.Epi Info™ - Web Analysis & Visualization: Epi Info™ is a public domain suite of software tools designed for the global community of public health practitioners and researchers. It provides for easy data entry form and database construction, a customized data entry experience, and data analyses with epidemiologic statistic Epi Info™ Web Analytics & Visualization is an open source project of the popular Epi Info™ suite of tools. The web product can be deployed as an intranet application and will provide analytical and visualization ...fOrganiz: This application allows you to automatically organize by date in specific subdirectories your picturesforwork: forworkGeneric Language - Mobile & Telephony Technologies: Genlang Mobile and Telephony Technologies, a complete application development platform for all platforms, Windows Mobile, Windows Desktop, Web, Apple, Android, BlackBerry.gindex: Graph has become increasingly important in modelling complicated structures and schemaless data such as proteins,chemical compounds, and XML documents. Given a graph query, it is desirable to retrieve graphs quickly from a large database via graph-based indices.Hijri Date SkinObject: Hijri date skin object for dotnetnuke copy to admin/skins use it in your skin file HorseRaces: Exercise inspired on example found in book "Designing for scalability with Microsoft Windows DNA" by Sten Sundblad and Per SundbladHotelMS: HotelManageSystemhtml5lmth: testjRulee: The jRulee javascript toolkit libraryKrishaTool: oloLegSec: LegSec is an small command line application for collating licence information based on that provided in Nuget packages. Modwind Domain Info: The program determines country of origin for top-level domains and purpose for international ones.MySCM Outlook Addin: This is another tool for SCM/TFS team. Use this add-in to create, update, refresh TFS work items from your Outlook emails. Not a substitution, but this little tool can help you to track your various work in TFS while educating and establishing the processes and policies.neptouni: This software can be used to convert nepali ttf text to the unicode characters.Northwind SSDT: An SSDT project for the Northwind database. This will enable you to deploy Northwind wherever you like. Note that to allow for hosting in a SQL Azure database that is used to host objects for other applications all the Northwind objects have been moved into a schema called [Northwind]Optional: Optional is a library to create options and commands from command-line arguments. It uses Convention over Configuration to get out of your way. Attributes can be used to set properties which differ from the convention.pbdevnpro1: pbdevnpro1,no1Projet LIF7 Snake: Projet LIF7 SnakePurpleStoat: A modular, extensible Silverlight application shell using Prism, Unity and the Enterprise Library, and written in C#. It includes WCF services which provide AuthZ and logging services to the shell, which are also available to the modules.Sharepoint 2010 Weather WebPart using Azure Data Market Met Office Feed: Sharepoint 2010 WebPart that displays a 5 day weather forecast for a given location. The weather data is retrieved from the Met Office feed hosted on the Windows Azure Data Market. This is a free data feed that provides weather data for the UK only.Silverlight Layouts: Silverlight Layouts is a project for controls that behave as content placeholders with pre-defined GUI layout for some of common scenarios: - frozen headers, - frozen columns, - cyrcle layouts etc.Snom Phone .NET Library: .NET Automation library for the snom IP phones. Provides simple class library to interact with you snom phone: - Press any key on the phone. - Dial numbers. - Answer or hang up call. - Mute and un-mute. - Hold and un-hold a call. - Navigate through a routing phone system using dial tone. - Get events on incoming or outgoing calls, as well as other events. - And more...Substrate Windows 8 XAML Framework: Framework for writing Windows 8 applications in XAMLTiger Converters: Tiger is a small languaje based on expressions, so it's perfect for writing the body of a WPF/SL converter.Time manager by bozheville: Time manager by bozhevilleUmbraco 501 on Windows Azure (with Dynamic Deploy): This project is configured to run Umbraco 5.0.1 on Windows Azure via the Dynamic Deploy platform. For more information on Dynamic Deploy visit http://www.dynamicdeploy.com Dynamic Deploy is a cloud deployment platform from where you can deploy applications directly to cloud platforms (like Windows Azure). UnitPrice: This is unit priceWebmedia: this is my webmedia projectWindows 8 Metro RSS Reader: A RSS Reader metro app for Windows 8 written in C# and XAML based on the sample Grid templateWindows Phone UPnP: The basics of a UPnP network stack for Windows Phone, based on a blog post originally. Written in C#, also requires the Async CTP. Includes device discovery via SSDP and method invocation.WinRT XAML Toolkit: A set of controls, extensions and helper classes for Windows Runtime XAML applicationsWmiGuru: WmiGuru is a lightweight F# library for WMI operations such as getting instances, creating instance, and querying associated instances.????: ???? ??.net mvc3??。??jquery+html5????。?????: openwebsite

    Read the article

  • Using Teleriks new LINQ implementation to connect to MySQL

    Last week Telerik released a new LINQ implementation that is simple to use and produces domain models very fast. Built on top of the enterprise grade OpenAccess ORM, you can connect to any database that OpenAccess can connect to such as: SQL Server, MySQL, Oracle, SQL Azure, VistaDB, etc. Today I will show you how to build a domain model using MySQL as your back end. To get started, you have to download MySQL 5.x and the MySQL Workbench and also, as my colleague Alexander Filipov at Telerik reminded me, make sure you install the MySQL .NET Connector, which is available here.  I like to use Northwind, ok it gives me the warm and fuzzies, so I ran a script to produce Northwind on my MySQL server. There are many ways you can get Northwind on your MySQL database, here is a helpful blog to get your started. I also manipulated the first record to indicate that I am in MySQL and gave a look via the MySQL Workbench. Ok, time to build our model! Start up the Domain Model wizard by right clicking on the project in Visual Studio (I have a Web project) and select Add|New Item and choose Telerik OpenAccess Domain Model from the new item list. When the wizard comes up, choose MySQL as your back end and enter in the name of your saved MySQL connection. If you dont have a saved MySQL connection set up in Visual Studio, click on New Connection and enter in the proper connection information. *Note, this is where you need to have the MySQL .NET connector installed. After you set your connection to the MySQL database server, you have to choose which tables to include in your model. Just for fun, I will choose all of them. Give your model a name, like NorthwindEntities and click finish. That is it. Now lets consume the model with ASP .net. I created a simple page that also has a GridView on it. On my page load I wrote this code, by now it should look very familiar, a simple LINQ query filtering customers by country (Germany) and binding the results to the grid.  1: protected void Page_Load(object sender, EventArgs e) 2: { 3: if (!IsPostBack) 4: { 5: //a reference to the data context 6: NorthwindEntities dat = new NorthwindEntities(); 7: //LINQ Statement 8: var result = from c in dat.Customers 9: where c.Country == "Germany" 10: select c; 11: //Databinding to the Gridview 12: GridView1.DataSource = result; 13: GridView1.DataBind(); 14: } 15: } .csharpcode, .csharpcode pre{ font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em;}.csharpcode .lnum { color: #606060; } F5 produces the following. Tomorrow Ill show how to take the same model and create an Astoria/OData data feed. Technorati Tags: MySQL Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • SQL SERVER – What is AdventureWorks?

    - by pinaldave
    NOTE: If you know the answer of this question, then I request you to stop reading this post right now. Please do not leave comment about this blog post not being useful to you, if you knew the answer. Few days ago, I received DM asking What is an AdventureWorks database and why in all the examples I use that instead of any other database (e.g. Pubs or  Northwind)? As matter of fact, when I went back to my question list, which I have yet not answered, there were a few more variations of this same question. AdventureWorks is a Sample Database shipped with SQL Server and it can be downloaded from http://codeplex.com site. AdventureWorks has replaced Northwind and Pubs from the sample database in SQL Server 2005. The Microsoft team keeps updating the sample database as they release new versions. Here are some quick links: AdventureWorks SQL Server 2008 SR4 AdventureWorks 2008R2 November CTP AdventureWorks for SQL Azure (December CTP) AventureWorks for SQL Server 2005 SP2A SQL SERVER – 2008 – Download and Install Samples Database AdventureWorks 2005 – Detail Tutorial I have previously written few other articles on the same subject; you can find them easily here: [email protected] Reference: Pinal Dave (http://blog.SQLAuthority.com) Filed under: Pinal Dave, SQL, SQL Authority, SQL Documentation, SQL Download, SQL Query, SQL Server, SQL Tips and Tricks, T SQL, Technology

    Read the article

1 2 3 4 5  | Next Page >