How to Retrieve News Feed using Facebook Graph API.? - facebook-graph-api

I am working on WPF application and I want to retrieve News Feed using facebook Graph API so how I can access it also convert into serialize.!
Thank you.

You're gonna use Facebook.dll u can download it using Package Manager in Visual studio if u are using C# for example
NuGet Package here..
and code may look like this
public List<string> Facebook(string query)
{
// Facebook.FacebookAPI api = new FacebookAPI();
List<string> list = new List<string>();
string[] arr = new string[5];
string result = null;
FacebookAPI api = new FacebookAPI(token);
// query is ur search criteria
JSONObject q = api.Get("https://graph.facebook.com/search?q="+query+"&type=post");
foreach (JSONObject item in q.Dictionary["data"].Array)
{
if (item.IsDictionary)
{
foreach (KeyValuePair<String,JSONObject> jso in item.Dictionary)
{
if (jso.Key == "message"/* || jso.Key == "name" || jso.Key == "description" || jso.Key == "link"*/)
{
for (int i = 0; i < 5; i++)
{
arr[i] = jso.Value.String;
}
list.Add (jso.Value.String);
}
else if (jso.Key == "likes")
{
foreach (JSONObject like in jso.Value.Dictionary["data"].Array)
{
foreach (KeyValuePair<String, JSONObject> lik in like.Dictionary)
{
if (lik.Key == "name")
{
result += lik.Value.String;
}
else if (lik.Key == "id")
{
result += lik.Value.String;
}
}
}
foreach (KeyValuePair<String, JSONObject> count in jso.Value.Dictionary)
{
if (count.Key == "count")
{
result += count.Value.String;
}
}
}
else if (jso.Key == "from")
{
foreach (KeyValuePair<String, JSONObject> froms in jso.Value.Dictionary)
{
if (froms.Key == "name")
{
result += froms.Value.String;
}
}
}
}
}
/*
else if (item.IsArray)
{
foreach (JSONObject j in item.Dictionary["data"].Array)
{
if (j.IsDictionary)
{
foreach (KeyValuePair<String,JSONObject> x in j.Dictionary)
{
result += (x.Key + " --- "+x.Value.String);
}
}
}
}
*/
}
return list;
}
you can of course change post and query to whatever you want to search in Facebook Graph API
and there is another way to do that using FQL and its really easy
hope that will be helpful.

Related

Update list in Kotlin

So here is my Data Class
data class Bestellung (var id:Int = 0, var anzahl:Int = 1, var speise:String? = null)
my List
private var bestellungList = ArrayList<Bestellung>()
Trying to update the list if "speise" equals "s" but its not working without any error..
if (bestellungList.contains(Bestellung(speise = s))) {
var i = bestellungList.indexOf(Bestellung(speise = s))
bestellungList.set(i, Bestellung(anzahl = +1))
problem is contains
pls try this if you want to check first:
if(bestellungList.any{ it.speise == "s" }) {
// do add logic
} else {
// do something else
}
The problem is your contains part. Replace it like this
val index = bestellungList.indexOfFirst {
it.speise == s
}
if (index >= 0) {
bestellungList[index] = Bestellung(anzahl = +1)
}
if (bestellungList.any{ it.speise == "s" }) {
bestellungList.addAll(Bestellung(anzahl = +1))
} else {
// handle else statement also
}

How to sync WebService operation in silverlight?

I am now on a project regarding controlling devices by using silverlight and web service(asmx page). The project flows like below:
pressing the button on the silverlight UI, it will send out a package by using socket to the middlewire. Then middlewire will accept the package and deconstructe it and return back another package to silverlight UI. I am using below code to load the button state, which will trigger database query:
private ButtonStateModel _buttonStateModel = new ButtonStateModel() { BtnOneImage = "Skins/images/flag/QU.png", BtnOneVisible = Visibility.Visible, BtnTwoVisible = Visibility.Collapsed };
public ButtonStateModel ButtonStateModel
{
get
{
ButtonStateModel btnState = null;
dataService.GetPR(BusEquipmentPermission.Control.RtuID, BusEquipmentPermission.Control.DevID, (result) =>
{
if (result != null && result.Count > 0)
{
var flag = result[0].PRFlag;
if (flag == 1)
{
btnState = new ButtonStateModel()
{
BtnOneImage = "Skins/images/flag/OP.png",
BtnOneVisible = Visibility.Visible,
BtnTwoImage = "Skins/images/flag/OFF.png",
BtnTwoVisible = Visibility.Visible
};
}
else if (flag == 2)
{
btnState = new ButtonStateModel()
{
BtnOneImage = "Skins/images/flag/OFF.png",
BtnOneVisible = Visibility.Visible,
BtnTwoImage = "Skins/images/flag/OR.png",
BtnTwoVisible = Visibility.Visible
};
}
}
});
return btnState;
}
set
{
if (value == _buttonStateModel)
{
return;
}
_buttonStateModel = value;
RaisePropertyChanged("ButtonStateModel");
}
}
Now the problem is, whenever I load the silverlight app, the button on the UI can't load its state correctly. I know the reason is because that the GetPR function is from webservice(asmx), it's very oddly that I can't do sync operation by using AutoResetEvent in silverlight generated client code:
public void GetPR(string rtuID, string devID, Action<List<BusControlPR>> action)
{
ServiceSoapClient proxy = new ServiceSoapClient();
proxy.GetPRAsync(rtuID, devID);
proxy.GetPRCompleted += (sender, args) =>
{
//I cannt do Sync Operation Here by using AutoResetEvent.
if (action != null)
action(args.Result.ToList());
};
}
I am using webservice (asmx page) instead of WCF ria service.
Above problem is what i meet, Anyone can give me some light?
The "GetPR" method is still running asynchronously, so the "ButtonStateModel" getter will return null immediately (the "completed" action will then have no effect). And, you do not want to use any kind of blocking inside your getters, as that will block the UI. Instead, you should put the "GetPR" in the initialization, and use the to set the "ButtonStateModel" property to the appropriate value:
public class TheViewModel
{
public ButtonStateModel ButtonStateModel
{
get
{
return _buttonStateModel;
}
set
{
if (value == _buttonStateModel)
{
return;
}
_buttonStateModel = value;
RaisePropertyChanged("ButtonStateModel");
}
}
public TheViewModel()
{
Initialize();
}
private void Initialize()
{
dataService.GetPR(BusEquipmentPermission.Control.RtuID, BusEquipmentPermission.Control.DevID, (result) =>
{
ButtonStateModel btnState = null;
if (result != null && result.Count > 0)
{
var flag = result[0].PRFlag;
if (flag == 1)
{
btnState = new ButtonStateModel()
{
BtnOneImage = "Skins/images/flag/OP.png",
BtnOneVisible = Visibility.Visible,
BtnTwoImage = "Skins/images/flag/OFF.png",
BtnTwoVisible = Visibility.Visible
};
}
else if (flag == 2)
{
btnState = new ButtonStateModel()
{
BtnOneImage = "Skins/images/flag/OFF.png",
BtnOneVisible = Visibility.Visible,
BtnTwoImage = "Skins/images/flag/OR.png",
BtnTwoVisible = Visibility.Visible
};
}
}
ButtonStateModel = btnState;
});
}
}

How to sort the selected items in a Sitecore Treelist?

Is there a way to always have the selected items in a Sitecore Treelist sorted alphabetically?
No, but you could look in to creating your own 'sorted treelist'. Someone asked a different question earlier today but it has basically the same answer:
Sitecore Tree list datasource - VersionExist
Sitecore lets you create custom field types. They can be based on existing ones, but with some added tweaks.
As mentioned in the answers to the other question, here are 2 articles which are good places to start:
Creating a Composite Custom Field
Apply Dynamic TreeList Source Parameters with the Sitecore ASP.NET CMS
Here's my implementation, which although long, is mostly copy-and-pasted from the decompiled Treelist code. I've highlighted which bits which are new in the Value property and the Add method:
namespace CustomFieldTypes
{
public class Treelist : Sitecore.Shell.Applications.ContentEditor.TreeList
{
public override string Value
{
get
{
// ---------- New code here -----------
var ids = base.Value.Split('|');
var db = Sitecore.Configuration.Factory.GetDatabase("master");
var items = ids.Select(id => db.GetItem(id)).Where(item => item != null);
var orderedItems = items.OrderBy(item => item.Name);
var orderedIds = orderedItems.Select(item => item.ID.ToString());
return String.Join("|", orderedIds);
// ---------------------------------------
}
set
{
base.Value = value;
}
}
protected void Add()
{
if (this.Disabled)
return;
string viewStateString = this.GetViewStateString("ID");
TreeviewEx treeviewEx = this.FindControl(viewStateString + "_all") as TreeviewEx;
Assert.IsNotNull((object) treeviewEx, typeof (DataTreeview));
Listbox listbox = this.FindControl(viewStateString + "_selected") as Listbox;
Assert.IsNotNull((object) listbox, typeof (Listbox));
Item selectionItem = treeviewEx.GetSelectionItem();
if (selectionItem == null)
{
SheerResponse.Alert("Select an item in the Content Tree.", new string[0]);
}
else
{
if (this.HasExcludeTemplateForSelection(selectionItem))
return;
if (this.IsDeniedMultipleSelection(selectionItem, listbox))
{
SheerResponse.Alert("You cannot select the same item twice.", new string[0]);
}
else
{
if (!this.HasIncludeTemplateForSelection(selectionItem))
return;
SheerResponse.Eval("scForm.browser.getControl('" + viewStateString + "_selected').selectedIndex=-1");
ListItem listItem = new ListItem();
listItem.ID = Sitecore.Web.UI.HtmlControls.Control.GetUniqueID("L");
// ----- New Code Here -----------------------
bool listItemAdded = false;
for (int i = 0; i < listbox.Controls.Count; i++ )
{
ListItem control = (ListItem)listbox.Controls[i];
if (control == null)
return;
if (String.Compare(GetHeaderValue(selectionItem), control.Header) < 0)
{
listbox.Controls.AddAt(i, listItem);
listItemAdded = true;
break;
}
}
if (!listItemAdded)
{
Sitecore.Context.ClientPage.AddControl((System.Web.UI.Control)listbox, (System.Web.UI.Control)listItem);
}
// ------------------------------------------
listItem.Header = this.GetHeaderValue(selectionItem);
listItem.Value = listItem.ID + (object) "|" + (string) (object) selectionItem.ID.ToString();
SheerResponse.Refresh((Sitecore.Web.UI.HtmlControls.Control) listbox);
SetModified();
}
}
}
protected static void SetModified()
{
Sitecore.Context.ClientPage.Modified = true;
}
private bool HasIncludeTemplateForSelection(Item item)
{
Assert.ArgumentNotNull((object)item, "item");
if (this.IncludeTemplatesForSelection.Length == 0)
return true;
else
return HasItemTemplate(item, this.IncludeTemplatesForSelection);
}
private bool HasExcludeTemplateForSelection(Item item)
{
if (item == null)
return true;
else
return HasItemTemplate(item, this.ExcludeTemplatesForSelection);
}
private bool IsDeniedMultipleSelection(Item item, Listbox listbox)
{
Assert.ArgumentNotNull((object)listbox, "listbox");
if (item == null)
return true;
if (this.AllowMultipleSelection)
return false;
foreach (Sitecore.Web.UI.HtmlControls.Control control in listbox.Controls)
{
string[] strArray = control.Value.Split(new char[1]
{
'|'
});
if (strArray.Length >= 2 && strArray[1] == item.ID.ToString())
return true;
}
return false;
}
private static bool HasItemTemplate(Item item, string templateList)
{
Assert.ArgumentNotNull((object)templateList, "templateList");
if (item == null || templateList.Length == 0)
return false;
string[] strArray = templateList.Split(new char[1]
{
','
});
ArrayList arrayList = new ArrayList(strArray.Length);
for (int index = 0; index < strArray.Length; ++index)
arrayList.Add((object)strArray[index].Trim().ToLowerInvariant());
return arrayList.Contains((object)item.TemplateName.Trim().ToLowerInvariant());
}
}
}
When this is compiled and in your application you need to go to /sitecore/system/Field types/List Types/Treelist in the core database. In there, you need to fill in the Assembly and Class fields, and clear out the Control fields.
You could create a custom field and sort the items in the selected list using generics, then save the guids back to the field. I covered this in a recent blog post. There isn't that much coding involved.

How to unit test unformatted method in mvc?

I have to unit test one of the very big and unformatted method in ASP.NET MVC 4.0.
Below is the code of action method :-
public ActionResult GetDetails(string ProdName, int ProdArea, int ProdAreaId= 0)
{
if (ProdAreaId == 0 && ProdArea == 1 && System.Web.HttpContext.Current.Session["ResponseProdAreaId"] != null)
{
ProdAreaId = (int)System.Web.HttpContext.Current.Session["ResponseProdAreaId"];
}
if (string.IsNullOrEmpty(ProdName))
{
if (System.Web.HttpContext.Current.Session["ProdName"] == null)
{
ProdName = Guid.NewGuid().ToString();
System.Web.HttpContext.Current.Session["ProdName"] = ProdName;
}
else
{
ProdName = System.Web.HttpContext.Current.Session["ProdName"].ToString();
}
}
else
{
ProdName = ProdName.Replace("___", " ");
}
List<StateDetail> stateList = ProductService.GetAllStates().Where(n => n.FKCountryID == (int)Countries.UnitedStates).ToList();
ProductAddressViewModel model = new ProductAddressViewModel
{
ProdArea = ProdArea,
FKProductID = CurrentProductId
};
model.States = stateList != null ? new SelectList(stateList, "StateID", "StateCode") : null;
if (System.Web.HttpContext.Current.Session[“ProdAddresses”] != null && ProdAreaId == 0 && ProdArea == 1)
{
List<ProductAddressDto> lstprodaddresses = (List<ProductAddressDto>)System.Web.HttpContext.Current.Session[“ProdAddresses”];
if (lstprodaddresses.Count > 0)
{
AddressDto addrDto = lstprodaddresses.First().Address;
//save address in DB
model.Address1 = addrDto.Address1;
model.Address2 = addrDto.Address2;
model.ProdArea = 1;
model.City = addrDto.City;
model.IsDefault = true;
model.ProdName = model.ProdName;
model.SelectedAddressTypeID = (int)AddressType.Street;
model.ZIPCode = addrDto.ZIPCode;
model.SelectedStateId = addrDto.FKStateID;
model.AddressTypes = GetAddressTypes();
}
}
else if (model.FKProductID > 0)
{
ToolDto tool = ToolService.GetToolDetails(model.FKProductID);
if (ProdAreaId > 0)
{
model.AddressTypes = GetAddressTypes();
ProductAddressDto prodaddr = tool.ToolAddresses.First(n => n.Tool_AddressID == ProdAreaId);
model.Address1 = prodaddr.Address.Address1;
model.Address2 = prodaddr.Address.Address2;
model.City = prodaddr.Address.City;
model.SelectedStateId = prodaddr.Address.FKStateID;
model.ZIPCode = prodaddr.Address.ZIPCode;
model.SelectedAddressTypeID = prodaddr.Address.FKAddressTypeID;
model.IsDefault = prodaddr.IsDefault;
model.FKAddressID = prodaddr.FKAddressID;
model.Tool_AddressID = prodaddr.Tool_AddressID;
model.FKProductID = prodaddr.FKProductID;
model.AddressTypes = GetAddressTypes();
}
else
{
//address types
List<int> excludeAddrTypes = new List<int>();
foreach (ProductAddressDto prodadrdto in tool.ToolAddresses)
{
if (prodadrdto.Tool_AddressID != ProdAreaId)
{
excludeAddrTypes.Add(prodadrdto.Address.FKAddressTypeID);
}
}
if (System.Web.HttpContext.Current.Session[“ProdAddresses”] != null)
{
excludeAddrTypes.Add((int)AddressType.Street);
}
var addrtypes = from AddressType e in Enum.GetValues(typeof(AddressType))
where !excludeAddrTypes.Contains((int)e)
select new { Id = (int)e, Name = e.ToString() };
model.AddressTypes = addrtypes.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name
});
if (tool.ToolAddresses.Count == 0)
{
model.IsDefault = (ProdArea == 1);
}
}
}
else
{
//filter out address types if responsed tool is there
if (System.Web.HttpContext.Current.Session[“ProdAddresses”] != null)
{
List<int> excludeAddrTypes = new List<int>();
excludeAddrTypes.Add((int)AddressType.Street);
var addrtypes = from AddressType e in Enum.GetValues(typeof(AddressType))
where !excludeAddrTypes.Contains((int)e)
select new { Id = (int)e, Name = e.ToString() };
model.AddressTypes = addrtypes.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name
});
}
else
{
model.AddressTypes = GetAddressTypes();
}
model.IsDefault = (ProdArea == 1);
}
model.ProdName = ProdName;
return PartialView("_AddUpdateAddress", model);
}
May be the method is not in correct format.But i have to do it's unit testing.I have do that in several different ways.But i am not sure about its correctness.
I want to know that how should we do unit test for such a big and unformatted method like this.
Can anyone help me out on this ?
Below is the piece of code of my unit testing method :-
[TestMethod]
public void GetDetailsTest_NotEmpty()
{
var ProdName = random.ToString();
var ProdArea = random.Next();
var ProdAreaId = 0;
var _toolServiceMock = new Mock<IToolService>();
var _lookupServiceMock = new Mock<ILookupService>();
var stateList = new List<StateDto> {
new StateDto() { StateID = random.Next(), StateCode = Guid.NewGuid().ToString(), Description = random.ToString(), FKCountryID = 1 },
new StateDto() { StateID = random.Next(), StateCode = Guid.NewGuid().ToString(), Description = random.ToString(), FKCountryID = random.Next() },
};
_lookupServiceMock.Setup(s => s.GetAllStates()).Returns(stateList); // .Returns(stateList);
//Arrange
CustomerDto cust = _toolService.LookupCustomers("", "").FirstOrDefault();
if (cust != null)
{
ToolDto tool = _toolService.GetToolDetails(cust.Tool.toolId);
if (tool.ToolAddresses.Count > 0 && tool.ToolAddresses.First().Address != null)
{
HttpContext.Current.Session["FKToolID"] = cust.FKToolID;
var controller = new ToolController(_toolServiceMock.Object);
PartialViewResult result = controller.SelectAddress(cust.Tool.Name, 1, tool.ToolAddresses.First().Tool_AddressID) as PartialViewResult;
var viewmodel = (ToolAddressViewModel)((ViewResultBase)(result)).Model;
if (viewmodel != null)
{
//Act
Assert.AreEqual(tool.ToolAddresses.First().Address.Address1, viewmodel.Address1);
Assert.AreEqual("_AddUpdateAddress", result.ViewName);
Assert.IsInstanceOfType(viewmodel, typeof(ToolAddressViewModel));
}
//Act
_lookupServiceMock.VerifyAll();
}
}
}
First of all, your method is a way too complicated and too long.
Make your actions short and with one responsability to respect SOLID principle (http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)).
It will make your methods easier to test.
To help you with your problem, you can do something quick with your code :
Split your actions in internal virtual methods with one concern each (internal to be testable in you unit test project, virtual to be able to mock them).
Put the [assembly: InternalsVisibleTo("YourTestAssembly")] on your controller
In your unit test project, you will be able to test any of your internal methods separately.
Finally, to test your action, use a mocking framework (RhinoMock, Moq) to mock all your internal virtual methods and test the logic of your action (proxies generated by mocking framework will let you mock virtual methods).
It's the easiest way you can test your logic without breaking the existing application.
The inconvenient is that your logic is in internal methods wich let the whole assembly able to use it.

The correct display name/field for a list item in a Sharepoint list (using Web Services)

I'm creating a program that uses SharePoint Web Services to query and show a Sharepoint list to the user. I can only show one column at a time, so I need to find a 'default column' or 'display column' to show. I know 'Title' is commonly used in many of the content types but I want this to be robust with any type of custom content type or list so I would like to find some way of querying the list to discover this field.
For example: I'm using SharePoint Manager 2010 here and looking at a Link Library (That doesn't have a Title field) but somehow it knows that the list item is called 'http://google.com'. How is it inferring this?
(source: adamburkepile.com)
Looks like DisplayName has quite a bit of logic behind it. Here is the code I got using Reflector:
public string DisplayName
{
get
{
if (!this.IsNew)
{
if ((!this.ParentList.AllowContentTypes && (this.ParentList.BaseType == SPBaseType.DocumentLibrary)) || (this.ParentList.AllowContentTypes && (this.ContentTypeId.IsNonDiscussionFolder || this.ContentTypeId.IsChildOf(SPBuiltInContentTypeId.Document))))
{
string str = (string) this.GetValue("BaseName", false);
if (!string.IsNullOrEmpty(str))
{
return SPHttpUtility.HtmlDecode(str);
}
}
SPField fieldByInternalName = this.Fields.GetFieldByInternalName("Title", false);
if (fieldByInternalName != null)
{
string fieldValueAsText = fieldByInternalName.GetFieldValueAsText(this.GetValue(fieldByInternalName, -1, false));
if (!string.IsNullOrEmpty(fieldValueAsText))
{
return fieldValueAsText;
}
}
if (this.ParentList.AllowContentTypes)
{
if (this.ContentTypeId.IsChildOf(SPBuiltInContentTypeId.Link))
{
SPFieldUrlValue value2 = new SPFieldUrlValue((string) this.GetValue("URL", false));
if (!string.IsNullOrEmpty(value2.Description))
{
return value2.Description;
}
if (!string.IsNullOrEmpty(value2.Url))
{
return value2.Url;
}
}
if (this.ContentTypeId.IsChildOf(SPBuiltInContentTypeId.Message))
{
Guid discussionTitleLookup = SPBuiltInFieldId.DiscussionTitleLookup;
SPField fld = this.Fields[discussionTitleLookup];
string str3 = fld.GetFieldValueAsText(this.GetValue(fld, -1, false));
if (!string.IsNullOrEmpty(str3))
{
return str3;
}
}
}
if (this.ParentList.BaseType != SPBaseType.Survey)
{
using (IEnumerator enumerator = this.Fields.GetEnumerator())
{
SPField field3;
string str5;
while (enumerator.MoveNext())
{
field3 = (SPField) enumerator.Current;
if (field3.GetFieldBoolValue("TitleField"))
{
goto Label_00C6;
}
}
goto Label_016F;
Label_00BB:
if (!(field3 is SPFieldMultiLineText))
{
return str5;
}
goto Label_00ED;
Label_00C6:
str5 = field3.GetFieldValueAsText(this.GetValue(field3, -1, false));
if (string.IsNullOrEmpty(str5))
{
goto Label_016F;
}
goto Label_00BB;
Label_00ED:
if (str5.Length <= 0xff)
{
return str5;
}
return str5.Substring(0, 0xff);
}
}
SPContext context2 = SPContext.Current;
if ((context2 == null) || (context2.FormContext.FormMode != SPControlMode.Edit))
{
return SPResource.GetString("ViewResponseTitle", new object[] { this.ID.ToString("N0", this.Web.Locale) });
}
return SPResource.GetString("ToolBarMenuRespondToSurvey", new object[0]);
}
SPContext current = SPContext.Current;
if (this.ParentList.BaseType != SPBaseType.Survey)
{
if ((current != null) && current.FormContext.IsNonDiscussionFolder)
{
return SPResource.GetString("ButtonTextNewFolder", new object[0]);
}
return SPResource.GetString("NewFormTitleNewItem", new object[0]);
}
return SPResource.GetString("ToolBarMenuRespondToSurvey", new object[0]);
Label_016F:
return SPResource.GetString("NoTitle", new object[0]);
}
}