What is REST and when it becomes RESTfull?

REST is the underlying architectural principle of the web. The amazing thing about the web is the fact that clients (browsers) and servers can interact in complex ways without the client knowing anything beforehand about the server and the resources it hosts. The key constraint is that the server and client must both agree on the media used, which in the case of the web is HTML.

An API that adheres to the principles of REST does not require the client to know anything about the structure of the API. Rather, the server needs to provide whatever information the client needs to interact with the service. An HTML form is an example of this: The server specifies the location of the resource, and the required fields. The browser doesn’t know in advance where to submit the information, and it doesn’t know in advance what information to submit. Both forms of information are entirely supplied by the server. (This principle is called HATEOAS.)

So, how does this apply to HTTP, and how can it be implemented in practice? HTTP is oriented around verbs and resources. The two verbs in mainstream usage are GET and POST, which I think everyone will recognize. However, the HTTP standard defines several others such as PUT and DELETE. These verbs are then applied to resources, according to the instructions provided by the server.

For example, Let’s imagine that we have a user database that is managed by a web service. Our service uses a custom hypermedia based on JSON, for which we assign the mimetype application/json+userdb(There might also be an application/xml+userdb and application/whatever+userdb – many media types may be supported). The client and the server has both been programmed to understand this format, but they don’t know anything about each other. As Roy Fielding points out:

A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types.

A request for the base resource / might return something like this:

Request

GET /
Accept: application/json+userdb

Response

200 OK
Content-Type: application/json+userdb

{
    "version": "1.0",
    "links": [
        {
            "href": "/user",
            "rel": "list",
            "method": "GET"
        },
        {
            "href": "/user",
            "rel": "create",
            "method": "POST"
        }
    ]
}

We know from the description of our media that we can find information about related resources from sections called “links”. This is called Hypermedia controls. In this case, we can tell from such a section that we can find a user list by making another request for /user:

Request

GET /user
Accept: application/json+userdb

Response

200 OK
Content-Type: application/json+userdb

{
    "users": [
        {
            "id": 1,
            "name": "Emil",
            "country: "Sweden",
            "links": [
                {
                    "href": "/user/1",
                    "rel": "self",
                    "method": "GET"
                },
                {
                    "href": "/user/1",
                    "rel": "edit",
                    "method": "PUT"
                },
                {
                    "href": "/user/1",
                    "rel": "delete",
                    "method": "DELETE"
                }
            ]
        },
        {
            "id": 2,
            "name": "Adam",
            "country: "Scotland",
            "links": [
                {
                    "href": "/user/2",
                    "rel": "self",
                    "method": "GET"
                },
                {
                    "href": "/user/2",
                    "rel": "edit",
                    "method": "PUT"
                },
                {
                    "href": "/user/2",
                    "rel": "delete",
                    "method": "DELETE"
                }
            ]
        }
    ],
    "links": [
        {
            "href": "/user",
            "rel": "create",
            "method": "POST"
        }
    ]
}

We can tell a lot from this response. For instance, we now know we can create a new user by POSTing to /user:

Request

POST /user
Accept: application/json+userdb
Content-Type: application/json+userdb

{
    "name": "Karl",
    "country": "Austria"
}

Response

201 Created
Content-Type: application/json+userdb

{
    "user": {
        "id": 3,
        "name": "Karl",
        "country": "Austria",
        "links": [
            {
                "href": "/user/3",
                "rel": "self",
                "method": "GET"
            },
            {
                "href": "/user/3",
                "rel": "edit",
                "method": "PUT"
            },
            {
                "href": "/user/3",
                "rel": "delete",
                "method": "DELETE"
            }
        ]
    },
    "links": {
       "href": "/user",
       "rel": "list",
       "method": "GET"
    }
}

We also know that we can change existing data:

Request

PUT /user/1
Accept: application/json+userdb
Content-Type: application/json+userdb

{
    "name": "Emil",
    "country": "Bhutan"
}

Response

200 OK
Content-Type: application/json+userdb

{
    "user": {
        "id": 1,
        "name": "Emil",
        "country": "Bhutan",
        "links": [
            {
                "href": "/user/1",
                "rel": "self",
                "method": "GET"
            },
            {
                "href": "/user/1",
                "rel": "edit",
                "method": "PUT"
            },
            {
                "href": "/user/1",
                "rel": "delete",
                "method": "DELETE"
            }
        ]
    },
    "links": {
       "href": "/user",
       "rel": "list",
       "method": "GET"
    }
}

Notice that we are using different HTTP verbs (GET, PUT, POST, DELETE etc.) to manipulate these resources, and that the only knowledge we presume on the clients part is our media definition.

Further reading:

(This answer has been subject of a fair amount of criticism for missing the point. For the most part, that has been a fair critique. What I originally described was more in line with how REST was usually implemented a few years ago when I first wrote this, rather than its true meaning. I’ve revised the answer to better represent the real meaning.)

Guid vs Identity columns (Ints)

SQL Studies

I came across an interesting question on SE last week. Guid vs INT – Which is better as a primary key? In addition to the quite good accepted answer I thought I would throw in my own take.

  • Size
    • GUIDs are 16 bytes and hold more values you then could ever use.
    • With an identity column you can choose a data type dependent on your need.
      • tinyint 1 byte 0-255
      • smallint 2 bytes -2^15 (-32,768) to 2^15-1 (32,767)
      • int 4 bytes -2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647)
      • bigint 8 bytes -2^63 (-9,223,372,036,854,775,808) to 2^63-1 (9,223,372,036,854,775,807)

    Remember that the size of your column affects not just how much space the table takes up but how many pages (both index and data) need to be read to perform a given operation. Bigger the column the less you can fit in a page, the more pages need to be read, the slower your queries…

View original post 458 more words

Calling an oData Batch using .net HttpClient class

You have full code here, no theory!

Private Async Function SaveEntityAsBatch() As Threading.Tasks.Task
Using Client As New HttpClient()
Dim APIhostUri As String = “http://localhost:2025/”
Dim APIResponse As HttpResponseMessage
Client.BaseAddress = New Uri(APIhostUri)
Dim content As HttpContent

‘Required if you need dates serialization

Dim microsoftDateFormatSettings As JsonSerializerSettings = New JsonSerializerSettings With {
.DateFormatHandling = DateFormatHandling.IsoDateFormat,
.DateParseHandling = DateParseHandling.DateTimeOffset, .DateTimeZoneHandling = DateTimeZoneHandling.Utc
}

‘ Batch Process
Dim boundary As String = “–changeset_Data—”
Dim batchContent As New MultipartContent(“mixed”, “–batch” & boundary)

‘Project
Dim RqP As New HttpRequestMessage(HttpMethod.Put, “URL(id)/”)
RqP.Content = New StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(projectRequest, microsoftDateFormatSettings))
If RqP.Content.Headers.Contains(“Content-Type”) Then RqP.Content.Headers.Remove(“Content-Type”)
RqP.Content.Headers.Add(“Content-Type”, “application/json”)
Dim ReqContent As New HttpMessageContent(RqP)
If ReqContent.Headers.Contains(“Content-Type”) Then ProjectContent.Headers.Remove(“Content-Type”)
ReqContent.Headers.Add(“Content-Type”, “application/http”)
ReqContent.Headers.Add(“Content-Transfer-Encoding”, “binary”)
ReqContent.Headers.Add(“client-request-id”, “12345678”)
ReqContent.Headers.Add(“return-client-request-id”, “True”)
ReqContent.Headers.Add(“Content-ID”, “1”)
ReqContent.Headers.Add(“DataServiceVersion”, “3.0”)
If ReqContent.Headers.Contains(“contentTypeMime-Part”) Then ReqContent.Headers.Remove(“contentTypeMime-Part”)
ReqContent.Headers.Add(“contentTypeMime-Part”, “Content-Type:application/http;”)

batchContent.Add(ReqContent)

‘Report1

Dim RqR As New HttpRequestMessage(HttpMethod.Put, “URL2/”, PtsAPIhostUri)
RqR.Content = New StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(report, microsoftDateFormatSettings))
If RqR.Content.Headers.Contains(“Content-Type”) Then RqR.Content.Headers.Remove(“Content-Type”)
RqR.Content.Headers.Add(“Content-Type”, “application/json”)
Dim ReqContent2 As New HttpMessageContent(RqR)

If ReqContent2.Headers.Contains(“Content-Type”) Then ReportContent.Headers.Remove(“Content-Type”)
ReqContent2.Headers.Add(“Content-Type”, “application/http”)
ReqContent2.Headers.Add(“Content-Transfer-Encoding”, “binary”)
ReqContent2.Headers.Add(“client-request-id”, “99999”)
ReqContent2.Headers.Add(“return-client-request-id”, “True”)
ReqContent2.Headers.Add(“Content-ID”, “2”)
ReqContent2.Headers.Add(“DataServiceVersion”, “3.0”)

If ReqContent2.Headers.Contains(“contentTypeMime-Part”) Then ReqContent2.Headers.Remove(“contentTypeMime-Part”)
ReqContent2.Headers.Add(“contentTypeMime-Part”, “Content-Type:application/http;”)
batchContent.Add(ReqContent2)
Dim batchRequest As HttpRequestMessage = New HttpRequestMessage(HttpMethod.Post, APIhostUri & “/$batch/”)
batchRequest.Content = batchContent
Dim APIResponseBatch = Await Client.SendAsync(batchRequest)
Dim streamProvider = APIResponseBatch.Content.ReadAsMultipartAsync().Result()

For Each cnt As HttpContent In streamProvider.Contents
Console.WriteLine(cnt.ReadAsStringAsync().Result)
Next

End Using
End Function

I got following errors in given sequences and I continued to add the header and finally I was able to two PUT request in Batch.

Error #1

The ‘Content-Type’ header value ‘application/http; msgtype=request’ is invalid. When this is the start of the change set, the value must be ‘multipart/mixed’; otherwise it must be ‘application/http’.

Error #2

The content type ‘multipart/mixed’ specifies a batch payload; however, the payload either does not include a batch boundary or includes more than one boundary. In OData, batch payload content types must specify exactly one batch boundary in the ‘boundary’ parameter of the content type.

Error #3

Nested change sets in a batch payload are not supported.

Error #3 took most of the time to find out this URL https://msdn.microsoft.com/en-us/library/azure/dn878159.aspx from MSDN, which speaks about adding following Header Content Types

ReqContent2.Headers.Add(“client-request-id”, “99999”)
ReqContent2.Headers.Add(“return-client-request-id”, “True”)
ReqContent2.Headers.Add(“Content-ID”, “2”)
ReqContent2.Headers.Add(“DataServiceVersion”, “3.0”)

After adding above four types to header Error #3 was gone and my Batch was working.

The URL from MSDN says;

Add Tasks requests in Batch service support the following concepts:

  • Each request must contain a unique Content-ID MIME part header. This header is returned with the result of the operation in the response, and can be used to match an individual request with its response.
  • The Batch service returns a HTTP Status Code 400 (Bad Request) if any request contains an invalid set of headers or contains operations which are not supported in the batch.
  • The Batch service returns a HTTP Status Code 202 (Accepted) for a valid Add Tasks request. The server will then stream the results of individual operations.
  • The Batch service can re-order the responses of these Add Task requests. The Content-Id MIME part header needs to be used by the Client to match the request corresponding to the response. The response contains the results and error information for each operation.If the server times out or the connection is closed during an Add Tasks request, the request may have been partially or fully processed, or not at all. In such cases, the user should re-issue the request. Note that it is up to the users to correctly deal with failures when re-issuing a request. For example, the users should use the same task names during retry, so that if the prior operation succeeded, the retry will not create extra tasks unexpectedly.
  • An Add Tasks request can include at most 100 operations.
  • All the tasks in an Add Tasks request must belong to the same workitem and job.

Doxygen-> LaTeX -> PDF using MikTex : Automatic Project Documentation

  1. Install Doxygen from URL
    1. 32 bit: http://ftp.stack.nl/pub/users/dimitri/doxygen-1.8.8.windows.bin.zip
    2. 64 bit: http://ftp.stack.nl/pub/users/dimitri/doxygen-1.8.8.windows.x64.bin.zip
  2. Install MikTex from URL http://miktex.org/download
  3. Select working directory to save/select setting file
  4. Fill Project Name
  5. Select source code directory from where documentation has to be generated
  6. Specify designation directory, where LaTeX will be stored.
  7. Click on next, select all entities.
  8. Click on next, select LaTeX and as intermediate format for PDF. Select required output HTML, LaTeX and RTF etc. For PDF LaTeX is mandatory.
  9. Clicking on next will open screen for diagram generator. Use built in class generator.
  10. Clicking on next last screen will be displayed.
  11. Click on Run doxygen button.
  12. Some message can be displayed, try to ignore.
  13. Progress will be displayed, please wait till “*** Doxygen has finished” is displayed.
  14. Open the target directory, specified in 3.d.
  15. modify the refman.tex file as per desired format like Logo on First Page, New Line, New Page etc
  16. Double click on refman.tex file from target directory.
  17. This will open MikTex editor, select XeLaTex command and click on “Green Run” button.
  18. Progress is displayed in console output.
  19. Some messages about “default to ^^91” can be ignored by hitting Enter key.

If left blank, this will default to ^^91

1^^92 P\+P\+D\+: 1 = Consu…

This will generate a pdf names refman.pdf in the destination directory. Like following is the completion message.

Output written on refman.pdf (318 pages).

SyncTeX written on refman.synctex.gz.

Transcript written on refman.log.

  1. It’s a two time compile process. 2nd time Toc is generated. Step 16 needs to be followed two times.

DO’s and DON’Ts when typesetting a document

LaTeX and Miscellaneous

The following rules apply when using LaTeX2e…

  • In display math mode, use [ ... ] instead of $$ ... $$.

$$... $$ is simply obsolete.

  • Use textbf, textit instead of bf, it.

bf, it are obsolete font selection commands. Under New Font Selection Scheme (NFSS), they should be replaced with textbf, textit. One immediate difference is that {itbf blabla} will not generate the composite effect of italic shape and bold series, while textit{textbf{blabla}} indeed produces bold italic fonts.

  • Put a tilde before references or citations, e.g., Jie~cite{habit06}.

This prevents LaTeX from putting a line break between the word and the citation. Similar cases are: length~$l$, function~$f(x)$, etc.

  • Be cautious when changing the page margin and page layout.

Studies show that articles with approximately 66 characters per line are the most readable. Reading would become difficult if putting more and more…

View original post 383 more words

Conflicting extensions for PHP development have been detected: Visual Studio

So you want to dedug PHP within Visual Studio.

You went ahead and installed extension 1 PhpTools from downloaded msi “PhpTools.xxxx.msi” from visualstudiogallery.

And for complete the installation, you also installed extension 2(like I did) Vs.php from installer “php vsphp_en_xxxx_web_installer.exe downloaded from URL

Then Visual Studio throws up below exception.

—————————
Microsoft Visual Studio
—————————
Conflicting extensions for PHP development have been detected:
– VS.Php
Continuing using of Visual Studio may result in an unpredictible behaviour. To fix this issue, please uninstall conflicting extension above and restart Visual Studio.

—————————
OK
—————————

Why???

Because both these extensions are not supported by Visual Studio at same time, as they are conflicting in nature.

Why conflicting?  Because both extensions extend same features of Visual Studio and studio is saying that configuration of extension 1 has been or may be overwritten by extension 2.

So we need to uninstall one of these to use another.

Setting up php on Windows to connect to Oracle

Good Article

Solutions to IT problems

Introduction

I recently needed to setup a Windows-Apache-PHP Server that can connect to Oracle. It turned out, that this is not a straight forward task to do if you are not used to it.

Which Apache and PHP Version to use

The newest Windows PHP version is compiled with the VC9 compiler. The default apache version for windows from http://httpd.apache.org/ is compiled with the VC6 compiler or said otherwise: they are not compatible. The solution is to either get the apache version from http://www.apachelounge.com/download which is complied with VC9 or use a older PHP version compiled with VC6. The approach you choose probably depends  if a VC9 compiled version if the modules is available. I went with the older PHP version (5.2.17) and VC6. Always select the thread-safe PHP version if you are using apache php module.
For this php version, download the zip archive. The installer did not work correctly…

View original post 307 more words