Get Elasticsearch response in DataTable in C#.Net - elasticsearch

I m new to Elasticsearch 2.1.1, I want to Ask you how to fetch records from index using Suggest and convert it to DataTable. I've installed Nest NuGet Packages and all in my project.
I have this block of code which I want it from Elasticsearch in DataTable format
curl -X POST 'localhost:9200/music/_suggest?pretty' -d '{
"song-suggest" : {
"text" : "n",
"completion" : {
"field" : "suggest"
}
}
}'

I've some blocks of code it should fulfill your requirements.
As you said you are new to Elasticsearch, so I shwoing you first how to initialize connection.
var settings = new ConnectionSettings(new Uri("http://localhost:9200"));
var clientElasticSearchNet = new ElasticsearchClient(settings);
then use
var ElasticSearchNetQuery = new { music = new { "n", completion = new { field = "name_suggest" } } };
ElasticsearchResponse<string> result = clientElasticSearchNet.Suggest<string>("music", ElasticSearchNetQuery);
JObject json = JObject.Parse(result.Response.ToString());
var hitsCount = ((Newtonsoft.Json.Linq.JContainer)(json["music"].First["options"])).Count;
DataTable dtEsReponnse = new DataTable();
for (int i = 0; i < hitsCount; i++)
{
dtEsReponnse = ConvertJSONToDataTable(json["music"].First["options"][i].ToString());
}
I have created one function which will return Datatable.
protected DataTable ConvertJSONToDataTable(string jsonString)
{
string[] jsonParts = Regex.Split(jsonString.Replace("[", "").Replace("]", ""), "},{");
List<string> dtColumns = new List<string>();
foreach (string jp in jsonParts)
{
string[] propData = Regex.Split(jp.Replace("{", "").Replace("}", ""), ",");
foreach (string rowData in propData)
{
try
{
int idx = rowData.IndexOf(":");
string n = rowData.Substring(0, idx - 1);
string v = rowData.Substring(idx + 1);
if (!dtColumns.Contains(n))
{
dtColumns.Add(n.Replace("\"", ""));
}
}
catch (Exception ex)
{
throw new Exception(string.Format("Error Column Name : {0}", rowData));
}
}
break;
}
foreach (string c in dtColumns)
{
if (!dt.Columns.Contains(c.ToString().Replace("\r\n", "").Trim())) {
dt.Columns.Add(c.ToString().Replace("\r\n", "").Trim());
}
}
foreach (string jp in jsonParts)
{
string[] propData = Regex.Split(jp.Replace("{", "").Replace("}", ""), ",");
DataRow nr = dt.NewRow();
foreach (string rowData in propData)
{
try
{
int idx = rowData.IndexOf(":");
string n = rowData.Substring(0, idx - 1).Replace("\"", "").Replace("\r\n", "").Trim(); //replaced
string v = rowData.Substring(idx + 1).Replace("\"", "");
nr[n] = v;
}
catch (Exception ex)
{
continue;
}
}
dt.Rows.Add(nr);
}
return dt;
}
Is this code you looking for?

Related

Load RadComboBoxItemData[] from web Api in asp.net

How to load RadComboBoxItemData[] from Web APi in aspx?
In Web API:
public RadComboBoxItemData[] ABC(object context)
{
List<RadComboBoxItemData> result = null;
...
return result.ToArray();
}
Following is the code that I have used with great success.
<telerik:RadComboBox runat="server" ID="comboSearch"
Width="350" Height="300"
EnableLoadOnDemand="true" ShowMoreResultsBox="true"
EnableVirtualScrolling="true"
EmptyMessage="Search Names..."
ItemsPerRequest="100">
<WebServiceSettings Method="GetNames"
Path="../../webservices/NamesWS.asmx">
</WebServiceSettings>
</telerik:RadComboBox>
Following is the custom web service I wrote for our use case.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Script.Services;
using System.Web.Services;
using Telerik.Web.UI;
namespace Webservices
{
[ScriptService]
public class NamesWS : WebService
{
[WebMethod]
public RadComboBoxData GetNames(RadComboBoxContext context)
{
RadComboBoxData comboBoxData = null;
if (!string.IsNullOrEmpty(context.Text) && !string.IsNullOrWhiteSpace(context.Text))
{
using (DbConn db = new DbConn())
{
int max_ret_count = 100;
List<Users> Users = db.Users
.Where(u => u.Users.Contains(context.Text.Trim()))
.Take(max_ret_count).ToList();
if (Users == null)
{
comboBoxData = new RadComboBoxData();
List<RadComboBoxItemData> result = new List<RadComboBoxItemData>(1);
RadComboBoxItemData item = new RadComboBoxItemData();
item.Text = "";
item.Value = "";
result.Add(item);
comboBoxData.Items = result.ToArray();
}
else
{
List<RadComboBoxItemData> result = new List<RadComboBoxItemData>(context.NumberOfItems);
comboBoxData = new RadComboBoxData();
try
{
int itemsPerRequest = Convert.ToInt32(max_ret_count);
int itemOffSet = context.NumberOfItems;
int endOffSet = itemOffSet + itemsPerRequest;
if (endOffSet > Users.Count)
{
endOffSet = Users.Count;
}
if (endOffSet == Users.Count)
{
comboBoxData.EndOfItems = true;
}
else
{
comboBoxData.EndOfItems = false;
}
result = new List<RadComboBoxItemData>(endOffSet - itemOffSet);
for (int i = itemOffSet; i < endOffSet; i++)
{
RadComboBoxItemData itemData = new RadComboBoxItemData();
itemData.Text = Users[i].UserName;
itemData.Value = Users[i].UserID;
result.Add(itemData);
}
if (Users.Count > 0)
{
comboBoxData.Message = String.Format("Items <b>1</b>-<b>{0}</b> out of <b>{1}</b>"
, endOffSet.ToString()
, Users.Count.ToString());
}
else
{
comboBoxData.Message = "No matches";
}
comboBoxData.Items = result.ToArray();
}
catch (Exception ex)
{
ins_error_log err = new ins_error_log();
err.runSP(ex, false);
}
}
}
}
else
{
comboBoxData = new RadComboBoxData();
List<RadComboBoxItemData> result = new List<RadComboBoxItemData>(1);
RadComboBoxItemData item = new RadComboBoxItemData();
item.Text = "";
item.Value = "";
result.Add(item);
comboBoxData.Items = result.ToArray();
}
return comboBoxData;
}
}
}

The specified string is not in the form required for an e-mail address.i am getting Emails from Database

this is method
#region StuDetailsMail
public List StuDetailsMail(string Stu_Name, string Stu_Email, string Stu_Mobile)
{
List data = new List();
SqlParameter[] sqlprm = new SqlParameter[3];
SqlDataReader dr = null;
try {
sqlprm[0] = new SqlParameter(DBProcedures.sqlparam_Name, Stu_Name);
sqlprm[1] = new SqlParameter(DBProcedures.sqlpram_Email, Stu_Email);
sqlprm[2] = new SqlParameter(DBProcedures.sqlpram_Mobile_Num, Stu_Mobile);
dr = objDAL.ExecuteReader(DBProcedures.Usp_StuEmail, ref sqlprm, false);
while (dr.Read())
{
InstEmails list1 = new InstEmails()
{
Emaillist = dr["email"].ToString(),
};
data.Add(list1);
};
foreach (var emailId in data)
{
string MessageBody = "studentname" + Stu_Name + " is Intersted" + "studentmail is" + Stu_Email;
string MailSubject = "this is from Traininghubs";
obj.SendEmailToInstitute(emailId.ToString(), MessageBody, MailSubject);
}
}
catch(Exception e)
{
}
return data;
}
#endregion

Can't apply Geo queries in parse (Parse Framework)

I have tried to apply the geopoints in parse but I can't do the query. The code is as follows.
ParseObject placeObject = new ParseObject("placeObject");
ParseGeoPoint userLocation = (ParseGeoPoint) placeObject.get("location");
ParseQuery query = new ParseQuery("PlaceObject");
query.whereNear("location", userLocation);
query.setLimit(10);
query.findInBackground(new FindCallback() {
public void done(List<ParseObject> Locaciones, ParseException e) {
if (e == null) {
Log.d("ERROR",Locaciones.toString());
// object will be your game score
} else {
Log.d("ERROR",e.toString());
// something went wrong
}
}
});
Try this:
ParseObject.registerSubclass(MasterEntity.class);
ParseGeoPoint userLocation = new ParseGeoPoint(latitude,longitude);
ParseQuery<MasterEntity> query = ParseQuery.getQuery("UserMaster");
query.whereNear("location", userLocation);
query.setLimit(30);
query.findInBackground(new FindCallback<MasterEntity>() {
#Override
public void done(List<MasterEntity> mlist, ParseException e) {
dlg.dismiss();
if (e==null) {
for (int i = 0; i < mlist.size(); i++) {
MasterEntity cc = mlist.get(i);
String s_email = cc.getEmail();
String s_uname = cc.getuserName();
String s_objid = cc.getObjectID();
List<ParseObject> aryFollower = cc.getFollowers();
List<ParseObject> aryFollowing = cc.getFollowing();
}
}
else
{
Alert.alertOneBtn(getActivity(),"Something went wrong.Please try again later");
}
}
});
Sample App : https://github.com/ParsePlatform/AnyWall/tree/master/AnyWall-android
Tutorial : https://parse.com/tutorials/anywall-android

Fill RadGridView dynamically

I am using RadControls for WinForms 2011 Q3
The datasource for a RadGridView is dynamically generated based on users' input/selection
Everytime when a datasource is generated, I will call SetDatasource2KeyValuesGrid()
What I expect to see is columns generated and values filled in gridview.
However what I see is columns generated but no value filled even though the number of rows in gridview match the number of items in its datasource(keyValuesList)
I must have missed something simple. Please help. thanks
Edit:
I create a DataTable from the list keyValueList, and then assign it to DataSource, then it works
Just wonder if there's a better way. thanks
private void CreateTableSetDatasource(List<FeedKeyValueOneSet>) keyValueList)
{
if(keyValueList==null) return;
var table = new DataTable();
table.Columns.Add("Check");
foreach (var feedKeyValueOneSet in keyValueList)
{
var oneset = feedKeyValueOneSet.KeyValueOneSet;
foreach (var oneKey in oneset)
{
table.Columns.Add(oneKey.key);
}
break;
}
foreach (var feedKeyValueOneSet in keyValueList)
{
var oneset = feedKeyValueOneSet.KeyValueOneSet;
var numOfCol = oneset.Length + 1;
var obj = new object[numOfCol];
obj[0] = "false";
int idx = 1;
foreach (var oneKey in oneset)
{
obj[idx] = oneKey.value;
idx++;
}
table.Rows.Add(obj);
}
radGridKeyValues.DataSource = table;
}
private void SetDatasource2KeyValuesGrid()
{
if (radGridKeyValues.Columns != null) radGridKeyValues.Columns.Clear();
radGridKeyValues.AutoGenerateColumns = false;
radGridKeyValues.EnableFiltering = false;
radGridKeyValues.ShowFilteringRow = false;
radGridKeyValues.ShowHeaderCellButtons = false;
radGridKeyValues.AllowDragToGroup = false;
radGridKeyValues.AllowAddNewRow = false;
radGridKeyValues.EnableGrouping = false;
var keyValueList = (List<FeedKeyValueOneSet>)TimeSeries.FeedValuesCache[m_strFeedName + "_KEYVALUES"];
if(keyValueList==null) return;
GridViewDataColumn checkBoxColumn = new GridViewCheckBoxColumn("columnState", "columnState");
checkBoxColumn.HeaderText = string.Empty;
if (radGridKeyValues.Columns != null) radGridKeyValues.Columns.Add(checkBoxColumn);
foreach (var feedKeyValueOneSet in keyValueList)
{
var oneset = feedKeyValueOneSet.KeyValueOneSet;
foreach (var oneKey in oneset)
{
var textboxCol = new GridViewTextBoxColumn(oneKey.key, oneKey.key);
textboxCol.Width = 150;
textboxCol.ReadOnly = true;
if (radGridKeyValues.Columns != null) radGridKeyValues.Columns.Add(textboxCol);
}
break;
}
radGridKeyValues.DataSource = keyValueList;
}
public class FeedKeyValueOneSet
{
public FeedFieldValues[] KeyValueOneSet;
}
public class FeedFieldValues
{
public string key { get; set; }
public string value { get; set; }
}
I create a DataTable from the list keyValueList, and then assign it to DataSource, then it works
see code in edit to the question

Assigning Linq result to Datatable

I am getting the result from linq query as var(IEnumrable<'T'> anonymous type<'string,int>')
i want the result to be in the datatable or dataset.
I found two sample for that issue;
Sample I:
I created a public method called LINQToDataTable as following:
public DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
{
DataTable dtReturn = new DataTable();
// column names
PropertyInfo[] oProps = null;
if (varlist == null) return dtReturn;
foreach (T rec in varlist)
{
// Use reflection to get property names, to create table, Only first time, others
will follow
if (oProps == null)
{
oProps = ((Type)rec.GetType()).GetProperties();
foreach (PropertyInfo pi in oProps)
{
Type colType = pi.PropertyType;
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()
==typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
}
}
DataRow dr = dtReturn.NewRow();
foreach (PropertyInfo pi in oProps)
{
dr[pi.Name] = pi.GetValue(rec, null) == null ?DBNull.Value :pi.GetValue
(rec,null);
}
dtReturn.Rows.Add(dr);
}
return dtReturn;
}
Sample II
Here is my second method:
public DataTable ToDataTable(System.Data.Linq.DataContext ctx, object query)
{
if (query == null)
{
throw new ArgumentNullException("query");
}
IDbCommand cmd = ctx.GetCommand(query as IQueryable);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = (SqlCommand)cmd;
DataTable dt = new DataTable("sd");
try
{
cmd.Connection.Open();
adapter.FillSchema(dt, SchemaType.Source);
adapter.Fill(dt);
}
finally
{
cmd.Connection.Close();
}
return dt;
}

Resources