.NET Components for Mobility

Send a file

Last post 10-25-2009 11:24 AM by songu. 26 replies.
Page 1 of 2 (27 items) 1 2 Next >
Sort Posts: Previous Next
  • 05-03-2007 5:55 PM

    • tremens
    • Not Ranked
    • Joined on 11-03-2006
    • Udine, Italy
    • Posts 0

    Send a file

    Hi,

    this is an example of program in C# to send a file from a Pocket PC to a PC (PC name is "PC_MARCO_01") using InTheHand and Bracham.Obex libraries.

     

    CLIENT - POCKET PC 

    function SendFileBT() {

    try {
      BluetoothRadio.PrimaryRadio.Mode = RadioMode.Discoverable;
    } catch (Exception exc) {
      // generic exception
      MessageBox.Show("Error: Bluetooth device isn't active (" + exc.Message + ").", "ERROR BLUETOOTH DEVICE");
    }

    BluetoothClient blue_client = new BluetoothClient();
    BluetoothDeviceInfo server = null;
    // the name of the Bluetooth server (PC name)
    string serverName = "PC_MARCO_01";
    string fileName = "test.txt";
    // boolean var
    bool fileSent = false;

    // discovery Bluetooth device
    BluetoothDeviceInfo[] devices = blue_client.DiscoverDevices();

    // search my Bluetooth server
    foreach (BluetoothDeviceInfo device in devices) {
      if (device.DeviceName == serverName)
        server = device;
    }

    // if I found my Bluetooth server, send a file
    if (server != null) {
      try {
        // define an EndPoint for the server and connect to it
        BluetoothEndPoint serverEP = new BluetoothEndPoint(server.DeviceAddress, BluetoothService.ObexObjectPush);
        blue_client.Connect(serverEP);

        // define the stream
        NetworkStream service;
        // if I am connected ...
        if (blue_client.Connected) {
          // receive the stream
          service = blue_client.GetStream();
          // connect to OBEX server
          ObexClientSession sessionFileSending = new ObexClientSession(service, 65535);
          sessionFileSending.Connect();
          // load the file to send
          FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read);
          // send file to server
          sessionFileSending.PutFrom(file, file.Name, null);
          // close resource
          file.Close();
          sessionFileSending.Disconnect();
          blue_client.Close();
          fileSent = true;

        } else { // if I am not connected ...
          fileSent = false;
        }
      } catch (ObexResponseException exc) {
        // exception caused from the lacked availability of Bluetooth server
      } catch (ObjectDisposedException exc) {
        // exception caused from the closing of the client
      } catch (Exception exc) {
        // generic exception caused from the other operation
      }
    }

    if (fileSent)
    {
      // file sent
    } else {
      // file not sent
    }

    } // end of the function SendFileBT() 

     

    SERVER - PC (PC name = "PC_MARCO_01")

    function ReceiveFileBT() {

    // enter the path where you want save the files
    string path = "C:\";

    try {
      BluetoothRadio.PrimaryRadio.Mode = RadioMode.Discoverable;
    } catch (Exception exc) {
      // generic exception
      MessageBox.Show("Error: Bluetooth device isn't active (" + exc.Message + ").", "ERROR BLUETOOTH DEVICE");
    }

    ObexListener blue_olistener = new ObexListener(ObexTransport.Bluetooth);
    blue_olistener.Start();

    while (blue_olistener.IsListening) {
      try {
        ObexListenerContext blue_olistener_c = blue_olistener.GetContext();
        ObexListenerRequest blue_olistener_r = blue_olistener_c.Request;

        // save the received file on PC after extract its name (without path)
        string[] temp = blue_olistener_r.RawUrl.Split('/');
        string fileName = path + temp[temp.Length - 1];
        blue_olistener_r.WriteFile(fileName);
      } catch (Exception exc) {
        // generic exception
      }
    }

    blue_olistener.Stop();

    } // end of the function ReceiveFileBT

     

    For me this client server works very very good. Pairing isn't support for the server.

    For any question, post here.

    tremens 

  • 05-23-2007 3:27 PM In reply to

    Re: Send a file

    hi,

        this example is very useful for me...I worked it..

    Now i need example program to send file from Pocket Pc to Pocket Pc using C#....

     

    Can u please Help me... Urgent... 

     

    Krishna 

     

  • 05-25-2007 12:10 PM In reply to

    Re: Send a file

    That sample code should work on both platforms as far as I can see.  What's your project for: commercial, college project etc?

    Alan J. McFarlane
    http://www.alanjmcf.me.uk/
    Please follow-up in the newsgroup for the benefit of all.
    Have I helped? Consider visiting my Amazon wishlist, see my homepage.
  • 05-26-2007 8:02 AM In reply to

    Re: Send a file

    Hi, Thanks for ur kind reply... Actually its commercial project... I used that code between pocket pcs...

    But it got some exception in,,

          // connect to OBEX server
          ObexClientSession sessionFileSending = new ObexClientSession(service, 65535);
          sessionFileSending.Connect();
          // load the file to send
          FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read);
          // send file to server
          sessionFileSending.PutFrom(file, file.Name, null); This line..

    Can u please help me ... 

     

    Krishna 

     

     

  • 06-01-2007 8:26 AM In reply to

    Re: Send a file

    Hi,

        I used these code for send file from pocket pc to pc......

        But it got some exception in,,

         // connect to OBEX server
        ObexClientSession sessionFileSending = new ObexClientSession(service, 65535);
        sessionFileSending.Connect();
        // load the file to send
        FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read);
        // send file to server
        sessionFileSending.PutFrom(file, file.Name, null); I got exception in this line..

    Can u please help me ...

     

    Krishna

  • 06-01-2007 2:11 PM In reply to

    Re: Send a file

    Using my psychic debugging abilities...  My best guess is that the FileStream.Name property as used in that line is returning a complete pathname, whereas the server probably only will accept a simple filename.  So try modifying it to be:

    String filename = Path.GetFileName(file.Name);
    sessionFileSending.PutFrom(file, filename, null);

    If that doesn't solve it, how about telling us what exception you are receiving... :-,)  ObexResponseException? And what response code if so?

    Alan J. McFarlane
    http://www.alanjmcf.me.uk/
    Please follow-up in the newsgroup for the benefit of all.
    Have I helped? Consider visiting my Amazon wishlist, see my homepage.
  • 06-04-2007 2:19 PM In reply to

    Re: Send a file

    hi,

          Thanks for ur reply..

           I used those lines, i mentioned below here

            FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read);                


            string filename = Path.GetFileName(file.Name);
            sessionFileSending.PutFrom(file, filename, null);

     

    But i got the Exception  "MissingMethodException was Unhandled"...

    "Could not load type 'System.Diagnostics.TraceSwitch' from assembly 'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=969DB8053D3322AC'."

     

    Regards,

    Krishna
     

  • 06-04-2007 3:13 PM In reply to

    Re: Send a file

    hii

     plz i want to know how can i send files from PC to PC via bluetooth and using this library .. inthehand ....

    alsoo i want to know how can i start application using bluetooth in smart devices in .Net either 2003 or 2005 ... as it always gives me the error that it cant find the bluetooth device attached 

    NB. my bluetooth device is not built in ... its external usb bluetooth device that works properly with microsoft stack

    please reply me as soon as possible because i need it urgently in my graduation project which is so sooon :( :( and i am soo late behind

    thanks alot in advance

    H.Barsoum

     

  • 06-04-2007 6:36 PM In reply to

    Re: Send a file

    hii

    please help me with the exception i have after i tried the above code ....

    the exception is invalid argument at :

    BluetoothEndPoint serverEP = new BluetoothEndPoint(server.DeviceAddress, BluetoothService.ObexObjectPush);

     

    blue_client.Connect(serverEP);

    please help me as soon as possible

    H.Barsoum

  • 06-05-2007 6:45 AM In reply to

    Re: Send a file

    hi,

           Use this coding instead of that.....

           public BluetoothClient btClient = new BluetoothClient();
     

           btClient = new BluetoothClient();

           btClient.Connect(new BluetoothEndPoint((BluetoothAddress)deviceComboBox.SelectedValue, BluetoothService.ObexObjectPush));

     

    Regards,

    Krishna 

  • 06-05-2007 2:43 PM In reply to

    Re: Send a file

    dear krishna .... thanks alot for your great help :)

    it really worked and I passed these statements .... but i still have a problem with the line :

    sessionFileSending.Connect();

    it throws an expection after a while ... and i dont know how to solve it !!

     please help me as soon as u can ...

    and thanks in advance

    H.Barsoum

  • 06-06-2007 7:26 AM In reply to

    Re: Send a file

    hi,

          Thanks for ur reply..

           I used those lines, i mentioned below here

            FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read);                


            string filename = Path.GetFileName(file.Name);
            sessionFileSending.PutFrom(file, filename, null);

     

    But i got the Exception  "MissingMethodException was Unhandled"...

    "Could not load type 'System.Diagnostics.TraceSwitch' from assembly 'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=969DB8053D3322AC'."

     

    Regards,

    Krishna
     

  • 06-07-2007 4:06 PM In reply to

    Re: Send a file

    I'm perplexed by that error.  The TraceSwitch class isn't supported on CF so no compiler would create an assembly referencing it, but you see it occuring...  If you're still experiencing this can you show me the exception stack trace, trap it in VS and "Copy exception detail to the clipboard"
    Alan J. McFarlane
    http://www.alanjmcf.me.uk/
    Please follow-up in the newsgroup for the benefit of all.
    Have I helped? Consider visiting my Amazon wishlist, see my homepage.
  • 06-07-2007 4:06 PM In reply to

    Re: Send a file

    What exception?
    Alan J. McFarlane
    http://www.alanjmcf.me.uk/
    Please follow-up in the newsgroup for the benefit of all.
    Have I helped? Consider visiting my Amazon wishlist, see my homepage.
  • 06-29-2007 1:34 AM In reply to

    Re: Send a file

    HI,

          I can use this code to send a file from Pocket pc to pocket pc

     

    #region Using directives

    using System;
    using System.IO;
    using System.Net.Sockets;
    using System.Drawing;
    using System.Collections;
    using System.Windows.Forms;
    using System.Data;

    using InTheHand;
    using InTheHand.IO;
    using InTheHand.Net;
    using InTheHand.Net.Bluetooth;
    using InTheHand.Net.Forms;
    using InTheHand.Net.Sockets;

    #endregion

    namespace SendXmlFile
    {
        public class Form1 : System.Windows.Forms.Form
        {
            private Button SelectFile;
            private Button ConnectDevices;
            private Button SendFile;
            private ComboBox deviceComboBox;
            private Button DiscoverDevices;
            private MenuItem menuItem1;
            private OpenFileDialog openFileDialog1;
            private System.Windows.Forms.MainMenu mainMenu1;

            public BluetoothClient btClient = new BluetoothClient();
            public string fileName;
            public string data;
            public bool fileSent = false;
            public NetworkStream stream;
            private TextBox textBox1;
            InTheHand.Net.BluetoothAddress[] address_array = new BluetoothAddress[1000];

          
           
            #region Form1() Constructor,Dispose Method,Form Designer Generated Code,Main Method
            public Form1()
            {
                InitializeComponent();
            }

            protected override void Dispose(bool disposing)
            {
                base.Dispose(disposing);
            }
           
            #region Windows Form Designer generated code
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                this.mainMenu1 = new System.Windows.Forms.MainMenu();
                this.menuItem1 = new System.Windows.Forms.MenuItem();
                this.SelectFile = new System.Windows.Forms.Button();
                this.ConnectDevices = new System.Windows.Forms.Button();
                this.SendFile = new System.Windows.Forms.Button();
                this.deviceComboBox = new System.Windows.Forms.ComboBox();
                this.DiscoverDevices = new System.Windows.Forms.Button();
                this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
                this.textBox1 = new System.Windows.Forms.TextBox();
                //
                // mainMenu1
                //
                this.mainMenu1.MenuItems.Add(this.menuItem1);
                //
                // menuItem1
                //
                this.menuItem1.Text = "CLOSE";
                this.menuItem1.Click += new System.EventHandler(this.menuItem1_Click);
                //
                // SelectFile
                //
                this.SelectFile.Location = new System.Drawing.Point(157, 87);
                this.SelectFile.Size = new System.Drawing.Size(83, 26);
                this.SelectFile.Text = "Select File";
                this.SelectFile.Visible = false;
                this.SelectFile.Click += new System.EventHandler(this.SelectFile_Click);
                //
                // ConnectDevices
                //
                this.ConnectDevices.Location = new System.Drawing.Point(0, 87);
                this.ConnectDevices.Size = new System.Drawing.Size(72, 26);
                this.ConnectDevices.Text = "Connect";
                this.ConnectDevices.Click += new System.EventHandler(this.ConnectDevices_Click);
                //
                // SendFile
                //
                this.SendFile.Location = new System.Drawing.Point(78, 87);
                this.SendFile.Size = new System.Drawing.Size(76, 26);
                this.SendFile.Text = "Send File";
                this.SendFile.Click += new System.EventHandler(this.SendFile_Click);
                //
                // deviceComboBox
                //
                this.deviceComboBox.Location = new System.Drawing.Point(124, 36);
                this.deviceComboBox.Size = new System.Drawing.Size(113, 22);
                //
                // DiscoverDevices
                //
                this.DiscoverDevices.Location = new System.Drawing.Point(3, 36);
                this.DiscoverDevices.Size = new System.Drawing.Size(72, 20);
                this.DiscoverDevices.Text = "Discover";
                this.DiscoverDevices.Click += new System.EventHandler(this.DiscoverDevices_Click);
                //
                // openFileDialog1
                //
                this.openFileDialog1.FileName = "openFileDialog1";
                //
                // textBox1
                //
                this.textBox1.Location = new System.Drawing.Point(3, 135);
                this.textBox1.Multiline = true;
                this.textBox1.Size = new System.Drawing.Size(234, 130);
                //
                // Form1
                //
                this.ClientSize = new System.Drawing.Size(240, 268);
                this.ControlBox = false;
                this.Controls.Add(this.textBox1);
                this.Controls.Add(this.SelectFile);
                this.Controls.Add(this.ConnectDevices);
                this.Controls.Add(this.SendFile);
                this.Controls.Add(this.deviceComboBox);
                this.Controls.Add(this.DiscoverDevices);
                this.Menu = this.mainMenu1;
                this.Text = "Send File Version 1.0";
                this.Load += new System.EventHandler(this.Form1_Load);

            }

            #endregion

            static void Main()
            {
                Application.Run(new Form1());
            }
            #endregion

            #region Form load
            private void Form1_Load(object sender, EventArgs e)
            {
                this.ConnectDevices.Enabled = false;
                this.SendFile.Enabled = false;
                this.SelectFile.Enabled = false;
            }
            #endregion

            #region Discover Devices
            private void DiscoverDevices_Click(object sender, EventArgs e)
            {
                this.DiscoverDevices.Enabled = false;

                BluetoothClient bluetoothClient = new BluetoothClient();
                BluetoothDeviceInfo[] bluetoothDeviceInfo = bluetoothClient.DiscoverDevices();

                for (int i = 0; i < bluetoothDeviceInfo.Length; i++)
                {
                    this.address_arrayIdea = bluetoothDeviceInfoIdea.DeviceAddress;
                }
                MessageBox.Show(bluetoothDeviceInfo.Length + " Devices found");

                deviceComboBox.DataSource = bluetoothDeviceInfo;
                deviceComboBox.DisplayMember = "DeviceName";
                deviceComboBox.ValueMember = "DeviceAddress";
                deviceComboBox.Focus();
                this.ConnectDevices.Enabled = true;
            }
            #endregion

            #region Connect Device
            private void ConnectDevices_Click(object sender, EventArgs e)
            {
                try
                {
                    btClient = new BluetoothClient();
                    btClient.Connect(new BluetoothEndPoint((BluetoothAddress)deviceComboBox.SelectedValue, BluetoothService.ObexObjectPush));
                    if (btClient.Connected)
                    {
                        MessageBox.Show("connected");
                        this.SelectFile.Enabled = true;
                        this.SendFile.Enabled = true;
                    }
                    else
                    {
                        MessageBox.Show("Not Connected");
                        this.DiscoverDevices.Enabled = true;
                    }
                    this.ConnectDevices.Enabled = false;
                }
                catch (SocketException se)
                {
                    MessageBox.Show(se.ToString());
                }
            }
            #endregion

            #region Select File
            private void SelectFile_Click(object sender, EventArgs e)
            {
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    fileName = openFileDialog1.FileName;
                }
                this.SelectFile.Enabled = false;
                this.SendFile.Enabled = true;
            }
            #endregion

            #region Send File
            private void SendFile_Click(object sender, EventArgs e)
            {
                if (btClient.Connected)
                {
                    stream = (NetworkStream)btClient.GetStream();
                    string fName = Path.GetFileName(fileName);
                    string fType = "";
                    StreamReader sr = File.OpenText(fileName);
                    string fFileContent = sr.ReadToEnd();
                    sr.Close();
                  
                    //send client request, start put
                    int result = OBEXRequest("PUT",fName,fType, fFileContent);

                    switch (result)
                    {
                        case 160: // 0xa0
                            MessageBox.Show("File Send");
                            break;

                        case 197: // 0xc5
                            MessageBox.Show("Method not allowed");
                            break;

                        case 192: // 0xc0
                            MessageBox.Show("Bad Request");
                            break;

                        default:
                            MessageBox.Show("Other Error");
                            break;
                    }
                }

                else
                {
                    MessageBox.Show("Failed to connect to OBEX Server");
                }
                //this.SendFile.Enabled = false;
                this.SelectFile.Enabled = true;
                this.DiscoverDevices.Enabled = true;
            }
           
            private int OBEXRequest(string tReqType, string tName,string tType ,string tFileContent)
            {
                //send client request

                int i;
                int offset;
                int packetsize;
                byte reqtype = 0x82;

                int tTypeLen = 0x03;
                int typeheadsize;
                int typesizeHi = 0x00;
                int typesizeLo = 0x03;

                if (tReqType == "GET")
                {
                    reqtype = 0x83;            // 131 GET-Final
                }

                if (tReqType == "PUT")
                {
                    reqtype = 0x82;            // 130 PUT-Final
                }

                packetsize = 3;

                //Name Header
                int tNameLength = tName.Length;
                int nameheadsize = (3 + (tNameLength * 2) + 2);
                int namesizeHi = (nameheadsize & 0xff00) / 0xff;
                int namesizeLo = nameheadsize & 0x00ff;
                packetsize = packetsize + nameheadsize;

                if (tType != "")
                {
                    //Type Header
                    tTypeLen = tType.Length;
                    typeheadsize = 3 + tTypeLen + 1;
                    typesizeHi = (typeheadsize & 0xff00) / 0xff;
                    typesizeLo = typeheadsize & 0x00ff;
                    packetsize = packetsize + typeheadsize;
                }

                //Body
                int fileLen = tFileContent.Length;
                int fileheadsize = 3 + fileLen;
                int filesizeHi = (fileheadsize & 0xff00) / 0xff; ;
                int filesizeLo = fileheadsize & 0x00ff; ;

                packetsize = packetsize + fileheadsize;

                int packetsizeHi = (packetsize & 0xff00) / 0xff;
                int packetsizeLo = packetsize & 0x00ff;

                byte[] tSendByte = new byte[packetsize];

                //PUT-final Header
                tSendByte[0] = reqtype;                                        // Request type e.g. PUT-final 130
                tSendByte[1] = Convert.ToByte(packetsizeHi);                // Packetlength Hi
                tSendByte[2] = Convert.ToByte(packetsizeLo);                // Packetlength Lo

                offset = 2;

                //Name Header
                tSendByte[offset + 1] = 0x01;                                    // HI for Name header       
                tSendByte[offset + 2] = Convert.ToByte(namesizeHi);            // Length of Name header (2 bytes per char)
                tSendByte[offset + 3] = Convert.ToByte(namesizeLo);            // Length of Name header (2 bytes per char)

                // Name+\n\n in unicode
                byte[] tNameU = System.Text.Encoding.BigEndianUnicode.GetBytes(tName);
                tNameU.CopyTo(tSendByte, offset + 4);

                offset = offset + 3 + (tNameLength * 2);
                tSendByte[offset + 1] = 0x00;                                    // null term
                tSendByte[offset + 2] = 0x00;                                    // null term

                offset = offset + 2;

                if (tType != "")
                {
                    //Type Header
                    tSendByte[offset + 1] = 0x42;                                    // HI for Type Header 66
                    tSendByte[offset + 2] = Convert.ToByte(typesizeHi);            // Length of Type Header
                    tSendByte[offset + 3] = Convert.ToByte(typesizeLo);            // Length of Type Header

                    for (i = 0; i <= (tTypeLen - 1); i++)
                    {
                        tSendByte[offset + 4 + i] = Convert.ToByte(Convert.ToChar(tType.Substring(i, 1)));
                    }
                    tSendByte[offset + 3 + tTypeLen + 1] = 0x00;                        // null terminator

                    offset = offset + 3 + tTypeLen + 1;
                }

                //Body
                tSendByte[offset + 1] = 0x49;                                    //HI End of Body 73
                tSendByte[offset + 2] = Convert.ToByte(filesizeHi);            //
                tSendByte[offset + 3] = Convert.ToByte(filesizeLo);            //1k payload + 3 for HI header

                for (i = 0; i <= (fileLen - 1); i++)
                {
                    tSendByte[offset + 4 + i] = Convert.ToByte(Convert.ToChar(tFileContent.Substring(i, 1)));
                }
                //tSendByte[offset+4+fileLen] = 0x00;                            // null terminator

                offset = offset + 3 + fileLen;

                stream.Write(tSendByte, 0, tSendByte.Length);

                //listen for server response

                //TODO: can hang here forever waiting response...

                bool x = stream.DataAvailable; // changed bluetoothclient - public NetworkStream GetStream()

                byte[] tArray4 = new byte[3];
                stream.Read(tArray4, 0, 3);

                x = stream.DataAvailable;

                if (tArray4[0] == 160) // 0xa0
                {
                    int plength = (tArray4[1] * 256) + tArray4[2] - 3;
                    byte[] tArray5 = new byte[plength];
                    if (plength > 0)
                    {
                        stream.Read(tArray5, 0, plength);
                        data = Convert.ToString(tArray5);
                        textBox1.Text = data.ToString();
                        //TODO: data in returned packet to deal with
                    }
                    return 160;
                }

                if (tArray4[0] == 197) // 0xc5 Method not allowed
                {
                    return 197;
                }

                if (tArray4[0] == 192) // 0xc0 Bad Request
                {
                    return 192;
                }

                return 0;
            }       
            #endregion      

            #region Close
            private void menuItem1_Click(object sender, EventArgs e)
            {
                Application.DoEvents();
                Application.Exit();
            }
            #endregion          
        }
    }

     Regards,

    Krishna 

Page 1 of 2 (27 items) 1 2 Next >
Copyright © 2001-2010 In The Hand Ltd. All rights reserved. Terms of Use and Privacy Policy.