How to display twitter feeds in my umbraco website? - twitter

I want to display twitter status of our customer site, but I need to give the control to him to change the twitter account. How to achieve this task? Please anyone give me a idea.
I already use twitter widget but it displays with header and I cant give control with username.
I use utweets package but it also don't have to to change the user account with user name.
Please anyone suggest a good way to display twitter feeds.

Get api credentials here: https://dev.twitter.com/
Get TweetSharp from nuget and then you can use this razor code for inspiration:
#using TweetSharp
#functions
{
private TwitterService GetAuthenticatedService()
{
var _consumerKey = "XXX";
var _consumerSecret = "XXX";
var _accessToken = "XXX";
var _accessTokenSecret = "XXX";
var service = new TwitterService(_consumerKey, _consumerSecret);
service.TraceEnabled = true;
service.AuthenticateWith(_accessToken, _accessTokenSecret);
return service;
}
}
#{
var account = "YOURACCOUNT";
var tweets = new List<TwitterStatus>();
const int take = 3;
try
{
var service = GetAuthenticatedService();
tweets = service.ListTweetsOnUserTimeline(new ListTweetsOnUserTimelineOptions() { Count = take, ScreenName = "k_h_schneider" }).ToList();
}
catch (Exception e)
{
}
}
<div class="box box-no-padding">
<div class="box-content">
<div id="twitterFeed">
#if (tweets != null)
{
foreach (var tweet in tweets)
{
<div class="tweet">
<small class="text-muted">#tweet.CreatedDate</small>
<div class="tweetContent">
#Html.Raw(tweet.TextAsHtml)
</div>
</div>
<div style="clear: both">
</div>
}
}
</div>
</div>
</div>

Take a look at the uTwit package on the Our Umbraco community site.
uTwit is a combination of two packages to allow you to easily embedd
twitter statuses on your website.

I'm using some small code that i obtained from http://social.skybrud.dk/twitter/endpoints/statuses/user-timeline/ that is causing Umbraco 7.5 to come back with Compilation error - TwitterTimelineResponse response = service.Statuses.GetUserTimeline("xxxxxxxxxx");.

Related

PagedList MVC stay on the same page after a post

I have a view where the side menu (where PagedList is populating data with no problems) that are also links to display another set of data on the same view. Once these links are clicked, I want to have the data on that field to be changed and have the side menu (PagedList) to stay on the same page. I can pass the id value to my controller and display the data, but the "page number" value is not being passed.
Any ideas on how to accomplish that.
Here's what my code looks like
[HttpPost]
public ActionResult Index(string id, int? page)
{
try
{
id = Request.Form["newsLinkButton"];
ViewBag.Id = id;
using (myEntities db = new myEntities())
{
var getNews = db.News.Where(x => x.Show == "Yes").OrderByDescending(x => x.Date).ToList();
return View(getNews.ToPagedList(page ?? 1, 5));
}
}
catch (Exception ex)
{
return View(ex);
}
}
<div class="sidebar blue-sidebar news-sidebar no-mobile">
<h2>Recent News</h2>
#using (Html.BeginForm("Index", "News", FormMethod.Post))
{
<form id="newsForm" name="newsForm">
<ul class="white-text">
#foreach (var item in Model.OrderByDescending(x => x.Date))
{
<li>
<button id="newsLinkButton" name="newsLinkButton" type="submit" value="#item.Id">#item.Title</button>
</li>
}
</ul>
</form>
<div class="center-block">
#Html.PagedListPager(Model, page => Url.Action("Index", new { page }),
new PagedListRenderOptions()
{
DisplayLinkToFirstPage = PagedListDisplayMode.Always,
DisplayLinkToPreviousPage = PagedListDisplayMode.Always,
DisplayLinkToLastPage = PagedListDisplayMode.Always,
DisplayLinkToNextPage = PagedListDisplayMode.Always,
MaximumPageNumbersToDisplay = 3, // number of pages in line
DisplayEllipsesWhenNotShowingAllPageNumbers = false
})
</div>
}
</div>
Once again, thanks for your help in advance. I appreciate.
I found out that the property PageNumber is what holds the value for the page number (yeah, I know huh?). Therefore, I created #{ Session["page"] = Model.PageNumber; } and passed on to the controller. Problem solved. I hope this can help someone else in the future.

Displaying a specific store from a list of store in MVC Store Locator

I am building a store locator for an online ordering service. I have a view and a controller. My view displays a list of stores based on a zip code search. from this list, you can click a button to place an order with that specific store. I have it linking to a new view where I want to display details about the specific store you selected. How can I do this?
<div class="store-list-box">
#{
foreach (var store in (List<Site>)ViewData["sites"])
{
<div class="store-list-style">
<h3>#store.name</h3>
<p>#store.address1</p>
<p>#store.city, #store.state #store.zip</p>
<p>#store.phone</p>
<button class="btn" type="submit" onclick='window.location = "#Url.Action("StoreInfo", "OrderTime")";'>Place Order</button>
</div>
<hr />
}
}
</div>
This is the code I have where it displays the list of stores.
public ActionResult Index(string search)
{
List<Site> result = SiteMgmt.GetByZip(search);
var emptyResult = new List<Site>();
if (string.IsNullOrEmpty(search))
{
View().ViewData["sites"] = emptyResult;
}
else
{
View().ViewData["sites"] = result;
}
return View();
}
This is the controller which displays the stores. On button click you go to the new view. How do I show the specific store details in that new view?
This is a screenshot of the list I currently display
Here is the StoreInfor() code.
public class OrderTimeController : Controller
{
public ActionResult StoreInfo(int siteID)
{
Site result = SiteMgmt.GetSite(siteID);
var emptyResult = new Site();
if (siteID == 0)
{
View().ViewData["sites"] = emptyResult;
}
else
{
View().ViewData["sites"] = result;
}
return View();
}
}

HttpServerUtility.Execute blocked while waiting for an asynchronous operation to complete for Social Providers

As Asked Question1, Question2 from other users but there is no any proper answer got so I asked here.
I am using ASP.NET MVC and trying to load social logins providers by partial view.
But I can't it gives me an error.
This is my code from where I return my partial view:
public async Task<PartialViewResult> GetProviders()
{
string apiUrl = "mywebsite";
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(apiUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("Account/externalloginpathhere");
//var result = Task.Run(async () => { await client.GetAsync("Account/externalloginpathhere"); }).Result;
if (response.IsSuccessStatusCode)
{
var data = await response.Content.ReadAsStringAsync();
var providers = Newtonsoft.Json.JsonConvert.DeserializeObject<List<ViewModel>>(data);
foreach(var provider in providers)
{
if (provider.Name == "Google")
{
//code come here
}
else if (provider.Name == "Facebook")
{
//code come here
}
else if (provider.Name == "Microsoft")
{
//code come here
}
}
return PartialView("~/Views/Account/_ExternalLoginsListPartial.cshtml", providers);
}
return null;
}
}
View calling from Home Controller View:
#{Html.RenderAction("GetProviders", "Account");}
This is what I have done please correct me whereever I goes wrong!
I have just figured it out don't know correct or not but I got the solution hope it helps someone.
I have just created one partial view and bind that partialview inside the page where I want login or signup process.
Bind the partial view:
#Html.Partial("~/Views/Account/_ExternalLoginsListPartial.cshtml")
External Providers Partial View:
#{
var loginProviders = Context.GetOwinContext().Authentication.GetExternalAuthenticationTypes();
if (loginProviders.Count() >= 0)
{
using (Html.BeginForm("ExternalLogin", "Account", FormMethod.Post, new { id = "externalLogin" }))
{
#Html.AntiForgeryToken()
<ul>
#foreach (var p in loginProviders)
{
<li>
<button value="#p.Caption" title="Login using #p.Caption account" name="provider" id="#p.Caption.ToLower()" type="submit" class="social-button">
<i class="fa fa-#p.Caption.ToLower()" id="#p.Caption"></i>
</button>
</li>
}
</ul>
}
}
}

When i try to execute foreach statement i am getting -Object reference not set to an instance of an object

i am working on mvc project. In my controller i am calling my stored procedure from terms class and I am returning Index page if it returns true or return terms page if it returns false.
Calling stored procedure in terms page :
public class Accept
{
public void Check()
{
using (var ctx = new termsEntities())
{
ctx.usp_ChkTerms(8, new ObjectParameter("Accepted", typeof(bool)));
ctx.SaveChanges();
}
}
}
Now i am calling this in my controller :
public ActionResult App()
{
// calling Stored procedure from Model to class
var accept = new Accept();
accept.Check();
// checking if accepted is true then return view else return another view
AppEntities Accepted = new AppEntities();
AppTerm user = new AppTerm();
AppHist history = new AppHist();
user = (from AppTerm app in Accepted.AppTerms
where app.userID == 8
select app).ToList().FirstOrDefault();
if (user != null)
{
if (user.Accepted)
{
return View("Index");
}
else
{
return View("terms");
}
}
And this is the code i am using in my terms view :
#{
ViewBag.Title = "terms";
}
<html>
<body>
<ul>
#foreach ( var item in Model)
{
<div class="Page" onclick="location.href='#Url.Action("Info", new { id = item.ID })'">
span class="Col1">
<br />
#item.ID
</span>
<span class="Title">#item.Name</span>
}
</ul>
</body>
</html>
Here when condition is true it is displaying Index page but when condition falls and when it tries to display terms page i am getting Object reference not set to an instance of an object and error is pointing to foreach loop. so what mistake i am doing here? i need help..
It is ugly, but you may try
<div class="Page" onclick='location.href="#Url.Action("Info", new { id = item.ID })"'>
<div class="Page" onclick="location.href='#Url.Action("Info", new { id = item.ID })'">
Change this to:
<div class="Page" onclick="location.href='#Url.Action('LinkText','Info', new { id = item.ID })'">
Note the quote marks around Info
edit:
Added extra argument to link.

Why Request.IsAuthenticated is false

I have the following script:
function OpenIdLogon(e) {
$.post("/Account/OpenIdLogOn/", { token: e }, function (data) {
$("#userNavigation").html(data);
$(".auth_box").hide();
$(".kb_fading").hide();
});
}
This is the action:
public ActionResult OpenIdLogOn(string token)
{
WebClient cli = new WebClient();
string json = cli.DownloadString(new Uri("http://ulogin.ru/token.php?token=" + Request.Params["token"] + "&host=" + Request.Url.Host));
var obj = JObject.Parse(json);
if (obj["error"] == null)
{
var userName = obj["nickname"].Value<string>();
var email = obj["email"].Value<string>();
FormsAuthentication.SetAuthCookie(userName, true);
}
return PartialView("UserNavigation");
}
And, my UserNavigation:
#if (Request.IsAuthenticated)
{
<span>#Context.User.Identity.Name</span><i class="icon iUser"></i>
<ul class="headLine_link">
<li>Profile</li>
<li>
#Html.ActionLink("Logg Off", "LogOff", "Account", null, new { #class = "exit" })</li>
</ul>
}
else
{
<ul class="headLine_link">
<li><a id="regLink">Register</a></li>
<li><a id="authLink">Log On</a></li>
</ul>
}
The problem in that Request.IsAuthenticated equals true only after refresh page.
The problem is the following:
At the time of making the request ($.post("/Account/OpenIdLogOn/"...) the user it not authenticated.
Then in your action method you authenticate the user, but on the Request object that represents the request the user made before you create the Auth cookie, the user was not authenticated. However, as you say on the next request it works since at that time the user has the Authentication cookie when he makes the request.
One solution here can be to create a viewmodel object to send from your controllers action method to your view. This viewModel can have a field called authenticated, and you can set it properly from the action method. Then check this value instead inside your view. I haven't checked this in Visual Studio, but it should be something like this:
Create the viewmodel:
public class LoginViewModel{
public bool Authenticated{ get; set; }
}
Your action method:
public ActionResult OpenIdLogOn(string token)
{
WebClient cli = new WebClient();
string json = cli.DownloadString(new Uri("http://ulogin.ru/token.php?token=" + Request.Params["token"] + "&host=" + Request.Url.Host));
var obj = JObject.Parse(json);
var viewModel = new LoginViewModel{ Authenticated = Request.IsAuthenticated };
if (obj["error"] == null)
{
var userName = obj["nickname"].Value<string>();
var email = obj["email"].Value<string>();
FormsAuthentication.SetAuthCookie(userName, true);
viewModel.Authenticated = true;
}
return PartialView("UserNavigation");
}
And your view
#model LoginViewModel
#if (Model.Authenticated)
{
<span>#Context.User.Identity.Name</span><i class="icon iUser"></i>
<ul class="headLine_link">
<li>Profile</li>
<li>
#Html.ActionLink("Logg Off", "LogOff", "Account", null, new { #class = "exit" })</li>
</ul>
}
else
{
<ul class="headLine_link">
<li><a id="regLink">Register</a></li>
<li><a id="authLink">Log On</a></li>
</ul>
}
Creating a viewmodel instead of just sending a bool as model is just because I like to always put the data I send to a view inside a viewmodel. Makes it much easier to extend later on, and makes it easier to read inside the view (you can write #if (Model.Authenticated) instead of #if (Model) for example)

Resources