Integrando sua Aplicação .Net com Twitter

by Fabiano 31. julho 2009 21:18

Acabei de implementar uma funcionalidade aqui na InfoMoney que integra nossos publicadores de noticias com o Twitter a nova rede social do momento, que e bem legal... 
Quando os redatores publicam uma nova noticia no site ela já vai para o Twitter automaticamente.

E seguindo a Dica do Tarifa vou publicar o conteudo.
Segue o Código Utilizado para que Vocês possam aproveitar também...

Primeiro Fiz integração com o Migre.me que e um serviço bem legal que reduz um URL já que no Twitter cada caractere poupado faz a diferença pois o post só pode ter 140 caracteres 

Segue o Método que gera a url:

    /// <summary>
    /// Que que recebe um URL normal e retorna uma menor gerada pelo migre-me
    /// </summary>
    /// <param name="OriginalURL"></param>
    /// <returns></returns>
    public string GenerateMigreMeURL(string OriginalURL)
    {

        try

        {

            string URIReturn, strURIGenerated; 

            //Trata se a url não começar com http://

            if (!OriginalURL.ToLower().StartsWith("http") && !OriginalURL.ToLower().StartsWith("ftp"))

            {

                OriginalURL = "http://" + OriginalURL;

            }

             var Request = System.Net.WebRequest.Create("http://migre.me/api.xml?url=" + OriginalURL);
             var Response = Request.GetResponse();

 
            XDocument xmlReturn;

            strURIGenerated = "";

            using (var reader = new StreamReader(Response.GetResponseStream()))

            {

                URIReturn = reader.ReadToEnd();

                xmlReturn = XDocument.Load(new StringReader(URIReturn), LoadOptions.SetBaseUri |      LoadOptions.SetLineInfo);

                strURIGenerated = xmlReturn.Descendants("migre").First().Value;

            }

             return strURIGenerated;

        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

Como o serviço disponibilizado pelo Migre.me retorna um XML, não poderia deixar de utilizar o LINT To XML para fazer o parse do mesmo, o XML retornado e bem completo tem ate mensagem de erro caso ocorra, mas no exemplo eu faço somente o tratamento da mensagem, caso queira aprimorá-lo fique a vontade basta dar uma olhada do XML de retorno e tratar os campos que desejar...

Ah uma dica importante por ser um serviço Free você so poderá gerar 30 URL`s por hora se o seu serviço precisar de mais ai você devera optar pelo serviço pago do Migre.me.

Método que Posta no Twitter:

Aqui eu utilizo uma API do Twitter chamada “Twitterizer.Framework”  que e bem simples de implementar.
Faça o Download da DLL e adicione como referência em seu projeto para poder utiliza-la. E bem legal tem varias funcionalidades, vale dar uma explorada.

 

  /// <summary>
        /// Método que faz o "Post" do texto no twitter.
        /// </summary>
        /// <param name="UserName">Usuário de acesso ao Twitter.</param>
        /// <param name="Password">Senha de acesso do Twitter.</param>
        /// <param name="Text">Texto a ser gravado no Twitter(Deve ter somente 140 caracteres).</param>
        Public static void Post(string UserName, string Password, string Text)
        {
            try
            {
                Twitter Tw = new Twitter(UserName, Password);
                TwitterStatus TwS = new TwitterStatus();
                TwS = Tw.Status.Update(Text);
            }
            catch (Exception ex)
            {
                throw new Exception("Ocorreu um erro ao salvar as informções: ", ex);
            }
        }

 

E o mais legal dessa API e que e muito rápido o post, muito rápido mesmo.
E fiz também um método que faz a regra para fazer a contagem dos caracteres para garantir que sua mensagem tenha mesmo os 140 caracteres.

///Onde faz o post literalmente

private void PostNews(int NewsId)
{

            string url = @"";

          //titulo da noticia. Aqui eu tiro tudo que tiver de tag HTML
          string tituloNoticia = FrameWork.Util.UtilString.UtilString.RemoverTags(HttpUtility.HtmlDecode(TITULOVINDODOBANCO), true, true, true, true, true, true); 

 

                //gera a url.

                string URLGerada = BiMigreMe.GenerateMigreMeURL(url);

                 //trata os erros.

                if (URLGerada != "")

                {

                    string TwPost = "";

                    TwPost = tituloNoticia + "..." + " " + URLGerada; // Aqui junto tudo para poder saber qu tamanho vai ficar o post inteiro

 

                    //verifica se o tamanho total é maior que 140.

                    if (TwPost.Length > 140)

                    {

                        //Agora separo todo mundo pra peder montar to tamanho correto cortando o somente o texto e nao o link

                        int totallink = URLGerada;

                        TwPost = tituloNoticia;

                        TwPost = TwPost.Substring(0, 137 - totallink);

                        TwPost = TwPost + "..." + URLGerada;

                    }

 

                    try

                    {

                        TwitterFrameWork.Post(UserTwitter, PasswordTwitter, TwPost);

                        lblInf.Text = "Notícia postada com sucesso!!";

                    }

                    catch (Exception ex)

                    {

                        lblInf.Text = "Ocorreu um erro: " + ex.Message.ToString();

                    }

                }

            }

        }

 

    }

PS: Segue abaixo o metod que retira os caracterer indesejado no post

 

public static string RemoverTags(string Texto,

                                         bool IsLink,

                                         bool IsHtml,

                                         bool IsCss, bool IsScript,

                                         bool IsHref, bool IsImg)

        {

            string ReturnText = string.Empty;

            StringBuilder Patterns = new StringBuilder();

 

            if (IsLink)

                Patterns.Append(@"(\<link[^\>]+\>)" + "|");

            if (IsHtml)

                Patterns.Append(@"<(.|\n)*?>" + "|");

            if (IsCss)

                Patterns.Append(@"(class=[""\w].*?[a-z].\"")" + "|");

            if (IsScript)

                Patterns.Append(@"(\<script[^\>]+\>)|(\</script[>])|(\<script[>])" + "|");

            if (IsHref)

                Patterns.Append(@"(\<a[^\>]+\>)|(\</a[>])" + "|");

            if (IsImg)

                Patterns.Append(@"(\<img[^\>]+\>)" + "|");

            try

            {

                return System.Web.HttpContext.Current.Server.HtmlDecode(Regex.Replace(Texto, Patterns.ToString().Substring(0, Patterns.Length - 1), string.Empty));

            }

            catch (Exception)

            {

                return Texto;

            }

        }

 

Bem pessoal e isso... E bem simples mais funciona.

 

Espero ter ajudado...

Bons Códigos...
Fabiano Belmonte


 

Tags: ,

.Net

Comentários

1/8/2009 00:01:45 #

1000ton

Que maneiro kra, parabens....fico muito show de bola Smile

vou implementar isto num site que administro

1000ton | Reply

5/8/2009 09:03:17 #

payday loans

Hello to all Smile I can�t understand how to add your site in my rss reader. Help me, please

payday loans | Reply

9/8/2009 10:46:56 #

Houston da Paz

Muito bom o post, só que precisa tambem saber como faço para receber o que é postado no twitter como resposta pra mim, no caso pegar todas as mensagem que começam ou tem no seu corpo o @nomedousuario. Sabe se tem alguma forma de fazer isto?

Houston da Paz | Reply

5/9/2009 10:47:05 #

payday loans online

i like your blog.I can copy some stuff for my blog?

payday loans online | Reply

7/9/2009 15:22:56 #

Property Lawyer

It is indeed a great resource to obtain information on this subject. Keep posting. Thanks.

Property Lawyer | Reply

28/9/2009 21:56:37 #

bad credit loans

found your site on del.icio.us today and really liked it.. i bookmarked it and will be back to check it out some more later ..

bad credit loans | Reply

3/10/2009 09:48:49 #

Contador de Visitas Gratis


I am always searching online for articles. Thank you.

Contador de Visitas Gratis | Reply

6/10/2009 15:04:05 #

buy desk chairs

very nice article.great blog here.thanks

buy desk chairs | Reply

6/10/2009 15:07:38 #

nice round rugs

i liked the article a lot.thanks a lot for the share.

nice round rugs | Reply

11/1/2010 16:29:21 #

SEO Services

This article simply ROCKS ! That was a great read for me. keep it up with all the good work..

www.clickresponse.net/...-optimization-service.htm

SEO Services | Reply

12/1/2010 18:36:19 #

 rich garry

Good post….thanks for sharing.. very useful for me i will bookmark this for my future needed. thanks for a great source.

Thanks
  <a href="www.seoservicesindia.mobi/.../link-building-services-india.html">Link Building company India</a>

rich garry | Reply

9/2/2010 11:16:59 #

Online Sweepstakes

Good work, i like your blog theme, and content ofcourse loved the way you explained things. Much better many here.

Online Sweepstakes | Reply

18/3/2010 12:47:34 #

Self Directed Ira

Nice coading.It is useful to me.please keep posting

Self Directed Ira | Reply

24/3/2010 11:38:12 #

parking ny

Thanks for sharing...very useful for me.
I will bookmark this for my future needed.

parking ny | Reply

29/3/2010 15:36:56 #

BUSINESS CONTINUITY SOFTWARE

There are very few people in this world who gives such tremendous views. I appreciate your work and hopping for some more informative posts.

BUSINESS CONTINUITY SOFTWARE | Reply

30/3/2010 15:07:01 #

SEO Services India

Hello,

Thanks for nice and informative sharing with us.

Regards
http://www.seoservicesindia.mobi

SEO Services India | Reply

31/3/2010 12:14:24 #

SWEEPSTAKES

This gives very fortunate information it helped a lot about twitter.Thank you for your comment.

SWEEPSTAKES | Reply

31/3/2010 15:16:12 #

SEO COMPANY

It appears that you have placed a lot of effort into your article and I require more of these on the net these days. I sincerely got a kick out of your post.I only wanted to comment to reply wonderful work.

SEO COMPANY | Reply

8/5/2010 15:28:20 #

Mumbai Real Estate

Hey I love your style I will subscribe for your feed please keep posting!

Mumbai Real Estate | Reply

31/5/2010 11:01:09 #

New Release Jordans

Absolutely u got this one down right man.. Keeped me entertained for ages.

New Release Jordans | Reply

5/6/2010 14:18:59 #

AIR JORDAN PACKAGES

Thanks for this article. It give me new spirit to continue my blogging journey.

AIR JORDAN PACKAGES | Reply

16/7/2010 13:15:29 #

Tour Bus Facilitator in pune

Hey - great blog, just looking around some websites, seems a really nice platform you are using.

Tour Bus Facilitator in pune | Reply

19/7/2010 16:39:13 #

Top packers and movers in pune


Wonderful technics!!!
Concepts are good!!!

Top packers and movers in pune | Reply

20/7/2010 11:28:10 #

Detective agencies in india

Admirable work and much success in your business efforts!

Detective agencies in india | Reply

27/7/2010 16:11:05 #

Post Free Ads

I like the part where you say you are doing this to give back but I would assume by all the comments that this is working for you as well.

Post Free Ads | Reply

Comentar




biuquote
  • Comentário
  • Pré-visualização
Loading



Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen

Fabiano Belmonte

Senior Architect, especialista em aplicações e-business com larga experiência em B2B (Submarino. Com e Saraiva.Com). Trabalha há 5 anos com a tecnologia .Net, aplicando conhecimentos nas diversas áreas: instituições financeiras (sistema SPB), e-commerce, gerenciamento logístico entre outras.