Ozeki Camera Recorder Stat

How to handle alarms by recording video and uploading it to an FTP server in C#

In this guide you can find information on how to record motion and send it to an FTP server. To implement this example, you must have OZEKI Camera SDK installed, and a reference to OzekiSDK.dll should be added to your Visual Studio project.

How to detect motions with an IP camera and send the captured video to an FTP server using C#?

To establish the connection properly between your application and an IP camera you should apply the same code snippet what you have used in the example (How to connect to an IP camera device using C#?). Important: you should study this article in order to find out how to setup your Windows Forms/WPF Application correctly. It's also recommended to visit the Viewer side motion detection detection article before you begin to study this functionality.

Getting started

To get started it is recomended to Download and Install the latest version of Ozeki Camera SDK. After installation you can find the example code discussed in this page with full source code in the following location on your harddrive:

Download Ozeki Camera SDK: http://www.camera-sdk.com/p_13-download-camera-onvif.html
Windows forms version: C:\Program Files\Ozeki\Ozeki SDK\examples.zip\Examples\Other\
Motion_Detection_Video_FTP_WF\Motion_Detection_Video_FTP_WF.sln
WPF version: C:\Program Files\Ozeki\Ozeki SDK\examples.zip\Examples\Other\
Motion_Detection_Video_FTP_WPF\Motion_Detection_Video_FTP_WPF.sln

To compile this example you will need Microsoft Visual Studio installed on your computer.

The additional statements and methods of this example are the following:

StartVideoCapture(string Path): This method starts the video recording.

StopVideoCapture(): This method finishes the video recording.

FtpUploadOnNewThread(): This method updates the recorded video.

With these lines you can get the object to communicate with the server:

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(FTPUrl + filename);
request.Method = WebRequestMethods.Ftp.UploadFile;

With these lines you can copy the contents of the file to the request stream:

request.Credentials = new NetworkCredential(username, password);
byte[] fileContents = File.ReadAllBytes(path);
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();

Notice, that in the ThreadingProcess() method you can modify the time period how long the camera should capture the actual image. The default value is 10000 (given in milliseconds). It's possible that the scanning process will take some extra time so the next detected scene won't be captured instantly.

Recording a video clip and uploading it to FTP server example in C#

Windows Form WPF  

Form1.cs

	using System;
	using System.Drawing;
	using System.Windows.Forms;
	using System.Net;
	using System.IO;
	using System.Threading.Tasks;
	using Ozeki.Media;
	using Ozeki.Camera;
	using Timer = System.Timers.Timer;
	
	namespace OnvifIPCameraMotionDetection09
	{
	    public partial class Form1 : Form
	    {
	        private IIPCamera _camera;
	        private DrawingImageProvider _imageProvider;
	        private MediaConnector _connector;
	        private VideoViewerWF _videoViewerWf;
	        private MPEG4Recorder _mpeg4Recorder;
	        private MotionDetector _motionDetector;
	        private bool _isVideoStartRecord;
	        private string _actualFilePath;
	
	        public Form1()
	        {
	            InitializeComponent();
	            _imageProvider = new DrawingImageProvider();
	            _connector = new MediaConnector();
	            _motionDetector = new MotionDetector();
	            SetVideoViewer();
	        }
	
	        private void SetVideoViewer()
	        {
	            _videoViewerWf = new VideoViewerWF
	            {
	                Size = new Size(260, 180),
	                BackColor = Color.Black,
	                TabStop = false,
	                Location = new Point(40, 20),
	                Name = "_videoViewerWf"
	            };
	            CameraBox.Controls.Add(_videoViewerWf);
	        }
	
	        private void button_Connect_Click(object sender, EventArgs e)
	        {
	            _camera=new IPCamera("192.168.112.109:8080","user","qwe123");
	            _connector.Connect(_camera.VideoChannel, _motionDetector);
	            _connector.Connect(_motionDetector, _imageProvider);
	            _videoViewerWf.SetImageProvider(_imageProvider);
	            _videoViewerWf.Start();
	            _camera.Start();
	            StartMotionDetection();
	        }
	
	        private void StartMotionDetection()
	        {
	            _motionDetector.HighlightMotion = HighlightMotion.Highlight;
	            _motionDetector.MotionColor = MotionColor.Red;
	
	            _connector.Connect(_camera.VideoChannel, _motionDetector);
	            _connector.Connect(_motionDetector, _imageProvider);
	            _motionDetector.MotionDetection += MotionDetector;
	            _motionDetector.Start();
	        }
	
	        private void MotionDetector(object sender, MotionDetectionEvent e)
	        {
	            if (e.Detection)
	            {
	                if (_isVideoStartRecord) return;
	                InvokeGUI(() => Lbl_MDoND.Text = "Motion Detected");
	                StartVideoCapture();
	                _isVideoStartRecord = true;
	
	                var timer = new Timer();
	                timer.Elapsed += (send, args) => ElapSedMotion(send, _mpeg4Recorder);
	                timer.Interval = 10000;
	                timer.AutoReset = false;
	
	                timer.Start();
	            }
	            else
	            {
	                InvokeGUI(() => Lbl_MDoND.Text = "Motion Not Detected");
	            }
	        }
	
	        private void ElapSedMotion(object sender, MPEG4Recorder recorder)
	        {
	            var timer = sender as Timer;
	            if (timer != null)
	            {
	                timer.Stop();
	                timer.Dispose();
	            }
	
	            StopVideoCapture();
	            _connector.Disconnect(_camera.VideoChannel, recorder.VideoRecorder);
	        }
	
	        private void InvokeGUI(Action action)
	        {
	            BeginInvoke(action);
	        }
	
	        private void StartVideoCapture()
	        {
	            var date = DateTime.Now.Year + "y-" + DateTime.Now.Month + "m-" + DateTime.Now.Day + "d-" +
	                                      DateTime.Now.Hour + "h-" + DateTime.Now.Minute + "m-" + DateTime.Now.Second + "s";
	            _actualFilePath = date + ".mp4";
	
	            _mpeg4Recorder = new MPEG4Recorder(_actualFilePath);
	            _mpeg4Recorder.MultiplexFinished += Mpeg4Recorder_MultiplexFinished;
	
	            _connector.Connect(_camera.AudioChannel, _mpeg4Recorder.AudioRecorder);
	            _connector.Connect(_camera.VideoChannel, _mpeg4Recorder.VideoRecorder);
	        }
	
	        void Mpeg4Recorder_MultiplexFinished(object sender, Ozeki.VoIP.VoIPEventArgs<bool> e)
	        {
	            if (!_isVideoStartRecord) return;
	
	            var recorder = sender as MPEG4Recorder;
	            _connector.Disconnect(_camera.AudioChannel, recorder.AudioRecorder);
	            _connector.Disconnect(_camera.VideoChannel, recorder.VideoRecorder);
	
	            recorder.Dispose();
	            Task.Factory.StartNew(FtpUploadOnNewThread);
	            _isVideoStartRecord = false;
	        }
	
	        private void StopVideoCapture()
	        {
	            _mpeg4Recorder.Multiplex();
	
	            _connector.Disconnect(_camera.AudioChannel, _mpeg4Recorder.AudioRecorder);
	            _connector.Disconnect(_camera.VideoChannel, _mpeg4Recorder.VideoRecorder);
	        }
	
	        private void FtpUploadOnNewThread()
	        {
	            var username = "a5527020";
	            var password = "testozeki15";
	            var FTPUrl = "ftp://testozeki.site90.com/etc/";
	            var filePathArray = _actualFilePath.Split('\\');
	            var filename = filePathArray.GetValue(filePathArray.Length - 1);
	
	            var request = (FtpWebRequest)WebRequest.Create(FTPUrl + filename);
	            request.KeepAlive = false;
	            request.Method = WebRequestMethods.Ftp.UploadFile;
	            request.Credentials = new NetworkCredential(username, password);
	            var fileContents = File.ReadAllBytes(_actualFilePath);
	            request.ContentLength = fileContents.Length;
	            var requestStream = request.GetRequestStream();
	            requestStream.Write(fileContents, 0, fileContents.Length);
	            requestStream.Close();
	            var response = (FtpWebResponse)request.GetResponse();
	            response.Close();
	        }
	    }
	}
	

Code 1 - Recording a video clip and uploading it to FTP server example in C#

Please note that none of the cancel and disconnect methods are included in the example because of the demonstrating intent and briefness of the article.

GUI

The Graphical User Interface of an application that handles alarms by recording video and uploading it to an FTP server in C#
Figure 1 - The graphical user interface of your application

After the successful implementation of the functions and the GUI elements, the application will work properly. Pressing the connect button will load in the image of the IP camera device connected to your PC into the panel that you can see on the picture.

Below you can find the code that belongs to the interface of the previously presented application. With the help of this section your Windows Forms Application will be able to work properly.

Form1.Designer.cs

	namespace OnvifIPCameraMotionDetection09
	{
	    partial class Form1
	    {
	        private System.ComponentModel.IContainer components = null;
	
	        protected override void Dispose(bool disposing)
	        {
	            if (disposing && (components != null))
	            {
	                components.Dispose();
	            }
	            base.Dispose(disposing);
	        }
	
	        private void InitializeComponent()
	        {
	            this.groupBox1 = new System.Windows.Forms.GroupBox();
	            this.Lbl_MDoND = new System.Windows.Forms.Label();
	            this.button_Connect = new System.Windows.Forms.Button();
	            this.CameraBox = new System.Windows.Forms.GroupBox();
	            this.groupBox1.SuspendLayout();
	            this.SuspendLayout();
	            // 
	            // groupBox1
	            // 
	            this.groupBox1.Controls.Add(this.Lbl_MDoND);
	            this.groupBox1.Controls.Add(this.button_Connect);
	            this.groupBox1.Location = new System.Drawing.Point(10, 10);
	            this.groupBox1.Name = "groupBox1";
	            this.groupBox1.Size = new System.Drawing.Size(335, 60);
	            this.groupBox1.TabIndex = 0;
	            this.groupBox1.TabStop = false;
	            this.groupBox1.Text = "Connect";
	            // 
	            // Lbl_MDoND
	            // 
	            this.Lbl_MDoND.AutoSize = true;
	            this.Lbl_MDoND.Location = new System.Drawing.Point(150, 25);
	            this.Lbl_MDoND.Name = "Lbl_MDoND";
	            this.Lbl_MDoND.Size = new System.Drawing.Size(106, 13);
	            this.Lbl_MDoND.TabIndex = 8;
	            this.Lbl_MDoND.Text = "Motion Not Detected";
	            // 
	            // button_Connect
	            // 
	            this.button_Connect.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
	            this.button_Connect.ForeColor = System.Drawing.Color.Black;
	            this.button_Connect.Location = new System.Drawing.Point(25, 20);
	            this.button_Connect.Name = "button_Connect";
	            this.button_Connect.Size = new System.Drawing.Size(80, 23);
	            this.button_Connect.TabIndex = 6;
	            this.button_Connect.Text = "Connect";
	            this.button_Connect.UseVisualStyleBackColor = true;
	            this.button_Connect.Click += new System.EventHandler(this.button_Connect_Click);
	            // 
	            // CameraBox
	            // 
	            this.CameraBox.Location = new System.Drawing.Point(10, 85);
	            this.CameraBox.Name = "CameraBox";
	            this.CameraBox.Size = new System.Drawing.Size(335, 210);
	            this.CameraBox.TabIndex = 3;
	            this.CameraBox.TabStop = false;
	            this.CameraBox.Text = "Live camera ";
	            // 
	            // Form1
	            // 
	            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
	            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
	            this.ClientSize = new System.Drawing.Size(354, 304);
	            this.Controls.Add(this.CameraBox);
	            this.Controls.Add(this.groupBox1);
	            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
	            this.MaximizeBox = false;
	            this.Name = "Form1";
	            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
	            this.Text = "Onvif Camera Motion Detection Video to FTP";
	            this.groupBox1.ResumeLayout(false);
	            this.groupBox1.PerformLayout();
	            this.ResumeLayout(false);
	        }
	
	        private System.Windows.Forms.GroupBox groupBox1;
	        private System.Windows.Forms.Button button_Connect;
	        private System.Windows.Forms.GroupBox CameraBox;
	        private System.Windows.Forms.Label Lbl_MDoND;
	    }
	}
	

Code 2 - GUI example in C#

DISCLAIMER: Please note that the following features will only work if your IP camera supports the given function. You should check the user manual of your IP camera to make sure it supports the feature that you wish to implement in C#.

Related Pages

FAQ

Below you can find the answers for the most frequently asked questions related to this topic:

  1. How can I get the URL of the camera?

    You can get the URL from the producer of the camera. (In the 10th tutorial you can find information on how to create an own IP camera discoverer program.)

  2. I have not managed to build the solution. How to solve it?

    • Please set the Target framework property of the project to .NET 4.0.
    • You should add the System.Drawing.dll and the OzekiSDK.dll to the references of the solution.
    • Please import the missing classes.
  3. I uploaded a video, but I didn't find it there. Why?

    • The FTP server is overloaded permanently.
    • The uploading speed is slow.