I need to bind the search result from NEST (ElasticSearch) to a Gridview in ASP.NET (Webform).
Code I get the result from ElasticSearch from using NEST:
public class Address
{
public int SN { get; set; }
public string JLN { get; set; }
}
protected void BtnSearch_Clicked(object sender, EventArgs e)
{
string SearchValue = txtSearchValue.Text;
string es_host = System.Configuration.ConfigurationManager.AppSettings["cnStringIP"];
string es_port = System.Configuration.ConfigurationManager.AppSettings["cnStringPort"];
string es_index = System.Configuration.ConfigurationManager.AppSettings["cnStringIndex"];
var settings = new ConnectionSettings(new Uri("http://" + es_host + ":" + es_port + ""))
.DefaultIndex("masterlist*");
var client = new ElasticClient(settings);
var searchResponse = client.Search<Address>(s => s
.Index("masterlist*")
.From(0)
.Size(10)
.Query(q => q
.QueryString(qs => qs
.Query("JLN:\""+ SearchValue +"\"")
)
)
);
var address = searchResponse.Documents.ToList();
ESGridview.DataSource = address;
ESGridview.DataBind();
}
With this code, the gridview can auto-generate two fields of correct header which is "SN" and "JLN", and it can auto generate 10 rows (I limit the size to 10 rows max in search syntax) but it's empty data in the column.
I did found another POST with this link
https://www.elastic.co/guide/en/elasticsearch/client/net-api/6.x/returned-fields.html#returned-fields
After check with this link,
I changed my code to:
string SearchValue = txtSearchValue.Text;
string es_host = System.Configuration.ConfigurationManager.AppSettings["cnStringIP"];
string es_port = System.Configuration.ConfigurationManager.AppSettings["cnStringPort"];
string es_index = System.Configuration.ConfigurationManager.AppSettings["cnStringIndex"];
var settings = new ConnectionSettings(new Uri("http://" + es_host + ":" + es_port + ""))
.DefaultIndex("masterlist*");
var client = new ElasticClient(settings);
var searchResponse = client.Search<Address>(s => s
.StoredFields(sf => sf
.Fields(
f => f.SN,
f => f.JLN
)
)
.From(0)
.Size(10)
.Query(q => q
.QueryString(qs => qs
.Query("JLN:\""+ SearchValue +"\"")
)
)
);
foreach (var fieldValues in searchResponse.Fields)
{
var document = new
{
SN = fieldValues.ValueOf<Address, int>(p => p.SN),
JLN = fieldValues.Values<Address, string>(p => p.JLN)
};
}
var address = searchResponse.Documents;
var count = "MaxScore" + searchResponse.MaxScore;
ESGridview.DataSource = address;
ESGridview.DataBind();
But I get an error while run the code from start on whole foreach (var...) area :
System.NullReferenceException:'Object reference not set to an instance of an object.'
Did anyone can teach me how can solve this problem or anything I do fault ?
Many many thanks ~
ElasticSearch 7.0.1
NEST 7.0.0
C#
ASP.NET (Webform)
I solve my problem already.
The code below is how to get the searchResult from ElasticSearch and bind the data into Gridview in ASP.NET by using NEST.
public class Address
{
[Text(Name = "SN")]
public string SN { get; set; }
[Text(Name = "JLN")]
public string JLN { get; set; }
}
protected void BtnSearch_Clicked(object sender, EventArgs e)
{
string SearchValue = txtSearchValue.Text;
string es_host = System.Configuration.ConfigurationManager.AppSettings["cnStringIP"];
string es_port = System.Configuration.ConfigurationManager.AppSettings["cnStringPort"];
string es_index = System.Configuration.ConfigurationManager.AppSettings["cnStringIndex"];
var settings = new ConnectionSettings(new Uri("http://" + es_host + ":" + es_port + ""))
.DefaultIndex("masterlist*");
var client = new ElasticClient(settings);
var searchResponse = client.Search<Address>(s => s
.From(0)
.Size(100)
.Query(q => q
.QueryString(qs => qs
.Query("JLN:\"" + SearchValue + "\"")
)
)
);
var address = searchResponse.Documents.ToList();
ESGridview.DataSource = address;
ESGridview.DataBind();
}
I have the code below:
using (var context = new ClientContext(URL))
{
context.Credentials = new SharePointOnlineCredentials(username, password);
Web web = context.Web;
context.Load(web.Lists, lists => lists.Include(list => list.Title, list => list.Id));
context.ExecuteQuery();
List SupportList = context.Web.Lists.GetByTitle("Support");
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
ListItem newItem = SupportList.AddItem(itemCreateInfo);
foreach (var selector in f.rtxt_select.Text.Split(','))
{
var s = selector.Split('=');
newItem[s[0].Trim()] = m.GetType().GetProperty(s[1].Trim()).GetValue(m, null);
}
newItem.Update();
context.ExecuteQuery();
f.txtMessage.AppendText("Message has been added to Sharepoint List \n ");
f.lbl_successCount.Text = (Convert.ToInt32(f.lbl_successCount.Text) + 1).ToString();
}
Everything works just fine if the username and password is correct. But Is there is a way i can validate if the user has access to the site(SharePoint Online)?
Check Web.GetUserEffectivePermissions method.
How to get a list users in Task Manager with status?
I found only how to get a list of domain users
var usersSearcher = new ManagementObjectSearcher(#"SELECT * FROM Win32_UserAccount");
var users = usersSearcher.Get();
You can try this code to get the list of users:
var usersSearcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_UserAccount");
var managementObjects = usersSearcher.Get();
List<string> result = new List<string>();
foreach (ManagementObject item in managementObjects)
{
foreach (var pr in item.Properties)
{
if (pr.Name == "Caption")
{
result.Add(pr.Value?.ToString());
}
}
}
var users = result.Distinct().ToList();
Also you may try this:
var usersSearcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Process");
var managementObjects = usersSearcher.Get();
List<string> allUsers = new List<string>();
foreach (ManagementObject obj in managementObjects)
{
string[] argList = new string[] { string.Empty, string.Empty };
int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));
if (returnVal == 0)
{
// return DOMAIN\user
allUsers.Add(argList[1] + "\\" + argList[0]);
}
}
var result = allUsers.Distinct().ToList();
I am trying to read the value of a particular field in a SharePoint Custom List.
The Custom List has the following fields: Field1, Field2 and Field3
When I call the code below:
public static string GetLastTargetColumnValue(string sharePointSiteUrl, string sharePointListName, string targetColumnName)
{
string targetColumnValue = string.Empty;
using (var clientContext = new ClientContext(sharePointSiteUrl))
{
clientContext.Credentials = new NetworkCredential("userName", "password");
var list = clientContext.Web.Lists.GetByTitle(sharePointListName);
var query = CamlQuery.CreateAllItemsQuery(100);
var items = list.GetItems(query);
clientContext.Load(items);
clientContext.ExecuteQuery();
var listItem = items.Last();
foreach (var fieldValue in listItem.FieldValues)
{
Console.WriteLine(fieldValue.Key + ":" + fieldValue.Value + Environment.NewLine);
}
}
targetColumnValue = listItem[targetColumnName] as string;
return targetColumnValue;
}
The error message is:
Additional information: The property or field has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.
The fields which are displayed in the foreach show "Field1" and "Field2". Do I have to explicitly request "Field3". If yes how?
I had to get the internal name before querying the value for some reason. Here is the code that worked:
public static string GetLastTargetColumnValue(string sharePointSiteUrl, string sharePointListName, string targetColumnName)
{
string targetColumnValue = string.Empty;
using (var clientContext = new ClientContext(sharePointSiteUrl))
{
clientContext.Credentials = new NetworkCredential("userName", "password");
var list = clientContext.Web.Lists.GetByTitle(sharePointListName);
var field = list.Fields.GetByInternalNameOrTitle(targetColumnName);
var textField = clientContext.CastTo<FieldText>(field);
var query = CamlQuery.CreateAllItemsQuery(100);
var items = list.GetItems(query);
clientContext.Load(textField);
clientContext.Load(items);
clientContext.ExecuteQuery();
var listItem = items.Last();
targetColumnValue = listItem[textField.InternalName] as string;
}
return targetColumnValue;
}
I use
https://developers.facebook.com/tools/access_token/
I create an App. I want get Posts of the wall of me and my friends.
I try me/feed and me/posts but I get nothing.
I have this unit test.
Any suggestions?
[TestMethod]
public void Basic_using_SDK()
{
// http://blog.prabir.me/posts/facebook-csharp-sdk-making-requests
var fb = new Facebook.FacebookClient();
var result = (IDictionary<string, object>)fb.Get("4");
var id = (string)result["id"];
var name = (string)result["name"];
var firstName = (string)result["first_name"];
var lastName = (string)result["last_name"];
var link = (string)result["link"];
var username = (string)result["username"];
var gender = (string)result["gender"];
var male = (string)result["locale"];
var parameters = new Dictionary<string, object>();
parameters["fields"] = "id,name";
result = (IDictionary<string, object>)fb.Get("4", parameters);
id = (string)result["id"];
name = (string)result["name"];
dynamic result2 = fb.Get("4");
id = result2.id;
name = result2.name;
firstName = result2.first_name;
lastName = result2.last_name;
link = result2.link;
username = result2.username;
gender = result2.gender;
male = result2.locale;
dynamic parameters2 = new ExpandoObject();
parameters2.fields = "id,name";
dynamic result3 = fb.Get("4", parameters);
id = result3.id;
name = result3.name;
dynamic me = fb.Get("zuck");
firstName = me.first_name;
lastName = me.last_name;
var client = new FacebookClient(AccessToken);
dynamic me2 = client.Get("me");
string aboutMe = me2.about;
dynamic result4 = client.Get("/me/feed");
foreach (dynamic post in result4.data)
{
var fromName = post.from.name;
Console.WriteLine(fromName);
}
dynamic result5 = client.Get("/me/posts");
for (int i = 0; i < result5.Count; i++)
{
}
// https://www.facebook.com/profile.php?id=xxxxxxx
// https://graph.facebook.com/xxxxxxx
var uidKiquenet = "xxxxx";
var query = string.Format(#"SELECT status_id,message,time,source,uid,place_id
FROM status WHERE uid IN (SELECT uid FROM status WHERE uid = '" + uidKiquenet + "') ORDER BY time DESC");
dynamic parameters6 = new ExpandoObject();
parameters6.q = query;
dynamic results6 = fb.Get("/xxxxx?fields=id,name,age_range,about,email,first_name,gender");
string myMessage = "Hello from Test";
fb.PostTaskAsync("me/feed", new { message = myMessage }).ContinueWith(t =>
{
if (!t.IsFaulted)
{
string message = "Great, your message has been posted to you wall!";
Console.WriteLine(message);
}
});
fb.GetTaskAsync("me").ContinueWith(t =>
{
if (!t.IsFaulted)
{
var result11 = (IDictionary<string, object>)t.Result;
string myDetails = string.Format("Your name is: {0} {1} and your Facebook profile Url is: {3}",
(string)result11["first_name"], (string)result11["last_name"],
(string)result11["link"]);
Console.WriteLine(myDetails);
}
});
// This uses Facebook Query Language
// See https://developers.facebook.com/docs/technical-guides/fql/ for more information.
query = string.Format("SELECT uid,name,pic_square FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1={0}) ORDER BY name ASC", "me()");
fb.GetTaskAsync("fql", new { q = query }).ContinueWith(t =>
{
if (!t.IsFaulted)
{
var result1 = (IDictionary<string, object>)t.Result;
var data = (IList<object>)result1["data"];
var count = data.Count;
var message = string.Format("You have {0} friends", count);
Console.WriteLine(message);
foreach (IDictionary<string, object> friend in data)
Console.WriteLine((string)friend["name"]);
}
});
}
You must authorize with the correct permission in order to get access to feed posts. Try authorizing with user_posts, as it is explained in the docs: https://developers.facebook.com/docs/graph-api/reference/v2.3/user/feed#read
Be aware that this does not get you access to posts of friends, unless they posted on the wall of the authorized user.
About review, you may want to read this: https://developers.facebook.com/docs/facebook-login/review/faqs#what_is_review
Btw, FQL is deprecated and will only work in v2.0 Apps - not in newer ones.
Same thing happened to me . Here is my Solution
I made my project registered on Facebook developer console. Then I did my code same as you but could not get posts / information . After some time i submitted my application for app review to facebook team (it was still in early development phase) and after their feedback I got my code working . So pending Application review can be your issue also . This option is available in application setting . Give it a shot
Update
Another code sample is here
if (Request["code"] == null)
{
Response.Redirect(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
FB_app_id, Request.Url.AbsoluteUri, FB_scope));
return false;
}
else
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}&perms=status_update"
, FB_app_id, Request.Url.AbsoluteUri, FB_scope, Request["code"].ToString(), FB_secret_id);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader rd = new StreamReader(response.GetResponseStream());
string vals = rd.ReadToEnd();
foreach (string token in vals.Split('&'))
{
tokens.Add(token.Substring(0, token.IndexOf('=')), token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf('=') - 1));
}
string access_token = tokens["access_token"];
Session["fb_access_token"] = access_token;
return true;
}
}