Sponsors

Thứ Bảy, 14 tháng 9, 2013

Jquery set HTML attributes CSS classes and HTML form values and element content and data

# 2- Element Get and Set-

How to set HTML attributes: CSS styles and classes,  HTML form values, and element content and data

Some of the simplest and most common operations on jQuery objects are to get or set the value of HTML attributes, CSS styles, element content here we learn those methods.


#2.1 -  Get and Set HTML Attributies:

The attr() method is the jQuery getter/setter for HTML attributes,
$("#BannerImg").attr("src", "icon.gif");     // Set the src attribute of element with id banner
$("a").attr("target", "_blank");   // Make all links load in new windows
$("#banner").attr({src:"banner.gif",          // Set 4 attributes at once
alt:"Advertisement",
width:720,
height:64});

The  attr() is jQuery’s master attribute-setting function, and you can use it to set things other than normal HTML attributes. If you use the attr() method to set an attribute named “css”, “val”, “html”, “text”, “data”, “width”, “height”, or “offset”, jQuery invokes the method that has the same name as that attribute and passes whatever value you specified as the argument.

For example, calling attr ("css", {backgroundColor:"gray"}) is the same as calling css({backgroundColor:"gray"}) .  
We’ll learn about css(), val(), html(), and other methods in later article.


#2.2 -  Get and Set CSS Attributies:

The  css() method is very much like the attr() method, but it works only with the CSS styles of an element ie sets or returns one or more style properties for the selected elements.
Sample Code:

$("h3").css("font-weight"); // Get font weight of 1st <h3>
$("h3").css("fontWeight"); // Camel case works, too
$("h3").css("font"); // ERROR: can't query compound style

$("h3").css("font-variant","smallcaps"); // Set style on all <h1> tags 

Thứ Sáu, 6 tháng 9, 2013

Learn jQuery in 11 Days

Learn jQuery in 11 Days


Hi, my name is Satinder Singh .  Here’s the tutorial “  Learn JQuery in 11 days “If you promise to give me thirty minitues a day, for an eleven day regularly , then I promise that you’ll come out the other side as a jQuery pro .

Introduction:  JQuery is the “write less, do more” JavaScript Library.   Its powerfull features and ease of use have made it the most popular client-side JavaScript framework for the Web.

JQuery makes developer life easy,  because using JQuery is easy to find the elements of a document, and then manipulate those elements by adding content, editing HTML attributes and CSS properties,  defining event handlersm and performing animations. It also has Ajax utilities for dynamically making  HTTP requests, and general-purpose utility functions for working with objects and arrays.

  1. Jquery Basic
  2. Element Set and get
  3. Altering document structure
  4. Events
  5. Effect Animation
  6. Ajax
  7. Utility funtions
  8. Selectors and selection method

#1- Basic of JQuery-

First you have to add Jquery to your web page .i.e HTML page.

Download jQuery from jQuery.com The jQuery Library is a single JavaScript file, and you reference it with the HTML <script> tag and that script tag should be inside the <head> tag.

CODE:


<head>
<script src="jquery-1.10.2.min.js"></script>
</head>


Or alternative to  downloading  you can include it from CDN .  I use google libraries Click Here .

CODE:


<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>

The Jquery Library Defines a single global function named JQuery(). This function is so Frequently used that the library also defines the global symbol $ as a shortcut for it.
The jQuery() function (a.k.a. $()) is the most important one in the jQuery library. When you pass a jQuery selector string to $(), it returns a jQuery object that represents the set of matched (or “selected”) elements. jQuery selectors are very much like the CSS selectors you use in stylesheets.


For example:
div // all <div> elements
#content // the element with id="content"
.warning // all elements with class="warning"


Live Demo

Explanation:

First we write this piece of code, which ensure that the document is ready for manipuulation. ie it prevent any jQuery code running before the document is finished loading.


$( document ).ready(function() {
   // Your code logic here.
 });

Example 1:  Display hello world alert message on click of a div
$(document).ready(function(){
$("#btnhelloworld").click(function(){
alert("Hello world!");
});
});

Example 2 : Change background-color of a element
$(document).ready(function(){
$("#btnchangebgColor").click(function(){
$("#content").css("background-color","#BDEA74");
});
});

Complete Code:
<html>
 <title>Learn JQuery in 11 days with satinder singh</title>
<head>
<style type="text/css">
#content{
  position:absolute;width:900px;height:600px;}

#btnhelloworld{
  border-radius: 2px;  cursor:pointer;  background: none repeat scroll 0 0 #FF5454;
  color: #FFFFFF;font-size: 17.5px; padding: 5px 10px;
  width:100px; float:left; margin-right:10px; border: 1px solid red ;}


#btnchangebgColor  { border-radius: 2px;cursor:pointer; background: none repeat scroll 0 0 #78CD51;   color: #FFFFFF; font-size: 17.5px; padding: 5px 10px; width:190px;  float:left;  margin-right:10px; border: 1px solid green;}
#btnchangebgColortowhite  { 
border-radius: 2px; cursor:pointer;   background: none repeat scroll 0 0 #67C2EF;
color: #FFFFFF; font-size: 17.5px;
padding: 5px 10px; width:130px; 
float:left;  margin-right:10px;
border: 1px solid green;}
</style>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
   $("#btnhelloworld").click(function(){
     alert("Hello world!");
  });

    $("#btnchangebgColor").click(function(){
     $("#content").css("background-color","#BDEA74");
  });

    $("#btnchangebgColortowhite").click(function(){
     $("#content").css("background-color","#fff");
});
});
</script>
</head>
<body>
  <div id="content">
    <div id="btnhelloworld"> Click for alert  </div>
     <div id="btnchangebgColor"> Change BG color to green</div>
    <div id="btnchangebgColortowhite"> Change to white </div>
     </div>
</body>
</html>

Chủ Nhật, 1 tháng 9, 2013

C# MongoDB Repository Implementation

I recently started a small project with a friend and we opted for MongoDB as our data store. One of the initial tasks was to write a repository class that allowed us to store, retrieve, update and search for entities in MongoDB. In the past, I've worked on codebases where there was one repository per entity, it didn't take long to discover that this resulted in a lot of code duplication across the data layer. So the goal here was to write the repository generically enough so that we only have one implementation that can be reused for any entity within our application. This meant that each entity would have its own MongoDB collection (if you're not familiar with MongoDB, a collection can be thought of as a table in the relational world - see this page for a comparison).

One of the first steps in this task was to write an interface for the repository - this is in case we decide to use a different data store in the future. A while back, I found a repository interface on the Redmondo blog which covers everything I'd want from a repository, so we'll use a slightly modified version of that interface (I've removed comments for brevity, you can download the code using a link further below and that'll contain the comments):
public interface IRepository<TEntity> where TEntity : EntityBase
{
    bool Insert(TEntity entity);
    bool Update(TEntity entity);
    bool Delete(TEntity entity);
    IList<TEntity> 
        SearchFor(Expression<Func<TEntity, bool>> predicate);
    IList<TEntity> GetAll();
    TEntity GetById(Guid id);
}
To paraphrase the code, this is a generic repository interface for an entity of type TEntity that must derive from a base class called EntityBase. The EntityBase class is a very simple abstract class and contains just one property, the identifier property:
/// <summary>
/// A non-instantiable base entity which defines 
/// members available across all entities.
/// </summary>
public abstract class EntityBase
{
    public Guid Id { get; set; }
}
The idea is for any entity that we want to manage in our data store, that entity must derive from EntityBase. So the infrastructure is all in place for our "MongoDbRepository". I used the official 10gen MongoDB C# driver (available as a NuGet package) and arrived at the following repository implementation:
/// <summary>
/// A MongoDB repository. Maps to a collection with the same name
/// as type TEntity.
/// </summary>
/// <typeparam name="T">Entity type for this repository</typeparam>
public class MongoDbRepository<TEntity> : 
    IRepository<TEntity> where 
        TEntity : EntityBase
{
    private MongoDatabase database;
    private MongoCollection<TEntity> collection;

    public MongoDbRepository()
    {
        GetDatabase();
        GetCollection();
    }

    public bool Insert(TEntity entity)
    {
        entity.Id = Guid.NewGuid();
        return collection.Insert(entity).Ok;
    }

    public bool Update(TEntity entity)
    {
        if (entity.Id == null)
            return Insert(entity);
        
        return collection
            .Save(entity)
                .DocumentsAffected > 0;
    }

    public bool Delete(TEntity entity)
    {
        return collection
            .Remove(Query.EQ("_id", entity.Id))
                .DocumentsAffected > 0;
    }

    public IList<TEntity> 
        SearchFor(Expression<Func<TEntity, bool>> predicate)
    {
        return collection
            .AsQueryable<TEntity>()
                .Where(predicate.Compile())
                    .ToList();
    }

    public IList<TEntity> GetAll()
    {
        return collection.FindAllAs<TEntity>().ToList();
    }

    public TEntity GetById(Guid id)
    {
        return collection.FindOneByIdAs<TEntity>(id);
    }

    #region Private Helper Methods
    private void GetDatabase()
    {
        var client = new MongoClient(GetConnectionString());
        var server = client.GetServer();

        database = server.GetDatabase(GetDatabaseName());
    }

    private string GetConnectionString()
    {
        return ConfigurationManager
            .AppSettings
                .Get("MongoDbConnectionString")
                    .Replace("{DB_NAME}", GetDatabaseName());
    }

    private string GetDatabaseName()
    {
        return ConfigurationManager
            .AppSettings
                .Get("MongoDbDatabaseName");
    }

    private void GetCollection()
    {
        collection = database
            .GetCollection<TEntity>(typeof(TEntity).Name);
    }
    #endregion
}
In case you're interested, a while ago I wrote a separate blog post on how to perform CRUD operations against MongoDB using the C# driver. To use the repository implementation, you'll need two application configuration settings defined - one that stores the name of the MongoDB database and the other that contains the MongoDB connection string (with a placeholder for the database name). You should have something like:
<appSettings>
  <add key="MongoDbDatabaseName" value="MyCarsDatabase" />
  <add key="MongoDbConnectionString" 
         value="mongodb://localhost/{DB_NAME}?safe=true" />
</appSettings>
Hopefully this repository is useful to someone else who is working with MongoDB in C#. Any questions or suggestions for improvements are always welcome via comments. You can download a console project from here which shows how to use the repository.