Advertisement

Monday 28 December 2015

oAuthTwitterWrapper

This provides a really simple solution to authenticating and wrapping twitter's API calls using the 1.1 API and OAuth.

Quick installation instructions:

Run the following nuget command from your project to install the package:

Install-Package oAuthTwitterWrapper

Amend the appsettings to add your consumer key, secret and screen name. Generate your key and secret here

Add the following code to return the raw json:

        var twit = new OAuthTwitterWrapper.OAuthTwitterWrapper();
        twit.GetMyTimeline();

If you would prefer to use serialiazed C# pocos use the following:

       var twit = new OAuthTwitterWrapper.OAuthTwitterWrapper();
       var json = twit.GetMyTimeline();
       var tweets = JsonConvert.DeserializeObject<List<TimeLine>>(json); // Deserialize with Json.NET

Notes

Currently it exposes timeline (twitter feed) and search calls, returned as raw json (which can be serialized into c# pocos, examples in the github project).

Screen shot below (please note there is no styling applied you have full control over how it is rendered in your application).

The idea stems from the following Stackoverflow question:

http://stackoverflow.com/questions/17067996/authenticate-and-request-a-users-timeline-with-twitter-api-1-1-oauth

Demo projects in GitHub

Console

This is the simplest form of use, it just makes the call and prints to the console window.

Web application

This uses a page WebMethod to make the api call and an Ajax json request to display the tweets. It could however be exposed in any kind of web service. It makes use of jQuery and this great library twitter-text.

Mvc application

This uses a controller action that returns the json and uses the same method to display them as above. Again this uses jQuery and twitter-text. * Please note that I created this in VS2010 and you need MVC4 installed, I will update this to VS2012 soon. There are also de-serialized versions of the c# pocos, please view the controller actions to see how this is done.

Umbraco razor solution

Here is a temporary solution, I plan to complete some further work on this in the future.

Run the following nuget command from your umbraco project to install the package:

Install-Package oAuthTwitterWrapper

Amend the appsettings to add your consumer key, secret and screen name. Generate your key and secret here

Create a macro script with the following code that outputs the json inline to the page:

      @using System
      @{
       var twit = new OAuthTwitterWrapper.OAuthTwitterWrapper();
       var json = twit.GetMyTimeline();
       }
       <div id="results"></div>
       <script type="text/javascript">
       var json = @Html.Raw(json);
       </script>

Add a reference to jQuery and twitter-text, then add some javascript to parse the json (The code here is just used for example purposes and not best practice):

            for (var i = 0; i < json.length; i++) {
                $("#results").append('<p><strong> - ' + json[i].created_at.substring(0, 16) + '</strong><br/>' + twttr.txt.autoLink(json[i].text) + '</p>');
                try {
                    for (var j = 0; j < json[i].entities.media.length; j++) {
                        $("#results").append('<a href="' + json[i].entities.media[j].media_url + '" ><img src="' + json[i].entities.media[j].media_url + ':thumb" /></a>');
                    }
                } catch(e) {
                }
            }

Add the macro to the template or content within Umbraco.

Latest IT News By Sajid

ComputerWeekly: Latest IT News
Follow the latest technology news that matters to UK IT leaders and IT professionals, as it happens, from the UK’s leading technology publication.

Top 10 financial services IT stories of 2015
by ComputerWeekly.com(editor@www.com)
24 Dec 2015 at 3:00am
The financial services industry is undergoing unprecedented change, driven by IT and regulation.

Top 10 IT security stories of 2015
by ComputerWeekly.com(editor@www.com)
24 Dec 2015 at 3:00am
Computer Weekly looks back at the most significant stories on IT security in the past 12 months

When a slowdown in IT budgets is a good thing
by Andrew Horne(editor@www.com
23 Dec 2015 at 12:00pm
IT budgets will grow at their slowest rate for four years in 2016, yet companies are spending more on digital technology

CIO interview: Henry Cohen, CIO, Telegraph Media Group
by ComputerWeekly.com(editor@www.com)
23 Dec 2015 at 11:30am
The newspaper publisher is developing an agile mindset in response to the growth of digital over printed publications

The Higher Education Academy gives universities £500,000 to develop cyber sec...
by ComputerWeekly.com(editor@www.com)
23 Dec 2015 at 8:45am
The Department for Culture, Media and Sports has partnered with the Higher Education Academy to provide universities with funding and support to train cyber security specialists

BBC CTO Matthew Postgate to head up technology division
by ComputerWeekly.com(editor@www.com)
23 Dec 2015 at 7:45am
Matthew Postgate, chief technology officer of the BBC, will take on a different role in April 2016 leading a new division for the firm

Top 10 broadband stories of 2015
by ComputerWeekly.com(editor@www.com)
23 Dec 2015 at 3:00am
The BDUK roll-out continued to gain momentum in 2015, but that didn’t mean for one second that the controversy that has dogged the programme died down. Meanwhile, BT began touting a new type of technology, called G.fast

Top 10 APAC IT stories of 2015
by ComputerWeekly.com(editor@www.com)
23 Dec 2015 at 3:00am
The top 10 Computer Weekly articles about enterprise IT in the Asean and ANZ regions

Current Feed Content By Sajid Khan

  • LinkedIn Rival Viadeo Exits China

    Posted:Mon, 28 Dec 2015 05:32:28 +0000
    viadeo Viadeo, the French rival to LinkedIn, is to exit China in order to focus on becoming a profitable business. In another cut-cutting move, it will also close its data center in California and migrate all data to the cloud. Read More
  • Facebook Confronts The Free Internet Neutrality Dilemma

    Posted:Sun, 27 Dec 2015 20:47:41 +0000
    Free Basics The subject of contention is Free Basics, Facebook and Internet.org‘s app that offers free data access but only to a limited section of the Internet. Free Basics is available in roughly 35 countries through Facebook’s partnerships with mobile carriers who see it as a way to persuade people to buy data plans. But Facebook’s control over the technical guidelines for what… Read More
  • Twitter’s Fiscal 2015: Up, Flat, And Down

    Posted:Thu, 24 Dec 2015 20:00:30 +0000
    twitter-down Twitter did not have a lovely 2015. The world-famous social company saw its revenue rise, its usage flatten, and its share price fall. The company failed to change the arc of its own narrative during the year: Strong financial performance, but continued failure to grow its user base, the latter of which the market appears to weight more strongly. It brought in a new CEO to turn things… Read More
  • Bessemer Venture Partners’ Ethan Kurzweil Talks Video In 2016

    Posted:Thu, 24 Dec 2015 19:01:44 +0000
    periscope-android 2015 was a big year for video — especially when it came to user-generated video. Now there are services like Periscope and Meerkat, which are enabling users to broadcast the world around them live. We also saw YouTube launch a subscription model. And, according to Bessemer Venture Partners’ Ethan Kurzweil — who led the firm’s investment in Twitch — we’re… Read More
  • Instagram Makes It Easier To Share From Boomerang

    Posted:Tue, 22 Dec 2015 19:01:35 +0000
    3648565639_38f500d564_b Right before the holidays, Instagram snuck in an update for its most second-most popular spun-out app, Boomerang. The app currently sits in the top 250 on the App Store’s free apps. The changes, although subtle, will probably make its users super happy. The premise of the app is to make little clipped-together videos, similar to an animated GIF or an Apple Live Photo. It feeds into… Read More
  • Are Tweeting Drones On The Way? Twitter Patent Tips Off Potential Future Of Selfies

    Posted:Mon, 21 Dec 2015 23:58:16 +0000
    Game+of+Drones,+Battle+Quads In today’s episode of “boring patents…wait, WHAT ARE THOSE???”, it looks like Twitter filed a patent for messaging with or from, or both, an unmanned vehicle (drone!) in June of this year. It was just published a few days ago. It’s probably something that was put together at a hackathon and someone at Twitter said “hey that’s cool let’s patent… Read More
  • Pinball In Virtual Reality? Yes Please

    Posted:Mon, 21 Dec 2015 19:28:37 +0000
    Screen Shot 2015-12-21 at 11.26.11 AM OK, it doesn’t exist just yet, but one group called “Pinball Labs” has a new Kickstarter to bring back the feels you felt when you entered an arcade with tons of pinball games. There’s nothing like the sounds and visuals of old pinball machines (I love Addams Family) and it could become a…reality once again in VR. The Kickstarter recently went live and this video… Read More
  • We Heart It, The Image-Sharing Site Used By 40 Million Teens, Launches Its Second App, Easel

    Posted:Mon, 21 Dec 2015 17:06:32 +0000
    Screen Shot 2015-12-21 at 12.00.04 PM We Heart It, an image bookmarking service popular with teenaged girls, is out now with its second mobile application called Easel. The new app is designed to complement We Heart It’s main app, as it serves as a way to quickly create images using quotes that can be shared on We Heart It’s service or elsewhere on social media, including Instagram, Tumblr, Twitter and Facebook.… Read More
  • Coffee Meets Bagel Adds Its Own Version Of Super Like With ‘Send A Woo’

    Posted:Mon, 21 Dec 2015 13:33:41 +0000
    Screen Shot 2015-12-21 at 8.30.28 AM In the past few months, Tinder has been working on a feature called Super Like, which let users tell one of their matches that the situation is more serious than simply swiping right. Today, Coffee Meets Bagel has added something similar in ‘Send A Woo’, letting CMB users express higher-than-usual interest in a potential match. Coffee Meets Bagel launched in 2013 with an… Read More
  • Extroverts Rejoice! Now Facebook Finds You Parties

    Posted:Fri, 18 Dec 2015 21:48:25 +0000
    giphy Facebook should tell me what to do tonight. It already knows what I like, where I live, and who I hang out with. Now it will. After accidentally becoming the most powerful force in party invitations, Facebook is jacking us into its omniscient view of the event landscape. Starting today on iOS, Facebook has a powerful new Event browsing experience. First, rather than suggesting Events on… Read More
  • Facebook Tests “Click For More” To Boost Video Views On Desktop

    Posted:Fri, 18 Dec 2015 13:57:26 +0000
    click_for_more_feed Facebook says it now gets around 8 billion video views on its platform each day, and the social network has made no secret of its plans to make it an even bigger part of the experience in the future. Now Facebook is testing a new “click for more” feature for desktop users of the service. Currently, clicking not just on the words — which appear in a place where they will… Read More
  • Colopl Launches $50M Global Fund Dedicated To Virtual Reality

    Posted:Thu, 17 Dec 2015 19:12:16 +0000
    Screen Shot 2015-12-17 at 11.10.21 AM There’s no shortage of ideas and projects in the virtual reality space. There are tons of studios popping up all over the world to create immersive content for the platform. With the Oculus, HTC and Sony offerings coming next year, now’s a better time than any to dabble in the space. If only there was money to be raised. Welp, Colopl, a company deeply rooted in mobile gaming,… Read More
  • Build Or Buy? Anatomy Of An Acquisition — Or Why Buffer Just Bought Respondly

    Posted:Thu, 17 Dec 2015 17:00:23 +0000
    buffer + respondly Radically transparent social media scheduling firm Buffer, which does stuff like publish its staff salaries and publicly detail its company revenue, has announced its first major acquisition — buying social media customer support tool Respondly for — wait for it — an undisclosed amount… Read More
  • Social Ad Startup Funnely Raises Seed Funding From Verizon Ventures

    Posted:Thu, 17 Dec 2015 15:57:19 +0000
    Funnely Funnely, a startup that helps e-commerce companies automate and improve their ad campaigns on Facebook and Instagram, has raised $988,000 in a seed round led by Verizon Ventures. The product uses businesses’ customer data to create and target ads. The goal is to effectively reach consumers throughout the sales funnel, whether it’s first getting their attention through lead… Read More
  • First Round’s Holiday Video Will Have You Reaching For Your Cell Phone

    Posted:Thu, 17 Dec 2015 15:00:48 +0000
    Screen Shot 2015-12-16 at 6.27.26 PM In the tech world it’s just not the holidays until First Round Capital drops its annual holiday video. It’s that time again, folks. The annual festivities started way back in 2008, the year of our blog. Then it happened again and again. If you’d like to sing along, you’ll find the lyrics below the video. They are most certainly…special. I won’t ruin anything… Read More
  • Telegram Gets 1.5M+ Download Spike As Brazil WhatsApp Shutdown Kicks In

    Posted:Thu, 17 Dec 2015 12:31:38 +0000
    telegram-whatsapp Messaging app Telegram is currently experiencing a bump in downloads in Brazil thanks to a local court ruling forcing a 48 hour shutdown of WhatsApp. Read More
  • CAH’s Max Temkin On ‘Secret Hitler’ And Making Fun Games For Money

    Posted:Wed, 16 Dec 2015 21:13:52 +0000
    25b7ae3d131bba43de5a08635766b024_original If you’re a maker, getting people excited about what you’re doing can be difficult — no matter what it is you’re making. One guy, Max Temkin, has been “lucky” enough to strike gold with his project Cards Against Humanity. His next act? A game called “Secret Hitler.” In case you haven’t heard about it, it’s a card game for 5-10 players… Read More
  • Facebook Filters Out Sadness And Adds Editing To Your Year In Review Photoset

    Posted:Wed, 16 Dec 2015 19:00:12 +0000
    Turn That Frown Upside Down Facebook broke some hearts in 2014 when its algorithmically selected Your Year In Review photosets accidentally included depressing photos of people’s exes, blocked friends and deceased loved ones. To avoid the same bad feels, Facebook “applied a unique set of filters” to prevent these people from showing up in this year’s stylized vertical card of 10 photos. Read More
  • Hit Or Miss, A Tinder-Like Curated Fashion Shopping App, Looks To Keep Shopping Simple

    Posted:Wed, 16 Dec 2015 18:57:05 +0000
    Woman-Holding-Hit-Miss-App Amber Reyngoudt and Dave Peck want to figure out how to perfect the mobile shopping experience — and they thinks it’s flipping through fewer products, not more. Skull Ninja Labs’ first product is Hit or Miss — a tinder-like interface where users can swipe through a curated set of products and quickly build a profile of the things they like. But the catch is that the… Read More
  • MIT Researchers Train An Algorithm To Predict How Boring Your Selfie Is

    Posted:Wed, 16 Dec 2015 15:00:55 +0000
    MemNet Researchers at MIT’s Computer Science and Artificial Intelligence Lab (CSAIL) have created an algorithm they claim can predict how memorable or forgettable an image is almost as accurately as a human — which is to say that their tech can predict how likely a person would be to remember or forget a particular photo. Read More

Sunday 27 December 2015

How to export data, dataset result to PDF using c#


Why iText?
By Sajid Khan   Download Demo Code

Updated 27-12-2015 - Added a bullet regarding using iTextSharp with a medium trust shared web hosting provider.
How many times have you been asked to generate a report in an open file format such as PDF? iTextSharp, a free C# PDF library ported from the Java-PDF Library iText, gives you a nice option.
Important / Breaking Changes
And you must take into consideration that iText[Sharp] has never made HTML/XML to PDF conversion one of it's main goals or selling points. Whether you use HTMLWorker or XMLWorkerDO NOT EXPECT A FULL-BLOWN CONVERSION TOOL, YOU WILL BE DISSAPOINTED!
Getting Started
In general creating a PDF with iText[Sharp] is a five-step process:
  1. Instantiate a Document object.
  2. Get an instance of the PdfWriter object.
  3. Open the Document instance.
  4. Add content to the Document instance.
  5. Close the document. As explained above you can omit step 5 from iTextSharp 5.0.6.


The following example shows how to:
  1. Create a centered, single-page document header. If you need to add page headers to all pages of your document see Adding PDF Page Headers, which shows the recommended method to add page headers using the PdfPageEventHelper class.
  2. Add a center-aligned image to the document.
  3. Add a center-aligned paragraph to the document.
  4. Add tabular formatted data to the document.
iTextSharp Versions 5 and Above
Creating our PDF going from step 1 through 4. Uncomment where specified (Document using statement) if using anything less than 5.0.6:
/*
 * step 1
 *
 * __ONLY__ if using version >= 5.0.6
 * see commented section directly below
 *
 */
    using (Document doc = new Document()) {
   
/*
 * uncomment this line __AND__ comment out line above if you're
 * using version < 5.0.6
 *
 * Document doc = new Document();
 *
 */
   
// step 2
    PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream);

// step 3
    doc.Open();

// step 4
/*
 * create document header; shows GMT time when PDF created.
 * HeaderFooter class removed in iText 5.0.0, so we instead write
 * content to an **absolute** position on the document
 */
    Rectangle page = doc.PageSize;
    PdfPTable head = new PdfPTable(1);
    head.TotalWidth = page.Width;
    Phrase phrase = new Phrase(
      DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + " GMT",
      new Font(Font.FontFamily.COURIER, 8)
    );   
    PdfPCell c = new PdfPCell(phrase);
    c.Border = Rectangle.NO_BORDER;
    c.VerticalAlignment = Element.ALIGN_TOP;
    c.HorizontalAlignment = Element.ALIGN_CENTER;
    head.AddCell(c);
    head.WriteSelectedRows(
      // first/last row; -1 writes all rows
      0, -1,
      // left offset
      0,
      // ** bottom** yPos of the table
      page.Height - doc.TopMargin + head.TotalHeight + 20,
      writer.DirectContent
    );

/*
 * add image to document
 */
    Image gif = Image.GetInstance(
      Request.MapPath("~/kyouyuu/image/kuujinbo2.gif")
    );
    gif.Alignment = Image.MIDDLE_ALIGN;
// downsize the image by specified percentage       
    gif.ScalePercent(50f);
    doc.Add(gif);

/*
 * add tabular data
 */
// table heading
    Paragraph p = new Paragraph("US Presidents Born in " + _state);
    p.Alignment = 1;
    doc.Add(p);
// table data, see code snippet following this one
    doc.Add( _stateTable() );

/*
 * step 5 is __REQUIRED__ if using version < 5.0.6; uncomment Close()
 * below and comment out the bracket below!
 *
 * doc.Close();
 *
 */
    }
Creating a simple table is easy; query the database (data access code omitted) and add each rowset to the table in the PDF:
// add a table to the PDF document
private PdfPTable _stateTable() {
  string[] col = { "No.", "Name", "City" };
  PdfPTable table = new PdfPTable(3);
/*
* default table width => 80%
*/ 
  table.WidthPercentage = 100;
// then set the column's __relative__ widths
  table.SetWidths(new Single[] {1, 5, 4});
/*
* by default tables 'collapse' on surrounding elements,
* so you need to explicitly add spacing
*/
  table.SpacingBefore = 10;

  for (int i = 0; i < col.Length; ++i) {
    PdfPCell cell = new PdfPCell(new Phrase(col[i]));
    cell.BackgroundColor = new BaseColor(204, 204, 204);
    table.AddCell(cell);
  }

// !! database code omitted !!
// r.Read is the DbDataReader for whatever flavor
// of database you're connecting to; we're iterating
// over the results returned from the database and
// adding rows to the table in the PDF
      while (r.Read()) {
        table.AddCell(r["id"].ToString());
        table.AddCell(r["name"].ToString());
        table.AddCell(r["city"].ToString());
      }
  }
  return table;
Example for iTextSharp Versions Less Than 5.XX
Here's a stand-alone working HTTP handler that works with 4.1.6.
<%@ WebHandler Language='C#' Class='itext' %>
/*
 * example ONLY WORKS for iTextSharp < 5.0.0;
 * as of 2011-03-28 source code for older versions __NOT__ available
 */
using System;
using System.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;

public class itext : IHttpHandler {
// =========================================================================== 
  public void ProcessRequest (HttpContext context) {
    HttpResponse Response = context.Response;
    Response.ContentType = "application/pdf";
    Response.AppendHeader(
      "Content-Disposition",
      "attachment; filename=itext.pdf"
    );
// step 1   
    Document doc = new Document();
   
// step 2   
    PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream);
      
/*
 * create document header; shows GMT time when PDF created.
 * set header [1] text [2] font style
 */       
    Phrase phrase = new Phrase(
      DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + " GMT",
      new Font(Font.COURIER, 8)
    );
    HeaderFooter header = new HeaderFooter (phrase, false);
// top & bottom borders on by default
    header.Border = Rectangle.NO_BORDER;
// center header
    header.Alignment = 1;
/*
 * HeaderFooter => add header __before__ opening document
 */
    doc.Header = header; 
// step 3
    doc.Open();
     
// step 4
/*
 * add image to document
 */
    Image gif = Image.GetInstance(
      "http://kuujinbo.info/kyouyuu/image/kuujinbo2.gif"
    );
    gif.Alignment = Image.MIDDLE_ALIGN;
// downsize the image by specified percentage    
    gif.ScalePercent(50f);
    doc.Add(gif);

/*
 * add tabular data
 */
// table heading
    Paragraph p = new Paragraph("Table Heading");
    p.Alignment = 1;
    doc.Add(p);
   
// table 'data'  
    Table table = new Table(3);
    table.BorderWidth = 1;
    table.BorderColor = new Color(0, 0, 255);
    table.Padding = 4;
    table.Width = 100;

    // set *column* widths
    float[] widths = {.3f, .5f, .4f};
    table.Widths = widths;

    string[] col = {"COL 1", "COL 2", "COL 3"};
    for (int i = 0; i < col.Length; ++i) {
      Cell cell = new Cell(col[i]);
      cell.Header = true;
      cell.BackgroundColor = new Color(204, 204, 204);
      table.AddCell(cell);
    }
    table.EndHeaders();
   
    for (int i = 1; i < 5; ++i) {
      for (int j = 0; j < col.Length; ++j) {
        table.AddCell(string.Format(
          "Row {0}, Cell {1}",
          i, j + 1
        ));
      }
    }
    doc.Add(table);
   
// step 5
    doc.Close();   
  }

  public bool IsReusable {
    get { return false; }
  }
// ===========================================================================
}
Notes
Don't forget to set the correct Content-Type before you send the PDF stream if you're running a web application:
Response.ContentType = "application/pdf";
// [optional]
Response.AddHeader(
  "Content-Disposition",
  "attachment; filename=itext.pdf"
);