WCF Data Services (formerly ADO.NET Data Services,) is a platform for what Microsoft calls Data Services.
It is actually a combination of the runtime and a web service through which the services are exposed.
WCF Data Services exposes data, represented as Entity Data Model (EDM) objects, via web services accessed over HTTP.
The data can be addressed using a REST-like URI. The data service, when accessed via the HTTP GET method with such a URI,
will return the data. The web service can be configured to return the data in either plain XML, JSON or RDF+XML.
In the initial release, formats like RSS and ATOM are not supported, though they may be in the future. In addition,
using other HTTP methods like PUT, POST or DELETE, the data can be updated as well. POST can be used to create new entities,
PUT for updating an entity, and DELETE for deleting an entity.
Create ASP.NET application to expose data as OData
I will be walking you through creating an ASP.NET application that
utilizes a WCF (Windows Communication Foundation) data service, along
with the WCF Data Services Entity Framework Provider to render the data
as an OData endpoint.
In this article, I will be using Visual Studio 2015 Community
version, which you can download for free by going to
this link and clicking the Download button under
Visual Studio Community.
You will create a sample data service that uses WCF
Data Services to expose an Open Data Protocol (OData) feed that is
based on the FaithDb sample database. The task involves the
following basic steps:
Create an ASP.NET Web application.
Define the data model by using the Entity Data Model tools.
Add the data service to the Web application.
Enable access to the data service.
Create an ASP.NET Web application.
Once you have, open it up and create an ASP.NET Web Application using
the Visual C# empty template. Name the project
Faith.FaithDataService and save it somewhere on your local drive
(see image below).
To define the data model
In Solution Explorer, right-click the
name of the ASP.NET project, and then click Add New
Item.
For the name of the data model, type
ArticleModel.edmx.
In the Entity Data Model Wizard, select Generate
from Database, and then click Next
Connect the data model to the database by doing one of
the following steps, and then click Next:
If you do not have a database connection already
configured, click New Connection and
create a new connection.
If you have a database connection already configured
to connect to the FaithDbdatabase, select that
connection from the list of connections.
On the final page of the wizard, select the check boxes
for all tables in the database, and clear the check boxes
for views and stored procedures.
Click Finish to close the wizard.
To create the data service
In Solution Explorer, right-click the
name of your ASP.NET project, and then click Add New
Item.
In the Add New Item dialog box, select
WCF Data Service.For the name of the service, type OurDataService.By
default, the code-editor window opens. In Solution Explorer,
the service will have the name, OurDataService,
with the extension .svc.cs or .svc.vb
In the code for the data service, replace the comment
/* TODO: put your data source class name
here */ in the definition of the class that defines
the data service with the type that is the entity container
of the data model, which in this case is
NorthwindEntities. The class definition should look
this the following:
IMPORTANT POINT:Incase you are using entity framework 6 you need to install WCF Data service Entity Framework Provider like shown below
Replace the base type of your DataService. For EF 5 or below, your data service
should inherit from DataService<T> where T is a DbContext or ObjectContext.
For EF 6 or greater, your data service should inherit from EntityFrameworkDataService<T>
where T is a DbContext like shown below
To enable access to data service resources
In the code for the data service, replace the placeholder
code in the InitializeService
function with the following:
This enables authorized clients to have read and write
access to all resources .You can set it for the specified entity sets
also.
Next & Final Steps
You have successfully created a new data service that exposes
an OData feed that is based on the FaithDbsample database,
and you have enabled access to the feed for clients that have
permissions on the ASP.NET Web application. Next, you will start
the data service from Visual Studio and you will access the
OData feed by submitting HTTP GET requests through a Web
browser:
Run Asp.net Application and Set OurDataService.srv as startup
Page or directly view ourservice.srv in browser The output will be shown like shown below
if you will observe It is showing list of tables from database
or list of entities Model is made of.
In this article, we are going to walk through how to create and deploy your Windows AZURE Cloud Service.
It also provides a good introduction on how to quickly create and
set up your Windows AZURE Cloud Service for deployment.
Cloud Computing
The
"cloud" in cloud computing can be defined as the set of hardware,
networks, storage, services, and interfaces (I.T Infrastructure) that
combine to deliver aspects of computing as a service. Cloud services can
be software, infrastructure, and storage over the Internet (either as
separate components or a complete platform) based on user demand.
It
can also be defined next stage in the Internets evolution, providing
the means by which everything — from computing power to computing
infrastructure,
applications and business processes can be
delivered to you as a service wherever and whenever you need and will be
charged on basis of usage like we use electricity and pay on basis of
monthly usage..
Some businesses, such as Google and Amazon, already have most of their
IT resources in the cloud. They have found that it can eliminate many of
the complex constraints from the traditional computing environment,
including space, time, power, and cost.
Now coming to Microsoft they have also setup cloud computing for their customers known as AZURE.
AZURE
Microsoft way of cloud computing :) Windows Azure is Microsoft's application platform for the public cloud.
You can use this platform in many different ways. For instance, you can
use Windows Azure to build a web application that runs and stores its
data in Windows Azure data centers. You can use Windows Azure just to
store data, with the applications that use this data running on-premises
(that is, outside the public cloud). You can use Windows Azure to
create virtual machines for development and test or to run SharePoint
and other applications. You can use Windows Azure to build massively
scalable applications with lots and lots of users. Because the platform
offers a wide range of services, all of these things-and more-are
possible.
Develop,Build and Deploy your windows AZURE Cloud Service in Steps
If you already have an account, connect by clicking on PORTAL
STEP2: CREATE A SERVICE CLOUD
Click on CLOUD SERVICE tab and Click New (+ New)
Here it is possible to create a Quick Cloud Service and configure it again later or create a custom cloud service by chosing configuration.
So lets create a Quick Cloud Service and fill parameters such as URL, REGION OR AFFINITY GROUP , SUBSCRIPTION. Next click on link Create Cloud Service
Service created screen
Our Cloud Service is now created Quickly or Customized, lets get Azure SDK Tools so as to code our service logic.
Click on OurCustomersService and click on link install a Windows AZURE SDK, and our Visual Studio Version and Install it.
STEP 3: CREATE A CLOUD SERVICE PROJECT
Here we are going to create a WCF Service and deploy it on our cloud Service.
So, create a new Project ,chose Windows Azure Cloud Service template and WCF Service Web Role.
A web role provides an environment for running web sites or applications as supported by Internet Information Services (IIS) 7.0
WCF web Service (OurCustomersService.svc) looks like as shown below:
To test this service locally first just create console application ,windows or web what ever you are comfort with .just fallow below steps
I will create windows console application to test this service
OUTPUT FROM THIS SERVICE IS:-
Now Deployment
STEP 4 : DEPLOY A CLOUD SERVICE PROJECT
To deploy our Cloud Service, we have to Create a Package : chose our
Service Configuration and Build Configuration and note the output
directory or remove files to our custom directory.
Next , Go back again to our Portal, click on OurCustomersService, and click on link New production deployment
Next chose a deployment name and our Package and configuration files
Every visitor i mean any user coming to your website/web application has
an IP address. If you want to keep track of user ip address along with
other details. I
The issue is when they're behind a proxy . So, here are the code
snippets in ASP and .Net that first check for an IP addresses that's
forwarded from behind a proxy, and if there's none then just get the IP
address.
And here's the IP retriever with proxy detection in .Net (C#)
And here's the same IP retriever with proxy detection in .Net, but in
VB.Net (CODE BEHIND FILE OR FUNCTIONS)
Public Function IpAddress()
Dim strIpAddress As String
strIpAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
If strIpAddress = "" Then
strIpAddress = Request.ServerVariables("REMOTE_ADDR")
End If
IpAddress = strIpAddress
End Function
Now question is how you retieve all the details like
counry,region,region code ,latitite and logitute
Here is the complate code for getting all details about user
private string GetVisitor()
{
//client connecting to a web server through an HTTP proxy or load balancer
String ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
{
ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
return ip;}
private DataTable GetLocation(string strIPAddress)
{
WebRequest rssReq = WebRequest.Create("http://freegeoip.net/xml/" +
strIPAddress);
WebProxy px = new WebProxy("http://freegeoip.net/xml/" + strIPAddress, true);
rssReq.Proxy = px;
rssReq.Timeout = 2000;
try
{
WebResponse rep = rssReq.GetResponse();
XmlTextReader xtr = new XmlTextReader(rep.GetResponseStream());
DataSet ds = new DataSet();
ds.ReadXml(xtr);
return ds.Tables[0];
A web API is just an application programming interface (API) over the web (that is, HTTP). When the resources of an
application can be manipulated over HTTP using the standard HTTP methods of GET, POST, PUT, and DELETE,
you can say that the application supports a web API for other applications to use. Because HTTP is platform-agnostic,
HTTP services can be consumed by disparate devices across different platforms.
A central concept of HTTP services is the existence of resources that can be identified through a uniform
resource identifier (URI). If you equate resources to nouns, then actions on a resource can be equated to verbs and
are represented by the HTTP methods such as GET, POST, PUT, and DELETE. For an application that deals with the
Users of an organization, each User is a resource the application deals with.
Let us see how an User’s details can be retrieved with an HTTP service. The URI is
http://server<port>/API/Users/1000. It includes the User ID and serves as an identifier to the resource,
which is an User in this case. Actions on this resource are accomplished through the HTTP verbs. To get the
details of an User, you will perform an HTTP GET on the URIhttp://server<port>/API/Users/1000.
To update this User, the request will be an HTTP PUT on the same URI. Similarly, to delete this User, the
request will be an HTTP DELETE request, again on the same URI. To create a new User, the request will be an
HTTP POST to the URI without any identifier (http://server<port>/API/Users).
LET US CREATE WEBAPI
Let us do something practical here. you will create a simple web API that basically exposes an in-memory List<User> over HTTP, for
a client application to manipulate the list members. I know this is just limited or small concept but i am sure this will give you clear concept about what webAPI is and how to use it or will give you understanding how to use the ASP.NET Web API
framework to build your web API.
Run Visual Studio and create a new project like shown below Give the project a
name of Users and click OK, as shown in Figure 1-1.
Select the ASP.NET Web template and click OK. You will see lots of option, as shown in
Figure 1-2.
Choose the Controllers folder in the Solution Explorer of Visual Studio. Select Add ➤ Controller and give a name of UsersController for the controller. Leave the option
Empty API Controller selected in the Template dropdown and click Add, as shown in Figure 1-3. Notice that the generated controller class inherits from ApiController, a class
that is part of the ASP.NET Web API framework.
Right-click the Models folder in the Solution Explorer of Visual Studio. Select Add ➤ Class to add a new class with a name of User
Add the code shown in Listing 1-3 to the User class.
Listing 1-3. The User Class
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Create a new static field at the controller level, as shown in Listing 1-4. This will be the list
that our web API exposes over HTTP.
Figure 1-3. Adding a controller
Listing 1-4. The List of Users
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Users.Models;
namespace Users.Controllers
{
public class UsersController : ApiController
{
private static IList<User> list = new List<User>()
{
new User()
{Id = 1000, FirstName = "Shabir", LastName = "Hakim" },
new User()
{Id = 1001, FirstName = "Raja", LastName = "Public"},
new User()
{Id = 1002, FirstName = "Rani", LastName = "Private"},
new User()
{Id = 1003, FirstName = "Shabir", LastName = "Robert" }
};
// Action Get methods go here
// GET api/Users
public IEnumerable<User> Get()
{return list;}
// GET api/Users/1000
public User Get(int id)
{return list.First(e => e.Id == id);}
}
}
Note: Since you used the User class, which is in a different namespace than HelloWebApi.Models in the
controller class, you will need to add a using directive. In Visual Studio, the User references in the preceding code
will have a wavy underline in red; right-click any of them and select Resolve ➤ using HelloWebApi.Models. This will add
the necessary directive. This is a standard procedure and I will not repeat this step in later exercises, for the sake
of brevity.
Add five action methods, as shown in Listing 1-5. It is important to use the name as shown
in the listing. You will learn more about why you must follow this naming convention in
the next exercise.
Listing 1-5. The Action Methods to Get, Post, Put, and Delete Users
// GET api/Users
public IEnumerable<User> Get()
{
return list;
}
// GET api/Users/1000
public User Get(int id)
{
return list.First(e => e.Id == id);
}
// POST api/Users
public void Post(User User)
{
int maxId = list.Max(e => e.Id);
User.Id = maxId + 1;
list.Add(User);
}
// PUT api/Users/1000
public void Put(int id, User User)
{
int index = list.ToList().FindIndex(e => e.Id == id);
list[index] = User;
}
// DELETE api/Users/1000
public void Delete(int id)
{
User User = Get(id);
list.Remove(User);
}
Build the Visual Studio solution and run it by pressing F5. Internet Explorer, which is
the default browser associated with Visual Studio, shows the home page with a URL of
http://localhost:55778/. (My ASP.NET Web API project uses port 55778. Your project
will use a different one and based on that, Internet Explorer will display a different port in
the URL.)
In the address bar type http://localhost:<port>/api/Users Replace <port> with
the actual port your application runs on.
Note:As you work through the exercises in this book, you will create several new projects, and the port will change
every time you create a new ASP.NET MVC project. Remember to replace the port specified in the example code with your
application’s actual port.
When Internet Explorer asks if you want to open or save, click Open and choose Notepad as the program to open the file. Notepad will display JSON as shown in Listing 1-6. I have
formatted the output for your reading pleasure.
You can also get the details of a specific User by performing an HTTP GET on http://localhost:63482/Api/Users/1000. In this case, you get the JSON output
shown in Listing 1-7.
If you see the preceding two JSON outputs, you have just created your first web API and
exposed the in-memory list of Users to the outside world over HTTP!
Currently, we have tested only the HTTP GET but we will test the other methods in the upcoming exercises.
ASSUMPTION:You have basic knowledge of Sql and c# and you have created already user table(collection ) in mongodb. 2. You have downloaded mongodb driver . I choose N-Get package manager. here is screen shot of how to refer mongodb driver
3.Set references to your visual studio project like shown below
INTRODUCTION:Let us just recall how our
traditional RDBM looks like, It is just based on tables made of rows and
columns.Similarly mongoDB are based on collection of documents, with each
of these documents consisting of key/value attributes(JSON format). A
single document can be thought of as the equivalent of a row in a table, with
each key being similar to a column name and each key’s value being similar to
the respective row’s value.
Here is the view of database collection where four rows(documents) are saved
The exact difference being that a document is not
constrained to a certain schema or columns within a table. Two documents
can share similar elements, like an ID field, as well as having completely
different elements. Data representation in both look like shown
below
RDBMS
NOSQL
.
.
just to recap, MongoDB is made up of databases which contain
collections. A collection in turn is made up of documents.Each document is made
up of fields. Collections can be indexed, which improves lookup and sorting
performance. The core difference is that relational databases define
columns at the table level whereas a document-oriented database defines its
fields at the document level.
In MongoDB, the data structure and hierarchy are like:
Databases
Collections
Documents
Fields
A field is a key-value pair. A key is a name (string). A value is a basic
type like string, integer, float, time-stamp, binary, etc., or a document, or an
array of values.
Conclusively you can say, collections are made of JSON-like documents. This
is the main difference from traditional RDBM. Note: The BSON is a binary-encoded serialization
of J SON-like documents.It is just lightweight, traversable, and efficient.
Why MongoDB
MongoDB is an open-source document database that provides high performance,
high availability, and automatic scaling what else you need if your business
data is huge or growing fast ?
IMPORTANT CONCEPTS
A database can have zero or more collections. A collection shares enough in
common with a traditional table that you can safely think of the two as the same
thing.
Collections are made up of zero or more documents. Again, a document can
safely be thought of as a row.
a lot like columns.
Indexes in MongoDB function mostly like their RDBMS(oracle sql server,sybase)
counterparts.
The Benefits of NoSQL
Large volumes of structured, semi-structured, and unstructured
data
Agile sprints, quick iteration, and frequent code pushes
Object-oriented programming that is easy to use and flexible
Efficient, scale-out architecture instead of expensive,
monolithic architecture
Windows Platform Support
Starting from MongoDB version 2.2, MongoDB doesn’t support Windows XP. So if
you are on Windows XP, either upgrade it or use the lower versions of MongoDB.
This tutorial is intended to help you in installing MongoDB on Windows latest
versions i.e Windows 7 and Windows 8, 8.1 etc.
Installation of MongoDB on Windows
Follow below steps to perform the installation of MongoDB into your windows
system.
Consider specific MongoDB build type which you need actually
Three build types of MongoDB for Windows are available.
MongoDB for Windows Server 2008 R2 series: This build type
runs only on 2008R2, Windows 7 64-bit, Windows 8, and latest versions of
Windows. MongoDB for Windows 64-bit: This build type of MongoDB runs
on any 64-bit version of Windows latest than Windows XP, involve Windows Server
2008 R2 and Windows 7 64-bit. MongoDB for Windows 32-bit: MongoDB runs on any 32-bit
version of Windows latest than Windows XP, 32-bit version of MongoDB are only
designed for older system and use for testing and developing systems. Windows
32-bit versions of MongoDB support only database smaller than 2GB.
Download MongoDB for Windows
download the latest version release from the MongoDB Download page. Make sure
you download the latest version of MongoDB for your Windows. Note that 64-bit
versions of MongoDB do not run with 32-bit Windows.
MongoDB installation folder move to another location (Optional)
Sometimes we want to move the installation to another directory, we can use
move command for this. This command needs to be run as administrator. For
example, to move the folder to C:\MongoDB follow the steps
shown in below images.
MongoDB does not depend at any other system because it is self contained. You
can execute MongoDB from the folder of your choice and can install it in any
folder (for, me it is programFiles folder like C:\Program
Files\MongoDB\Server\3.0\bin)
Running MongoDB Server
We need to create a directory where MongoDB server will store all it’s data.
The MongoDB default data directory path is \data\db. Make this folder using the
following commands from Command Prompt. Note that if the directory doesn’t
exists, MongoDB will try to create it. But it’s good to create it before hand.
Microsoft Windows [Version
6.3.9600]
(c) 2013 Microsoft Corporation.
All rights reserved.
C:\>md \data\db
To start MongoDB server, we need to run mongod.exe just fallow below listed
commands
Note: I am setting path just to run mongodb from c drive every time rather
than going to installation folder every time
This MongoDB starts the main databases process. The waiting for connection
message in the console results determines that the mongod.exe process is
complete.
you will see below
You can use a different path for data files using the –dbpath option to
mongod.exe, for example:
Getting Started with MongoDB and C#
So, let’s get started!
EXAMPLE:
In the MongoDB world, the Document class is the center of it’s universe.
Because the very concept of the database is built upon the concept of this
document, this is what you’ll find yourself using most. You use them to
insert data, update data, delete data, query data. You will find it easy
Here’s where I’m going to write code it do some database related
operations like INSERT UPDATE SELECT..
Here you see
Please note that i am not fallowing coding best practice just for the
sake of making code more understandable. CODE BEHIND FILE
using MongoDB.Bson;using MongoDB.Bson.IO;using MongoDB.Bson.Serialization;using MongoDB.Bson.Serialization.Serializers;using MongoDB.Driver;using MongoDB.Driver.Builders;using System;using System.Configuration;using System.Globalization;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace AspAppwithMongoDb
{
public partial class _Default : Page{ protected void Page_Load(object sender, EventArgs e){ }protected void btnSave_Click(object sender, EventArgs e){//Get Connection Details var strConn = new MongoConnectionStringBuilder(ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString);var server = MongoServer.Create(strConn);// Create a myUser object from database by using the connection string MongoDatabase myUser = server.GetDatabase(strConn.DatabaseName); //get mongodb collectionvar collection = myUser.GetCollection<User>("User");//document just like record/row in rdbmsBsonDocument doc = new BsonDocument();doc["FirstName"] = txtFirstName.Text;doc["lastname"] = txtLastName.Text;collection.Insert(doc);lblSuccess.Text = "Saved Successfully";}protected void btnView_Click(object sender, EventArgs e)
{//Get Connection Details
var strConn = new MongoConnectionStringBuilder(ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString);
var server = MongoServer.Create(strConn);
// Create a myUser object from database by using the connection string MongoDatabase myUser = server.GetDatabase(strConn.DatabaseName);
MongoCollection<User> Users =
myUser.GetCollection<User>("User");
nameLabel.Text = nameLabel.Text + "<table class='table'><thead><th>First Name</th><th>Last Name</th></thead>";
foreach (User usr in Users.FindAll())
{
nameLabel.Text = nameLabel.Text + "<tr>";
nameLabel.Text = nameLabel.Text + "<td>" + usr.FirstName + "</td>";
nameLabel.Text = nameLabel.Text + "<td>"+ usr.lastname + "</td>";
nameLabel.Text = nameLabel.Text + "</tr>";
}
nameLabel.Text = nameLabel.Text + "</table>"; }protected void btnUpdate_Click(object sender, EventArgs e)
{//Get Connection Details var strConn = new MongoConnectionStringBuilder(ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString);var server = MongoServer.Create(strConn);// Create a myUser object from database by using the connection string MongoDatabase myUser = server.GetDatabase(strConn.DatabaseName);var collection = myUser.GetCollection<User>("User");var update = new UpdateDocument { { "$set", new BsonDocument("lastname",txtLastName.Text) } };var query = new QueryDocument { {"lastname", "" } };collection.Update(query, update);lblSuccess.Text = "Updated Successfully";
}
}public class User
{public ObjectId _id { get; set; }public string FirstName { get; set; }public string lastname { get; set; }}
}
Using MongoVUE Is just like SQL Management tool which help you to handle
database operation using GUI
A nice
GUI makes it easy. Fortunately for us
MongoVUE exists and
provides a very pleasant SQL Management Studio like experience over MongoDB
First download
and install MongoVUE.
Next, run MongoVUE and connect to the default “local” connection. Once
connected you should see a User . If you double click the Club node a table view will be rendered,
expand the first document to see its data:
Or click Text View to see the raw document.if
you are interested in learning more of its features, read through its
tutorials.