Wednesday, February 13, 2013

windows8 develop metro sample code-7 ListView and Web Datasource

1.bing search code sample(Controls_ListViewWorkingWithDataSources):

scenario1.html:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link rel="stylesheet" href="/css/scenario1.css" />
<script src="/js/scenario1.js"></script>
<script src="/js/BingImageSearchDataSource.js"></script>
</head>
<body>
<div data-win-control="SdkSample.ScenarioInput">
<p>
This scenario demonstrates how to create a data adapter to interface with a web
service. A data adapter is the component to interface between the list view and
the supply of data, enabling virtualization. This specific example uses XmlHttpRequest
to access the image search feature of <a href="http://www.bing.com/images">Bing</a>
which is exposed as a web service.
</p>
<p>
The Bing API is part of the Windows Azure Marketplace and requires an account key to identify the application. To use this sample you will need
to get a key from the <a href="https://datamarket.azure.com/dataset/5ba839f1-12ce-4cce-bf57-a49d98d29a44">Bing Search API</a>.
Then paste the key into the text box below.</p>
<div>
<label for="devkey">
Account Key:
</label>
<input id="devkey" placeholder="Enter Account Key here" />
<button class="action secondary" id="savekey">
Save key
</button>
</div>
<br />
<div id="queryCtrls">
<label for="query">
Query:
</label>
<input id="query" value="cats" />
<button class="action" id="runquery">
Search
</button>
</div>
</div>
<div data-win-control="SdkSample.ScenarioOutput">
<div id="itemTemplate" data-win-control="WinJS.Binding.Template">
<div class="itemTempl">
<img data-win-bind="src: thumbnail" alt="Databound image" />
<span class="content" data-win-bind="innerText: title"></span>
</div>
</div>
<div id="listview1" class="box"
data-win-control="WinJS.UI.ListView"
data-win-options="{ selectionMode: 'none', tapBehavior: 'none', swipeBehavior: 'none', layout: { type: WinJS.UI.GridLayout, maxRows: 2 } }"
></div>
</div>
</body>
</html>




scenario1.js:

//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//// PARTICULAR PURPOSE.
////
//// Copyright (c) Microsoft Corporation. All rights reserved

(function () {
"use strict";
var page = WinJS.UI.Pages.define("/html/scenario1.html", {
ready: function (element, options) {
WinJS.Utilities.query("#savekey").listen("click", saveKey);
WinJS.Utilities.query("#runquery").listen("click", doSearch);
loadKey();
}
});

// Save the dev key in app state and toggle the control enablement
function saveKey() {
var devkey = document.getElementById("devkey").value;
if (devkey !== "" && devkey.length > 12) {
try {
var localSettings = Windows.Storage.ApplicationData.current.localSettings;
localSettings.values["devkey"] = devkey;
}
catch (err) {
//do nothing;
}
toggleControls(true);
doSearch();

} else {
toggleControls(false);
}
}

// load the key from app state
function loadKey() {
var devkey = "";

try {
var localSettings = Windows.Storage.ApplicationData.current.localSettings;
devkey = localSettings.values["devkey"];
if (devkey === null || devkey === undefined) {
devkey = "";
}
}
catch (err) {
devkey = "";
}

if (devkey !== "" && devkey.length > 12) {
document.getElementById("devkey").value = devkey;
toggleControls(true);

} else {
toggleControls(false);
}

}

// Toggles the enablement of the controls when we have a dev key
function toggleControls(enabled) {
document.getElementById("queryCtrls").disabled = (!enabled);
if (enabled) {
document.getElementById("savekey").className = "action secondary";
document.getElementById("runquery").className = "action";

} else {
document.getElementById("savekey").className = "action";
document.getElementById("runquery").className = "action secondary";
}
}

// Initializes the data adapter and pass to the listview
// Called when the search button is pressed.
// The code for the data adapter is in js/BingImageSearchDataSource.js
function doSearch() {
var devkey = document.getElementById("devkey").value;
if (devkey !== "" && devkey.length > 12) {
var searchTerm = document.getElementById("query").value;

var listview = document.getElementById("listview1").winControl;
var myTemplate = document.getElementById("itemTemplate");

//Create the bing itemDataSource
var myDataSrc = new bingImageSearchDataSource.datasource(devkey, searchTerm);

// Set the properties on the list view to use the itemDataSource
listview.itemDataSource = myDataSrc;
listview.itemTemplate = myTemplate;
}
}

})();




scenario1.css:

/* styles */
.box
{
border: 1px solid #222222;
background-color: #ffffff;
}

#listview1
{
height: 272px;
}

.itemTempl
{
width: 120px;
height: 120px;
padding: 0px;
overflow: hidden;
display: -ms-grid;
}

.itemTempl img
{
min-width: 120px;
min-height: 120px;
}

.content
{
width: 110px;
height: 12px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
padding: 8px 5px;
background-color: rgba(0, 0, 0, 0.65);
color: White;
position: absolute;
bottom: 0px;
}

/* CSS to align form elements */
label
{
float: left;
text-align: right;
width: 150px;
margin-right: 20px;
}

#devkey
{
width: 400px;
}

#query
{
width: 400px;
}


/*
// scenario 2 & 3 styles
*/

#listView2, #listView3
{
width: calc(100%-20px);
margin: 0 20px 0 0;
height: 100px;
}

.tileTempl
{
width: 60px;
height: 60px;
margin: 2px;
padding: 3px;
background-color: #ffffcc;
border: 2px solid #663300;
border-radius: 4px;
font-family: Arial;
text-align: center;
position: relative;
}

.counter
{
font-size: 8pt;
position: absolute;
top: 0px;
right: 4px;
width: 20px;
height: 20px;
text-align: right;
}

.letter
{
font-size: 40pt;
font-weight: bold;
line-height: 48pt;
}

.win-selected .tileTempl
{
color: Black;
}

BingImageSearchDataSource.js:

// Bing image search data source example
//
// This implements a datasource that will fetch images from Bing's image search feature of the azure data marketplace.
// The Azure Marketplace requires the developer to subscribe to services and get an account key. Bing offers a free
// trial subscription which can be used with this sample. For more details see:
// https://datamarket.azure.com/dataset/5BA839F1-12CE-4CCE-BF57-A49D98D29A44

(function () {

// Definition of the data adapter
var bingImageSearchDataAdapter = WinJS.Class.define(
function (devkey, query) {

// Constructor
this._minPageSize = 50;
this._maxPageSize = 50;
this._maxCount = 1000;
this._devkey = devkey;
this._query = query;
},

// Data Adapter interface methods
// These define the contract between the virtualized datasource and the data adapter.
// These methods will be called by virtualized datasource to fetch items, count etc.
{
// This example only implements the itemsFromIndex and count methods

// Called to get a count of the items
// The value of the count can be updated later in the response to itemsFromIndex
getCount: function () {
var that = this;

// As the bing API does not return a count at this time, and the queries invariably return
// large datasets, we'll check the results and then assume its maxcount if the result set is full

// Build up a URL to request 50 items so we can get the count if less than that
var requestStr = "https://api.datamarket.azure.com/Data.ashx/Bing/Search/Image"

// Common request fields (required)
+ "?Query='" + that._query + "'"
+ "&$format=json"
+ "&Market='en-us'"
+ "&Adult='Strict'"
+ "&$top=50"
+ "&$skip=0";

//Return the promise from making an XMLHttpRequest to the server
// The bing API authenticates using any username and the developer key as the password.
return WinJS.xhr({ url: requestStr, user: "foo", password: that._devkey, }).then(

//Callback for success
function (request) {
var obj = JSON.parse(request.responseText);

// Verify if the service has returned images
if (obj.d && obj.d.results) {
var count = obj.d.results.length < 50 ? obj.d.results.length : that._maxCount;
if (count === 0) { WinJS.log && WinJS.log("The search returned 0 results.", "sample", "error"); }
return count;
} else {
WinJS.log && WinJS.log("Error fetching results from the Bing API", "sample", "error");
return 0;
}
},
// Called if the XHR fails
function (request) {
if (request.status === 401) {
WinJS.log && WinJS.log(request.statusText, "sample", "error");
} else {
WinJS.log && WinJS.log("Error fetching data from the service. " + request.responseText, "sample", "error");
}
return 0;
});
},

// Called by the virtualized datasource to fetch items
// It will request a specific item and optionally ask for a number of items on either side of the requested item.
// The implementation should return the specific item and, in addition, can choose to return a range of items on either
// side of the requested index. The number of extra items returned by the implementation can be more or less than the number requested.
//
// Must return back an object containing fields:
// items: The array of items of the form items=[{ key: key1, data : { field1: value, field2: value, ... }}, { key: key2, data : {...}}, ...];
// offset: The offset into the array for the requested item
// totalCount: (optional) update the value of the count
itemsFromIndex: function (requestIndex, countBefore, countAfter) {
var that = this;
if (requestIndex >= that._maxCount) {
return WinJS.Promise.wrapError(new WinJS.ErrorFromName(WinJS.UI.FetchError.doesNotExist));
}

var fetchSize, fetchIndex;
// See which side of the requestIndex is the overlap
if (countBefore > countAfter) {
//Limit the overlap
countAfter = Math.min(countAfter, 10);
//Bound the request size based on the minimum and maximum sizes
var fetchBefore = Math.max(Math.min(countBefore, that._maxPageSize - (countAfter + 1)), that._minPageSize - (countAfter + 1));
fetchSize = fetchBefore + countAfter + 1;
fetchIndex = requestIndex - fetchBefore;
} else {
countBefore = Math.min(countBefore, 10);
var fetchAfter = Math.max(Math.min(countAfter, that._maxPageSize - (countBefore + 1)), that._minPageSize - (countBefore + 1));
fetchSize = countBefore + fetchAfter + 1;
fetchIndex = requestIndex - countBefore;
}

// Build up a URL for the request
var requestStr = "https://api.datamarket.azure.com/Data.ashx/Bing/Search/Image"

// Common request fields (required)
+ "?Query='" + that._query + "'"
+ "&$format=json"
+ "&Market='en-us'"
+ "&Adult='Strict'"
+ "&$top=" + fetchSize
+ "&$skip=" + fetchIndex;

// Return the promise from making an XMLHttpRequest to the server
// The bing API authenticates using any username and the developer key as the password.
return WinJS.xhr({ url: requestStr, user: "foo", password: that._devkey }).then(

//Callback for success
function (request) {
var results = [], count;

// Use the JSON parser on the results, safer than eval
var obj = JSON.parse(request.responseText);

// Verify if the service has returned images
if (obj.d && obj.d.results) {
var items = obj.d.results;

// Data adapter results needs an array of items of the shape:
// items =[{ key: key1, data : { field1: value, field2: value, ... }}, { key: key2, data : {...}}, ...];
// Form the array of results objects
for (var i = 0, itemsLength = items.length; i < itemsLength; i++) {
var dataItem = items[i];
results.push({
key: (fetchIndex + i).toString(),
data: {
title: dataItem.Title,
thumbnail: dataItem.Thumbnail.MediaUrl,
width: dataItem.Width,
height: dataItem.Height,
linkurl: dataItem.SourceUrl,
url: dataItem.MediaUrl
}
});
}

WinJS.log && WinJS.log("", "sample", "status");
return {
items: results, // The array of items
offset: requestIndex - fetchIndex, // The offset into the array for the requested item
};

} else {
WinJS.log && WinJS.log(request.statusText, "sample", "error");
return WinJS.Promise.wrapError(new WinJS.ErrorFromName(WinJS.UI.FetchError.doesNotExist));
}
},

//Called on an error from the XHR Object
function (request) {
if (request.status === 401) {
WinJS.log && WinJS.log(request.statusText, "sample", "error");
} else {
WinJS.log && WinJS.log("Error fetching data from the service. " + request.responseText, "sample", "error");
}
return WinJS.Promise.wrapError(new WinJS.ErrorFromName(WinJS.UI.FetchError.noResponse));
});
}

// setNotificationHandler: not implemented
// itemsFromStart: not implemented
// itemsFromEnd: not implemented
// itemsFromKey: not implemented
// itemsFromDescription: not implemented
});

WinJS.Namespace.define("bingImageSearchDataSource", {
datasource: WinJS.Class.derive(WinJS.UI.VirtualizedDataSource, function (devkey, query) {
this._baseDataSourceConstructor(new bingImageSearchDataAdapter(devkey, query));
})
});
})();

25 comments:

http://www.hummaa.com/user/townsilver99 said...

This is the right blog for everyone who wishes to understand this topic.

You realize so much its almost hard to argue with you (not that I really
would want to…HaHa). You definitely put a fresh spin on a subject that has been written about for many
years. Wonderful stuff, just great!

no deposit bingo casinos said...

This is the right website for anyone who wishes to understand this topic.
You understand so much its almost hard to argue with you (not that I really will need to…HaHa).
You definitely put a brand new spin on a subject that's been discussed for ages. Excellent stuff, just wonderful!

George said...

Great blog! Do you have any helpful hints for aspiring writers?
I'm hoping to start my own website soon but I'm a little lost on everything.
Would you suggest starting with a free platform like Wordpress or go for a paid option?
There are so many options out there that I'm completely confused .. Any ideas? Appreciate it!

Russel said...

Its like you learn my mind! You appear to grasp so much approximately this, like you
wrote the book in it or something. I believe that you could do with a few percent to force the message house a bit, but other than that, this
is wonderful blog. An excellent read. I'll certainly be back.

play bingo for free said...

I love reading a post that can make men and women think.
Also, thanks for permitting me to comment!

Brittany said...

First off I want to say wonderful blog! I had a quick question which I'd like to ask if you do not mind. I was interested to know how you center yourself and clear your thoughts before writing. I've had
trouble clearing my thoughts in getting my thoughts out there.

I do enjoy writing however it just seems like the first 10 to 15 minutes are wasted just
trying to figure out how to begin. Any suggestions or hints?
Kudos!

bingo no deposit free cash said...

Woah! I'm really digging the template/theme of this site. It's simple, yet effective.
A lot of times it's tough to get that "perfect balance" between user friendliness and visual appeal. I must say that you've done a superb
job with this. Also, the blog loads extremely quick for me on Internet explorer.
Exceptional Blog!

http://blingee.com/profile/cellpowder6 said...

It's an awesome paragraph for all the internet visitors; they will obtain advantage from it I am sure.

Devon said...

I do believe all of the ideas you've presented to your post. They're very convincing and will certainly
work. Still, the posts are very short for beginners.
May just you please extend them a bit from next
time? Thank you for the post.

free no deposit bingo sites usa said...

It's very effortless to find out any topic on net as compared to textbooks, as I found this piece of writing at this web site.

free no deposit bingo casinos said...

Hi, this weekend is nice in support of me, for the reason that this occasion i am
reading this impressive educational paragraph here at my home.

play bingo for free said...

My partner and I absolutely love your blog and find nearly
all of your post's to be precisely what I'm
looking for. Do you offer guest writers to write content for you personally?
I wouldn't mind creating a post or elaborating on most of the subjects you write in relation to here. Again, awesome blog!

http://www.cellsea.com/ said...

Marvelous, what a blog it is! This weblog presents helpful facts to us, keep it up.

new no deposit bingo sites said...

I usually do not write a leave a response, however after reading a bunch of remarks on this page windows8 develop metro sample code-7 ListView and Web Datasource | pkrss blog.
I actually do have a few questions for you if it's okay. Is it simply me or do a few of the comments appear as if they are written by brain dead individuals? :-P And, if you are writing on additional places, I would like to keep up with you. Would you post a list of every one of all your public pages like your linkedin profile, Facebook page or twitter feed?

dirtyoilsands.org said...

Thanks in favor of sharing such a fastidious idea, piece of writing is fastidious, thats why i have read
it entirely

free bingo no deposit usa 2013 said...

We absolutely love your blog and find most of your post's to be precisely what I'm
looking for. Does one offer guest writers to write content available for
you? I wouldn't mind composing a post or elaborating on many of the subjects you write in relation to here. Again, awesome weblog!

newyorkneedsyou.org said...

I do not even know the way I stopped up right here, but
I thought this publish used to be great. I do not realize who you're however certainly you are going to a famous blogger for those who are not already. Cheers!

Kazuko said...

It's really a nice and helpful piece of information. I am satisfied that you simply shared this helpful info with us. Please stay us informed like this. Thanks for sharing.

Willis said...

No matter if some one searches for his required thing,
so he/she needs to be available that in detail, therefore that thing is maintained over here.

Hypothyroidism Revolution said...

Helpful information. Lucky me I discovered your site
accidentally, and I am shocked why this accident did not came about
earlier! I bookmarked it.

Online casinos for us players said...

I am actually thankful to the owner of this website
who has shared this wonderful piece of writing at
at this time.

candy crush saga cheats said...

Excellent goods from you, man. I've consider your stuff prior to and you're simply extremely excellent.

I actually like what you've acquired here, really like what you are saying and the way through which you are saying it. You're making it entertaining and you still take care of to
keep it sensible. I can't wait to read far more from you. This is really a great site.

How To Get YouTube Subscribers said...

I think this is among the mowt imortant information for me.
And i'm glad reading our article. But wanna remark on some
general things, The website style is perfect, thee articles is really nice :
D. Good job, cheers

slim n up xtreme reviews said...

You're so interesting! I do not believe I've
truly read through something like that before.
So great to discover someone with some genuine
thoughts on this topic. Really.. thanks for
starting this up. This web site is one thing that's needed on the internet, someone with some originality!

graphics card reviews 2014 said...

When I originally left a comment I seem to have clicked
the -Notify me when new comments are added- checkbox and now each time a comment is
added I recieve four emails with the same comment.

Perhaps there is a means you can remove me from that service?
Thanks a lot!