Contact us

LinkedIn Tytex

Exception in template (Designs/Website/Paragraph/ParagraphLinkedInFeeds.cshtml): System.Net.WebException: The remote server returned an error: (403) Forbidden.
   at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)
   at System.Net.WebClient.DownloadString(Uri address)
   at CompiledRazorTemplates.Dynamic.afabcedffcb.LinkedInAPI.GetCompanyUpdates()
   at CompiledRazorTemplates.Dynamic.afabcedffcb.Execute()
   at RazorEngine.Templating.TemplateBase.RazorEngine.Templating.ITemplate.Run(ExecuteContext context)
   at RazorEngine.Templating.TemplateService.Run(ITemplate template, DynamicViewBag viewBag)
   at RazorEngine.Templating.TemplateService.Parse(String razorTemplate, Object model, DynamicViewBag viewBag, String cacheName)
   at RazorEngine.Razor.Parse[T](String razorTemplate, T model, String cacheName)
   at Dynamicweb.Rendering.Template.Output()
@using System.IO @functions { string GetImage(string image, int width, int height, int compression, int crop, string colorSpace, bool doNotUpscale) { // Crop // 0 = Center // 1 = From upper left // 2 = From lower left // 3 = From lower right // 4 = From upper right // 5 = Keep aspect ratio // 6 = Fit image // ColorSpace // rgb // cmyk // grayscale var param = new List<string>(); param.Add("Image=" + image); param.Add("Format=" + Path.GetExtension(image).Substring(1)); if (width > 0) { param.Add("Width=" + width); } if (height > 0) { param.Add("Height=" + height); } param.Add("Compression=" + compression); param.Add("Crop=" + crop); param.Add("ColorSpace=" + colorSpace); param.Add("DoNotUpscale=" + (doNotUpscale ? "True" : "False")); return "/Admin/Public/GetImage.ashx?" + string.Join("&amp;", param); } string GetImagePlaceholder(int width, int height) { return GetImagePlaceholder(width, height, null, null, null); } string GetImagePlaceholder(int width, int height, string backgroundColor, string textColor, string text) { var r = "https://placehold.it/" + width; if (height > 0) { r += "x" + height; } if (!string.IsNullOrWhiteSpace(backgroundColor) && !string.IsNullOrWhiteSpace(textColor)) { r += "/" + backgroundColor; r += "/" + textColor; } if (!string.IsNullOrWhiteSpace(text)) { r += "?text=" + text.Replace(" ", "+"); } return r; } T LoadContextItem<T>(string key) { var pw = Dynamicweb.Frontend.PageView.Current(); var obj = pw != null && pw.Context != null ? pw.Context.GetValue(key) : null; return obj == null ? default(T) : (T)obj; } void SaveContextItem(string key, object value) { var pw = Dynamicweb.Frontend.PageView.Current(); if (pw == null) { return; } if (pw.Context == null) { pw.Context = new Dynamicweb.Frontend.PageViewContext(); } pw.Context.SetValue(key, value); } string PathCombine(params string[] paths) { return Path.Combine(paths); } string NullIfEmpty(string value) { return string.IsNullOrEmpty(value) ? null : value; } string NullIfWhiteSpace(string value) { return string.IsNullOrWhiteSpace(value) ? null : value; } string ToJson(object value) { return ToJson(value, false); } string ToJson(object value, bool indented) { return Newtonsoft.Json.JsonConvert.SerializeObject( value, indented ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None, new Newtonsoft.Json.Converters.IsoDateTimeConverter { DateTimeFormat = "yyyyMMdd'T'HHmmss" } ); } void AddCssFile(params string[] files) { var list = LoadContextItem<List<string>>("SB.CssFiles"); if (list == null) { list = new List<string>(); } foreach (var file in files) { if (!list.Contains(file, StringComparer.OrdinalIgnoreCase)) { list.Add(file); } } SaveContextItem("SB.CssFiles", list); } void AddJsFile(params string[] files) { var list = LoadContextItem<List<string>>("SB.JsFiles"); if (list == null) { list = new List<string>(); } foreach (var file in files) { if (!list.Contains(file, StringComparer.OrdinalIgnoreCase)) { list.Add(file); } } SaveContextItem("SB.JsFiles", list); } } @using System.Collections.Specialized @using System.Globalization @using System.IO @using System.Net @using System.Text @functions { public class LinkedInAPI { public string DesignBaseUrl { get; set; } public string CompanyId { get; set; } public string State { get; set; } public string ClientId { get; set; } public string ClientSecret { get; set; } public string AuthorizedRedirectURL { get; set; } private string TokenPath; private Newtonsoft.Json.Linq.JObject _Token; private Newtonsoft.Json.Linq.JObject Token { get { if (_Token == null) { var json = default(string); if (File.Exists(TokenPath)) { json = File.ReadAllText(TokenPath); } if (!string.IsNullOrWhiteSpace(json)) { _Token = Newtonsoft.Json.Linq.JObject.Parse(json); } } return _Token; } } public string AccessToken { get { return (string)Token["access_token"]; } } public int ExpiresIn { get { return (int)Token["expires_in"]; } } public DateTime Expires { get { return DateTime.ParseExact((string)Token["_expires"], "yyyyMMdd'T'HHmmss", CultureInfo.InvariantCulture); } } public LinkedInAPI(string designbaseurl, string companyid, string state, string clientid, string clientsecret, string authorizedredirecturl) { DesignBaseUrl = designbaseurl; CompanyId = companyid; State = state; ClientId = clientid; ClientSecret = clientsecret; AuthorizedRedirectURL = authorizedredirecturl; TokenPath = Dynamicweb.Context.Current.Server.MapPath(DesignBaseUrl + "LinkedIn-Token.txt"); } public void Auth() { Dynamicweb.Context.Current.Response.Redirect( "https://www.linkedin.com/oauth/v2/authorization?response_type=code" + "&client_id=" + ClientId + "&state=" + State + "&redirect_uri=" + AuthorizedRedirectURL, true ); } public void SetToken(string code) { using (var wc = new WebClient()) { var nvc = new NameValueCollection(); nvc.Add("grant_type", "authorization_code"); nvc.Add("code", code); nvc.Add("client_id", ClientId); nvc.Add("client_secret", ClientSecret); nvc.Add("redirect_uri", AuthorizedRedirectURL); var result = wc.UploadValues("https://www.linkedin.com/oauth/v2/accessToken", nvc); var json = Encoding.UTF8.GetString(result); var jObj = Newtonsoft.Json.Linq.JObject.Parse(json); var expires = DateTime.Now.AddSeconds((int)jObj["expires_in"]); jObj["_code"] = code; jObj["_expires"] = expires.ToString("yyyyMMdd'T'HHmmss"); File.WriteAllText(TokenPath, jObj.ToString()); _Token = null; } } public CompanyUpdate[] GetCompanyUpdates() { var cached = Dynamicweb.Caching.Cache.Current.Get<CompanyUpdate[]>("LinkedInAPI.GetCompanyUpdates"); if (cached != null) { return cached; } var json = default(string); using (var wc = new WebClient()) { wc.Encoding = Encoding.UTF8; wc.Headers[HttpRequestHeader.Authorization] = "Bearer " + AccessToken; json = wc.DownloadString("https://api.linkedin.com/v1/companies/" + CompanyId + "/updates?format=json"); } if (!string.IsNullOrWhiteSpace(json)) { var jObj = Newtonsoft.Json.Linq.JObject.Parse(json); var result = jObj["values"].Select(o => new CompanyUpdate { Comment = (string)o["updateContent"]["companyStatusUpdate"]["share"]["comment"], Date = LinkedInAPI.JavaTimeStampToDateTime((double)o["updateContent"]["companyStatusUpdate"]["share"]["timestamp"]), Image = (string)o["updateContent"]["companyStatusUpdate"]["share"]["content"]["submittedImageUrl"], Url = (string)o["updateContent"]["companyStatusUpdate"]["share"]["content"]["shortenedUrl"] }).ToArray(); Dynamicweb.Caching.Cache.Current.AddOrUpdate<CompanyUpdate[]>("LinkedInAPI.GetCompanyUpdates", result, new Dynamicweb.Caching.CacheItemPolicy() { AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(30) }); return result; } return null; } private static DateTime JavaTimeStampToDateTime(double javaTimeStamp) { var result = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); result = result.AddMilliseconds(javaTimeStamp).ToLocalTime(); return result; } public class CompanyUpdate { public string Comment { get; set; } public DateTime Date { get; set; } public string Image { get; set; } public string Url { get; set; } } } } @{ var paragraphId = GetInteger("ParagraphID"); var maxFeeds = GetInteger("Item.MaxFeeds"); // Advanced var cssClassName = GetString("Item.CssClassName"); var clearfix = GetBoolean("Item.Clearfix"); var unwrap = GetBoolean("Item.Unwrap"); // Bootstrap var phones = GetString("Item.Phones"); var tablets = GetString("Item.Tablets"); var mediumDesktops = GetString("Item.MediumDesktops"); var largeDesktops = GetString("Item.LargeDesktops"); var offsetPhones = GetString("Item.OffsetPhones"); var offsetTablets = GetString("Item.OffsetTablets"); var offsetMediumDesktops = GetString("Item.OffsetMediumDesktops"); var offsetLargeDesktops = GetString("Item.OffsetLargeDesktops"); var pushPhones = GetString("Item.PushPhones"); var pushTablets = GetString("Item.PushTablets"); var pushMediumDesktops = GetString("Item.PushMediumDesktops"); var pushLargeDesktops = GetString("Item.PushLargeDesktops"); var pullPhones = GetString("Item.PullPhones"); var pullTablets = GetString("Item.PullTablets"); var pullMediumDesktops = GetString("Item.PullMediumDesktops"); var pullLargeDesktops = GetString("Item.PullLargeDesktops"); phones = !string.IsNullOrWhiteSpace(phones) ? "col-xs-" + phones : string.Empty; tablets = !string.IsNullOrWhiteSpace(tablets) ? "col-sm-" + tablets : string.Empty; mediumDesktops = !string.IsNullOrWhiteSpace(mediumDesktops) ? "col-md-" + mediumDesktops : string.Empty; largeDesktops = !string.IsNullOrWhiteSpace(largeDesktops) ? "col-lg-" + largeDesktops : string.Empty; offsetPhones = !string.IsNullOrWhiteSpace(offsetPhones) ? "col-xs-offset-" + offsetPhones : string.Empty; offsetTablets = !string.IsNullOrWhiteSpace(offsetTablets) ? "col-sm-offset-" + offsetTablets : string.Empty; offsetMediumDesktops = !string.IsNullOrWhiteSpace(offsetMediumDesktops) ? "col-md-offset-" + offsetMediumDesktops : string.Empty; offsetLargeDesktops = !string.IsNullOrWhiteSpace(offsetLargeDesktops) ? "col-lg-offset-" + offsetLargeDesktops : string.Empty; pushPhones = !string.IsNullOrWhiteSpace(pushPhones) ? "col-xs-push-" + pushPhones : string.Empty; pushTablets = !string.IsNullOrWhiteSpace(pushTablets) ? "col-sm-push-" + pushTablets : string.Empty; pushMediumDesktops = !string.IsNullOrWhiteSpace(pushMediumDesktops) ? "col-md-push-" + pushMediumDesktops : string.Empty; pushLargeDesktops = !string.IsNullOrWhiteSpace(pushLargeDesktops) ? "col-lg-push-" + pushLargeDesktops : string.Empty; pullPhones = !string.IsNullOrWhiteSpace(pullPhones) ? "col-xs-pull-" + pullPhones : string.Empty; pullTablets = !string.IsNullOrWhiteSpace(pullTablets) ? "col-sm-pull-" + pullTablets : string.Empty; pullMediumDesktops = !string.IsNullOrWhiteSpace(pullMediumDesktops) ? "col-md-pull-" + pullMediumDesktops : string.Empty; pullLargeDesktops = !string.IsNullOrWhiteSpace(pullLargeDesktops) ? "col-lg-pull-" + pullLargeDesktops : string.Empty; // init var clsCol = string.Join(" ", (new[] { phones, tablets, mediumDesktops, largeDesktops, offsetPhones, offsetTablets, offsetMediumDesktops, offsetLargeDesktops, pushPhones, pushTablets, pushMediumDesktops, pushLargeDesktops, pullPhones, pullTablets, pullMediumDesktops, pullLargeDesktops }).Where(o => !string.IsNullOrWhiteSpace(o)).ToList()); if (string.IsNullOrWhiteSpace(clsCol)) { clsCol = "col-xs-12"; } if (maxFeeds <= 0) { maxFeeds = 10; } var linkedInAPI = new LinkedInAPI( GetString("Template:DesignBaseUrl"), (string)Pageview.Area.Item["LinkedIn_CompanyId"], (string)Pageview.Area.Item["LinkedIn_State"], (string)Pageview.Area.Item["LinkedIn_ClientId"], (string)Pageview.Area.Item["LinkedIn_ClientSecret"], (string)Pageview.Area.Item["LinkedIn_AuthorizedRedirectURL"] ); var feeds = linkedInAPI.GetCompanyUpdates(); if (feeds != null && feeds.Any()) { feeds = feeds.Take(maxFeeds).ToArray(); } } @if (clearfix) { <div class="clearfix"></div> } @if (feeds != null && feeds.Any()) { if (!unwrap) { @: <div class="@(clsCol)"> } <div class="paragraphlinkedinfeeds-block @(cssClassName)"> @foreach (var item in feeds) { if (item.Image != item.Url) { <a href="@(item.Url)" class="paragraphlinkedinfeeds-item"> <div class="paragraphlinkedinfeeds-item-image"> <img src="@(item.Image)" alt=""> </div> <div class="paragraphlinkedinfeeds-item-content"> <i class="fa fa-linkedin-square" aria-hidden="true"></i> <small>@(item.Date.ToString("d. MMMM yyyy"))</small> <p>@(item.Comment)</p> </div> </a> } else { <div class="paragraphlinkedinfeeds-item"> <div class="paragraphlinkedinfeeds-item-image"> <img src="@(item.Image)" alt=""> </div> <div class="paragraphlinkedinfeeds-item-content"> <i class="fa fa-linkedin-square" aria-hidden="true"></i> <small>@(item.Date.ToString("d. MMMM yyyy"))</small> <p>@(item.Comment)</p> </div> </div> } } </div> if (!unwrap) { @: </div> } }
Share the page: