OpenSearch Autocomplete with ASP.net - c#

My website currently adds a custom Omnibox search engine to chrome using the following code:
ombnibox.xml
<?xml version="1.0"?>
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
<ShortName>Example </ShortName>
<Description>Example Search</Description>
<Url type="text/html" template="http://Example.com /search.aspx?searchVal= {searchTerms}"></Url>
</OpenSearchDescription>
My site master page includes:
<link type="application/opensearchdescription+xml" title="Example" rel="search" href="/omnibox.xml" />
This is working great and users are brought to my search results page without any issues. I would like to integrate search suggestions into this custom search engine but I don't even know where to start. I have found a bunch of PHP examples returning JSON but I cannot find an example for ASP.net or an example that retrieves the result suggestions from a database.
Any help would be awesome.

you need to add the following line to your xml file
<Url type="application/x-suggestions+json" method="get" template="http://www.domain.co.uk/autocomplete" />
and gets result in the following format:
["bm",["BMW","BMW X5","BMW X3","BMW 5 Series","BMW 1 Series","BMW 1 Series Cabriolet","BMW 3 Series","BMW Z4","BMW 3 Series Compact","BMW 116i"]]
Have a look at Mozilla's documentation
I hope this help you.

I looked into this more and I was able to create a web-service that returns properly formatted JSON values to be used by the Omnibox !!BUT!! the Omnibox code requires that a "GET" request is called to access the web-service which is blocked by ASP.net by default. Once I overwrote the default settings for ASP.NET to allow GET requests, it would only allow me to return XML formatted values.
I am currently under the assumption that using the Omnibox type-ahead feature isn't an option unless I create a non-ASP.net web-service.
UPDATE
I was able to figure this out using an ASP.NET MVC WebAPI and the following code:
public object Get(string id)
{
List<ResultObject> resultValues = new List<ResultObject>();
foreach (string val in ***SQLQUERYRESULTS***)
{
test singleResult = new ResultObject();
singleResult.Name = val;
singleResult.Description = "Server";
singleResult.Url = "***CUSTOMURL***?ServerName=" + val;
resultValues.Add(singleResult);
}
var entities = resultValues;
var names = entities.Select(m => m.Name);
var description = entities.Select(m => m.Description);
var urls = entities.Select(m => m.Url);
var entitiesJson = new object[] { id, names, description, urls };
return entitiesJson;
}
}
public class ResultObject
{
public string Name { get; set; }
public string Description { get; set; }
public string Url { get; set; }
}

Related

Insert in DB a JSON object from a URL

I'm new to the REST API world. I explain my need: at a specific URL I have a raw JSON text, I would like this text to be acquired by my application and inserted later in the DB as a model I created previously through EF. C# NET-CORE 2.2.
if I wasn't clear enough, don't hesitate to ask me for more details.
Thanks in advance!
Edit:
I'm sorry if it' was unclear, I will provide more detail:
Actually, i have a JSON string downloaded from an url. I did it with the following code:
var client = new WebClient();
var jsonFull = client.DownloadString(string.Format("https://url"));
It's working fine. Now, I need to take from this string only a little part of the JSON, so i did:
using var jsonDoc = JsonDocument.Parse(jsonFull);
var jsonParsed = jsonDoc.RootElement;
var myCV = jsonParsed.GetProperty("cv");
CVE is an object of this JSON, and I succesfully take it.
Inside this object, there is another one called CV_data, so I extract this:
var myCVLE = myCV.GetProperty("CV_data_meta");
The result is a var with inside
ValueKind = Object : "{
"ID": "CV-2019",
"ASS": "cv#ms.org"
}"
Now, I have a class like that
public class CV_data_meta
{
[JsonPropertyName ("ID")]
public string ID { get; set; }
[JsonPropertyName("ASS")]
public string ASS { get; set; }
}
The question is: how i can put the value in the var myCVLE in the class CV_data_meta?
I tried with
var myCVClass = JsonSerializer.Deserialize<CV_data_meta>(myCVLE);
But I get an error.
Note: I can't deserialize all the string JSON into an object, because there are a lot of information that I don't need.
Thanks in advance all!
As I understand from your question, it follows:
You first need to create the JSON object mapping (class) that the API URL will return.
Then consume the API url like this:
var client = new WebClient();
var reply =
client.DownloadString(
string.Format("https://www.yourapi.com/yourpath?yourkey={0}", yourkey));
receive and map object with mapped class
var yourvar = JsonConvert.DeserializeObject<yourclass>(reply);
Now you have the API return mapped to a class in your application, you can do whatever you want with it, including saving to a database.

Get HTML string from web in C#, but does not contain data part

I'm trying to get a data from webpage(https://finance.naver.com/sise/sise_trans_style.nhn) In my UWP App.
I write following source code in my project.
public class MainPageViewModel : Observable
{
public string urlAddress = "https://finance.naver.com/sise/sise_trans_style.nhn";
public string data { get; set; }
public MainPageViewModel()
{
ButtonClick = new RelayCommand(Click);
}
public async void Click()
{
HttpClient httpClient = new HttpClient();
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var result = await httpClient.GetStringAsync(new Uri(urlAddress));
data = result;
OnPropertyChanged("data");
}
public RelayCommand ButtonClick { get; set; }
}
But, the problem is, I'm not getting document's data part. following picture depicts the part of docs that I want to get.
In "data" variable, I get docs without data the most important part to me. I can get just other html parts.
I was trying to figure out where data are coming from, or which source helps me to get data. but I failed.
Are the data made from javascript? .. ajax... and,, how can I get data from that web page? .. And if I encounter this kind of problems next time, how can I figure out the reason?
(EDIT)Added HTML Source. and more specified.
when I see HTML DOCS with my source, I can get following contents.
<div class="box_type_m">
<iframe name="time" src="/sise/investorDealTrendTime.nhn?bizdate=20181005&sosok=" width="100%" height="380" marginheight="0" bottommargin="0" topmargin="0" SCROLLING="no" frameborder="0" title="시간별 순매수"></iframe>
</div>
but iframe has another html source ( contatining head & body).
The data you want is in iframes. These are loaded as pages within the page. You can see this in the source.
The actual URLs you should check out are:
https://ssl.pstatic.net/imgfinance/chart/sise/trendUitradeDayKOSPI.png?sid=1538753584555
https://finance.naver.com/sise/investorDealTrendTime.nhn?bizdate=20181005&sosok=
https://finance.naver.com/sise/investorDealTrendDay.nhn?bizdate=20181005&sosok=

ASP.NET Core Razor Page multiple path routing

I'm building a system using ASP.NET Core 2.0 Razor Pages (not MVC) and I'm having trouble adding multiple routes for pages. For example, all pages should be able to be reached by abc.com/language/segment/shop/mypage or abc.com/language/shop/mypage, where both paths point to the same page. The segment path section is optional, then the pages do stuff with the optional segment info.
The question mark syntax in the CombineTemplates markup doesn't seem to work, it seems to only work in the last section of the path. Browsing to a url without a value in the {segment?} section resulted in 404. For example:
AttributeRouteModel.CombineTemplates("{language}/{segment?}/shop", selector.AttributeRouteModel.Template);
I tried code like this below but it only appends the two paths to each other, and I need to be able to enable them both as valid.
options.Conventions.Add(new DefaultPageRouteModelConvention());
options.Conventions.Add(new SegmentPageRouteModelConvention());
In ASP.NET MVC, I could just add two different routes pointing to the same area/controller/action with two different named MapRouteWithName.
Any ideas how to do this with .NET Razor Page syntax?
This code works:
Add a single convention (not two different conventions):
options.Conventions.Add(new CombinedPageRouteModelConvention());
In the new convention, add both route selectors:
private class CombinedPageRouteModelConvention : IPageRouteModelConvention
{
private const string BaseUrlTemplateWithoutSegment = "{language}/shop";
private const string BaseUrlTemplateWithSegment = "{language}/{segment}/shop";
public void Apply(PageRouteModel model)
{
var allSelectors = new List<SelectorModel>();
foreach (var selector in model.Selectors)
{
//setup the route with segment
allSelectors.Add(CreateSelector(selector, BaseUrlTemplateWithSegment));
//setup the route without segment
allSelectors.Add(CreateSelector(selector, BaseUrlTemplateWithoutSegment));
}
//replace the default selectors with new selectors
model.Selectors.Clear();
foreach (var selector in allSelectors)
{
model.Selectors.Add(selector);
}
}
private static SelectorModel CreateSelector(SelectorModel defaultSelector, string template)
{
var fullTemplate = AttributeRouteModel.CombineTemplates(template, defaultSelector.AttributeRouteModel.Template);
var newSelector = new SelectorModel(defaultSelector)
{
AttributeRouteModel =
{
Template = fullTemplate
}
};
return newSelector;
}
}

How can i get my own wall posts using the Facebook c# API

I am being incredible dim, but i cannot seem to get my head around or find any examples of using the Facebook c# API to get a list of wall posts. Now initially, for testing i just want to get my own, this will be replaced with the clients wall posts, but in essence the procedure will be the same. It is simply to show the wall posts in a styled format on my clients new website.
I need some help/guidance with
Becuase this is data owned by the person (i.e. me and my client) do i still need to get an authentication token or can i generate one for this purpose (i already have an app token/secret)
How can i grab the posts, i tried looking at the examples but even though i really see the benefit of the dynamic approach, especially with a beast like Facebook, without the intellisence i am like a beached whale, flapping around but going nowhere.
Does anyone know how to do this, or have any good examples anywhere?
No matter what you do, you need users permission, for that, you need to create a Facebook App first.
Go to https://developers.facebook.com/apps and create one.
If you are using it only in a website, just fillup the website URL with your http://localhost:12345 save it, grab the secret and api key and ad to your web.config file in the Facebook C# SDK area.
Now that you can get information on your page, you need to ask permission to the user to request the wall posts, you will find all request permissions in facebook.
That goes on either the javascript if you want to use the Facebook javascript API (fastest) or as an attribute in the Action that needs that permission.
You might find the Video from the author of this SDK that he gave in MIX this year, to be a nice tool to start you up really nice.
heyy rob,
to get the user's wall post, you have to make use of facebook graph API...check out here..
https://developers.facebook.com/docs/reference/api/
this document is pretty cool...
you can generate API call
for example.... to get the wall post..
JsonObject fbJsonFeedObj = (JsonObject)fb.Get(" https://graph.facebook.com/me/home?fields=from,message,name,picture&access_token=" + _accessToken);
this can be useful, it will return the result in json object.
and be sure that you have read_stream permission!
this is how to view your facebook post using c# and asp.net:
protected void Button2_Click(object sender, EventArgs e)
{
var fb = new FacebookClient("your token here");
var query = string.Format(#"SELECT status_id,message,time,source,uid,place_id
FROM status WHERE uid IN (SELECT uid FROM status WHERE uid = 'Your FB ID here') ORDER BY time DESC");
dynamic parameters = new ExpandoObject();
parameters.q = query;
dynamic results = fb.Get("/fql", parameters);
List<MyPost> q = JsonConvert.DeserializeObject<List<MyPost>>(results.data.ToString());
GridView2.DataSource = q;
GridView2.DataBind();
}
public class MyPost
{
public long status_id { get; set; }
public string message { get; set; }
public string time { get; set; }
public string source { get; set; }
public long uid { get; set; }
public string place_id { get; set; }
}

Caching JSON Data in C# MVC3

I am developing an application that presents a company's twitter feed on a Facebook application. This is a large company with lots of traffic to the FB App so I need to cache the Twitter data I receive (from the twitter API) so that I can avoid their rate limits.
In my code, I use LinqToTwitter to call the API and then I construct a string of JSON with the results. That string is then fed to the user's browser via AJAX.
The rate limit for Twitter API calls is 150 per hour, so I figure I will just place the string of JSON data I construct in a cache object and only refresh it once per minute leaving me well below the Twitter rate limit.
The problem is that I am fairly new to MVC for .NET and can't seem to use System.Web.Caching like I could do in a webforms application.
In older webforms apps I simply did something like:
private string KeyTwitterData;
...
string data = null;
if (Cache[KeyTwitterData] == null)
{
var url = LinqToTwitter.Request.Url;
data = ServiceMethods.GetConversation(url);
Cache.Insert(KeyTwitterData, data);
}
else
{
data = (string)Cache[KeyTwitterData];
}
Can someone please tell me how to accomplish this in MVC3?
Thanks!
Matt
In ASP.NET MVC 3 if you want to cache the result of a controller action you could decorate it with the [OutputCache] attribute:
[OutputCache(Duration = 3600, Location = OutputCacheLocation.Server, VaryByParam = "none")]
public ActionResult Foo()
{
var model = SomeExpensiveOperationToFetchData();
return View(model);
}
If you don't want to cache the entire output of a controller action you could use the MemoryCache class:
var data = MemoryCache.Default[KeyTwitterData];
if (data == null)
{
data = SomeExpensiveOperationToFetchData();
MemoryCache.Default.Add(KeyTwitterData, data, DateTime.Now.AddMinutes(5));
}
// use the data variable here
Use HttpContext.Cache in your controller
string data = null;
if (HttpContext.Cache[KeyTwitterData] == null)
{
var url = LinqToTwitter.Request.Url;
data = ServiceMethods.GetConversation(url);
HttpContext.Cache.Insert(KeyTwitterData, data);
}
else
{
data = (string)HttpContext.Cache[KeyTwitterData];
}

Categories

Resources