Showing posts with label urprob. Show all posts
Showing posts with label urprob. Show all posts

Tuesday, July 27, 2010

Youtube Video search and play control

logo_300
Today we gonna tell about making a project that could extract the video from YouTube using a keyword entered by the user and then playing it.
We’ll make a control and you would be able to use it any where you want.
Before going forward let me tell you what u’ll need for it.
You’ll need a developer key issued by Google to make use of any of Google API. here we’ll be using YouTube API.
here are some links.
http://code.google.com/apis/youtube/dashboard/ (for getting DEV key)
http://code.google.com/apis/youtube/code.html#client_libraries( Download API).
So let me tell you how it gonna look like
image
Designing is pretty easy
  • just take one panel
  • set dock property to top
  • right click over it and press bring to front
  • drag and drop a textbox and a button inside it and align them
  • take a flowlayout panel
  • set dock property to fill
  • right click over it and choose bring to front.
So now you are completed with design
so i guess we should start coding don’t you?. really excited to listen songs in your apps. ;)
so here we go
Class variables are as given
string id; static public Point loc; public bool Search; public string currentlink = ""; string item; bool feed; Feed<Video> yt_vid; YouTubeRequestSettings Ysettings = new YouTubeRequestSettings("Your app name", "Your app name", "Your Dev key", "Username","Password"); YouTubeRequest Yrequest; public static YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri); List<Video> _vidlist = new List<Video>(); YouTubeService Yservice = new YouTubeService(Your app name", "Your app name", "Your Dev key"); static public List<AtomCategory> atcat = new List<AtomCategory>(); static public List<string> cat_vid = new List<string>();
So i guess you need some explanations that what are these strange things don’t you?
Well. String id is for our Video ID, its a simple id that you see in any Video URL of Youtube.
Current link will give us the the link of selected Video.
Some important variables are
  • YouTubeRequestSettings : It’ll provide settings for your application. It takes mentioned parameters and all of them are string. It’ll used for making our YouTubeRequest Variable
  • Youtube querry will be used or searching video
  • List of video has been taken as the number of extracted video can be any thing from 0 to 25 or even more.so i have taken list instead of array
  • Another one is YouTubeService
  • List<AtomCategory> has been choiosen for choosing catagory of video
Click event of button will be as shown
private void button1_Click(object sender, EventArgs e) { Search = true; Yrequest = new YouTubeRequest(Ysettings); this.item = txtSearch.Text; query.Query = item.Replace(' ', '+'); yt_vid = Yrequest.Get<Video>(query); for (int i = 1; i < 3; i++) {
this.Height *= i; flowLayoutPanel1.Height *= i; } printvids(); Search = false; }
So you can see we have used Youtube settings for making Youtube request.
we took the search term and assign that to the youtubequery
in the next line we just increased the size of Flowlayout panel.
printvids function is as given below
void printvids() {
foreach (Video entry in yt_vid.Entries) { foreach (MediaContent Mcon in entry.Contents) { try {
int x = Mcon.Url.IndexOf('?'); id = Mcon.Url.Remove(x); id = id.Substring(25);
Label lblviewcount = new Label(); lblviewcount.ForeColor = Color.White; lblviewcount.Text = entry.ViewCount + " VIEWS"; lblviewcount.Width = flowLayoutPanel1.Width;
PictureBox img = new PictureBox(); img.SizeMode = PictureBoxSizeMode.StretchImage; //Bitmap bmp = new Bitmap("http://img.youtube.com/vi/_XUe6Obeyk0/0.jpg"); img.ImageLocation = "http://img.youtube.com/vi/" + id + "/0.jpg"; img.Width = 170; img.Height = 170; img.Left = flowLayoutPanel1.Left;
LinkLabel lblName = new LinkLabel(); lblName.AccessibleName = id; lblName.ForeColor = Color.White; lblName.Text = entry.Title.ToString(); lblName.Width = flowLayoutPanel1.Width; lblName.Click += new EventHandler(lnk_click); flowLayoutPanel1.Controls.Add(lblviewcount); flowLayoutPanel1.Controls.Add(img); flowLayoutPanel1.Controls.Add(lblName);
//if (flowLayoutPanel1.InvokeRequired) //{ //    connect add = new connect(addcontrol); //    object[] param = new object[3]; //    param[0]= lblName; //    param[1]=lblviewcount; //    param[2]=img; //    flowLayoutPanel1.BeginInvoke(add); //} } catch (Exception ex) { }
}
} }
In the click event of button we had extracted the videos and added them into Feed<Video>
In this method we extract video from the feed and the video infos from the video to print to the form, so we extracted the infos into MediaContent.
using following lines we got the id of Youtube video
int x = Mcon.Url.IndexOf('?'); id = Mcon.Url.Remove(x); id = id.Substring(25);
Using MediaContent we extracted infos like URL and Thumbnail of the videos. and as we got them added into linklabel, label and picture box and added them into Flowlayout control to display them on our Control.
By now we have created Search control
Now will do something that will be able to play video extracted from Youtube.
It’ll be quite easy as we are going to just create an html file and then embedding code of video in that html file
Now we will do it by clicking on linklabel.
So we need a form that will contain a web browser to run our .htm file .
The click event of the linklabel hase been defind in the above method
The event definition will be as given
private void lnk_click(object sernder, EventArgs e) { LinkLabel lnk = (LinkLabel)sernder; id = lnk.AccessibleName; Save("video.htm");                                                                                                 Player ob = new Player(); ob.Show(); }
PLayer is another form  that contains our web browser.
Here we created a link label and assinged the ID of selected video as shown above. in the previous method we had taken id of video in the accessible name of linklabel. so we got the selected video id.
Now we need to write embedding code to the html file. the save method does the same.
But be sure to add an html file exclusively to your project and pass the name of the html file to save method.
Save method is as shown below
public void Save(string fileName) { FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite); StreamWriter sw = new StreamWriter(fs); try { string  Embedcode =@”<body style=" + "background:#000000" + ">" + "<div id=\"video" + id + "\"><object width=\”425\” height=\"355\"><param name=\"movie\" value=\"http://www.youtube.com/v/"+ id + "&rel=1\"></param><param name=\"wmode\" value=\"transparent\”></param><embed src=”\"http://www.youtube.com/v/" + id + "&rel=1\"type=\"application/x-shockwave-flash\" wmode=\"transparent\" width=\"425\" height=\"355\">></embed></object></div></body>";”
sw.WriteLine(Embedcode); }
finally { sw.Close(); fs.Close(); } }
Embedcode has been defined and written in the html file.
rest of the line of click event of LinkLabel just show the Player form.
The load event of the Player form is as given below
private void Player_Load(object sender, EventArgs e) { this.Left = UserControl1.loc.X; this.Top = UserControl1.loc.Y; string path = Path.GetFullPath("video.htm"); webBrowser1.Navigate(path); }
Now would you like to believe that you have just coded your very own Youtube Control. :)
Here’s the working snap
image
Hope you’ll find this post useful. Keep on posting suggestions and questions.
THX
You can get our working project on youtube from http://syd.codeplex.com.

Chat Server and Chat Client

logo_300
Hi. Today we gonna show you how you can make your own chat application using TCP and UDP protocols.
This will be based on server client architecture. The basic work flow will be as given below
imageThe basic working of this model is as given below
  1. Client sent a message to server that contains two information,  Address of destination and the message to send.
  2. Client send this message to server on the port 8080 (shown here you can take any one which is available to use)
  3. Server looks for destination address and forward message to destination on port 8085(shown here you can take any one which is available to use).
  4. Destination which is another client get this message as it keep on listening to the port num 8085
So hope by now you have learnt the basic processing of the program. So here are the resources to be used

  • .Net Framework 2.0
  • Language c#
  • Development Platform Visual Studio 2008
So let’s start from Designing Windows.
SERVER:
  • Create a new project, name it Chat Server
  • Drop a ListBox into the Form created by Default.
  • Drop a Lable and set Text property to, Connected Member.
  • From the properties bar choose Form1( or whatever you named the first form)
  • Go to Event Double click on Load event.
  • This is How it should Look Like image

Now we can start the game “Coding”.
Using statements are as
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net.Sockets; using System.Net; using System.Threading;
Define Following Variables as Class variables ie out side any function.
delegate void connect(object obj); /* This is delegate for adding connection to our List Box*/ UdpClient up_send = new UdpClient(1024);/* this is our Udp Client For sending Texts string word; bool showcon = true;/* this bool variable to show whether Connection is needed*/ static int recieveport; /* this is the Port number of Client which is sending message*/ string msg = "";/* this is the receive message from Client*/ int senderport; /* this is port num of client which will receive message*/
recieveport and senderport is not as such required, this will become necessary when you will make two client for the same pc mean for testing the project on your pc only not on LAN.
In the Constructor add following Codes
InitializeComponent();// this method will initialize all controls used Thread serverthread = new Thread(new ThreadStart(server)); /* this is our server thread which will keep on running continuously*/ serverthread.Start();  //Here we started our server thread
Server thread is an Object of a thread that takes a method “server” as a parameter of Threadstart, When this thread will start running the method “server” will start executing
here’s the methode “Server”( make sure the return type of parameter of thread it should be void only)
private void server() { UdpClient up_recieve = new UdpClient(8080);/* this is udp client for Listening to client’s message*/ while (true)/* an infinite while loop for keep on checking for new message*/ { IPEndPoint remoteipendpoint = new IPEndPoint(IPAddress.Any, 0);/* this will give u the connection which is established*? byte[] recievebyte = up_recieve.Receive(ref remoteipendpoint);/* here' we re getting the message in Bytes*/ word = Encoding.ASCII.GetString(recievebyte);/* here we converted our message into string, ready to send to destination client*/ recieveport =Convert.ToInt32(word.Substring(0,4));/* here we get  the port number of destination Client, This is for only if you are testing two client on the same pc, you can send Ip address and port number of client instead of just port number*/ if (lstbxMsg.InvokeRequired&& showcon)/* here we are checking whether current thread can access list box or not. it won’t as lstBox is not defined under scope of this thread*/ { connect con = new connect(connectmem);/* here we made an object of our delegate*/ lstbxMsg.BeginInvoke(con, remoteipendpoint);/*connectmem method will be able to access llistbox as we have given object of delegate of this method as a object of begine invoke method*/ showcon=false;/* we made the connection so make it false*/ } if(!string.IsNullOrEmpty(word))/* checking whether the received message is empty*/ { Thread thrdsend = new Thread(new ThreadStart(send)); thrdsend.Start();/* if not then this thread will send the message*/ } } }
Here’s the method to insert connected member into List Box
void connectmem(object obj) { IPEndPoint remote = (IPEndPoint)obj; lstbxMsg.Items.Add(remote.ToString()+" Connected"); }
Here’s our Send method
private void send() { byte[] sendbyte = Encoding.ASCII.GetBytes(word); up_send.Connect("localhost", recieveport); up_send.Send(sendbyte, sendbyte.Length); }
In first line we taken the message as Byte which will be sent to another client.
In second line we made connection to another client. In our case we have run server and two client on the same pc hence instead of giving any IP address we have taken “localhost”. If you are testing it on LAN then you will have to send message from Client that include destination’s IP address and use the IP address to connect from this statement.
In Third statement we are sending message using the UDP client defined as class variable.
So by now we are Completed with our server that is able to send and receive texts.
Now we will create Our Chat Client. I’ll explain you you file sharing Module of this project in later Blog.
Client:
Let’s start With designing.
  • Create a New Project name it Chat Client
  • Drag and drop a list box, a textbox and a Button into form
  • This should Look Like
Chat Client
Let start game again “Coding”
Using statements are as
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net.Sockets; using System.Net; using System.Threading;
Define following as Server variables
UdpClient up = new UdpClient(8582); delegate void connect(object obj); Thread thrd;
up is our UDP Client for sending data, hence we will send data from port number 8582
The form Load event should be like this
private void Form1_Load(object sender, EventArgs e) { thrd = new Thread(new ThreadStart(recieve)); thrd.Start(); }
Here we started our thread for receiving message. this thread will be like receiving thread of server.
Here’s our Receive method
void recieve() { UdpClient up = new UdpClient(8085); while (true) { IPEndPoint remoteipendpoint = new IPEndPoint(IPAddress.Any, 0); byte[] recievebyte = up.Receive(ref remoteipendpoint); string word = Encoding.ASCII.GetString(recievebyte); if (lstbxMsg.InvokeRequired) { connect con = new connect(connectmem); lstbxMsg.BeginInvoke(con,remoteipendpoint.ToString()+" "+word); } } }
this method is exactly same as the one of server. remoteipendpoint is IP address of the pc from where the message is coming from. In our Case server.
In server we were inserting connected member into listBox, here will add message.
for adding message the method is as given below
void connectmem(object obj) { lstbxMsg.Items.Add(obj.ToString()); }
This is quite understandable
On click event of Button we will send our message to server
the click event will be like this
private void btnSend_Click(object sender, EventArgs e) { byte[] sendbyte = Encoding.ASCII.GetBytes("8086"+textBox1.Text); up.Connect("localhost", 8080); up.Send(sendbyte, sendbyte.Length); lstbxMsg.Items.Add(textBox1.Text); textBox1.Text = ""; }
This quite same as the sending method of server
1st converting message to byte and connecting to server(in server we were connecting to client) and then sending the message and adding that message to list box as well so that the user will be able to see his/ her own message. the thing to notice here is that we are adding 8086 port number here, You should add IP address of the client to whom user is going to send the message (if you are using LAN).
Here we are completed our Chat client and chat Server.
Isn’t it easy????
Hope you liked it. In next post we will describe File Sharing using TCP.