Showing posts with label Rest. Show all posts
Showing posts with label Rest. Show all posts

Tuesday, November 21, 2023

SharePoint Online - Custom Raw Http calls using Graph SDK v5

The Graph SDK is a nuget library to interact with Graph API from .Net applications. Earlier this year they released¹ Graph .Net SDK v5. That highly simplified the coding with fewer lines than v4 but has breaking changes from v4 even in the basic interactions. The good part is that the Graph SDKs simplify the HTTP operations to Graph API but in some cases, we may need to deal with Raw HTTP calls. 

This post discusses such scenarios. A basic idea about Kiota and building API clients using Kiota² is helpful to easily understand the code.

Problem - Custom Url

Support we are dealing with the cutting edge of Graph API, sometimes the API or property in the result may not be available in the Graph SDK as the SDK needs some time to catch up. Unfortunately, no examples can be included due to NDA. In such cases, we need to craft the URL ourselves but we don't need to deal with the authentication. How can we customize the URL in Graph SDK with the result object using the known types in Graph SDK?

Solution

Below is the notebook³ that has the code
Hope the code is self-explanatory. The catch here is the V5 SDK will serialize the result for us. Here we are getting the known Drive object

Problem - Custom URL and Raw JSON results

Sometimes we need to deal with totally custom URLs and the result JSON. In such scenarios, we can only leverage the authentication mechanism of Graph SDK only not even the result object. How can we have a custom HTTP URL and raw JSON result using Graph SDK?

Solution - Using IRequestAdapter

One way is to use the IRequestAdapter and have NativeResponseHandler. The code in a notebook⁴ is below. This uses a dummy object to satisfy the adapter and get the JSON via NativeResponseHander.

Solution - Using native HttpClient

The above does not fully give the native experience. To get the feel of native experience we can have the below approach⁵ that uses familiar HttpClient.

Please have a look at the warning.

References

¹ - https://devblogs.microsoft.com/microsoft365dev/microsoft-graph-net-sdk-v5-is-now-generally-available/

² - https://learn.microsoft.com/en-us/openapi/kiota/quickstarts/dotnet

³ - https://github.com/dotnet-demos/graph-sdk-sharepoint-online-notebooks/blob/main/custom-rawhttp-calls.ipynb

⁴ - https://github.com/dotnet-demos/graph-sdk-sharepoint-online-notebooks/blob/main/custom-rawhttp-IRequestAdapter-json.ipynb

⁵ - https://github.com/dotnet-demos/graph-sdk-sharepoint-online-notebooks/blob/main/custom-rawhttp-HttpClient-json.ipynb

Tuesday, January 2, 2018

ReST based Web Sites & ReSTful Navigation

Introduction

ReST is highly considered as architectural pattern for integrating systems. It mainly uses APIs
point to resource and do operation on those. The URL often follows a cleaner hierarchical path pattern without much key value pairs than conventional key value pair based URL schemes. People often follow the ReST based URL format for APIs but not widely accepted for web sites.

This post aims to investigate on bringing this ReST based URL schemes to web sites similar to APIs.

Why should I do create web sites as ReSTful URLs

The same benefit of ReST based API URLs applies here as well. The URL will be easy to remember. It is easy to have separation of concerns. New features can be totally implemented separately. using their own area / virtual directories. No need to mix with existing screens even it they are related. Simple and short URLs than lengthy story telling URLs.

eg: www.mycompany.com/employeelist.aspx?empId=1 can be easily represented via
www.mycompany.com/employees/1

Why there are not much web sites following ReSTful pattern

One reason could be the difficulty to follow the pattern. If it is product company the development team will get more freedom to select URLs. Again if the product owners don't know what is ReST and the advantages they may influence the URL pattern. In the other side the consulting industry is heavily driven by client demands. Though regular clients may not ask for particular URLs, semi technical clients may ask.

Some tips for ReSTful web site URLS

Below are some tips to design web site URLs in resource oriented way

No operation oriented screens

The screens should be pointing to resources to display those. For example the below URL displays the employee resource.

www.mycompany.com/employees/1

Lists and details screens

If the URLs display the resource how to edit them? Which screen to edit those resources? The better way is to use lists and details mechanism.

If we display the resources in a list those can be edited in the same list itself and save using a button. Here the single page application (SPA) concept helps us than navigating to an edit page.

Circular navigation

If the resources have circular relation the navigation may also becomes circular.
For example, the employee page may show the department where he belongs to as hyper link. Clicing that will navigate to dept page where it lists the employees in that dept including the manager. Going to the manager page may display employees under him and clicking on the same employee's link there will end up in same employees page where we started.

Multiple navigation paths

Similarly there would be multiple navigation paths to reach one resource. For example the home page of company may show the departments and various project it is doing currently. Navigating to department as well as project may end up in same employee page.

A powerful search experience to navigate

If a resource is buried under the hierarchy, it would be difficult to find it without multiple clicks. So better to have a search mechanism where the resource can be searched and navigated on clicking the associated URLs.

http://mikeschinkel.com/blog/welldesignedurlsarebeautiful/

Tuesday, November 17, 2015

Adding ReST endpoint/webHttpBinding to an existing WCF service along with basicHttpBinding

The beginning

Long long ago, in the middle of a big system, there was a WCF service who lived happily by serving its WPF based .Net client. When the service is installed in local laptop, it served the requests via net.pipe to the requests in same machine and net.tcp to the requests coming from other machines. When it was in data centers, it was accepting requests in http(s) using basicHttpBinding. In everyplace it was secured with X509 certificates. So it never got attention of attackers. In fact there were no attackers as most of the time it was inside the boundary of corporate network.

Things were good until some crazy boys came up with the idea of converting its huge WPF based business client in to HTML. Though they were excited to create HTML application they were not brave enough to generate HTML inside browser. Instead they tried to create a MVC application from which they called this service and generated HTML to sent to client. Their strategy was to not touch anything much which are working. Just create more things around the existing. Beautiful Open-Closed principle. More than that, their aim was to prove that Yes the WPF based business application can be converted to HTML.

Half the way this leadership of the team go changed. They found that its not good to have all the HTML getting generated at the server side. Why can't we generate HTML / view at client side by calling our little service completely avoiding the intermediate MVC site which was acting like proxy and generated HTML?

It went back and forth. Many meetings held at high level. People debated at high level without looking at the code. Finally in a meeting when the code was exposed in projector, everybody agreed to have a try at client side HTML generation by calling the service.

Minimal changes for ReST

The developers were believing on the policy of "Less code less defects" so they tried to expose service via webHttpBinding with only web config changes though they new the contract needs to be changed. They simply added new endpoint with webHttpBinding.


<service name="WcfService1.Service">
  <endpoint address=""
            binding="basicHttpBinding"
            contract="WcfService1.IService"/>
  <endpoint address="rest"
            binding="webHttpBinding"
            contract="WcfService1.IService"/>
</service>


When they first called our little service via rest endpoint with only web.config changes, the gate keeper WCF framework didn't invoke the service. Instead it wrote the below details in the svclog file.


"The message with To 'http://localhost/WcfService/Service.svc/rest/GetData?value=2' cannot be processed at the receiver, due to an AddressFilter mismatch at the EndpointDispatcher.  Check that the sender and receiver's EndpointAddresses agree."

The developers understood that they missed end point behavior configuration for the new webHttp end point added to the service. They added end point behavior as below and used this in webHttpEndPoint.

<endpointBehaviors>
        <behavior name="restBehavior">
          <webHttp />
        </behavior>
</endpointBehaviors>

After this change they tried to call the service via ReST url. But this time they got another error in the browser.

405 Method Not Allowed

There was no entries in the svclog file. The developers realized that, there is no way to expose a service via ReST using webHttpBinding without a contract change. They did that contract change and compiled the assembly and put into bin folder.

[ServiceContract]
public interface IService
{
    [OperationContract]
    [WebGet]
    string GetData(int value);
}

After that they called the service using direct url and they got the result. Everybody became happy that the service worked. The result was as follows for the URL

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">You entered: 2</string>

But there was one more question. How to use this in browser application where the language is Javascript? If its in JSON, Javascript knows how to process it. They modified the contract again as follows to get in JSON.

[ServiceContract]
public interface IService
{
    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json)]
    string GetData(int value);
}

Calling from Javascript

Once they were able to call the ReST url directly from the browser, they used the same url to call from the Javascript code written inside HTML application.


<script type="text/javascript">
    var baseUrl = "http://localhost/WcfService1/Service.svc/rest";
    function testWCFReSTCall() {
        var urlToServiceMethod = getUrlToGetDataMethod();
        
        var xhr = new XMLHttpRequest();
        xhr.open("Get", urlToServiceMethod, false);
        xhr.send();
        if (xhr.status === 200) {
            alert("200" + xhr.responseText);
        }
        else {
            alert("Error on XMLHttpRequest: " + xhr.status + " " + xhr.statusText);
        }
    }
    function getUrlToGetDataMethod() {
        var urlToGetData = baseUrl + "/GetData";
        var urlToGetDataWithParameters = urlToGetData + "?value=2";
        return urlToGetDataWithParameters;
    }
</script>

Monday, December 26, 2011

Creating and exposing simple REST based services in WCF 4.0

ReST (Representational State Transfer) is something which makes the web service url easy to remember by pointing a resource rather than a web page.ie it done have the page.aspx and the query string syntax. For example consider the scenario where I need to get the details of employee named “Joy”

Traditional way : www.company.com/Employee.aspx?name=Joy
ReST way : www.company.com/employees/Joy

There is not question that the Rest URL is simple. Now lets look at how to create such a service in .Net 4.0.
  • Create a web application normally.
  • Add a WCF service to the project.
  • Right click on the .svc file and view markup . Add Factory="System.ServiceModel.Activation.WebServiceHostFactory into the <%@ ServiceHost node.
  • In the Service interface methods add [WebGet] attribute. This makes them visible to the ReST service. Set the URI template of the WebGet properly.
So above are the steps to follow. Lets now see one example Service contract.Famous DoWork method to ReST.
[ServiceContract]
public interface IMyService
{
        [OperationContract]
        [WebGet]
        string DoWork ();
}
The implementation is same.No change .
public class MyService : IMyService
{
    public string DoWork ()
    {
        return "Yes.Our ReST service worked!!!";
    }
}

All set.Hit F5 and in the browser type http://localhost:<port>/myservice.svc/dowork .You can see the output as xml.
<?xml version="1.0"?>
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Yes.Our ReST service worked!!!</string>


WCF ReST return as JSON

Its little difficult for the calling party to process the xml and one more issue is the xml is heavy.So the immediate solution which comes to this scenario is the JSON format. Its easy to make our output to JSON.Just change the WebGet to specify JSON format as follows.

[WebGet(ResponseFormat=WebMessageFormat.Json)]


How to pass parameters to the WCF ReST services

Nobody is going to have only simple services as above in any of the projects. Passing arguments are necessary in WCF ReST services and its supports too using the UriTemplate property of WebGet.

[OperationContract]
[WebGet(UriTemplate="/Add/{a}/{b}")]
int Add ( string a, string b );
Implementation as follows.
public int Add(string a, string b)
{
    int num1, num2;
    if (int.TryParse(a, out num1) && int.TryParse(b, out num2))
    {
        return num1 + num2;
    }
    throw new ArgumentException("Give numbers to add");
}

Look at the UriTemplate it tells how the arguments are going to arrive. So call the service appropriately.


Points to Note

The steps which I performed are very basic and this is working since the framework is 4.0 where it automatically use the WebHttpBinding and other configurations. If you are using old frameworks you may need to set the binding properly.

Another thing is the parameters here are string. So convert them accordingly. I don't thing a sample is needed to see this in your computer.

There are more scenarios in this like such as how to pass and return complex types and how to use the Http Post etc...Hope I can post later.

Tuesday, May 19, 2009

Implementing REST using WCF

REpresentational State Transfer is an architectural approach which treats the url as resource pointer which is more human readable by its syntax.

For example see the Google Picasa urls.They just denote the resource rather than a physical aspx, php or html files.Below is the link to my picasa home page.It just says my username alone.
http://picasaweb.google.com/joymon/

If we navigate again into any album the url will change and that again point to a resource than a file with query strings.
http://picasaweb.google.com/joymon/Identitymine_Anniversary_23Jan2009#

Don’t think that there is some magic going on.Internally this url is getting mapped to a file which process and outputs the required data as html format.Hope the concept is clear.
The main advantage of this approach is simplicity.Urls are all predictable and easy to remember.
Links to implement this in WCF
http://blogs.msdn.com/bags/archive/2008/08/05/rest-in-wcf-blog-series-index.aspx
http://msdn.microsoft.com/en-us/netframework/cc950529.aspx

Thursday, May 8, 2008