Loading

Consume REST service on the server

In my previous post I showed you how to consume REST service on the client side. Today I want to share my experience of consumption it on the server side.

Sometimes there are situation when you need to get some data from Kentico application by either third party application, or, even, another Kentico application. Of course, you might think about connection directly to it's database, using staging, etc. But direct access to database might give third party app more access, than we'd like, staging either requires manual action to stage only object you need, or automatic staging will stage more than you really, etc. 

So after a few minutes of analysis of the requirements, I decided to use Kentico REST service in order to get needed data. The benefit of this approach is that I can control from within the Kentico what object could be accessed and whether this only read or read/write access. This could be configured either in REST settings or with role.

Role is enough flexible approach as I can allow read/write permission to one object, but read only to another. With this approach you need to setup Basic authentication for REST service and create user account you are going to use for REST service. Now you have to create a role and configure the least permissions for it and add just created user account to it. In my case I need to read all user accounts. So I've created RestUserReader role and granted it with Read permission for User module:
 


Also I've configured REST service to use Basic authentication and allowed to read CMS.User objects only, but the last one is not applicable when you need to read one object and read/write another, as mentioned above. So my settings look like this:
 

So now we are ready to write code within any .NET application, which will read users from Kentico. Actually Kentico documentation contains appropriate article, which shows us how to achieve this, but I don't like the fact that they are getting string object, meanwhile REST service always returns either XML or JSON. So I've decided to utilize HttpClient with Media Type Formatters, those are already in pipeline, in order to automatically deserialize response to a particular strongly typed object. Here my code sample:
 

using (var client = new HttpClient())

        {

            client.BaseAddress = new Uri(this.URL);

            client.DefaultRequestHeaders.Accept.Clear();

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));



            var byteArray = Encoding.ASCII.GetBytes(string.Format("{0}:{1}", this.username, this.pass));

            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));



            client.Timeout = new TimeSpan(0, 0, 30);



            Task<HttpResponseMessage> t = client.GetAsync(this.getUsersURLPath);

            HttpResponseMessage response = t.Result;

            if (response.IsSuccessStatusCode)

            {

                Task<Rootobject> tsk = response.Content.ReadAsAsync<Rootobject>();

                Rootobject responseData = tsk.Result;

                return responseData.cms_users.FirstOrDefault().CMS_User;

            }

        }



You might notice the weird way to access the actuall list of users I was looking for, as well strange type Rootobject. Let me explain...

If you'll request data from Kentico REST like this:
http://domain.com/rest/cms.user?topn=1&columns=username,fullname,firstname,lastname&format=json

You'll find response message also formatted in a bit weird way:
{"cms_users": 
    [
        {"CMS_User": 
            [
                {"fullname":"A Abcd","firstname":"A","username":"laberna","lastname":"Abcd"}
            ]
        },{
        "TotalRecords": 
            [
                {"TotalRecords":"1"}
            ]
        }
    ]
}
I believe Kentico team ahs really good reason to format data like this, but unfortunately, I coundn't recognize it yet. 

Anyway, when reading data from HttpResponseMessage object, Media Type Formatter requires to specify the type of the object we are expecting to read from the response. To be honest with you, I really had hard times to build that object on my own. But suddenly I've recollected one sweet feature of Visual Studio: Paste Specials -> Paste JSON as Classes, so I simply copied JSON from the response (like above) and Visual Studio built following objects for me:
 

    class Rootobject

    {

        public Cms_Users[] cms_users { get; set; }

    }



    class Cms_Users

    {

        public CMS_User[] CMS_User { get; set; }

        public Totalrecord[] TotalRecords { get; set; }

    }



    class CMS_User

    {

        public string fullname { get; set; }

        public string firstname { get; set; }

        public string username { get; set; }

        public string email { get; set; }

        public string lastname { get; set; }

    }



    class Totalrecord

    {

        public string TotalRecords { get; set; }

    }



So that was the a final step and now you should be able to get users, or any other object you need, consuming REST service. It works preatty well for me: I'm reading 5 columns of ~25K records in JSON format, which turned to be less than 4 MB, which, in my opinion, is fine to be trasfered over HTTP. 

Hope you will find this post useful. Let us know what you think about this or feel free to ask questions if any.


Comments
Escorts in Karachi
A hyge Welcome form Paki Babes one of the best award winning escorts agencies. We are known for serving high-class service in Lahore, Islamabad and many more. Our Pakistani call girls are sexy and beautifull. The Paki Babes are committed themselves protecting privacy of clients. Our agency hire only professional girls for customers.
2/21/2018 2:33:54 PM

hp technical support
I love the way you write and share your niche! Very interesting and different! Keep it coming!
2/17/2018 6:15:52 PM

Riscilla Lauryn
We at Famous Movie Jackets offer an extensive variety of celebrity enthused outfit at best price. We never trade off quality against the prices. We claim to provide the best quality with authenticity and durability. Mark yourself on the height of fashion by picking one of your favorite style. Famous Movie Jacket is back with another catchy offer now you can enjoy flat 15% off on all products by using coupon code "win2017". Hurry up pick your fashion wear now before the offer fades away. Just Click on <a href="https://www.famousmoviejackets.com">famous Movie jackets</a>
2/17/2018 11:13:14 AM

govt jobs in pakistan
so happy to find good place to many here in the post, the writing is just great, thanks for the post.
2/17/2018 10:20:54 AM

voyance en ligne
Super-Duper site! I am Loving it!! Will come back again, Im taking your feed also, Thanks..
2/15/2018 12:45:06 PM

ali hajvery
Many thanks for this post. Wow! Amazing he did the best job I really got amazing traffic results for my website.
I prefer you all to get more information of him by open this link.
<a href="https://www.fiverr.com/shafi2khatri/do-150-high-da-pa-manual-blog-comments-for-backlinks">SEO Expert</a>
2/13/2018 7:36:21 AM

Karachi Call Girls
The Karachiescorts69 girls are the best girls in Industry. Our Each girls has a different body type. Our Karachi Escorts are willing to give you the best service. Every girls of our team will satisfy you on everything.
2/12/2018 1:57:52 PM

bark box coupon
Love this! My Dog loves to destroy soft fuzzy toys so we go through a lot of them.
2/7/2018 11:19:05 AM

http://happyvalentinesdayquotescards.com/
Very interesting blog. Alot of blogs I see these days don't really provide anything that I'm interested in, but I'm most definately interested in this one. Just thought that I would post and let you know.
2/7/2018 11:18:24 AM

http://valentinesdaypro.com/
Nice blog and absolutely outstanding. You can do something much better but i still say this perfect.Keep trying for the best.
2/7/2018 11:17:47 AM

make money while traveling
I am hoping the same best effort from you in the future as well. In fact your creative writing skills has inspired me. <a href="http://outoff.com.co/step-step-guide-visa-process-india/">make money while traveling</a>
2/5/2018 8:48:19 PM

togel sgp
I am looking for and I love to post a comment that "The content of your post is awesome" Great work!
2/1/2018 9:55:31 PM

Karachi Call Girls
Welcome to our escorts agency we vow to provide best escorts in Pakistan. We are the no-1 provider of Pakistan Escorts. Our girls are fully specialize in several arts such as exotic dancing, body massage and many more. Our ladies are affordable but not are cheap. The prices of our girls very easily afford.
2/1/2018 2:55:02 PM

Fliqi ISRO Recruitment
Nice post. Thanks for sharing.
<a href="http://edu.fliqi.com/isro-govt-jobs
">Fliqi ISRO govt jobs</a>
2/1/2018 6:04:38 AM

unroom construction company in Newport news
This is also a very good post which I really enjoyed reading. It is not every day that I have the possibility to see something like this..
1/31/2018 6:05:39 AM

egypt spiritual tours
This is also a very good post which I really enjoyed reading. It is not every day that I have the possibility to see something like this.. <a href='http://kemettravel.com/'>egypt spiritual tours</a>
1/30/2018 9:34:55 PM

fareedy
This is my first time i visit here. I found so many entertaining stuff in your blog, especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the leisure here! Keep up the good work. I have been meaning to write something like this on my website and you have given me an idea. <a href="www.quickbookserrorsupport.com/">quickbooks help</a>
1/30/2018 8:35:05 PM

ark survival game alternatives
ark survival game alternatives ARK SURVIVAL EVOLVED Wiki is an action cum adventure survival video game
1/30/2018 6:40:39 AM

fareedy
I really enjoy simply reading all of your weblogs. Simply wanted to inform you that you have people like me who appreciate your work. Definitely a great post. Hats off to you! The information that you have provided is very helpful. <a href='http://www.radonsystemsolutions.com/kenosha.html'>Radon Mitigation Kenosha</a>
1/29/2018 12:33:33 PM

Lahore Call Girls
Welcome to Pakistani Escorts website and we believe that we will have a long association with our customers. At Pakistan-escorts.com, our customers find the very sexy Pakistani escorts who are here to offer the most exciting journey and experience to their customers. Our Pakistani Girl have a great variety of beautifull girls who can satisfy all the cravings of the clients. We always hire pakistani girls on the basis of their intelligence, sexual appearance, beauty, attractiveness and friendly nature. We are here to provide the luxurious and satisfying experience to our clients at any cost. Our client’s portfolio consists of Actress,ministers, businessmen, TV actor,local people and many more. These girls have the experience to deal with all kinds of customers. So, it doesn’t matter from which category you are from, we will provide Pakistani call girls that can satisfy you with all the possible erotic techniques, art and poses.
1/28/2018 11:53:44 AM

fareedy
Very informative post ! There is a lot of information here that can help any business get started with a successful social networking campaign ! <a href="http://mysoftwarekeys.com/product-category/microsoft-windows-product-keys/windows-10/">Windows 10 Key</a>
1/27/2018 8:24:08 PM

Bookmarking in SEO
In any case, one social bookmarking in SEO conveys next to no an incentive according to the web indexes. <b><a href="https://bookmarkinginseo.com">Boookmarking in SEO</a></b>
1/27/2018 6:44:45 PM

Sexy girls in Lahore
The Lahore Escorts aim is to provide finest service to the customers. All the girls in our company are 18 years or more. The Lahore Call Girls are not only from the beautiful land of Pakaistan. You can select our girls from our website, mail us and you can also book our Girls in Lahore on call.
1/27/2018 2:42:45 PM

fareed
Hello! I just wish to give an enormous thumbs up for the nice info you've got right here on this post. I will probably be coming back to your weblog for more soon! <a href="https://corpuschristi-homeinspections.com/">property home inspection , home inspection company,</a>
1/27/2018 10:38:47 AM

fareedy
I feel very grateful that I read this. It is very helpful and very informative and I really learned a lot from it. <a href="http://citrus.uspnet.usp.br/biomecan/ojs/index.php/rbb/comment/view/200/0/2586">desempenho cerebral</a>
1/27/2018 6:56:25 AM

Happy Valentines Day 2018
This is an awesome motivating article.I am practically satisfied with your great work.You put truly extremely supportive data. Keep it up. Continue blogging. Hoping to peruse your next post
1/26/2018 8:56:55 PM

isleeplikethedead.com
How to check out from the way of this REST service of server...
1/25/2018 4:47:43 AM

how to download a video from facebook
You have done a amazing job with you website
1/24/2018 10:52:58 AM

youtube converter video to mp3
Super site! I am Loving it!! Will return once more, Im taking your food likewise, Thanks.
1/24/2018 10:30:25 AM

fareedy
I feel very grateful that I read this. It is very helpful and very informative and I really learned a lot from it. <a href='http://valentinesdaypro.com/'>ideas for valentines day</a>
1/23/2018 7:20:29 PM

Escorts in Kolkata
Renu Das Kolkata Escorts Services has gorgeous females provides Independent Escorts Service in Kolkata call girls at 100% satisfaction with VIP models. Provided Kolkata escorts at our agency are professional in nature and are eager to serve you at your place.
1/23/2018 2:48:28 PM

Escorts in Kolkata
Beauti Queen amazing kolkata escorts agency alwyas ready for you at your doorstep. Beauti Queen provide you high profile independent girl in kolkata, escorts service in kolkata, kolkata escorts. If you are looking for the ultimate encounter in Kolkata then I am your sophisticated young Kolkata escorts that provides upscale companionship for making your night becomes true.
1/20/2018 6:57:12 PM

Escorts Agency in Pakistan
A hyge Welcome form Paki Babes one of the best award winning escorts agencies. We are known for serving high-class service in Lahore, Islamabad and many more. Our Pakistani call girls are sexy and beautifull. The Paki Babes are committed themselves protecting privacy of clients. Our agency hire only professional girls for customers.
1/18/2018 2:42:01 PM

JEE MAIN 2018
want to know about Jee main 2018 and wbjee 2018 check here !!
1/16/2018 3:09:26 PM

convert psd to wordpress theme
Always so interesting to visit your site.What a great info, thank you for sharing. this will help me so much in my learning
1/7/2018 10:45:13 AM

cialis
Nothing found for -ontario-canada .
1/7/2018 8:00:23 AM

fareedy
I wanted to thank you for this excellent read!! I definitely loved every little bit of it. I have you bookmarked your site to check out the new stuff you post.
<a href="http://home2bis.com/">ייעוץ עסקי</a>
1/7/2018 6:43:50 AM

VIP Escorts in Karachi
The Karachiescorts69 girls are the best girls in Industry. Our Each girls has a different body type. Our Karachi Escorts are willing to give you the best service. Every girls of our team will satisfy you on everything.
1/6/2018 3:56:14 PM

Baltazar
I've read both your article consume REST service, on the client side and on the server side. It helped a lot, thanks
1/4/2018 11:21:33 AM

Xerxes
thanks

<a href="http://sbhmagazine.com">สมัครบาคาร่า</a>
12/27/2017 6:50:37 AM

تور تایلند
Nice post. Thank you for the info. Keep it up.
12/23/2017 11:29:21 AM

pnr status
This is such a great resource that you are providing and you it away for free. I love seeing blog that understand the value.
12/19/2017 8:49:31 AM

animeyt
The benefit of this approach is that I can control from within the Kentico
12/18/2017 9:49:38 AM

blackboard grossmont
After all I’ll be subscribing to your feed and I hope you write again soon!
12/12/2017 1:04:39 PM

tips
This is such a great resource that you are providing and you give it away for free.
12/11/2017 11:41:25 AM

putlocker
I have been searching out for this similar kind of post for past a week and hardly came across this. Thank you very much and will look for more postings from you.
11/16/2017 9:27:32 AM

SleepLikeTheDead.xyz
Incredible posting this is from you. I am really and truly thrilled to read this marvelous post.
11/13/2017 4:56:59 AM

Christianwatch
Wonderful blog post. This is absolute magic from you! I have never seen a more wonderful post than this one. You've really made my day today with this. I hope you keep this up!
11/12/2017 3:23:20 AM

Off-White
What a sensational blog! This blog is too much amazing in all aspects. Especially, it looks awesome and the content available on it is utmost qualitative.
11/11/2017 3:31:54 PM

UGG Boots
Wonderful article, thanks for putting this together! This is obviously one great post. Thanks for the valuable information and insights you have so provided here.
11/11/2017 2:49:43 PM

Hostgator black friday coupon
I like this post,And I guess that they having fun to read this post,they shall take a good site to make a information,thanks for sharing it to me.
11/11/2017 12:10:31 PM

first date ideas
Thank you very much for keep this information.
11/11/2017 11:06:46 AM

health and fitness blog
I was surfing net and fortunately came across this site and found very interesting stuff here. Its really fun to read. I enjoyed a lot. Thanks for sharing this wonderful information.
11/10/2017 4:43:19 AM

Căn hộ Saigon riverside city Thủ Đức
Very useful post. This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. Really its great article. Keep it up.
11/9/2017 3:38:54 PM

tinh bột nghệ nano
I want you to thank for your time of this wonderful read!!! I definately enjoy every little bit of it and I have you bookmarked to check out new stuff of your blog a must read blog!
11/4/2017 6:21:09 AM

black friday vpn deals
I will instantly grab your rss feed to stay informed of any updates.
11/4/2017 3:52:48 AM

Mortgage Calculator with Taxes and Insurance
This article gives the light in which we can observe the reality. This is very nice one and gives in depth information. Thanks for this nice article.
11/2/2017 7:15:03 AM

Miss World Live Stream
I definitely enjoyed every bit of it and I have you bookmarked to see new information on your blog.
11/2/2017 6:16:29 AM

click here
This is a topic which is near to my heart…
11/1/2017 3:58:51 PM

check more details
The website is looking bit flashy and it catches the visitors eyes. Design is pretty simple and a good user friendly interface.
10/31/2017 3:39:44 PM

strong healthy life
This article gives the light in which we can observe the reality. This is very nice one and gives in depth information. Thanks for this nice article.
10/31/2017 10:12:02 AM

f4kfree.net
I am happy to find this post very useful for me, as it contains lot of information. I always prefer to read the quality content and this thing I found in you post. Thanks for sharing.
10/30/2017 3:47:32 PM

start business in texas
It really is good to know that this topic is being covered also on this web site so cheers for taking time to discuss this
10/27/2017 3:35:06 AM

áo da thật
These are some great tools that i definitely use for SEO work. This is a great list to use in the future..
10/26/2017 3:48:38 PM

áo da nam
I admire this article for the well-researched content and excellent wording. I got so involved in this material that I couldn’t stop reading. I am impressed with your work and skill. Thank you so much.
10/25/2017 3:48:47 PM

Cho thuê máy photocopy giá rẻ
that this topic is being covered also on this web site so cheers for taking time to discuss this!
10/25/2017 12:25:08 PM

bplt20livestreaming.net
I like viewing web sites which comprehend the price of delivering the excellent useful resource free of charge.
10/22/2017 3:49:45 PM

thùng rác
The website is looking bit flashy and it catches the visitors eyes. Design is pretty simple and a good user friendly interface.
10/21/2017 1:04:19 AM

Best portable mattress
I definitely enjoyed every bit of it and I have you bookmarked to see new information on your blog.
10/15/2017 10:03:38 AM

Androforce X10
Thank you for taking the time to publish this information very useful!
10/14/2017 9:37:18 AM

jee main 2018 application form
Amazing information is provided here.
10/8/2017 2:26:21 PM

voyance telephone
Very useful info. Hope to see more posts soon!.
10/6/2017 5:34:59 AM

youtube mp3 org
Cool stuff you have and you keep overhaul every one of us
9/28/2017 12:09:03 PM

pokemon go android
I used to have three pairs of damsels in my small aquarium. I live in a cold place so I had to give them some temperature since they are tropical fishes. I gave them to a boy in my neighborhood when I moved from the city.
9/26/2017 12:29:51 PM

mobdro tv
I used to have three pairs of damsels in my small aquarium. I live in a cold place so I had to give them some temperature since they are tropical fishes. I gave them to a boy in my neighborhood when I moved from the city.
9/25/2017 3:41:07 PM

Volusion Customization Services
sdf sdf sdfsd
9/21/2017 11:42:17 AM

Massage in Abu Dhabi
First of all, fullbodymassage want to welcome you to the new world of pleasure from pain. It is the perfect option from us to enjoy a top-class massage session in the city. We believe in offering top class massage in Abu Dhabi to all our clients. There are people from different parts of the world that include politicians, businessmen, and actors. The Abu Dhabi Massage is popular for eliminating all the stress from the life of their clients.
8/26/2017 3:17:51 PM

Pokemon Jacket
Interesting article! Thank you for sharing them! I hope you will continue to have similar posts to share with everyone.
7/12/2017 4:56:17 AM

Jyn Erso Rogue One Jacket
This is an educational post study. I am so fulfilled to get this post article and lovely information. I was foreseeing get such a post which is greatly valuable to us. A noteworthy thank for posting this article in this site. Keep it up.
6/7/2017 9:30:50 AM

1y0-201 exam prep
It’s very excellent information and more real facts to provided that post.Thank you for sharing this information.
6/1/2017 7:40:50 AM

tricks central
Here TricksCentral is a place where we will share latest Android Tricks, Windows Tips, iOS apps, Android Apk Downloads and more.
5/20/2017 6:44:11 AM

Chats Finder
So informative post.
4/21/2017 8:49:51 AM

bulk computer recycling
It was wondering if I could use this write-up on my other website, I will link it back to your website though.Great Thanks.
4/10/2017 12:29:25 PM

 Security code