OData webservice quering from VS Service Reference - visual-studio-2010

I want to send request like this:
/odata.svc/Pages(ItemId=27,PublicationId=1)
Here's the code I'm using:
CdService.ContentDeliveryService cdService = new ContentDeliveryService(new Uri("http://xxx.xx:81/odata.svc"));
var pages = cdService.Pages;
pages = pages.AddQueryOption("ItemId", "270");
pages = pages.AddQueryOption("PublicationId", "2");
var result = pages.Execute();
My problem is that this code is sending request like this:
/odata.svc/Pages()?ItemId=270&PublicationId=2
The problem with this request is that it returns me all the pages there are and not just the one I need.
I could use LINQ:
result.Single(page => page.ItemId == 27 && page.PublicationId == 1);
But the problem is that all the pages will still be sent over the wire

I've done a quick test with LINQ and it seems to be doing the correct query:
ContentDeliveryService.ContentDeliveryService service =
new ContentDeliveryService.ContentDeliveryService(new Uri("http://localhost:99/odata.svc"));
var page = from x in service.Pages
where x.ItemId == 2122
&& x.PublicationId == 16
select x;
foreach (var page1 in page)
{
Console.WriteLine(page1.Title);
}
Console.Read();

You can try this:
EntityDescriptor entityDescriptor = service.Entities.Where(c =>
c.Entity is CDService.Page
&& ((CDService.Page)c.Entity).ItemId == pageId.ItemId
&& ((CDService.Page)c.Entity).PublicationId == pageId.PublicationId)
.FirstOrDefault();
if (entityDescriptor != null)
{
return (CDService.Page)entityDescriptor.Entity;
}

I have found a solution, although not very nice:
ContentDeliveryService cdService1
= new ContentDeliveryService(new Uri("http://xxx.xx:81/odata.svc"));
var page = cdService1.Execute<Page>(
new Uri("http://xxx.xx:81/odata.svc/Pages(ItemId=27,PublicationId=1)"));

Related

Get courses.list without archived classes

Using a HTTP GET request, how would you only get the classes that are active. Could you add a parameter to the Google API URL that only returns a list of active classes? Or do you have to search through the returned array and delete any classes are archived using a for loop?
var classroom = new XMLHttpRequest();
var accessToken = localStorage.getItem('accessToken');
classroom.open('GET',
'https://classroom.googleapis.com/v1/courses');
classroom.setRequestHeader('Authorization',
'Bearer ' + accessToken);
classroom.send();
classroom.onload = function () {
if (classroom.readyState === classroom.DONE) {
if (classroom.status === 200) {
var response = JSON.parse(classroom.response);
vm.classes = response.courses;
console.log(response);
for (var i = 0; i < response.courses.length; i++){
var courses = response.courses[i];
console.log(courses.name);
}
} else {
console.log("Error Unknown");
}
}
};
Any help would be much appreciated.
Thanks!
There's no filter option yet like with User objects. (That's documented for at least as far as I can tell). So yes you'll have to pull all of the courses and then just filter out the archived courses. https://developers.google.com/classroom/reference/rest/v1/courses there's a CourseState section that lists the 5 possible states a course can be in. [COURSE_STATE_UNSPECIFIED, ACTIVE, ARCHIVED, PROVISIONED, DECLINED]
Reading through the docs, courses.list returns a list of courses that the requesting user is permitted to view. It does not state a direct way of retrieving active classes only. You may have to resort to your said implementation.
Try this:
function get_courses(student) {
var optionalArgs = {
studentId: student
};
var response = Classroom.Courses.list(optionalArgs);
var courses = response.courses;
var active_courses = [];
if (courses && courses.length > 0) {
for (i = 0; i < courses.length; i++) {
var course = courses[i];
if(course.courseState == "ACTIVE"){
active_courses.push(course);
Logger.log('%s (%s)', course.name, course.id);
}
}
} else {
Logger.log('No courses found.');
}
return active_courses;
}

Deep LINQ projections, how?

Let's say I have a model created with EF 4.0
User
Roles
Permissions
Each entity has a DeleteDate property.
I want to get a specific user (with Name =...) and have the tree filled with items where DeletedDate == null..
This must be done with anonymous type projection as result, but I don't know how to accomplish this with a hierachy deeper than 2..
This is what I already have:
public MyProjection MyCall(string givenName)
{
var result = from s in context.Users
where (s.Name == givenName &&
s.DeletedDate == null)
select new
{
s,
roles = from r in s.Roles
where r.DeletedDate == null
select r
};
var outcome = result.FirstOrDefault();
if (outcome != null)
{
var myProjection = new MyProjection()
{
User = outcome.s,
Roles = outcome.roles
};
return myProjection;
}
return null;
}
Depending on your structure you could do something like this:
var result = m.Users.Where(u => u.DeletedDate == null)
.Select( u => new
{
u,
roles = u.Roles.Where(r => r.DeletedDate == null)
.Select(r => new
{
r,
permissions = r.Permissions.Where(p => p.DeletedDate == null)
})
}).FirstOrDefault(item => item.u.Name == givenName);
If you retrieve with the following:
var result = from s in MyUsers
where s.DeletedDate == null
select new aUser{
Roles = (from r in s.Roles
where r.DeletedDate == null
select r).ToList()
};
And then create a TreeView:
TreeView treeView = new TreeView();
Then set the ItemsSource of the TreeView to the IEnumerable:
treeView.ItemsSource = result;
Then build a HierarchicalDataTemplate in your TreeView to represent your Lists (similar to this or for more in depth this), then voila!

Parsing Financial information from HTML

First attempt at learning to work with HTML in Visual Studio and C#. I am using html agility pack library. to do the parsing.
From this page I am attempting to pull out the numbers from the "Net Income" row for each quarter.
here is my current progress, (But I am uncertain of how to proceed further):
String url = "http://www.google.com/finance?q=NASDAQ:TXN&fstype=ii"
var webGet = new HtmlWeb();
var document = webGet.Load(url);
var body = document.DocumentNode.Descendants()
.Where(n => n.Name == "body")
.FirstOrDefault();
if (body != null)
{
}
Well, first of all there's no need to get the body first, you can directly query the document for what you want. As for finding the value you're looking for, this is how you could do it:
HtmlNode tdNode = document.DocumentNode.DescendantNodes()
.FirstOrDefault(n => n.Name == "td"
&& n.InnerText.Trim() == "Net Income");
if (tdNode != null)
{
HtmlNode trNode = tdNode.ParentNode;
foreach (HtmlNode node in trNode.DescendantNodes().Where(n => n.NodeType == HtmlNodeType.Element))
{
Console.WriteLine(node.InnerText.Trim());
//Output:
//Net Income
//265.00
//298.00
//601.00
//672.00
//666.00
}
}
Also note the Trim calls because there are newlines in the innertext of some elements.

C#/ Html agility pack, is there a more eloquent way to screen scrape?

I'm working on an app in C# that gathers web data from a few different pages daily and saves it in SQL Server. I'm using html agility pack... at the moment I have an xpath for each field/ column in the database. There are 62 columns in the table, and with checking for proper values and formatting, the code below is VERY verbose and repetitive (specifically, xpath expressions and associated blocks). I was wondering if there was a nicer, more concise way, perhaps using LINQ? (which I haven't used much yet but would like to) Here's just the first couple fields set below, this repeats .... 62 cols. I'm not looking for a rewrite, just any suggestions I can get.
List<IDataPoint> list = new List<IDataPoint>();
HtmlWeb hwObject = new HtmlWeb();
HtmlDocument htmlDoc = hwObject.Load(AddressString);
if (htmlDoc.DocumentNode != null && !htmlDoc.DocumentNode.InnerHtml.Contains("There is no key statistics data available"))
{
var symbolNode = htmlDoc.DocumentNode.SelectSingleNode("/html/body/div[3]/div[4] /div/div/div/div/div/div/h2");
if (symbolNode != null)
{
KeyStatsDP keyStatsDp = new KeyStatsDP();
String symb = "";
symb = symbolNode.InnerHtml;
symb = symb.Substring(symb.LastIndexOf("(") + 1);
symb = symb.Substring(0, symb.Length - 1);
keyStatsDp.Symbol = symb;
String mktCapXPath = "//*[#id=\"yfs_j10_" + symb.ToLower() + "\"]";
var mktCapNode = htmlDoc.DocumentNode.SelectSingleNode(mktCapXPath);
if (mktCapNode != null)
{
String mktCap = mktCapNode.InnerHtml;
keyStatsDp.MarketCapIntraDay = ConvertMoneyInStrToInt(mktCap);
}
var entValNode = htmlDoc.DocumentNode.SelectSingleNode("//html/body/div[3]/div[4]/table[2]/tr[2]/td/table[2]/tr/td/table/tr[2]/td[2]");
if (entValNode != null)
{
if (!entValNode.InnerHtml.Contains("N"))
{
String entVal = entValNode.InnerHtml;
keyStatsDp.EntValue = ConvertMoneyInStrToInt(entVal);
}
}

API to create cookie for FireFox

I want to write an application which will create cookies for firefox.
I want to create Client cookies so that firefox will send cookie content in HTTP request.
Similar to the win32 API InternetSetCookie()
Can you please guide on this ?
If you can point me to some code snippet or help, I will try to figure out from that.
This cookie needs to go to SQLITE database, but it seems from old questions that this database get locked if firefox is running. This locking is done in FF 3.5
Just want to confirm if this is the case with FF9 or do we have any API ?
Regards
On Firefox, you can write an add-on to achieve that. Take a look at the source code of the following add-ons. They provide features such as adding, deleting, editing cookies while Firefox is running. It seems they all work with Firefox 9.0.1 (latest stable).
Cookie Manager+
Advanced Cookie Manager
Add N Edit Cookie
Edit Cookie
Edit:
I am posting some cookie management code from the Evernote plugin's MozillaCookieManagerImpl.js file. I think the code speaks for itself. Have a look below. It shows how to access cookies, set, get and remove them etc.
Accessing Mozilla's Cookie Management Interface
Evernote.MozillaCookieManagerImpl = function MozillaCookieManagerImpl() {
};
Evernote.inherit(Evernote.MozillaCookieManagerImpl,
Evernote.CookieManagerImpl, true);
Evernote.MozillaCookieManagerImpl.isResponsibleFor = function(navigator) {
var ua = navigator.userAgent.toLowerCase();
return (ua.indexOf("firefox") >= 0 || ua.indexOf("thunderbird") >= 0 || ua
.indexOf("shredder") >= 0);
};
Evernote.MozillaCookieManagerImpl.prototype.manager = null;
Evernote.MozillaCookieManagerImpl.prototype._ios = null;
Evernote.MozillaCookieManagerImpl.prototype._cookieSrv = null;
Evernote.MozillaCookieManagerImpl.prototype._cookieManagerSrv = null;
Evernote.MozillaCookieManagerImpl.prototype.getIOService = function() {
if (this._ios == null) {
this._ios = Components.classes["#mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
}
return this._ios;
};
Evernote.MozillaCookieManagerImpl.prototype.getCookieService = function(
force) {
if (this._cookieSrv == null || force) {
this._cookieSrv = Components.classes["#mozilla.org/cookieService;1"]
.getService(Components.interfaces.nsICookieService);
}
return this._cookieSrv;
};
Evernote.MozillaCookieManagerImpl.prototype.getCookieManagerService = function(
force) {
if (this._cookieManagerSrv == null || force) {
this._cookieManagerSrv = Components.classes["#mozilla.org/cookiemanager;1"]
.getService(Components.interfaces.nsICookieManager);
}
return this._cookieManagerSrv;
};
Get Cookie
Evernote.MozillaCookieManagerImpl.prototype.get = function(name, url) {
var uri = this.getIOService().newURI(url, null, null);
var cookieMgr = this.getCookieManagerService();
if (cookieMgr) {
for ( var e = cookieMgr.enumerator; e.hasMoreElements();) {
var cookie = e.getNext().QueryInterface(Components.interfaces.nsICookie);
if (cookie && cookie.host == uri.host && cookie.name == name) {
return new Evernote.Cookie(cookie);
}
}
}
return null;
};
Set Cookie
Evernote.MozillaCookieManagerImpl.prototype.set = function(cookie, url) {
var uri = (typeof url == 'string') ? this.getIOService().newURI(url, null,
null) : null;
if (cookie instanceof Evernote.Cookie && typeof cookie.name == 'string'
&& cookie.name.length > 0) {
this.getCookieService().setCookieString(uri, null,
(cookie.name + "=" + cookie.value + ";"), null);
}
};
Removie Cookie
Evernote.MozillaCookieManagerImpl.prototype.remove = function(name, url) {
var cookieMgr = this.getCookieManagerService();
var urlParts = url.split("://", 2);
var domain = (urlParts.length == 2) ? urlParts[1] : urlParts[0];
urlParts = domain.split("/", 2);
var path = (urlParts.length == 2) ? urlParts[1] : null;
cookieMgr.remove(domain, name, path, false);
};

Resources