Mostrando entradas con la etiqueta C#. Mostrar todas las entradas
Mostrando entradas con la etiqueta C#. Mostrar todas las entradas

jueves, 11 de agosto de 2011

[C#] Simple Slpash Screen

What I'm doing here is a very simple splash screen, must clients wnats their applications to have a splash screen, even when there is really nothing that worth preloading, so if this is the case keep reading, if not go and find another post.

So basically what we do is, create a new Thread that will wrap a method called wait();
in the form_load, like this:


private void Form1_Load(object sender, EventArgs e)
{
ThreadStart ts = new ThreadStart(wait);
Thread t = new Thread(ts);
t.Start();
}


and then we create a method that will trigger the main form or application after a little wait, this gives the idea of "preloading" but without actually preloading anything.


public void wait()
{
Thread.Sleep(5000); //time to wait in milliseconds
MessageBox.Show("done loading"); // actions to take when the wait is done
}


and that's it.

Happy Coding!

viernes, 24 de junio de 2011

Printing Rich TextBox Without PrintDialog [C#]

So I was in need to print the contents of a rich TextBox, but scince the PrintDialog buttons are so small, and I'm working on a touchscreen application I needed to make it automatic, so I spent like 4 hours fooling around msdn with gigantic ass complex tutorials, but I insist on keeping things Simple. So after tons of googling I finally found this awesome code snipet that saved the day :)

23.51.1.Basic Printing

Dont know who is the author but thanks man! :)

so I've added a few lines to print the images in the text box, notice I saved the images in data structures first and then print out. So my version of this wonderfull codesnipet is:


/*the button to do the magic no-PrintDialog thing*/
private void button12_Click(object sender, EventArgs e) {
    PrintDocument pd = new PrintDocument();
    pd.PrintPage += new PrintPageEventHandler(PrintPageEvent);
    pd.Print();
}

/*and the PrintPage Event Handler where the magic happens.*/
private void PrintPageEvent(object sender, PrintPageEventArgs ev) {
    string contents = "Date: " + DateTime.Now.ToShortDateString() + Environment.NewLine;
    contents += txtTicket.Text;
    contents = contents.Normalize();
    Font oFont = new Font("Arial", 10);

    /*the next two lines are commented because they add a margin to the page (I dont want that)
    Rectangle marginRect = ev.MarginBounds;
    ev.Graphics.DrawRectangle(new Pen(System.Drawing.Color.Black), marginRect);*/

    /*Here I print the Image(s) with the DrawImage Method of the handler*/
    ev.Graphics.DrawImage(global::MyProgram.Properties.Resources.Header3, 10, 10);

    /*and now the string.  */
    ev.Graphics.DrawString(contents, oFont, new SolidBrush(System.Drawing.Color.Black), 10, 90);
}

this is it :)
Happy Coding!
P.S:
Remember folks:

lunes, 30 de mayo de 2011

Download Youtube Videos With C#

All right since youtube changed around its layout and user terms
it seems to be that so many unattended, yet good apps to download
videos from youtube just stoped working. This is because now youtube
makes the final user completely responsable for the content he/she uploads
and visits.

Basically what we do is get the "movie_player" element in the video page
then scrap a little this element, to find the "fmt_url_map", which is kind
of complex as its provides up to 4 video formats, in this code snippet
I show how to get the mp4 file, but you can hop between the options
to have the other formats, flv, mp3 or whatever...

in order to do this you will need the Html agility pack found here:
http://htmlagilitypack.codeplex.com/
download it and add it as a reference in your project.

then you need this two methods:

  /*this methods get's the download link for youtube videos in mp4 format.*/
  public string url(string url)
        {
            string html = getYoutubeHtml(url);
            HtmlAgilityPack.HtmlDocument hDoc = new HtmlDocument();
            hDoc.LoadHtml(html);
            HtmlNode node = hDoc.GetElementbyId("movie_player");
            string flashvars = node.Attributes[5].Value;
            string _url = Uri.UnescapeDataString(flashvars);
            string[] w = _url.Split('&');
            string link = "";
            bool foundUrlMap = false;
            for (int i = 0; i < w.Length; i++)
            {
                if (w[i].Contains("fmt_url_map="))
                {
                    foundUrlMap = true;
                    link += w[i].Split('|')[1];
                }
                if (foundUrlMap)
                {
                    /*add the parameters to the url*/
                    link += "&" + w[i];
                    if (w[i].Contains("id="))
                    {
                        link = link.Split(',')[0]; /*change the array index for different formats*/
                        break;
                    }
                }
            }
            link = link.Split('|')[1] + "&title=out";
            return link;
        }
  
  /*this method downloads the html code from the youtube page.*/
        private string getYoutubeHtml(string url)
        {
            string html = "";
            WebRequest request = WebRequest.Create(url);
            WebResponse response = request.GetResponse();
            TextReader reader = new StreamReader(response.GetResponseStream());
            string line = "";
            while ((line = reader.ReadLine()) != null)
            {
                html += line;
            }
            return html;
        }

then you can use a webclient to get the video to your coumputer simple use this code lines:
 WebClient wc = new WebClient();
    location = YoutubeSaveDialog.FileName;
    wc.DownloadFile(download_url, location);

Thanks again youtube for making our lifes a little more complicated :) (just kidding this was easy!)

HAPPY CODING!

lunes, 4 de abril de 2011

[C#] get the time duration of an audio file

There is a lot fo tutorials explaining how to do this, showing how thousands of codelines
will finally show you how many time will your song least, using lots of references and stuff.

I wonder why in the internet sometimes, people show us how to invent the wheel but not how to use it, of course knowing how is invented is very intresting and you should read it every time, but when you have milestones to acomplish, deliverables to finish and time is against you, you can't reinvent the wheel every time.

So the other day I came with this problem, I needed to know the audio duration of some "x" audio format, and I found tutorials on how to get it from wav files, using math formulas based on the bitrate and file size, importing windows media player, low level programming, but nothing as portable as I wanted.

Finally after lots of research, I found this amazing library:


it is openSource which is great, and also gave me the solution to my problem in 3 code lines, suporting a lot of audio formats or at least the most used/important/comercial.

if you ever want to use this codesnipet to get the audio file duration, here it is:

private static string AudioDuration(string FileFullPath) {
   TagLib.File file = TagLib.File.Create(FileFullPath);
   int s_time = (int)file.Properties.Duration.TotalSeconds;
   int s_minutes = s_time / 60;
   int s_seconds = s_time % 60;
   return s_minutes.ToString() + ":" + s_seconds.ToString() + " minutes";
}

this will get you the duration of your audio file in the format of "mm:ss minutes " of course you have to reference the library above mentioned, and use the using TagLib; reference at the top of your class.

if you dont know how to reference a library in visual studio, simply click "porject->Add reference..." in the dialog select browse and find the TagLib.dll, double click it and then click OK, and you are good to go :)

Happy coding.

domingo, 30 de enero de 2011

[C#] Get Alexa Page Rank Programmatically


So basically we if we want to get the Alexa Page Rank for
a certain url, we have to access their xml API, (I'm sure there's
JSON outhere) and pass the url via querystring, and then just parse
the response.

Here is how:


public static int getAlexa(String URL) {
    int AlexaRank = 0;
    WebRequest request = WebRequest.Create("http://data.alexa.com/data? cli=10&dat=snbamz&url=" + URL);
    WebResponse response = request.GetResponse();
    StreamReader sr = new StreamReader(response.GetResponseStream());
    string line = "";
    while ((line = sr.ReadLine()) != null) {
        Regex rankRegex = new Regex("");
        Match match = rankRegex.Match(line);
        if (match.Success) {
            AlexaRank = int.Parse(match.Groups[1].Value);
        }
    }
    sr.Close();
    return AlexaRank;
}

and there you go, you can also convert this int, to string
or whatever, nothing complex.

Hope you find this code snippet usefull :)