Sponsors

Thứ Sáu, 11 tháng 10, 2013

The ExpandoObject Stringified

I had a requirement to output some data as part of a number of pages in an e-commerce site. This data would change from page to page and typically get richer as a user would go through an order path in the application. The data needed to be in JSON format and was going to be used by the marketing guys to help track information about user behaviour across the order process. The data was also subject to change regularly depending on what the marketing team wanted to track. In short, I had to construct a JSON string on the server side in C#.

I had seen something like this done before where a StringBuilder was used to construct a large JSON string which was then pushed out in the response with the rest of the page markup. This approach seemed messy and difficult to maintain. I did a bit of research on some approaches to constructing a potentially complex and changing JSON object using C# and came across the ExpandoObject class. MSDN has a nice succinct explanation of ExpandoObject:
"Represents an object whose members can be dynamically added and removed at run time."
You can find this class in .NET 4 in the System.Dynamic namespace. ExpandoObject lets you effectively "model" an object on the fly with properties that don't really exist (just like using the ViewBag in ASP.NET MVC). In my case, it saved me from writing a number of classes or complex strings just to hold data that was to be output in page responses. Instead, I could use ExpandoObject and then use a JSON serializer to stringify the object.

The example below shows how easy and flexible it is to use ExpandoObject with the Newtonsoft .NET JSON library (available as a NuGet package):
dynamic orderInfo = new ExpandoObject();

orderInfo.OrderDate = DateTime.Today;

orderInfo.ProductTypesAdded = new List<dynamic>();
orderInfo.ProductTypesAdded.Add("Radio");
orderInfo.ProductTypesAdded.Add("Television");
orderInfo.ProductTypesAdded.Add("Recorder");

orderInfo.ReachedCheckout = true;
orderInfo.PaymentMethod = "Card";
            
orderInfo.DeliveryInfo = new ExpandoObject();
orderInfo.DeliveryInfo.Method = "First";
orderInfo.DeliveryInfo.Country = "UK";

var json = JsonConvert.SerializeObject(orderInfo);
The resulting JSON is:
{
    "OrderDate":"2013-10-11T00:00:00+01:00",
    "ProductTypesAdded":[
        "Radio",
        "Television",
        "Recorder"
    ],
    "ReachedCheckout":true,
    "PaymentMethod":"Card",
    "DeliveryInfo":{
        "Method":"First",
        "Country":"UK"
    }
}

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.

Thứ Năm, 29 tháng 8, 2013

CRM Blog World Updated

One of the most viewed pages on my blog is still the Blog World. When Dynamics CRM wasn't called Dynamics CRM yet, I have started to gather a list of blogs which targeted this software. Over the years this list has grown and I have just updated the list with the blogs which I have been requested to add. I guess soon I'll need to do a full review of this list as I've noticed that some people have

Thứ Năm, 8 tháng 8, 2013

Project Euler

I came across the Project Euler site the other day. If you enjoy solving mathematical/programming problems then I recommend this site. You're given a number of problems to solve with each problem in the series getting progressively more difficult. If you sign up, you can submit your answer and if your answer is correct then you'll get access to the message boards for the problem you worked on. The problem message boards are where you can share your solution and see solutions by other people who may have used a different programming language. It's interesting to see the C# solutions compared to the solutions in other languages. Worth a look if you have time!

Chủ Nhật, 28 tháng 7, 2013

Implicit/Explicit Conversion Operators

I saw some code yesterday which at first glance looked odd. A method was accepting a parameter of a custom type named Money and the calling code was passing in a double value. After a bit of confusion I recalled that the C# language natively supports conversion operators.

If you have a custom type, you have the option to define conversion operators on your type which let you convert from your custom type to a target type and from the target type back to the custom type. Conversion can be implicit or explicit. Implicit conversion means that users of your custom type can convert to the target type without having to perform a type cast operation. Explicit conversion forces a type cast to be performed.

To demonstrate this, we'll use the case I came across. Imagine we have a Money class which is composed of a currency and a value that the money represents. We may initially decide that we want the Money class to be flexible so that users of the class can treat it is a value (a double type in this case). This means that when a double is expected (e.g. as an argument to a method), the user of the class can pass the Money instance which will implicitly be converted to its value form. Moreover, we can also make the conversion from double to Money implicit, meaning that whenever a Money instance is expected, we can pass in a double. Our initial attempt at the Money class implementation would therefore look something like:
public class Money
{
    public string Currency { get; set; }
    public double Value { get; set; }

    // Implicit conversion from Money to double
    public static implicit operator double(Money money)
    {
        return money.Value;
    }

    //  Implicit conversion from double to Money
    public static implicit operator Money(double @double)
    {
        return new Money { Value = @double };
    }
}
With the above class, the following code would therefore compile:
var money = new Money() { Currency = "GBP", Value = 10.5 };
            
// Implicitly convert Money to a double
double moneyValue = money;

// Convert a double to Money (Money.Currency will be null!)
Money moneyInstance = moneyValue;
Notice that when converting a Money instance to a double, we would lose information on the Money instance (the currency in this case). Also, when converting a double to a Money, the currency is never set. It would therefore make more sense in this scenario to use explicit conversion operators so that the user is forced to be aware that they could lose information in the conversion or have a partially initialised Money instance (it isn't a straight-forward conversion). To define explicit conversion on the Money class, the only change required would be to replace the "implicit" keyword with the "explicit" keyword on the two conversion methods. The Money class would now look like:
public class Money
{
    public string Currency { get; set; }
    public double Value { get; set; }

    // Explicit conversion from Money to double
    public static explicit operator double(Money money)
    {
        return money.Value;
    }

    //  Explicit conversion from double to Money
    public static explicit operator Money(double @double)
    {
        return new Money { Value = @double };
    }
}
After making this change, the example calling code above would fail to compile with the following two compile-time error messages:

Cannot implicitly convert type 'ConversionOperators.Money' to 'double'. An explicit conversion exists (are you missing a cast?)
Cannot implicitly convert type 'double' to 'ConversionOperators.Money'. An explicit conversion exists (are you missing a cast?)

As the errors point out, we now need to explicitly cast between the types - as demonstrated in the code below.
var money = new Money() { Currency = "GBP", Value = 10.5 };
            
double moneyValue = (double) money;

Money moneyInstance = (Money) moneyValue;

You can download the example code by clicking here.