Two weeks ago, I mentioned that I I attended "Hackathon” workshop at Microsoft office located at Polaris. During the workshop, a few speaker gave some presentations and demos on all kind fun and cool staff. the organizer provided promotional items for the attendances. these promotional items including books, software etc. one of them caught my eyes, that is a 2014 calendar titled “Software Craftsmanship- Anit-patterns” from a company named Telerik.
it list one anit-pattern in each month and with photo and explanation elaborates what is the anti-pattern and why it is bad. I thought it is a fun way to address Software development issues..
Anti-pattern of January is Mushroom Management- Keep them in the dark
The elaboration says:
The practice of reducing or eliminating the development team’s contact with the end user and the reasons for the project requirements, thereby risking the creation of unwanted features
The link above provides some further reading on the anti-pattern ( including this interesting photo). for your convenience, I copied some here:
Mushroom Management refers to the practice of treating your developers like mushrooms - to wit, "keep them in the dark and feed them BS." By introducing barriers between those who develop the software and those who use it, feedback loops are extended (or destroyed) and the likelihood of mis-communication, invalid assumptions, and building the wrong thing skyrockets.
Ideally, the customer or their representative should be co-located with the developers, who themselves should be co-located. This minimized the communication friction involved in the development process, which should be a shared effort between all members of the team (yes, the customer should be a part of the team, along with the developers, designers, testers, etc. involved).
At the business level, ensure your employees feel like they know what is going on with the organization. Share as much as you can, especially about big picture items like the mission, goal, vision, or strategy that everyone should currently be following. Thus, even if the details of the plan aren't yet ready, or an individual department's plan hasn't been formulated, individual employees can make good decisions in the best interests of the company's internally expressed intent. Without sharing this information, employees are each left to their own devices, which causes stress in the best case and results in inefficiencies and possibly conflict with management (when the wrong decision has been made due to lack of information) in worse cases.
In my over 3 decades of working experience in IT industry, my observation is that this anti-pattern happens when these in the projects felt less confident than they should be. they felt more comfort when they withhold information to themselves; they felt they would be more indispensable when they are the information hub for all parties. they like to be the decision makers for as many decisions as possible; they like the sense of being “in control”
The question would be asked is “how to break the pattern?” Well, the leadership is the key. The leadership is the crucial factor in establishing positive culture in an organization or a project team… It is similar to a family, when the elder son wants to withhold his toy from his younger brother, it is the time for the daddy or mommy to step up and say “ no, you should share the toy with your brother!” For a leader in any team, if he or she is really put the project interest at his or her heart, he or she would never want to put his team in the dark…
At the bottom of the calendar of the month it quoted Edward Yourdon as as saying "If you think your management doesn't know what it's doing or that your organization turns out low-quality software crap that embarrasses you, then leave."
Friday, February 28, 2014
Friday, February 21, 2014
Cloud is within your Reach -- Introduction of Microsoft Azure
First of all, I want to admit that I am not an Azure expert, all I know about Azure is very basic… but it is good enough to get me started with Azure, so can you!
When you do a search on the internet for “Azure”, more than likely to get this site https://www.windowsazure.com, if you are in the States you will be likely led to https://www.windowsazure.com/en-us/.
There is a big image read as <Try for Free> , click that link to enroll the free try offer, you get to use Azure for free for one month. After that you can use you MSDN Ultimate subscription to enroll to Azure or enroll into Azure as “pay-as-you go”. for MSDN Ultimate subscription account, you will have $200 credit per month to use, according to the regulation, MSDN resource is limited to “development and learning purpose". you are not supposed to use it for production purpose.
I have 3 accounts created with Azure, ( trial, MSDN and “pay-as-you-go” from my own pocket). all I can say is “for your learning and development purpose, it will be free. ( considering $200 monthly credit ); If you want to use it for your own production usage like my case, it is “close to free”. if you want to use it for commercial use, it has very strong competitive edge in term of cost .”
Azure offers lots of services, so far I only touched a few of them. for your reference, I list the ones I used below. Others like Virtual machine, SQL/Server, Mobile Service. one interesting one is Visual Studio Online, you get to use Visual Studio without having it be installed on your PC. Specially on Virtual Machine, It provides pre- built images includes Windows Serer 2012, Windows Server 2008 R2, SUSE Linus Enterprise, SQL/Server 2012 in Windows Server 2008 or Windows Server 2012. Ubuntu Server 12, OpenLogic, Oracle Linux, Microsoft Dynamics on Windows Server 2012. Total number of pre-built images available is around 50 or so. You also can install your own OS by providing your own ISO file. The regulation says you only can run Server OS in these Virtual Machines. if you want to run Windows 8.0 or 8.1 on these Visual machine, there are ways to make it work, but that is against Microsoft regulation.
1. Active Directory
2. Web site
3. SQL database
4. Storage
5. Service bus
when you create first service, Azure gives you the AD service for authentication and Authorization purpose at no additional charge.
for each account you can create 5 web sites with one SQL/Server database (max size of 20MB) for free. The total capacity for these web sites is 1GB. and up to 165MB outbound traffic daily included.
For additional database <100MB: $5 a month, if the database size goes bigger, the price per GB goes lower, when the DB size is >50GB, each additional GB cost only $1, besides charges on database size, it also charge for all out bound traffic but the first 5GB per month is free, the charge rate goes from $0.12 per GB to $0.05 per GB depends the traffic volume.
For each additional web site, ( I have not used that yet, as 5 sites are more than enough for me for play with).
1 CPU, 1.75GB RAM : $0.10 per month
2 CPUs, 3.5 GB RAM : $0.20 per month
4CPUs, 7GB RAM 0.40 per month
outbound traffic is charged from $0.10 per GB to $0.05 per GB
for Service Bus: the price is $0.01 per 10K messages and $0.10 for every 100 relay hours
for Data storage: the prices goes from $0.12 per GB to $0.037 per GB
I list all the price information here is to make a point that it is inexpensive. given the credit you have with your MSDN subscription. you basically use it for free. in my case, to host all services I need for my windows store app, it costs me less than $5 a month if any. that was because I have 2 databases. If I merge them into one database, it would be free.
ok, enough about the pricing, let’s get into some technical stuff. in this article, I will touch on web site, database and Service bus.
After the web site is created, you can specific .Net framework version, it supports both V3.5 and V4.5. you also can configure PHP version together with all kind settings you normally do with IIS if not more. On the portal site you have a link with the caption of “Download the publishing profile”, once you have that file, you can directly publish your site from within Visual Studio by loading the profile you just downloaded. with that, make a new release is as simple as a single button click.
This is the screen shot I took after I loaded the publishing profile, all I need to do is click on <Next> <Next> and finally <Publish>. IDE will build my project in release mode and push the bits to the site in Azure. it is simpler than running MSI package like we do.
That is for Web site, let me move on to SQL/Server database. About a few clicks, you will get your database created. after the database been created, you can view the database connection strings for ADO.NET, ODBC, PHP and JDBC) . I copy the connection string for one of my database here to show you how it looks like:
Server=tcp:jno757ecc5.database.windows.net,1433;Database=OAuth20;User ID=<your_user_id_here>@jno757ecc5;Password={your_password_here};Trusted_Connection=False;Encrypt=True;Connection Timeout=30;
with the Connection string, you can work on the database using SQL/Server Management Studio as you do with SQL/Server database on promise.
This screen shot is when I try to connect to my DB server in Azure. after login you can do almost anything you can do with the database on promise. you also can use your SSDT ( SQL Server Data Tool) project in your Visual Studio to the publish your database schema to your targeted DB in Azure. the only difference I found is that in Azure, you do not need to specific file group when you create database object. when I move the database from my sql server in my home network to Azure, I need to remove “ON [PRIMARY]”
This is the screen shot of my publish database scream from with Visual Studio to Azure
When you do a search on the internet for “Azure”, more than likely to get this site https://www.windowsazure.com, if you are in the States you will be likely led to https://www.windowsazure.com/en-us/.
There is a big image read as <Try for Free> , click that link to enroll the free try offer, you get to use Azure for free for one month. After that you can use you MSDN Ultimate subscription to enroll to Azure or enroll into Azure as “pay-as-you go”. for MSDN Ultimate subscription account, you will have $200 credit per month to use, according to the regulation, MSDN resource is limited to “development and learning purpose". you are not supposed to use it for production purpose.
I have 3 accounts created with Azure, ( trial, MSDN and “pay-as-you-go” from my own pocket). all I can say is “for your learning and development purpose, it will be free. ( considering $200 monthly credit ); If you want to use it for your own production usage like my case, it is “close to free”. if you want to use it for commercial use, it has very strong competitive edge in term of cost .”
Azure offers lots of services, so far I only touched a few of them. for your reference, I list the ones I used below. Others like Virtual machine, SQL/Server, Mobile Service. one interesting one is Visual Studio Online, you get to use Visual Studio without having it be installed on your PC. Specially on Virtual Machine, It provides pre- built images includes Windows Serer 2012, Windows Server 2008 R2, SUSE Linus Enterprise, SQL/Server 2012 in Windows Server 2008 or Windows Server 2012. Ubuntu Server 12, OpenLogic, Oracle Linux, Microsoft Dynamics on Windows Server 2012. Total number of pre-built images available is around 50 or so. You also can install your own OS by providing your own ISO file. The regulation says you only can run Server OS in these Virtual Machines. if you want to run Windows 8.0 or 8.1 on these Visual machine, there are ways to make it work, but that is against Microsoft regulation.
1. Active Directory
2. Web site
3. SQL database
4. Storage
5. Service bus
when you create first service, Azure gives you the AD service for authentication and Authorization purpose at no additional charge.
for each account you can create 5 web sites with one SQL/Server database (max size of 20MB) for free. The total capacity for these web sites is 1GB. and up to 165MB outbound traffic daily included.
For additional database <100MB: $5 a month, if the database size goes bigger, the price per GB goes lower, when the DB size is >50GB, each additional GB cost only $1, besides charges on database size, it also charge for all out bound traffic but the first 5GB per month is free, the charge rate goes from $0.12 per GB to $0.05 per GB depends the traffic volume.
For each additional web site, ( I have not used that yet, as 5 sites are more than enough for me for play with).
1 CPU, 1.75GB RAM : $0.10 per month
2 CPUs, 3.5 GB RAM : $0.20 per month
4CPUs, 7GB RAM 0.40 per month
outbound traffic is charged from $0.10 per GB to $0.05 per GB
for Service Bus: the price is $0.01 per 10K messages and $0.10 for every 100 relay hours
for Data storage: the prices goes from $0.12 per GB to $0.037 per GB
I list all the price information here is to make a point that it is inexpensive. given the credit you have with your MSDN subscription. you basically use it for free. in my case, to host all services I need for my windows store app, it costs me less than $5 a month if any. that was because I have 2 databases. If I merge them into one database, it would be free.
ok, enough about the pricing, let’s get into some technical stuff. in this article, I will touch on web site, database and Service bus.
After the web site is created, you can specific .Net framework version, it supports both V3.5 and V4.5. you also can configure PHP version together with all kind settings you normally do with IIS if not more. On the portal site you have a link with the caption of “Download the publishing profile”, once you have that file, you can directly publish your site from within Visual Studio by loading the profile you just downloaded. with that, make a new release is as simple as a single button click.
Publish to web site Hosted by Azure |
This is the screen shot I took after I loaded the publishing profile, all I need to do is click on <Next> <Next> and finally <Publish>. IDE will build my project in release mode and push the bits to the site in Azure. it is simpler than running MSI package like we do.
That is for Web site, let me move on to SQL/Server database. About a few clicks, you will get your database created. after the database been created, you can view the database connection strings for ADO.NET, ODBC, PHP and JDBC) . I copy the connection string for one of my database here to show you how it looks like:
Server=tcp:jno757ecc5.database.windows.net,1433;Database=OAuth20;User ID=<your_user_id_here>@jno757ecc5;Password={your_password_here};Trusted_Connection=False;Encrypt=True;Connection Timeout=30;
with the Connection string, you can work on the database using SQL/Server Management Studio as you do with SQL/Server database on promise.
work with DB hosted by Azure using SSMS |
This screen shot is when I try to connect to my DB server in Azure. after login you can do almost anything you can do with the database on promise. you also can use your SSDT ( SQL Server Data Tool) project in your Visual Studio to the publish your database schema to your targeted DB in Azure. the only difference I found is that in Azure, you do not need to specific file group when you create database object. when I move the database from my sql server in my home network to Azure, I need to remove “ON [PRIMARY]”
This is the screen shot of my publish database scream from with Visual Studio to Azure
Now, let me move on to Service bus, the service bus I created is a notification hub. it provides 2 end points, one is for the publisher to publish message to it, and one is for it subscribers to receive the message from it.
all you need to do is plugging these keys in your publisher and subscriber respectively, it will start to work.
The first screen shot is a window desktop app I used to send the message. the second screen shot is from My Surface 2 box where I installed the app subscribes to the notification bus.
all of Azure services have very good monitoring feature and alert feature. I put here a screen shot to show you how it looks like, to make the picture interesting, I hit the site a few times in the course of writing this article.
Monitoring your Service |
As it is a POC kind of site, it is sleeping in most of time. but in case the site become busy and the response become slow. you want to define some alerts to get yourself notified. when that happens, you can easily scale up your site or your database. scaling is done within Azure portal by adding more CPUs or adding more RAM. From application point of view, these changes does not affect the deployment process.it is still one single logical site or database. from free tier to shared tier or from shared tier to standard tier, it is just one click of the mouse.
Scale your web site |
For Database, from 1GB max size for Web site to 150GB max size for LOB operation is just 2 clicks of mouse. an empty Database is around 4MB in size, I got about 3000 rows of data in the DB, it is only 4.8MB. with that kind or rate, in the foreseeable future, I will not need to pay anything….
Scale your Database |
let’s say you need to do data migration, testing, or host a dev site or dev database, but due to some reason, we do not have the space or box to do what we need to do, just keep in mind that Azure could be one of your options. it is there for free, why not use it.
As always, please feel free to comment on this article or the future topic you would like to see me writing…
hope you enjoy reading it.
Wednesday, February 12, 2014
Manifesto for Software Craftsmanship Manifesto for Agile Software Development
Manifesto for Software Craftsmanship
Last Saturday, I attended “Hackathon” workshop at Microsoft office located at Polaris. During the workshop, a few speakers gave some presentations and demos on all kind fun and cool staff. The organizer provided promotional items for the attendances. these promotional items including books, software etc. One of them caught my eyes, that is a 2014 calendar titled “Software Craftsmanship- Anit-patterns” from a company named Telerik.
It lists one anit-pattern in each month and with photo and explanation elaborates what is the anti-pattern and why it is bad. I thought it is a fun way to address issues in software development projects.. you can purchase the calendar at this site at $4.95 each.
I plan to incorporate it in my weekly writing, but for this week, I would like to touch on Software Craftsmanship aspect of the calendar.
This is the original site of Manifesto for Software craftsmanship
If for some reason you are not able to view the content of the sites, I have it below:
As aspiring Software Craftsmen we are raising the bar of professional software development by practicing it and helping others learn the craft. Through this work we have come to value:
Not only working software, but also well-crafted software
Not only responding to change, but also steadily adding value
Not only individuals and interactions, but also a community of professionals
Not only customer collaboration, but also productive partnerships
That is, in pursuit of the items on the left we have found the items on the right to be indispensable.
there are countless professionals sign up the pledge. I am one of them. I encourage you sign up for it as well.
We are uncovering better ways of developing software by doing it and helping others do it. Through this work we have come to value:
Individuals and interactions over processes and tools
Working software over comprehensive documentation
Customer collaboration over contract negotiation
Responding to change over following a plan
That is, while there is value in the items on the right, we value the items on the left more
Last Saturday, I attended “Hackathon” workshop at Microsoft office located at Polaris. During the workshop, a few speakers gave some presentations and demos on all kind fun and cool staff. The organizer provided promotional items for the attendances. these promotional items including books, software etc. One of them caught my eyes, that is a 2014 calendar titled “Software Craftsmanship- Anit-patterns” from a company named Telerik.
It lists one anit-pattern in each month and with photo and explanation elaborates what is the anti-pattern and why it is bad. I thought it is a fun way to address issues in software development projects.. you can purchase the calendar at this site at $4.95 each.
I plan to incorporate it in my weekly writing, but for this week, I would like to touch on Software Craftsmanship aspect of the calendar.
This is the original site of Manifesto for Software craftsmanship
If for some reason you are not able to view the content of the sites, I have it below:
As aspiring Software Craftsmen we are raising the bar of professional software development by practicing it and helping others learn the craft. Through this work we have come to value:
Not only working software, but also well-crafted software
Not only responding to change, but also steadily adding value
Not only individuals and interactions, but also a community of professionals
Not only customer collaboration, but also productive partnerships
That is, in pursuit of the items on the left we have found the items on the right to be indispensable.
there are countless professionals sign up the pledge. I am one of them. I encourage you sign up for it as well.
Manifesto for Agile Software Development
We are uncovering better ways of developing software by doing it and helping others do it. Through this work we have come to value:
Individuals and interactions over processes and tools
Working software over comprehensive documentation
Customer collaboration over contract negotiation
Responding to change over following a plan
That is, while there is value in the items on the right, we value the items on the left more
Tuesday, February 11, 2014
Microsoft Ads control throwing exception in Windows Store App
This is the XAML you can get from Microsoft Ads SDK sample. According
to the documentation, put this block of code in your page and replace the ApplicationId with
the id you get from PubCenter by register your app for the ads purpose:
<StackPanel Grid.Row="3"
Grid.ColumnSpan="3" Background="{StaticResource
MSAdsBackgroundThemeBrush}" Orientation="Vertical">
<UI:AdControl
ApplicationId="4d075f8c-2db3-4484-ac37-6e446da687bd"
AdUnitId="150628"
Width="728"
Height="90"
Margin="0,0,0,0"
HorizontalAlignment="Center"
VerticalAlignment="Bottom"/>
</StackPanel>
But from time to time, if you pay attention to the output
view when your app is running. You can find the following messages:
A first chance exception of type
'MicrosoftAdvertising.Shared.AdException' occurred in
MicrosoftAdvertising.winmd
A first chance exception of type 'MicrosoftAdvertising.Shared.AdException' occurred in MicrosoftAdvertising.winmd
A first chance exception of type 'MicrosoftAdvertising.Shared.AdException' occurred in mscorlib.dll
A first chance exception of type 'MicrosoftAdvertising.Shared.AdException' occurred in MicrosoftAdvertising.winmd
A first chance exception of type 'MicrosoftAdvertising.Shared.AdException' occurred in mscorlib.dll
Sometimes it is led by some error message like this:
A first chance exception of type
'System.Net.WebException' occurred in System.dll
A first chance exception of type 'System.Net.WebException' occurred in System.dll
A first chance exception of type 'System.Net.WebException' occurred in System.dll
A first chance exception of type 'System.Net.Http.HttpRequestException' occurred in mscorlib.dll
A first chance exception of type 'System.Net.WebException' occurred in System.dll
A first chance exception of type 'System.Net.WebException' occurred in System.dll
A first chance exception of type 'System.Net.Http.HttpRequestException' occurred in mscorlib.dll
Even your app does not access network at all. The interesting
this is you still get to see ads in your app.
Then I put some code in my page to catch the error
condition:
<UI:AdControl
ApplicationId="4d075f8c-2db3-4484-ac37-6e446da687bd"
AdUnitId="150628"
Width="728"
Height="90"
Margin="0,0,0,0"
HorizontalAlignment="Center"
VerticalAlignment="Bottom" ErrorOccurred="AdControl_ErrorOccurred"/>
private void AdControl_ErrorOccurred(object sender, Microsoft.Advertising.WinRT.UI.AdErrorEventArgs e)
{
Debug.WriteLine(String.Format("Spelling
Champion Message AdControl Error
Exception: {0}; AdControl Error Code {1}",
e.Error.Message, e.ErrorCode.ToString()));
}
Then I run the app again, I got the exception.message as “No ad available”
and the error code is NoAdAvailable.
Remember that the app still show ads, so “NoAdAvailable” is not
true.
This is my guess:
The Ads control fires HTTP calls to pull contents from
Ads service. When certain call is not success, it throws Http exception. But as long as some important pieces of information
is collected, it will show the ads. This exception is either some kind of debugging
info should be removed but not or this is a indication that something is wrong
in MS Ads service/Coontrol.
I filed a ticket to MS, when I get response back I will
post it here.
Friday, February 7, 2014
Implement CRUD operation with Web API 2.0
Previously I had 2 articles on Web API:
Developing Services for Modern Apps using MVC Web API 2 with Visual Studio 2013
Securing ASP.Net Web API Service
In these articles I shown you how to set the service up and how to secure your service. Today I am going to show you how to implement CRUD operations using Web API.
CRUD stands for Create, Read, Update and Delete. In any application, CRUD operations are the basic operations. One could not imagine a comprehensive application (or software) can live without CRUD operations. any services for an application more than likely needs to provide these basic operations for its applications.
It is especially true for modern app, because most of modern apps run in limited environment. Limited in processing power, limited in memory, limited in second tier storage. Besides, as cloud technologies become common in mobile computing world, it is common that one could uninstall the app and install it back. and when the app is been reinstalled, he or she wants to see the data he had before. on the other end, it is a critical requirement that when an app is uninstalled, NOTHING should be left behind on the device. So you need to save the data for user but cannot save it locally. the only answer is "save the data in the server". With that CRUD operations on the server side become a crucial element in mobile computing.
As I mentioned in my previous article, HTTP is the preferred protocol for services for mobile apps ( modern apps) and Web API is Microsoft's answer to the demand of providing RESTful service through HTTP. As positioned in such way, you might guess, Web API should provide CRUD operations. you guess it right ! Web API does provide CRUD operations. and the implementation is surprisely simple. in this article I will walk you through on how to implement these operation in detail.
Before I go to the detail, I want to touch on HTTP protocol a bit ( I am not HTTP expert for sure, some of you might have far more experience on HTTP than I do, please bear with me for the moment, if you do, you can skip this part of the article)
There are GET, PUT, POST and DELETE operations in HTTP protocol. in GET operation, you can just get and you also can provide parameter for the operation. This is prefect for the CRUD operations:
GET : Read All
GET with parameter: Read by key
POST :Create ( or Add or Insert)
PUT :Update
DELETE :Delete
Enough talking, let's dive into the code... Talk is cheap, ( isn't it?) show me the code ( here you are!)
The following code example assume you have created an WebAPI project following my first article and you have a Web API project up and running. in this example for simplicity, I omitted the Data access layer You can hook it up with any data access layer you want, I personally prefer Entity Framework. In fact, Visual Studio 2013 offer many template when creating Controller. One of them is a template that directly hook up with EF. I also omitted security implementation you can refer to my second article for security implementation..
1) create your Model class under Models folder: in my example, I have the following very simple class:
public class Person
{
public int Id { get; set; }
public String LastName { get; set; }
public String FirstName { get; set; }
}
2) add your controller
Under Controllers folder, right mouse click and select <Add><Controller>. you will be presented with 7 options on what kind of controller you want to create (I choose Web API2 Controller with read/write actions for simplicity reason, you could choose Web API2 Controller with actions using Entity Framework. ) then provide a name for your controller.( you are able to do so because there is a Sample factory behind it) In my case I select Person. and IDE will create a class as following:
public class PersonController : ApiController
{
// GET api/person
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/person/5
public string Get(int id)
{
return "value";
}
// POST api/person
public void Post([FromBody]string value)
{
}
// PUT api/person/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/person/5
public void Delete(int id)
{
}
}
}
3) add code to replace these stub code for those operations
code block one:
For this demo, I created a static list as data store, and instantiate it with some members in a static contractor
private static List<Person> _MyFamily = new List<Person>();
static PersonController()
{
_MyFamily.Add(new Person { Id = 1, LastName = "Lu", FirstName = "Peter" });
_MyFamily.Add(new Person { Id = 2, LastName = "Yin", FirstName = "Maggie" });
_MyFamily.Add(new Person { Id = 3, LastName = "Lu", FirstName = "Claire" });
_MyFamily.Add(new Person { Id = 4, LastName = "Lu", FirstName = "Wendy" });
_MyFamily.Add(new Person { Id = 5, LastName = "Lu", FirstName = "Olivia" });
}
Code block 2: Get All
you will change you Get method to the following:
public IEnumerable<Person> Get()
{
return _MyFamily;
}
That means whenever your site is hit with http:/<your site address>/api/Person/, the site will return all it has in MyFamily list
Code block 3: Get Person by Id
you will change you get by id method as following:
public Person Get(int id)
{
return _MyFamily.Where(p => p.Id == id).First();
}
In this method, you will search for the person with the specified id and return it back to the caller. ( this is kind of POC code, in live development, you need to handle scenarios like not found.)
Code block 4: Post
you will replace you Post method as following:
public void Post([FromBody]Person value)
{
_MyFamily.Add(value);
}
In this method, you add the person you are given into the list. ( this is kind of POC code, in live development, you need to handle scenarios what happen if the person exists.)
Code block 5: Put
you will change you Put method as following:
public void Put(int id, [FromBody]Person value)
{
var target = _MyFamily.Where(p => p.Id == id).First();
if (target != null)
{
target.FirstName = value.FirstName;
target.LastName = value.LastName;
}
}
Code block 6: Delete
you will change you Delete method as following:
public void Delete(int id)
{
_MyFamily.Remove(this.Get(id));
}
4) test your web app service with test client
Build your project and start your project in IE. you will see a screen shot like this:
Click on <API> you will get to see your Person Controller as following:
Click on first link GET api/Person you will get to see this screen:
Click on TestAPI and then click on <Send> button on the right bottom of the dialog, . you will get the body content as following:
[{"Id":1,"LastName":"Lu","FirstName":"Peter"},{"Id":2,"LastName":"Yin","FirstName":"Maggie"},{"Id":3,"LastName":"Lu","FirstName":"Claire"},{"Id":4,"LastName":"Lu","FirstName":"Wendy"},{"Id":5,"LastName":"Lu","FirstName":"Olivia"}]
this is List<Person> instance in Json format. if you want it to be XML form, just add a header "Accept" , "application/xml" then click on <Send>, you will get the object serialized in xml format as following:
<ArrayOfPerson xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/PeterLu.ChampionService.Models"><Person><FirstName>Peter</FirstName><Id>1</Id><LastName>Lu</LastName></Person><Person><FirstName>Maggie</FirstName><Id>2</Id><LastName>Yin</LastName></Person><Person><FirstName>Claire</FirstName><Id>3</Id><LastName>Lu</LastName></Person><Person><FirstName>Wendy</FirstName><Id>4</Id><LastName>Lu</LastName></Person><Person><FirstName>Olivia</FirstName><Id>5</Id><LastName>Lu</LastName></Person></ArrayOfPerson>
you can use the test client to test other API calls...( test client is very handy when ity comes to testing your Web API functionality.
Developing Services for Modern Apps using MVC Web API 2 with Visual Studio 2013
Securing ASP.Net Web API Service
In these articles I shown you how to set the service up and how to secure your service. Today I am going to show you how to implement CRUD operations using Web API.
CRUD stands for Create, Read, Update and Delete. In any application, CRUD operations are the basic operations. One could not imagine a comprehensive application (or software) can live without CRUD operations. any services for an application more than likely needs to provide these basic operations for its applications.
It is especially true for modern app, because most of modern apps run in limited environment. Limited in processing power, limited in memory, limited in second tier storage. Besides, as cloud technologies become common in mobile computing world, it is common that one could uninstall the app and install it back. and when the app is been reinstalled, he or she wants to see the data he had before. on the other end, it is a critical requirement that when an app is uninstalled, NOTHING should be left behind on the device. So you need to save the data for user but cannot save it locally. the only answer is "save the data in the server". With that CRUD operations on the server side become a crucial element in mobile computing.
As I mentioned in my previous article, HTTP is the preferred protocol for services for mobile apps ( modern apps) and Web API is Microsoft's answer to the demand of providing RESTful service through HTTP. As positioned in such way, you might guess, Web API should provide CRUD operations. you guess it right ! Web API does provide CRUD operations. and the implementation is surprisely simple. in this article I will walk you through on how to implement these operation in detail.
Before I go to the detail, I want to touch on HTTP protocol a bit ( I am not HTTP expert for sure, some of you might have far more experience on HTTP than I do, please bear with me for the moment, if you do, you can skip this part of the article)
There are GET, PUT, POST and DELETE operations in HTTP protocol. in GET operation, you can just get and you also can provide parameter for the operation. This is prefect for the CRUD operations:
GET : Read All
GET with parameter: Read by key
POST :Create ( or Add or Insert)
PUT :Update
DELETE :Delete
Enough talking, let's dive into the code... Talk is cheap, ( isn't it?) show me the code ( here you are!)
The following code example assume you have created an WebAPI project following my first article and you have a Web API project up and running. in this example for simplicity, I omitted the Data access layer You can hook it up with any data access layer you want, I personally prefer Entity Framework. In fact, Visual Studio 2013 offer many template when creating Controller. One of them is a template that directly hook up with EF. I also omitted security implementation you can refer to my second article for security implementation..
1) create your Model class under Models folder: in my example, I have the following very simple class:
public class Person
{
public int Id { get; set; }
public String LastName { get; set; }
public String FirstName { get; set; }
}
2) add your controller
Under Controllers folder, right mouse click and select <Add><Controller>. you will be presented with 7 options on what kind of controller you want to create (I choose Web API2 Controller with read/write actions for simplicity reason, you could choose Web API2 Controller with actions using Entity Framework. ) then provide a name for your controller.( you are able to do so because there is a Sample factory behind it) In my case I select Person. and IDE will create a class as following:
public class PersonController : ApiController
{
// GET api/person
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/person/5
public string Get(int id)
{
return "value";
}
// POST api/person
public void Post([FromBody]string value)
{
}
// PUT api/person/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/person/5
public void Delete(int id)
{
}
}
}
3) add code to replace these stub code for those operations
code block one:
For this demo, I created a static list as data store, and instantiate it with some members in a static contractor
private static List<Person> _MyFamily = new List<Person>();
static PersonController()
{
_MyFamily.Add(new Person { Id = 1, LastName = "Lu", FirstName = "Peter" });
_MyFamily.Add(new Person { Id = 2, LastName = "Yin", FirstName = "Maggie" });
_MyFamily.Add(new Person { Id = 3, LastName = "Lu", FirstName = "Claire" });
_MyFamily.Add(new Person { Id = 4, LastName = "Lu", FirstName = "Wendy" });
_MyFamily.Add(new Person { Id = 5, LastName = "Lu", FirstName = "Olivia" });
}
Code block 2: Get All
you will change you Get method to the following:
public IEnumerable<Person> Get()
{
return _MyFamily;
}
That means whenever your site is hit with http:/<your site address>/api/Person/, the site will return all it has in MyFamily list
Code block 3: Get Person by Id
you will change you get by id method as following:
public Person Get(int id)
{
return _MyFamily.Where(p => p.Id == id).First();
}
In this method, you will search for the person with the specified id and return it back to the caller. ( this is kind of POC code, in live development, you need to handle scenarios like not found.)
Code block 4: Post
you will replace you Post method as following:
public void Post([FromBody]Person value)
{
_MyFamily.Add(value);
}
In this method, you add the person you are given into the list. ( this is kind of POC code, in live development, you need to handle scenarios what happen if the person exists.)
Code block 5: Put
you will change you Put method as following:
public void Put(int id, [FromBody]Person value)
{
var target = _MyFamily.Where(p => p.Id == id).First();
if (target != null)
{
target.FirstName = value.FirstName;
target.LastName = value.LastName;
}
}
Code block 6: Delete
you will change you Delete method as following:
public void Delete(int id)
{
_MyFamily.Remove(this.Get(id));
}
4) test your web app service with test client
Build your project and start your project in IE. you will see a screen shot like this:
Click on <API> you will get to see your Person Controller as following:
Click on first link GET api/Person you will get to see this screen:
Click on TestAPI and then click on <Send> button on the right bottom of the dialog, . you will get the body content as following:
[{"Id":1,"LastName":"Lu","FirstName":"Peter"},{"Id":2,"LastName":"Yin","FirstName":"Maggie"},{"Id":3,"LastName":"Lu","FirstName":"Claire"},{"Id":4,"LastName":"Lu","FirstName":"Wendy"},{"Id":5,"LastName":"Lu","FirstName":"Olivia"}]
this is List<Person> instance in Json format. if you want it to be XML form, just add a header "Accept" , "application/xml" then click on <Send>, you will get the object serialized in xml format as following:
<ArrayOfPerson xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/PeterLu.ChampionService.Models"><Person><FirstName>Peter</FirstName><Id>1</Id><LastName>Lu</LastName></Person><Person><FirstName>Maggie</FirstName><Id>2</Id><LastName>Yin</LastName></Person><Person><FirstName>Claire</FirstName><Id>3</Id><LastName>Lu</LastName></Person><Person><FirstName>Wendy</FirstName><Id>4</Id><LastName>Lu</LastName></Person><Person><FirstName>Olivia</FirstName><Id>5</Id><LastName>Lu</LastName></Person></ArrayOfPerson>
you can use the test client to test other API calls...( test client is very handy when ity comes to testing your Web API functionality.
Subscribe to:
Posts (Atom)