So CSS has these thing called pseudo-class selectors that can be used to, well, select specific elements in HTML. There are these ones called :first-child and :last-child, which I already knew about. You can use it to target styling for the first or last child of an element. Below I can target the first and last paragraphs in divs.
div p:first-child { ... } div p:last-child { ... }
What I didnāt know you could do, which I should have thought to try before (whoops!), was to not include a specific element before the pseudo-selector class. This way, I can apply styling to the first or last element without having to know the childās element type. The power of this is awesome.
div :first-child { ... } div :last-child { ... }
Could have saved me some headaches and lots of lines of CSS in the past if I had known, but oh well. I know now!
Anya is live and ready to show you everything. Watch her strip, dance, and perform exclusive shows just for you. Interact in real-time and make your fantasies come true.
ā Live Streamingā Interactive Chatā Private Showsā HD Quality
Anya is LIVE right now
FREE
Free to watch ⢠No registration required ⢠HD streaming
Recently Iāve been working with an application where I need to test and fix problems that occur when updating it with a newer version of jQuery from a much older version. Naturally, things broke and functionality wasnāt, well, functioning. Plus, old plugins.Ā
I ended up diving into a plugin to figure out what it was doing. Thatās when I stumbled on some code that looked strange to me. It looked something like this.Ā
$("#someID")[effectShow]();
Note that effectShow is a string that signifies what jQuery effect to use to show the element labeled with id āsomeIDā. The value of the string in this example will be āslideDownā. The jQuery UI library also has a function called slideDown() to display an element. I thought it was weird that this worked and didnāt give it much thought since that part of the code was still working.
But just a while later it hit me. The ā$ā makes a jQuery object that references the element with id ā someIDā. The slideDown() function is a property of a jQuery object when you have the jQuery UI library added. Since functions are just objects, and functions like slideDown() are properties of the jQuery objects, you can access the functions like you would any other property with bracket notation.
I was just used to seeing jQueryObject.function(). It never occurred to me that I could do this instead: jQueryObject["function"]().
Itās a good way to swap out what effect option to use. If the user of the plugin set the option for the effect as a string and that option is supposed to be the name of a jQuery effect, you can do this instead of using an if/else or switch statement to check the value of the string and then run the appropriate function.
On another note, making plugins isnāt as scary as I first thought. jQuery has some good documentation for jQuery plugins and how to make them. You can learn more about jQuery plugins here.
Side Note: Oh wow, itās been a while since I posted here. Sort of fell off the wagon on the 100 Days of Code challenge, but I promise Iāve still been learning! Iāve recently been employed and have been learning all sorts of things. Iām also taking an Intro to Design Principles course on Coursera. So Iām picking up where I left off on the challenge. I might not post everyday, but rest assured that this programmer is always learning something new.
A more in-depth look at the select clause. LINQ allows you to do data transformations on the source sequence via the select clause. You can perform the following tasks as well as combine these tasks to carry out data transformations that create new types for the elements of the output sequence.
All examples are taken from Microsoft Developer Network's Data Transformations with LINQ (C#) page.
1. Join Multiple Inputs into a Single Output Sequence
You can merge multiple input sequences into one output sequence. A new type will be created for the elements of the output sequence. Note that you can combine sequences of different formats as well, such as XML and SQL.
Example
The example below displays people who live in Seattle. The data is taken from two different in-memory data structures, one that holds a list of students and one that holds a list of teachers.
// Assume these two classes class Student { public string First { get; set; } public string Last { get; set; } public int ID { get; set; } public string Street { get; set; } public string City { get; set; } public List Scores; } class Teacher { public string First { get; set; } public string Last { get; set; } public int ID { get; set; } public string City { get; set; } }
class DataTransformations { static void Main() { // Create the first data source List students = new List() { new Student {First="Svetlana", Last="Omelchenko", ID=111, Street="123 Main Street", City="Seattle", Scores= new List {97, 92, 81, 60}}, new Student {First="Claire", Last="OāDonnell", ID=112, Street="124 Main Street", City="Redmond", Scores= new List {75, 84, 91, 39}}, new Student {First="Sven", Last="Mortensen", ID=113, Street="125 Main Street", City="Lake City", Scores= new List {88, 94, 65, 91}} }; // Create the second data source List teachers = new List() { new Teacher {First="Ann", Last="Beebe", ID=945, City = "Seattle"}, new Teacher {First="Alex", Last="Robinson", ID=956, City = "Redmond"}, new Teacher {First="Michiyo", Last="Sato", ID=972, City = "Tacoma"} }; // Create the query var peopleInSeattle = (from student in students where student.City == "Seattle" select student.Last) .Concat(from teacher in teachers where teacher.City == "Seattle" select teacher.Last); Console.WriteLine("The following students and teachers live in Seattle:"); // Execute the query. foreach (var person in peopleInSeattle) { Console.WriteLine(person); } Console.WriteLine("Press any key to exit."); Console.ReadKey(); } } /* Output: The following students and teachers live in Seattle: Omelchenko Beebe */
The two input sequences come from the data sources students and teachers. The Concat() method is used to combine the results of what could be two separate queries for finding people who live in Seattle. The new data type for the elements in the output sequence is merely a string, which is specified by the select clause. We selected students' last names and teachers' last names. Since these properties are both of type string, that is the type of the returned elements.
2. Select a Subset of each Source Element
You can create an output sequence where the elements will be of a new type that consists of one or more properties of the source sequence's elements. There are two primary ways to select a subset of properties from each element in the source sequence.
(1) Dot Operation
This method is used to select a single property. The type of the property will be the type of the returned elements.
Assume that the Customers data source holds Customer objects. Also assume that each Customer object has multiple public properties, one of them being City which is of type string. The returned elements will be of type string since we are selecting the City property.
var query = from cust in Customers select cust.City;
(2) Object Initializer
Use this method to create elements that contain one or more properties from each element of the source sequence. The object initalizer can be used with a named object or anonymous type.
The code below uses an object initializer to create a new type for the returned elements. The new type is an object with the string properties Name and City.
var query = from cust in Customers elect new {Name = cust.Name, City = cust.City};
3. Perform Operations on Source Elements
You can create an output sequence where it will be the result of operations performed on the source sequence elements. You don't need the type returned to be the same type or a subset of the properties of the elements in the source sequence.
Example
In the code below, the elements of the source sequence are used as inputs. They are the radii of circles. The operations performed on them are to calculate the area and turn the result into a string. This new string type is shaped in the select clause and becomes the type of the returned elements.
class FormatQuery { static void Main() { // Data source. double[] radii = { 1, 2, 3 }; // Query. IEnumerable query = from rad in radii select String.Format("Area = {0}", (rad * rad) * 3.14); // Query execution. foreach (string s in query) Console.WriteLine(s); // Keep the console open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); } } /* Output: Area = 3.14 Area = 12.56 Area = 28.26 */
Note: "Calling methods in query expressions is not supported if the query will be translated into some other domain" (MSDN). You can, however, map stored procedures to methods and call those instead of plain, old ordinary C# methods.
4. Transform Data into a New Format
You can create an output sequence that tranforms the source sequence data from one format into another. For example, you can go from SQL rows or text files to an XML format.
Example
The example below is a transformation of an in-memory data structure (a list of students) to XML.
class XMLTransform { static void Main() { // Create the data source by using a collection initializer. // The Student class was defined previously on this post List students = new List() { new Student {First="Svetlana", Last="Omelchenko", ID=111, Scores = new List{97, 92, 81, 60}}, new Student {First="Claire", Last="OāDonnell", ID=112, Scores = new List{75, 84, 91, 39}}, new Student {First="Sven", Last="Mortensen", ID=113, Scores = new List{88, 94, 65, 91}} }; // Create the query var studentsToXML = new XElement("Root", from student in students let x = String.Format("{0},{1},{2},{3}", student.Scores[0], student.Scores[1], student.Scores[2], student.Scores[3]) select new XElement("student", new XElement("First", student.First), new XElement("Last", student.Last), new XElement("Scores", x) ) // end "student" ); // end "Root" // Execute the query Console.WriteLine(studentsToXML); // Keep the console open in debug mode Console.WriteLine("Press any key to exit."); Console.ReadKey(); } } /* Output: <Root> <student> <First>Svetlana</First> <Last>Omelchenko</Last> <Scores>97,92,81,60</Scores> </student> <student> <First>Claire</First> <Last>O'Donnell</Last> <Scores>75,84,91,39</Scores> </student> <student> <First>Sven</First> <Last>Mortensen</Last> <Scores>88,94,65,91</Scores> </student> </Root> */
Notice how we create nested XElements and how they translate into the nesting in the output. Also, notice the use of the let keyword in the query. It creates a new range variable, x, and stores results from a sub expression, which will be used in another clause that's used for a student's scores.
Click to learn more about creating XML Trees in C#
Side Note: You can use the the output of a query as the input of another query.
You can use the where clause to choose which elements are included in the returned sequence. So long as the element causes the expression in the where clause to be true, it will be returned.
var queryLondonCustomers = from cust in customers where cust.City == "London" select cust;
The query goes through all the people in the customers data source and filters them via the city they live in. Only customers who are located in London are placed in the returned sequence.
You can apply the AND and OR operators to add additional filtering.
This expression returns customers who live in London AND have the name Devon.
where cust.City=="London" && cust.Name == "Devon"
This expression returns customers who live in London OR Paris.
where cust.City == "London" || cust.City == "Paris"
Ordering
You can sort the elements in the returned sequence via the orderby clause. The default comparer for the type being sorted is used.
By default, the elements are sorted in ascending order. You can explicitly specify this though. The code below sorts the customers by their names.
// Sort in ascending order var queryLondonCustomers = from cust in customers where cust.city == "London" orderby cust.Name select cust; // Sort in ascending order explicitly var queryLondonCustomers2 = from cust in customers where cust.city == "London" orderby cust.Name ascending select cust; // Sort in descending order var queryLondonCustomers3 = from cust in customers where cust.city == "London" orderby cust.Name descending select cust;
Grouping
You can use the group clause to group the elements returned based on a specified key. The code below returns all the customers, from the source data and groups them by the city they live in.
var queryCustomersByCity = from cust in customers group cust by cust.City;
When a query ends with a group clause, the returned sequence is a list of lists. Each element returned is an object that has a key member and a list of the elements grouped to that key. Because of this, iterating through the whole sequence requires nested looping. The outer loop will iterate through the different keys and the inner loop will iterate through all the elements grouped under the current key.
foreach (var customerGroup in queryCustomerByCity) { Console.WriteLine(customerGroup.Key); foreach (Customer customer in customerGroup) { Console.WriteLine(" {0}", customer.Name); } }
You can use the into keyword to create an identifier that "can serve as a reference to the results of a join, group or select clause". In the code below, we create an identifier named custGroup which serves as a reference for a sequence that groups customers by city. We can then use the reference in the where clause to filter out groups that do not have more than two customers. The groups are specified to be ordered by custGroup's key, which is the city, as specified in the group clause.
var custQuery = from cust in customers group cust by cust.City into custGroup where custGroup.Count() > 2 orderby custGroup.Key select custGroup;
Click to learn more about the group clause.
Joining
You can use the join clause to join two data sources together based on some matching criteria. Below, a join is performed to find all customers and distributors who are located in the same city.
namespace LINQJoinPractice { class Program { public class Customer { public string First { get; set; } public string Last { get; set; } public string City { get; set; } public int ID { get; set; } } public class Distributor { public string First { get; set; } public string Last { get; set; } public string City { get; set; } public int ID { get; set; } } static List customers = new List { new Customer { First="Daniel", Last="Johnson", ID=111, City="Austin" }, new Customer { First="Cory", Last="Coulson", ID=112, City="Chicago" } }; static List distributors = new List { new Distributor { First="Alex", Last="Jarvis", ID=211, City="Austin" }, new Distributor { First="Maggy", Last="Carter", ID=212, City="Chicago" }, new Distributor { First="William", Last="Rogers", ID=213, City="Austin" } }; static void Main(string[] args) { var innerJoinQuery = from cust in customers join dist in distributors on cust.City equals dist.City select new { CustomerName = cust.First, DistributorName = dist.First }; foreach (var x in innerJoinQuery) { StringBuilder sb = new StringBuilder(); sb.Append(x.CustomerName); sb.Append("\t"); sb.Append(x.DistributorName); Console.WriteLine(sb); } /* Output: * Daniel Alex * Daniel William * Cory Maggy */ } } }
Selecting
You can use the select clause to specify the type of the elements returned. You can shape the return type to be something like a customer object, a single property of a customer object like the customer's first name, a subset of properties, or even a new type all together.
Notice in the filtering example, we select a copy of the source element. The source elements are customer objects and the returned sequence's elements are customer objects.
If we do not select a copy of the source element, we call the operation a projection. The code example in the joining section does a projection. Notice that the select clause sets the type of the returned elements to be an anonymous type. The elements will be objects with the properties CustomerName and DistributorName.
Generic collections allow programmers to create instances of collections that are strongly-typed. They have an advantage over non-generic collections which store all their elements with the type Object. Since they are strongly-typed, you don't need to perform run-time type-casting and you'll get warned by compiler errors if you try using the wrong types. For example, if you try to add a Customer object into a List that has been strongly-typed to contain string elements, you will get an error.
When creating an instance of a generic collection class, merely replace the "T" between the angle brackets with the type of objects that you want the collection to hold. For example, if you want a list of strings, you replace the "T" in List<T> to List<string>.
Generic collection classes support IEnumerable<T>. IEnumerable<T> is an interface that enables generic collection classes to be enumerated via a foreach loop.
LINQ query variables are of type IEnumerable<T> or a derived typed such as IQueryable<T>. This just means that the result of a query will be an enumerable sequence that can have zero or more values.
Example
IEnumerable<Customer> customerQuery = from cust in customers where cust.City = "London" select cust; foreach (Customer customer in customerQuery) { Console.WriteLine(customer.LastName + ", " customer.FirstName); }
In the above code, the query variable customerQuery is of type IEnumerable<Customer>. This just means that since we select the range variable cust, the returned sequence will be a sequence of Customer objects.
You can let the compiler handle generic type declarations with the var keyword. The var keyword has the compiler infer the type of the query variable based on the data source specified in the from clause of the query. You can write the above query as the following and it will return the same result.
var customerQuery = from cust in customers where cust.City == "London" select cust; foreach(var customer in customerQuery) { Console.WriteLine(customer.LastName + ", " + customer.FirstName); }
Although the var keyword is useful, remember that is may make your code more difficult to read.
Anya is live and ready to show you everything. Watch her strip, dance, and perform exclusive shows just for you. Interact in real-time and make your fantasies come true.
ā Live Streamingā Interactive Chatā Private Showsā HD Quality
Anya is LIVE right now
FREE
Free to watch ⢠No registration required ⢠HD streaming
While going through the video series Pluralsight Building Applications with ASP.NET MVC 4, I realized I didn't really understand LINQ so I ended up going through the Microsoft Developer's Network's "Introduction to LINQ" and "Getting Started with LINQ in C#" sections listed here. The link also has more references to learning about LINQ in more depth, but I just wanted to get the basics down.
LINQ allows you to retrieve data from a variety of different data sources such as SQL databases, XML documents, etc. for your projects without having to learn each of their individual query languages. LINQ queries can be written for any collection of objects that support IEnumerable or the generic IEnumerable<T> interface. Note that when you create a query variable, when the program runs and reaches that line of code, the query does NOT execute. The query executes when the program reaches a line of code where the results of the query are used.
Three Parts of a Query Operation
Obtain the data source
Create the query variable
Execute the query
Example
class IntroToLINQ { static void Main() { // The Three Parts of a LINQ Query: // (1) Data source int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 }; // (2) Query creation/Query variable // numQuery is an IEnumerable<int> var numQuery = from num in numbers where (num % 2) == 0 select num; // (3) Query execution foreach (int num in numQuery) { Console.Write("{0} ", num); } } }
A query retrieves information from the data source. The query can sort, group, and even shape how the data is returned. For example, say you have a table of customers in a database which stores a customer's id number, first and last names, city they live in, and so on. You can write queries that return all the customer objects sorted in alphabetical order by their last names, or group the customers by the city they live in, or just return the id numbers of customers.
A query always starts with the from clause. This specifies the data source you're getting information from. The line from num in numbers specifies the data source as being the int array numbers. The variable num is referred to as a range variable, which represents each element in the source sequence (the data source).
The where clause is used to filter out elements from the source sequence. The code above only selects numbers which are divisible by two, so the result will be a sequence of even numbers.
The select clause specifies the type of the returned elements. In the above code, since numbers is an int array and the range variable num represents each element in that array, selecting num specifies the returned elements as having type int.
Remember that the query variable does not execute the query and it never holds the query results itself. You can think of the variable as storing the text for the query, which will be used to run the query at some later point in the program. In our example, that later point is the foreach loop, where the query results are retrieved. Inside the foreach loop, you loop through the returned sequence. The iteration variable num holds each value of the sequence, one at a time. Note that you can run the query again with the same query variable.
There are some queries that immediately execute. For example, queries that perform aggregation functions like Count, Max, and Average require iterating through the source sequence in order to return a result. So the query itself must perform a foreach. Note that these types of queries return a single value, not an IEnumerable collection. Below is an example of one such query.
var evenNumQuery = from num in numbers where (num % 2) == 0 select num; // Counts the number of even numbers int evenNumCount = evenNumQuery.Count();
You can also force immediate execution of a query and cache its results by using the ToList<TSource> or ToArray<TSource> methods.
List numQuery2 = (from num in numbers where (num % 2) == 0 select num).ToList(); // OR something like this // Note: numQuery3 is still an int[] var numQuery3 = (from num in numbers where (num % 2) == 0 select num).ToArray();
List of Links
MDN LINQ (Language-Integrated Query)
MDN Introduction to LINQ
MDN Getting Started with LINQ in C#
Pluralsight Building Applications with ASP.NET MVC 4
While working on a website, I needed to give a highlight effect to certain phrases of text. I thought it would be easy. Just wrap the text in a span. Then give it a class that adds some padding and a yellow background color. Done, right? Mission complete? Nope.
Problem
The problem I ran across is demonstrated below. When an inline box wraps around multiple lines, padding for the left is only preserved on the first line and padding on the right is only preserved on the right side of the last line. The rest of the text is pressed against the left and right edges with no padding.
Lorem ipsum dolor sit amet, sea ne choro accusam instructior. Consul sententiae vix an, nostrud dissentias ei sit, est phaedrum nominati ad. Cum cu soluta mediocrem, laboramus percipitur at has.
(HTML) <p> <span class="highlight"> Lorem ipsum dolor sit amet, sea ne choro accusam instructior. Consul sententiae vix an, nostrud dissentias ei sit, est phaedrum nominati ad. Cum cu soluta mediocrem, laboramus percipitur at has. </span> </p>
I ended up using "Fabien Doiron's box-shadow Method", a CSS only solution I found on CSS-Tricks. It uses the box-shadow property to give a padded look to the left and right sides of wrapped text via a shadow effect.
Lorem ipsum dolor sit amet, sea ne choro accusam instructior. Consul sententiae vix an, nostrud dissentias ei sit, est phaedrum nominati ad. Cum cu soluta mediocrem, laboramus percipitur at has.
(HTML) <p> <span class="highlight"> Lorem ipsum dolor sit amet, sea ne choro accusam instructior. Consul sententiae vix an, nostrud dissentias ei sit, est phaedrum nominati ad. Sum cu soluta mediocrem, laboramus percipitur at has. </span> </p>
The box-shadow property here adds two shadow effects. The first effect adds a shadow to the right side of the text on the x-axis. The second effect adds a shadow to the left side of the text via a negative x-axis offset. Both effects set the y-axis offset to zero, set the blur radius to zero to keep the shadow color sharp, and set the shadow's color to match the yellow highlight color.
I switched padding-left and padding-right for margin-left and margin-right since keeping the padding would add an extra 10px to the left and right of the 10px shadows.
The box-decoration-break property is used since the box-shadow method no longer works for FireFox. This is because box-decoration-break is set to split by default in FireFox. The box-decoration-break property defines how browsers handle the background, padding, border, border-radius, border-image, box-shdow, margin, and clip properties of the fragmented boxes created when inline boxes wrap. The value of clone tells the browser to render those properties independently for each box fragment. It essentially clones the properties specified for the element to its fragments when the element wraps. You can learn more about this property and its values from the links listed below.
Once you have a database set up, you can use LINQ (Language Intergrated Query) statements to query information from that database. The Entity Framework translates these statements into queries the database understands and then returns a result set from the server, but transforms the result set into objects you can use with C# code.
Two Different Styles of Queries
1. Comprehensive Query Syntax
This syntax style is similar to the structured query language in SQL Server.
Example
var query = from r in _db.Restaurants where r.Country == "USA" order by r.Name select r;
Unlike the structured query language in SQL, the select appears at the end of the statement rather than at the beginning. The query starts with a from keyword to specify where the data is coming from. r is the name of the range variable, which can be used for filterng, grouping, joining, and projecting. You can use similar keywords found in the structured query langauge like orderby and where to do that.
Note that projecting is for selecting a smaller set of data. For example, let's say you have a table for restaurants that stores the information about them like their names, locations, ratings, etc. You can use projection to just query for the restaurant names rather than the whole restaurant object.
2. Extension Method Syntax
This method uses extension methods and lambda expressions for querying. This method provides additional operators and options not available to you when using comprehensive query syntax. You can also define your own extension methods.
Above is an example of what is possible only when using extensive method syntax.
The .Skip(10) skips the first 10 results when returning the result set. We then use the .Take(10) to take the next 10 results following the skip. This can be used for pagination where you display the first ten results on the first page and the next ten results using this query for the the second page.
Configure Where the Entity Framework Creates a Database
Method 1
You can configure your database context with a database connection string. Do this by calling into the base class contructor and pass in a connection string that specifies the specific server, database, and credentials.
Note: You generally don't want to do it this way. Hard coding the connection string into the application requires you to change the code and recompile every time you want the application to point to a different database. You might be using multiple databases for an application such as one for development, one for deployment, and even one for testing.
// Models > OdeToFoodDb.cs using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; namespace OdeToFood.Models { // Connection string public OdeToFoodDb() : base("server=production;initial catalog=fooddb;integrated security=true") { } public class OdeToFoodDb : DbContext { public DBSet Restaurants { get; set; } public DBSet Reviews { get; set; } } }
Method 2
You can store connection strings in the Web.config file that exists in the root of the application. In OdeToFoodDb.cs, just use the name of the connection string you want to use instead of hard coding the value. This way, you don't need to recompile the application when you want to point to a different database. All you need to do is update the Web.config file.
Place the connection string between the opening and closing tags of connectionStrings in the Web.config file. Fill in the appropriate values for the connection string's attributes.
// Models > OdeToFoodDb.cs public OdeToFoodDb() : base("name=DefaultConnection") { }
You should be able to see the database in the Solution Explorer inside the App_Data folder. You may need to select the App_Data folder and then click the "Show All Files" icon in the Solution Explorer for it to display. It should end with the file extension *.mdf.
Configure How the Entity Framework Creates Your Schema
You can use the feature called Entity Framework Migrations. It allows you to configure the database schemas using C# code. It also allows you to initially populate some data into the databases, track changes that you make in your entity classes, and keep the database schema in sync with the changes you make in your C# code.
Get Started with Migrations
Open the Package Manager Console. It's essentially a PowerShell command line.
Method 1: View > Other Windows > Package Manager Console
Method 2: Use the Quick Launch Search Box on the top right.
Enable Migrations via the command line.
Type in: Enable-Migrations -ContextTypeName OdeToFoodDb
You need to specify the database context you want to enable Migrations for, which in this case is OdeToFoodDb.
A new folder called Migrations should appear inside the root directory of the project.
Configuration.cs
Inside the newly made Migrations folder is a Configuration.cs file and another file that's basically a schema change script. The Configuration.cs file is all about controlling Code First Migrations (how do you want it to perform, when should it run, etc.).
Example: Configuration.cs
// Migrations > Configuration.cs namespace OdeToFood.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationConfiguration { public Configuration() { AutomaticMigrationsEnabled = true; } protected override void Seed (OdeToFood.Models.OdeToFoodDb context) { context.Restaurants.AddOrUpdate( r => r.Name, new Restaurant { Name = "Sabatino's", City = "Baltimore", Country = "USA" }, new Restaurant { Name = "Great Lake", City = "Chicago", Country = "USA" }, new Restaurant { Name = "Smaka", City = "Gothenburg", Country = "Sweden", Reviews = new List { new RestaurantReview { Rating = 9, Body = "Great Food!" } } }); } // End Seed() } // End Class Configuration }
The AutomaticMigrationsEnabled property inside the Configuration.cs file is set to false by default. This means that the Entity Framework won't make any changes to your database unless you explicitly tell it to. It's a good idea to keep it set to false when you're working on a project that's more mature since you'll want to be more careful with the changes you make to the database. When you're intially starting out on a project, it's not a bad idea to set it to true to allow you to make changes and just have the database be ready for you when running the application.
The Seed() method is where you can tell the Entity Framework to populate the database with some initial data. It's good for populating tables that always need data such as a table that holds a list of postal codes or countries or for inserting and updating test data. The Seed() method executes when the database is first created and every time the database is updated (Migration updates). You usually run a database update when you want to migrate the schema.
You use the passed in argument of the Seed() method called context to insert data into the database. The property named Restaurants for the context object, refers to the Restaurants table. context.Restaurants walks up to the Restaurants DbSet on our OdeToFoodDb context.
The first parameter of the AddOrUpdate() method is what decides whether to add the following restaurant into the DbSet or update it with the following information. If the restaurant name already exists in the DbSet, it will update the restaurant's info, else it will add the row into the table. Use the AddOrUpdate() method so your information isn't duplicated every time the Seed() method runs.
How to Update the Database
You can configure an application to automatically apply updates or you can do it explicitly via the Package Manager Console. Type this command into the console: Update-Database -Verbose.
The command should output any changes made to your C# classes, which would require it to change the database. If no changes were made, it should output something like "No pending code-base migrations". It should also output "Running Seed method" so you know that the data specified in the Seed() method has been added to the database.
Sync the Database with Your Model on Database Updates
Example
Say you add want to add a property to a restaurant review such as the reviewer's name. First, just add the property in the RestaurantReview.cs class file in the Models folder and do a build.
// Models > RestaurantReview.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace OdeToFood.Models { public class RestaurantReview { public int Id { get; set; } public int Rating { get; set; } public string Body { get; set; } public int RestaurantId { get; set; } // Added property public string ReviewerName { get; set; } } }
Next you can do one of two things:
1. You can use the Package Manager Console to tell the Entity Framework that you need a Migration script to move the current database schema into a new database schema that can store ReviewerName.
2. You can let the Entity Framework figure out how to do it by just updating the database via the Package Manager Console. Refer to the "How to Update the Database" section on how to do that.
Note: You can only use the second method if AutomaticMigrationsEnabled is set to true in the Configuration.cs file.
Migration Script File
Remember that inside the Migrations folder is the Configuration.cs file and a Migration script file, which has a name that starts with a bunch of numbers. It would look something like this: "201210161548264_InitialCreate.cs". It's a schema change in C# code. It's not really a SQL script, but C# code that can generate SQL scripts.
The Entity Framework keeps track of which files have been applied to a database, which ones need to be applied and in what order to apply them in. This is done via a system table inside of your database called "_MigrationHistory".
Example
Below is an example of part of a Migration script file.
// Migrations > 201210161548264_InitialCreate.cs namespace OdeToFood.Migrations { using Systems; using Systems.Data.Entity.Migrations; public partial class InitialCreate: DbMigration { public override void Up() { CreateTable( "dbo.Restaurants", c => new { // (1) Id = c.Int(nullable: false, identity: true), Name = c.String(), City = c.String(), Country = c.String(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.RestaurantReviews", c => new { Id = c.Int(nullable: false, identity: true), Rating = c.Int(nullable: false), Body = c.String(), RestaurantId = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Restaurants", t => t.RestaurantId, cascadeDelete: true) // (2) .Index(t => t.RestaurantId); // (3) // (4) } ... } }
(1) Setting identity: true specifies that Id will be an identity column, which means in SQL Server, it will auto populate when you insert a new row.
(2) A foreign key is used to reference another table. In this case, the foreign key for a review in the RestaurantReviews table will link the review to a specific restaurant.
(3) An Index is applied to RestaurantId, because it will probably be important to query reviews when given a specific RestaurantId so we can find all the reviews for a given restaurant.
(4) You can run many types of commands inside the Up() function, which will run during a Migration. You can even run raw SQL statements via the Sql() method. Example: Sql("UPDATE ...");
Sometimes the fields generated inside the database are given types that we don't want. You can change this via data annotations.
Related Links
Code First Migrations and Deployment with the Entity Framework in an ASP.NET MVC Application
Just wanted to know how to center an image in Photoshop so I looked it up.
Note: Make sure the image you want to center has a transparent background and the size of its layer is the same as the background layer you want to center it on.
Inside the Layers panel, select the background layer and the layer for the image you want to center.
To align the image vertically (on the y-axis), in the top menu, click on:
Layers > Align Layers to Selection > Vertical Centers.
To align the image horizontally (on the x-axis), click on:
Layers > Align Layers to Selection > Horizontal Centers.
You can also align the image to the top or bottom edge of the background layer or even to the left or right edge. These options exist under the same Align Layers to Selection sub-menu used for vertical and horizontal centering. The options are called: Top Edges, Bottom Edges, Left Edges, and Right Edges.
Anya is live and ready to show you everything. Watch her strip, dance, and perform exclusive shows just for you. Interact in real-time and make your fantasies come true.
ā Live Streamingā Interactive Chatā Private Showsā HD Quality
Anya is LIVE right now
FREE
Free to watch ⢠No registration required ⢠HD streaming
The ADO.NET Entity Framework is part of the .NET Framework. It allows you access to a relational database using any .NET langauage. You can use the language feature called LINQ (Language Integrated Queries) to issues queries to the database.
Several relational databases are supported. You can use Oracle, a SQL Server installation on a remote server, Azure in the cloud, SQL Server Compact, or DB2. Your code doesn't need to know what's used on the back end since the Entity Framework knows how to work with them.
Note: You will already have a reference to the Entity Framework when you create an MVC application on Visual Studio.
Ways to Get Started with the Entity Framework
Schema First Approach
Open up a graphical designer in Visual Studio.
Point it to an existing database.
You can import the database schema and generate all the classes you need to query and update that database.
Model First Approach
Use a graphical designer like the Schema First Approach to draw a conceptual model for apps, which specifies what classes you want.
The Entity Framework will generate both your class definitions and database schema.
Code First Approach
Write C# classes.
The Entity Framework can use those class definitions to create a database for you. It will do this using naming conventions.
You can provide explicit mappings instead or even change the default mappings if you don't like the ones used by the Entity Framework.
Building Entities with Code First Approach
Entities are the objects you initiate and save into a database and retrieve from the database. You can place them in the Models folder. For larger applications, it might be a good idea to create a separate folder or even a separate project to define your entities in, or else your Models folder might get too big.
Example
Create the Entities
Below are the entites Restaurant and RestaurantReview, which are written as C# classes in the Models folder. A restaurant will have a collection of restaurant reviews.
// Models > Restaurant.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace OdeToFood.Models { public class Restaurant { public int Id { get; set;} public string Name { get; set;} public string Country { get; set;} public string City { get; set;} // Holds all reviews for the restaurant public ICollection Reviews { get; set;} } }
// Models > RestaurantReview.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace OdeToFood.Models { public class RestaurantReview { public int Id { get; set;} public int Rating { get; set;} public string Body { get; set;} // Points back to the restaurant the review is for public int RestaurantId { get; set;} } }
Below is the class that will use the Entity Framework to store and retrieve the restaurant and reviews data. You will want the class to inherit from the Entity Framework class DbContext. This will allow you to have properties with the type DbSet. Type DbSet allows you to represent the entities you want to store and query.
// Models > OdeToFoodDB.cs using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; namespace OdeToFood.Models { public class OdeToFoodDb : DbContext { // Will do something like a Select * on some // Restaurants table in your database public DBSet<Restaurant> Restaurants { get; set; } public DBSet<RestaurantReview> Reviews { get; set; } } }
Use the Entity Framework to Retrieve Information
You can use the OdeToFoodDb class to display restaurants on your home page. If you instantiate this class in a controller, because the class derives from DbContext, the the Entity Framework will go out and see if a database exists. If not, it will create one for you on a build.
// Controllers > HomeController.cs using OdeToFood.Models using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace OdeToFood.Controllers { // Instantiate OdeToFoodDb class OdeToFoodDb _db = new OdeToFoodDb(); public ActionResult Index() { // (1) var model = _db.Restaurants.ToList(); return View(model); } // (2) protected override void Dispose(bool string) { if(_db != null) { _db.Dispose(); } base.Dispose(disposing); } ... }
(1) The Entity Framework will go into SQL Server, find where it stored all the restaurants, retrieve all of them, and put them into a list. In the future, when there are more restaurants, you may need to provide some way to search for restaurants. You may also need to add paging if there are too many restaurants for one page.
(2) Since _db is a disposable resource, you should override the Dispose() method. The Dispose API in .NET is just a way to clean up resources that might be open. It's a good idea to call the Dispose method as soon as possible for anything that implements the IDisposable interface or has a Dispose method.
Location of the Created Database
Go to View > Database Explorer.
Right-click Data Connections > Add Connection...
Select the Data source and click Continue.
Fill in the Server name for the server you want to connect to.
Open the dropdown list for the Select a database name option. The name of the database created by the Entity Framework should match the name of the class that dervies from DbContext: OdeToFood.Models.OdeToFoodDb.
Select that database and click Ok.
A new connection should be listed under Data Connections in the Database Explorer. From there you can look at the properties of that database or even change them. Some properties include the database's tables, stored procedures, and functions.
You can insert data into the tables manually by right-clicking on a table name and clicking Show Table Data.
Display the Retrieved Information
Below is the code for the view associated with the home page. The view will loop through all the restaurants in the list and display the name of the restaurant and its location.
Partial views allow you to put HTML and C# code into a file that can be reused across multiple views or can be used to simply a view that has a complex model. It has all the same features as any other view.
Making a Partial View
1. Right-click on the folder of views you want the partial view to be accessible for and click Add > View. (Note that you can add the view to the Views/Shared folder for it to be available anywhere in the app for any view.)
2. Place an underscore at the front of the partial view's name to follow convention (ex. _Review).
3. Choose the Razor Engine option.
4. Create a strongly-typed view against the appropriate model class.
5. Choose any type of scaffold template such as Empty.
6. Choose the Create as a partial view option.
7. Place HTML and C# code in the partial view.
Using a Partial View Inside a View
Format: Note that the file extension is not needed.
@Html.Partial("_NameOfPartialView", "modelItNeedsToRender")
You can only pass in model data into Html.Partial() that is already available inside of the view you're using it in. You can pass in the model or a subset of the model.
Example
_Review.cshtml is a partial view used to display properties of a review. It is used inside Index.cshtml to simplify the view and output review information for each review in its model.
What if you want to display model information on every page of the application? The _Layout.cshtml view would be a good place to start, but that view is not tied to a particular model. You can use an HTML helper to solve this problem.
This HTML helper enables you to set up something like a sub request that can go out and call another controller action that builds its own model, independent of what the main controller is doing, and render a partial view wherever this method is called.
The output of the specified action method in the specified controller will be placed in the location of where the HTML helper is called. This method can be placed in the _Layout.cshtml view to display model information on all pages of the application.
Example
Below is an example of displaying the best review on every page. It uses the partial view, _Review.cshtml, from the previous example.
// (ReviewController.cs) ... public class ReviewsController : Controller { [ChildActionOnly] public ActionResult BestReview() { // Somehow find the best review var bestReview = ...; // Return a partial view return PartialView("_Review", bestReview); } }
Html is a property of the ViewPage base class. It provides many methods for generating small blocks of HTML such as links, forms, validation messages, inputs, etc. These HTML helper methods are available inside of views as views inherit the HTML property.
Below are some of the helper methods you can use.
Note: Any parameters surrounded by brackets "[ ]" are optional.
@Html.EditorFor(model => model.PropertyName)
Used to create input fields based on the type of PropertyName. If it's a string, it will create an input with type equal to text. If it is of type Boolean, it will create a checkbox input.
// If the PropertyName is named "Rating" and is a number <input class="text-box single-line" data-val="true" data-val-number="The field Rating must be a number." data-val-required="The Rating field is required." id="Rating" name="Rating" type="number" value="10" />
The data-* attributes provide data for client side validation. It sets the id and name attributes to match with the property names of the model.
Used to create links that perform a specific action on the current controller. You can pass in an anonymous object to pass in any extra information you might need to run the action.
Text:
The text of the link displayed on the view.
Action:
Name of the action on the current controller to invoke when the link is clicked.
Object (optional):
Contains any extra information you might need to complete the action
An example of it's use can be for editing a review.
@Html.ActionLink("Edit", "Edit", new { id = Item.Id })
// GET: /Review/Edit/5 public ActionResult Edit(int id){ // Somehow get the review via the id passed in var review = _review.Single(r => r.Id == id); // The review will be the model for our view return View(review); }
You will then need to create an Edit view. A quick way to do this is to right-click inside the Edit action method and select Add View. If you choose Edit as the Scaffold Template, it will create a view with a form that can be used to edit the values of the review object.
@Html.BeginForm()
Used to write out an opening form tag. You can pass in additonal parameters to change the action and method attributes of the form element. If you don't pass in any parameters, it will set the action for that form tag to go to the same URL you came from and has the form do a post back when the submit button is clicked.
<form action="/Reviews/Edit/3 method="post">
@Html.HiddenFor(model => model.PropertyName)
Used to create an input element with the type attribute set to hidden. It will store model.PropertyName in the form without letting the user edit the value.
Used to create labels, which are great for accessibility.
<label for="PropertyName">PropertyName</label>
Other HTML Helper Methods
You can see what other methods are available to you via Intellisense in Visual Studio or check out the link below.
https://msdn.microsoft.com/en-us/library/system.web.mvc.htmlhelper_methods(v=vs.118).aspx
You can also create your own custom helpers which can be useful for removing logic out of your view.
Side Note: TryUpdateModel() method
The TryUpdateModel() method goes through a process called model binding. It relies on the names of properties to match up data for what needs to be pushed into the model. Using the HTML helper method .EditorFor() creates inputs that automatically set the id and name attributes to match the model property names, which makes populating the model easier for updating.
The action method below runs when the user submits a form used to edit a review. If the the id and name properties of the inputs match the model property names, the TryUpdateModel() will update the review with the correct values for us.
// POST: /Reviews/Edit/5 [HttpPost] public ActionResult Edit(int id, FormCollection collection) { // Get the review you need to edit var review = _review.Single(r => r.Id == id); // Move values into the review if(TryUpdateModel(review)) { // Save the review into the database ... // Take the user somewhere after updating the review. return RedirectToAction("Index"); } // If TryUpdateModel() fails, return to edit the review return View(review); }
Layout views hold the common markup shared between views such as the Doctype and head tag. Layout views are typically not returned as a view result for controllers and by convention, like any other non-primary content view, their names begin with an underscore. By default, there is a _Layout.cshtml file inside the Views > Shared folder.
Two Special Methods
There are two special methods that layout views can use.
@RenderBody(): (Not Optional) Wherever this is placed in the layout view is where the content view will be inserted.
@RenderSection("sectionName", required:false): (Optional) You can have more than one of these in the layout view. "sectionName" can be anything you want. Since required is set to false, you can choose which views the section will show up in.
To have a section appear in a particular view, like say Index.cshtml, just add code like the one shown below anywhere in your content view.
// (Index.cshtml) @section featured { This is some featured content. }
It will be inserted wherever @RenderSection("featured", required:false) is placed in the _Layout.cshtml.
Specifying the Layout View
MVC knows which layout view to use as it is specified in a file called _ViewStart.cshtml inside the Views folder. Code inside this file will execute before your view starts rendering and sets the Layout property.
Since the _ViewStart.cshtml is in the root of the Views folder, it will apply to all views that are inside the Views folder. You can change which file to use by changing the path string assigned to the Layout property.
Changing the Layout View for Subfolders
You can specify a different layout file to use in subfolders of the Views folder. For example, say you have a subfolder called Reviews inside of Views. If you make another _ViewStart.cshtml file, assign a different path string for the Layout property, and place the file inside the Reviews folder, it will override the Layout property of the _ViewStart.cshtml inside the root of the Views folder. This layout view will apply to all the views inside the Reviews folder.
Changing the Layout View for a Single View
You can specify the layout file inside a particular view as well so it only applies to one view. To do this, you can set the Layout property at the top of the view.
The Razor View Engine allows us to use Razor templates to create views that are a combination of HTML and C# code. Razor templates use the .cshtml file extension. HTML is written normally, but to integrate C# code you need to use code expressions or code blocks, which will be explained later in this blog post.
A quick way to add a new view for an action inside a controller is to right click inside that action method and choose Add View. A window will pop up where you can customize the view you're creating. Remember to pick Razor as the view engine type.
You have the option to "Create a strongly-typed view", which allows you to choose the type of model object you'll be passing into the view. By specifying the type, the created view will add the appropriate directive for the model for you. Also, if you check this option, you can select a scaffold template to create a basic UI for displaying properties of the model object.
Note: Razor will automatically HTML encode data sent to the view to help prevent cross site scripting (xss) attacks.
Code Expressions
Code expressions can be used in Razor views to pull out data from your model or contain expressions for Razor to evaluate and then display as text. The "@" symbol is used to indicate a code expression.
If your model is enumerable, a couple methods are available to you.
<!-- The model is a list of restaurant reviews --> @model IEnumerable <!-- .First() gives you the first review in the list --> <p>Name of the first reviewer: @Model.First().Name</p> <!-- .Last() give you the last review in the list --> <p>Rating from the last review: @Model.Last().Rating</p> <!-- .Count() returns the number of reviews in the list --> <p>Number of reviews for the restaurant: @Model.Count()</p>
Note: You can add comments to .cshtml files, which will not be visible in the output html file by placing the comment between "@*" and "*@".
@* Commented out code *@
Implicit vs Explicit C# Code Expressions
When using implicit C# code, we let Razor figure out what is C# code and what is markup. Razor is able to parse the line of code below correctly.
<p>The number is @item.Number</p>
But what if you wanted to divide the number by 10? Doing the code below will display "/ 10" as text and not include it in the C# expression for evaluation.
<span>@item.Number / 10</span>
This is where explicit C# code expressions are useful. Simply wrap the entire expression in parentheses after the "@" symbol as seen below. Now the @item.Number is divided by 10 and then displayed.
<span>The number divided by 10 is @(item.Number / 10)</span>
Razor is generally good at differentiating between C# code and markup, but there are a couple gotchas. Below are some of the common ones.
If you want to add the "@" symbol as text before some text, such as a twitter handle, you will need to escape the "@" sign via another "@" symbol. This way, it doesn't think the twitter handle is C# code that needs to be evaluated.
<p>Twitter Handle: @@TwitterName</p>
Another gotcha is when you use want to append some text, such as the letter 'R' to a rating score stored in a model property. You want it to display something like "R5". The below code will NOT work.
<span>Incorrect: [email protected]</span>
It will assume "@item.Rating" is text. This assumption is default so it is easier to display email addresses which follow the format of something@something. To get around this, just use explicit C# expressions.
<span>Correct: R@(Item.Rating)</span>
Tidbit: The @VirtualPath property is inherited by views and can be used to display the virtual path of the view.
Code Blocks
You can make C# code blocks in .cshtml files to write multiple lines of consecutive C# code. Code blocks allow you to do the same things you can do in .cs files. You can change properties of the ViewBag and even declare variables, which can be used anywhere in the .cshtml file after the variable declaration.
@ { ViewBag.Title = "New Title"; int num = 5; }
For each statements work a little differently to make it easier to read, write, and transition between C# code and markup. We can use the for each statement to iterate through a list of items in a model and display their properties one by one. Razor is smart enough to differentiate between C# and the table markup so we can write code like the example below.
To solve this problem, you can indicate that "Review" is literal text by adding "@:" before it as shown below.
@:Review
Reminder: Try to keep the view simple. Usually having a lot of C# code in the View is a bad sign. Try to keep most of the heavy lifting and logic inside the Models and Controllers.
Anya is live and ready to show you everything. Watch her strip, dance, and perform exclusive shows just for you. Interact in real-time and make your fantasies come true.
ā Live Streamingā Interactive Chatā Private Showsā HD Quality
Anya is LIVE right now
FREE
Free to watch ⢠No registration required ⢠HD streaming
A sticky footer is a footer that displays at the bottom of the screen when thereās not enough content above it. That way, thereās not a bunch of empty space below your footer. When there is enough content, the footer gets pushed down as it should normally and youāll need to scroll to get to it.
Thereās a number of ways to implement a sticky footer. The first I found required knowing the height of the footer. The problem with this method is that for responsive designs that lead to a changing footer height, you would need to add multiple media queries to adjust the css.
The second way I found used the table value for the display property. Unlike the first method, you donāt need to known the height of the footer. This way, if the height changes from adding or removing content to it, you donāt need to redo the height values for the media queries. This is the one Iām using for my current project.
Day 11 of 100: Photoshop Color Replacement and Stock Images
Iām working on a new project for my volunteer work. Itās a responsive website and I feel more confident this time around since I learned a lot from the last big project. But that doesnāt mean there isnāt anything new to learn.Ā
I recently discovered http://pixabay.com/,Ā a resource for stock images, which I heard about during a one day WordPress basics workshop. Itās got a nice selection and lists the licensing for each image. The best part is that several images have CC0 licensing, which means theyāre in the public domain and you can do whatever you want with them, even use them for commercial purposes.
I found an image from pixabay, but needed to replace the green in the image to a blue to match the siteās color scheme. I used Photoshopās color replacement tool in a way that worked, but was time consuming. I figured there was probably a better way to do it, which led me to the Youtube video linked below by Roberto Blake. The video gives two methods for color replacement. Below are my notes for the video.
Photoshop Color Replacement Tool | Photoshop CC Tutorial
https://www.youtube.com/watch?v=4vq8vznq59Q
Method 1: Color Replacement Tool
This method is good for quick and general purpose use. However, it does change the pixels on the image.
Click on Image > Adjustments > Replace Color
A window should pop up and the cursor should turn into the eyedropper tool. Use it to select the color in the image you want to replace. If you want to select multiple colors to replace, hold the shift key and click on the colors.
In the window, there is a smaller image of the one you're working on that's in black and white. Anything in white is your color selection and anything in black is not. You can subtract colors from the selection with the alt key.
Once that's done, use the hue, saturation, and lightness sliders to adjust the color. That's it.
Method 2: Adjustment Layer
Unlike the first method, this one does not alter the original image. It just adds a layer over it which you can adjust to turn off the effect or easily change the color whenever you want without having to reselect eveything.
First use any selection tool to select the parts of the image where you want to adjust the color. Then, add a Hue/Saturation adjustment layer. From there, use the sliders to adjust the hue, saturation, and lightness.