I got some code to load rss feeds to my WindowsPhone app:
var result = e.Result;
result = result.Replace("\t", string.Empty);
result = result.Replace("\n", string.Empty);
var rssItems = XDocument.Parse(result.Replace("dc:creator", "creator")).Descendants("item").Select(
x => new RssItem()
{
Title = (string)x.Element("title"),
Description = (string)x.Element("description"),
Link = (string)x.Element("link"),
Author = (string)x.Element("creator"),
Comments = (string)x.Element("comments"),
PubDate = ParseNewsDateToStringFormatExtended(Convert.ToDateTime((string)x.Element("pubDate"))),
ThumbnailPart = stripImagePathFromDescription((string)x.Element("description").Value.ToString()),
StrippedHtml = strippedHtmlConversion((string)x.Element("title"), (string)x.Element("creator"), ParseNewsDateToStringFormatExtended(Convert.ToDateTime((string)x.Element("pubDate"))), (string)x.Element("description").Value.ToString())
}
).ToList();
success(rssItems);
When it loads feeds containing this symbol « or » it crashes. How can i make my app able to read these symbols?
EDIT: here is one element from my rss feed:
<item>
<title>Norges «skjulte perle» utvider</title>
As you can see there a «» in the title of the item. And i know that's why it crashes. But why? And how to handle these symbols?
Related
I wanted a Twitter forwarder to Telegram.
I found this one: https://github.com/franciscod/telegram-twitter-forwarder-bot
The problem is now, that if a tweet contains a hashtag before a link, Telegram show me the link to the hashtag.
I tried different things and searched about that, but I don't know how to only receive plain text from twitter.
Also I don't get the short link t.co if the tweet is to long. It's just a long link.
for tweet in tweets:
self.logger.debug("- Got tweet: {}".format(tweet.text))
# Check if tweet contains media, else check if it contains a link to an image
extensions = ('.jpg', '.jpeg', '.png', '.gif')
pattern = '[(%s)]$' % ')('.join(extensions)
photo_url = ''
tweet_text = html.unescape(tweet.text)
if 'media' in tweet.entities:
photo_url = tweet.entities['media'][0]['media_url_https']
else:
for url_entity in tweet.entities['urls']:
expanded_url = url_entity['expanded_url']
if re.search(pattern, expanded_url):
photo_url = expanded_url
break
if photo_url:
self.logger.debug("- - Found media URL in tweet: " + photo_url)
for url_entity in tweet.entities['urls']:
expanded_url = url_entity['expanded_url']
indices = url_entity['indices']
display_url = tweet.text[indices[0]:indices[1]]
tweet_text = tweet_text.replace(display_url, expanded_url)
tw_data = {
'tw_id': tweet.id,
'text': tweet_text,
'created_at': tweet.created_at,
'twitter_user': tw_user,
'photo_url': photo_url,
}
try:
t = Tweet.get(Tweet.tw_id == tweet.id)
self.logger.warning("Got duplicated tw_id on this tweet:")
self.logger.warning(str(tw_data))
except Tweet.DoesNotExist:
tweet_rows.append(tw_data)
if len(tweet_rows) >= self.TWEET_BATCH_INSERT_COUNT:
Tweet.insert_many(tweet_rows).execute()
tweet_rows = []
Just disable markdown_twitter_hashtags() function, make it return text without replace that.
Reporting-services 2016 (currently only available as a technical preview) comes with big-upgrades including HTML5 rendering and compliance. See: https://msdn.microsoft.com/en-us/library/ms170438.aspx
My desire is to embed SSRS 2016 reports into another webpage using native mode (no Sharepoint or aspx, just pure HTML5).
The traditional fashion to do this is to use an iFrame.
This is an half-way okay method as it's possible to remove the toolbar, hide parameters etc but still you end up losing a lot of control over the document. This is a cross-site implementation from a different domain so I can't manipulate the contained iFrame document as I please.
Does there exist an official way to embed the report element 'natively'?
I could envision a URL parameter option like rs:Format=REPORTDIV which serves me a html element.
I also tried fetching the report as an image (rs:Format=IMAGE&rc:OutputFormat=PNG) but the resulting PNG has a huge white frame (even when setting background to transparent in Report Builder) around the report element which is a no-go.
This should work. It should work outside of the environment as well as it embeds the images from memory instead of fetching them from the database
// Create service instance
ReportExecutionServiceSoapClient rsExec = new ReportExecutionServiceSoapClient(binding, endpoint);
rsExec.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
rsExec.ChannelFactory.Credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
ReportingServices.Extension[] extentions = null;
ReportingServices.TrustedUserHeader trustedUserHeader = new ReportingServices.TrustedUserHeader();
rsExec.ListRenderingExtensions(trustedUserHeader, out extentions);
string reportPath = "/Untitled";
ExecutionInfo execInfo = new ExecutionInfo();
ExecutionHeader execHeader = new ExecutionHeader();
ReportingServices.ServerInfoHeader serverInfo = new ReportingServices.ServerInfoHeader();
string historyID = null;
rsExec.LoadReport(trustedUserHeader, reportPath, historyID, out serverInfo, out execInfo);
//Get execution ID
execHeader.ExecutionID = execInfo.ExecutionID;
string deviceInfo = null;
string extension;
string encoding;
string mimeType;
ReportingServices.Warning[] warnings = new ReportingServices.Warning[1];
warnings[0] = new ReportingServices.Warning();
string[] streamIDs = null;
string format = "HTML5";
Byte[] result;
rsExec.Render(execHeader, trustedUserHeader, format, deviceInfo, out result, out extension, out mimeType, out encoding, out warnings, out streamIDs);
var report = Encoding.UTF8.GetString(result);
int streamIdCount = streamIDs.Length;
Byte[][] imageArray = new Byte[streamIdCount][];
String[] base64Images = new String[streamIdCount];
for (int i = 0; i <= streamIdCount - 1; i++)
{
Byte[] result2;
string streamId = streamIDs[i];
rsExec.RenderStream(execHeader, trustedUserHeader, format, streamId, deviceInfo, out result2, out encoding, out mimeType);
imageArray[i] = result2;
base64Images[i] = Convert.ToBase64String(result2);
string replace = string.Format("https://<reportserver>/ReportServer?%2FUntitled&rs%3ASessionID={0}&rs%3AFormat={1}&rs%3AImageID={2}", execInfo.ExecutionID, format, streamId);
string src = string.Format("data:{0};charset=utf-8;base64, {1}", mimeType, base64Images[i]);
report = report.Replace(replace, src);
}
I'm having problems to get my Windows Phone 8.1 live tile update by itself daily (around 7am)
My project has 2 parts :
a Web API project hosted on Azure that provides the tile template in XML (that part works fine)
a Windows Phone 8.1 project with a single MainPage.xaml where I build 2 square/wide tiles
When I pin my app to the start screen from the app list, my tile (whether I choose the square or wide format) flips back and forth between my 2 brands of the day just fine.
The next morning at 7:15 am, the tile won't update with the 2 new brands :(
I noticed that if I tap the tile to launch the app and come back to the start screen, the tile has updated.
It also works if I unpin and repin the tile but in both cases, that's "cheating" :-/
I call my Azure website like this to get the tile templates of both brands :
http://example.azurewebsites.net/api/tiles/0 (BRAND1)
http://example.azurewebsites.net/api/tiles/1 (BRAND2)
The XML tile template looks like this (example):
<tile>
<visual>
<binding template="TileWide310x150ImageAndText01">
<image id="1" src="http://www.example.com/sales/BRAND1/visualWide.png"/>
<text id="1">Brand 1</text>
</binding>
<binding template="TileSquare150x150PeekImageAndText04">
<image id="1" src="http://www.example.com/sales/BRAND1/visualSquare.png"/>
<text id="1">Brand 1</text>
</binding>
</visual>
</tile>
The WP8.1 page contains this :
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
TileUpdateManager.CreateTileUpdaterForApplication().EnableNotificationQueue(true);
PeriodicUpdateRecurrence recurrence = PeriodicUpdateRecurrence.Daily;
Task<string> responseBody;
for (int i = 0; i < 2; i++)
{
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri("http://xxxxx.azurewebsites.net/api/tiles/" + i); //I hid the address here for discretion
HttpResponseMessage response = httpClient.GetAsync(httpClient.BaseAddress).Result;
string statusCode = response.StatusCode.ToString();
response.EnsureSuccessStatusCode();
responseBody = response.Content.ReadAsStringAsync();
}
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(responseBody.Result);
string srcWide, srcSquare, textWide, textSquare, templateWide, templateSquare;
XElement root = XElement.Parse(responseBody.Result);
IEnumerable<XElement> wideElement = root.Descendants("binding").Where(a => a.Attribute("template").Value.ToLower().Contains("wide"));
IEnumerable<XElement> squareElement = root.Descendants("binding").Where(a => a.Attribute("template").Value.ToLower().Contains("square"));
templateWide = wideElement.Attributes("template").SingleOrDefault().Value;
srcWide = wideElement.Descendants("image").Attributes("src").SingleOrDefault().Value;
textWide = wideElement.Descendants("text").SingleOrDefault().Value;
templateSquare = squareElement.Attributes("template").SingleOrDefault().Value;
srcSquare = wideElement.Descendants("image").Attributes("src").SingleOrDefault().Value;
textSquare = wideElement.Descendants("text").SingleOrDefault().Value;
XmlDocument wideTileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150ImageAndText01);
XmlNodeList wideTileTextAttributes = wideTileXml.GetElementsByTagName("text");
wideTileTextAttributes[0].InnerText = textWide;
XmlNodeList wideTileImageAttributes = wideTileXml.GetElementsByTagName("image");
((XmlElement)wideTileImageAttributes[0]).SetAttribute("src", srcWide);
((XmlElement)wideTileImageAttributes[0]).SetAttribute("alt", textWide);
XmlDocument squareTileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare150x150PeekImageAndText01);
XmlNodeList squareTileTextAttributes = squareTileXml.GetElementsByTagName("text");
squareTileTextAttributes[0].AppendChild(squareTileXml.CreateTextNode(textSquare));
XmlNodeList squareTileImageAttributes = squareTileXml.GetElementsByTagName("image");
((XmlElement)squareTileImageAttributes[0]).SetAttribute("src", srcSquare);
((XmlElement)squareTileImageAttributes[0]).SetAttribute("alt", textSquare);
IXmlNode node = wideTileXml.ImportNode(squareTileXml.GetElementsByTagName("binding").Item(0), true);
wideTileXml.GetElementsByTagName("visual").Item(0).AppendChild(node);
TileNotification tileNotification = new TileNotification(wideTileXml);
tileNotification.ExpirationTime = DateTimeOffset.UtcNow.AddDays(1).AddHours(7).AddMinutes(0);
TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);
}
List<Uri> urisToPoll = new List<Uri>(5);
urisToPoll.Add(new Uri("http://example.azurewebsites.net/api/tiles/0")); //fake url
urisToPoll.Add(new Uri("http://example.azurewebsites.net/api/tiles/1")); //fake url
//I want the tile to update its content every day at 7:15am
//(the Azure website supposedly returns new brands of the day at 7am)
DateTime dtTomorrow7 = DateTime.SpecifyKind(DateTime.Today.AddDays(1).AddHours(7).AddMinutes(15), DateTimeKind.Local);
DateTimeOffset dtoTomorrow7 = dtTomorrow7;
TileUpdateManager.CreateTileUpdaterForApplication().StartPeriodicUpdateBatch(urisToPoll, dtoTomorrow7, recurrence);
}
I'm not sure I'm using the StartPeriodicUpdateBatch method correctly.
In debug mode,I can see the DateTimeOffset value is Day+1 7:15am +2:00 which looks correct but the tile does not update.
I live in France that is UTC+2
Thanks for your suggestions.
Your dtTomorrow7 is incorrect. It should just be 7:15 AM. Then it will first do an update at 7:15 AM and subsequent updates occurring at the periodic interval thereafter(you set it to daily).
Example of start time where the last TimeSpan is offset from UTC:
DateTime tomorrow = DateTime.Today.AddDays(1);
var startTime = new DateTimeOffset(tomorrow.Year, tomorrow.Month, tomorrow.Day, 7, 15, 0, TimeSpan.FromHours(2));
For my current assignment I need to make an extension for Adobe InDesign using Adobe Creative Suit Extension Builder and Flash Builder. I guess this is more of a question for ones that know Extension Builder and InDesign API.
The point of this extension is to load some data and send some data to a server. I need to make a screenshot of a page, then send it in jpg to a server. But, there are no (or at least i couldnt find any) ways to create a bitmap(to cast it on a object seems impossible, because this Objects are just Objects, and not DisplayObjects).
I managed to silently export pages as jpegs, now I'm thinking about loading them and sending but that will require building an AIR app to handle it all, so this will be a bit bulky.
So to sum up the question, how to take a screencapture of all elements on a page in InDesign using CS Ext.Builder?
what is the problem with export to JPG ? You can choose to export the page or the objects themselves.
Here is a snippet I wrote in a recent project. Hope it helps.
public static function getFilePath():String {
var app:com.adobe.indesign.Application = InDesign.app;
var sel:* = app.selection, oldResolution:Number, oldColorSpace:JpegColorSpaceEnum, groupItems:Array = [], i:int = 0, n:int = sel.length;
if (!sel || !n )
{
Alert.show("Pas de selection !", "title", Alert.OK, Sprite(mx.core.Application.application));
return "";
}
for ( i = 0 ; i < n ; i ++ )
{
groupItems [ groupItems.length ] = sel[i];
}
sel = ( sel.length > 1 )? app.activeDocument.groups.add ( sel ) : sel[0] ;
var tempFolder:File = File.createTempDirectory();
AppModel.getInstance().jpgFolder = tempFolder;
var jpgFile:File = new File ();
jpgFile.nativePath = tempFolder.nativePath + "/temp.jpg";
oldResolution = app.jpegExportPreferences.exportResolution;
app.jpegExportPreferences.exportResolution = 72;
oldColorSpace = app.jpegExportPreferences.jpegColorSpace;
app.jpegExportPreferences.jpegColorSpace = JpegColorSpaceEnum.GRAY;
sel.exportFile ( ExportFormat.jpg, jpgFile );
app.jpegExportPreferences.jpegColorSpace = oldColorSpace;
app.jpegExportPreferences.exportResolution = oldResolution;
if ( sel is Group )
{
sel.ungroup();
app.select ( groupItems );
}
return jpgFile.nativePath;
}
I am getting a string from Twitter into my Actionscript which is a unformatted string. I want to be able to extract any links and or any #replies from the string, then display it in htmlText.
So far I have this
var txt:String = "This is just some text http://www.thisisawebsite.com and some more text via #sumTwitter";
var twitterText:String = txt.slice(txt.indexOf("#"),txt.indexOf(" ",txt.indexOf("#")));
var urlText:String = txt.slice(txt.indexOf("http"),txt.indexOf(" ",txt.indexOf("http")));
var newURL:String = ""+urlText+"";
var arr:Array = txt.split(urlText);
var newString:String = arr[0] + newURL + arr[1];
var txtField:TextField = new TextField();
txtField.width = 500;
txtField.htmlText = newString;
addChild(txtField);
This is fine for extracting links, which finish with a space. But what if, like the #sumTwitter, it finishes at the end of the string. And also what if there are multiple links or #'s, is the best way to put it in a while loop?
Regular expressions are the best option for what you want, I think.
Check Grant Skinner's RegExr. You could write and test your own RegExp there, which is very convenient. But you also can find a lot of useful ready-to-use regexps created by different users. Check out the "community" tab in the right panel. There, search by some meaningful keywords like "twitter" and "url" and you'll get a good number of options.
For example,
Grab urls:
http://regexr.com?2s5m4
Capture twitter usernames:
http://regexr.com?2s5m7