示例#1
0
        public void runing(object param)
        {
            try
            {
                bool   calculate_flag = true;
                byte[] writebuffer    = new byte[20480];
                //String strPipeName = @"\\.\pipe\myPipe2";
                string g_czPipName_Base = "\\\\.\\pipe\\HST_Output_Pip_Gpu_%d"; //0~3
                string strPipeName      = "\\\\.\\pipe\\HST_Output_Pip_Gpu_0";
                Console.WriteLine(strPipeName);

                DataRec dr = new DataRec(Convert.ToInt32(param));
                while (true)
                {
                    Thread.Sleep(1000);
                    if (dr.PipeFlag)
                    {
                        while (true)//连接管道
                        {
                            //dr.hPipe = PipeNative.WaitNamedPipe
                            dr.hPipe = PipeNative.CreateFile(
                                strPipeName,                                                      //管道名称
                                FileDesiredAccess.GENERIC_READ | FileDesiredAccess.GENERIC_WRITE, //访问模式,读模式或写模式
                                FileShareMode.Zero,                                               //0表示不共享,共享模式
                                IntPtr.Zero,                                                      //一个只读字段,代表已初始化为零的指针或句柄。指向安全属性的指针
                                FileCreationDisposition.OPEN_EXISTING,                            //如何创建。文件必须已经存在。由设备提出要求
                                0,                                                                //文件属性
                                0);                                                               //用于复制文件句柄,不使用模板
                            if (dr.hPipe.ToInt32() != PipeNative.INVALID_HANDLE_VALUE)
                            {
                                break;                                                     //PipeNative.INVALID_HANDLE_VALUE = -1.管道创建失败
                            }
                            if (PipeNative.GetLastError() != PipeNative.ERROR_PIPE_BUSY || //PipeNative.ERROR_PIPE_BUSY = 231
                                PipeNative.WaitNamedPipe(strPipeName, 5 * 1000))           //在超时时间前管道的一个实例有效则返回非0,在超时时间内没有一个有效的实例,则返回0
                            {
                                Console.WriteLine("无法连接管道:{0} ERROR:{1}", strPipeName, PipeNative.GetLastError());
                                continue;
                            }
                            else
                            {
                                Console.WriteLine("管道连接成功:{0}", strPipeName);
                            }
                        }

                        while (dr.PipeFlag)
                        {
                            #region [接收数据]

                            SHstPipeInfo    sPipeInfo       = new SHstPipeInfo();
                            MyPipPersistane myPipPersistane = new MyPipPersistane();

                            int iRes = myPipPersistane.ReadPipeInfo(dr.hPipe, ref sPipeInfo);
                            if (iRes == 0)
                            {
                                //todo 参数处理
                                Console.WriteLine("\r ReadPipeInfo videocount: {0} time: {1} \t v0:{2}:{3} \t  v1:{4}:{5} \t  v2:{6}:{7} \t  v3:{8}:{9} \t"
                                                  , sPipeInfo.iVideoCount, sPipeInfo.szVideoInfo[0].i64Time
                                                  , sPipeInfo.szVideoInfo[0].iVideoID, sPipeInfo.szVideoInfo[0].iObjCount
                                                  , sPipeInfo.szVideoInfo[1].iVideoID, sPipeInfo.szVideoInfo[1].iObjCount
                                                  , sPipeInfo.szVideoInfo[2].iVideoID, sPipeInfo.szVideoInfo[2].iObjCount
                                                  , sPipeInfo.szVideoInfo[3].iVideoID, sPipeInfo.szVideoInfo[3].iObjCount
                                                  );

                                continue; //测试用,需删除 吴超

                                //Console.WriteLine("{0},{1}", sPipeInfo.szVideoInfo[0].iVideoID, sPipeInfo.szVideoInfo[0].szObjInfo[0].center_x);
                                //Console.WriteLine("***********{0}************",sPipeInfo.szVideoInfo[0].szObjInfo[0].ID);

                                bool caculateflag = true;
                                //Console.WriteLine("{0} ready to caculate", param.ToString());
                                if (simulation_flag)
                                {
                                    //模拟计算
                                    calculate2();//模拟数据计算
                                }
                                else
                                {
                                    //实际计算
                                    //if (sPipeInfo.szVideoInfo[0].iObjCount != 0)
                                    //{
                                    //    Console.WriteLine("");
                                    //    caculateflag = pcalculate.calculate(sPipeInfo);
                                    //}

                                    //for (int i = 0; i < pcalculate.AllOutputData.Count; i++)
                                    //{
                                    //    resultParam.CamID = pcalculate.AllOutputData[i].CamID;
                                    //    //if (pcalculate.AllOutputData[i].CamID==)

                                    //    resultParam.CPos = pcalculate.AllOutputData[i].UpHumanVolume;
                                    //    resultParam.CNeg = pcalculate.AllOutputData[i].DownHumanVolume;
                                    //    resultParam.CPos_incr = pcalculate.AllOutputData[i].DeltUpHuman;
                                    //    resultParam.CNeg_incr = pcalculate.AllOutputData[i].DeltDownHuman;
                                    //    resultParam.DetectTime = DateTime.Now;
                                    //    resultParam.Speed = pcalculate.AllOutputData[i].AverageSpeed;
                                    //    resultParam.Density = pcalculate.AllOutputData[i].AverageDensity;
                                    //}
                                }

                                if (caculateflag)
                                {
                                    if (simulation_flag)
                                    {
                                        //模拟参数插入数据库
                                        resultParam.CamID     = 123;
                                        resultParam.CPos     += 1;
                                        resultParam.CNeg     += 1;
                                        resultParam.CPos_incr = 1;
                                        resultParam.CNeg_incr = 1;
                                        Random rad = new Random();
                                        double d   = rad.NextDouble();                                  //double本来就是产生0-1之间小数的
                                        resultParam.Density    = Convert.ToDouble(d.ToString("#0.00")); //这里输出是控制输出几位数,0.00表示小数点后两位!
                                        resultParam.Speed      = rad.Next(5, 10);
                                        resultParam.DetectTime = DateTime.Now;
                                    }
                                    mp.insertData(resultParam);
                                }
                                ///////////////////////////插入原始数据////////////////////////
                                for (int i = 0; i < sPipeInfo.szVideoInfo.Length; i++)           //第i个摄像头
                                {
                                    for (int j = 0; j < sPipeInfo.szVideoInfo[i].iObjCount; j++) //第j个轨迹点
                                    {
                                        if (lastCarId == sPipeInfo.szVideoInfo[i].szObjInfo[j].ID)
                                        {
                                            result.center_x = sPipeInfo.szVideoInfo[i].szObjInfo[j].center_x;
                                            result.center_y = sPipeInfo.szVideoInfo[i].szObjInfo[j].center_y;
                                            //listinfo.Add(result);
                                            str += result.center_x.ToString() + "," + result.center_y.ToString() + "|";
                                        }
                                        if (lastCarId != 999 && lastCarId != sPipeInfo.szVideoInfo[i].szObjInfo[j].ID && sPipeInfo.szVideoInfo[i].szObjInfo[j].ID != 0)//不同ID表示轨迹信息为下一辆车的,则开始计算上一辆车的轨迹数据
                                        {
                                            //if (listinfo.Count != 0)
                                            //{
                                            //tracker.Add(listinfo);
                                            //listinfo.Clear();
                                            //flag_2 = 1;
                                            Points point = new Points();
                                            point.points     = str;
                                            point.DetectTime = DateTime.Now;
                                            point.track_id   = lastCarId;
                                            if (str != "")
                                            {
                                                //mp.insertPoint(point);
                                            }

                                            str = "";
                                            tracker.Clear();
                                            //}
                                        }
                                        if (sPipeInfo.szVideoInfo[i].szObjInfo[j].ID != 0)
                                        {
                                            lastCarId = sPipeInfo.szVideoInfo[i].szObjInfo[j].ID;//替换上一个carID
                                        }
                                    }
                                }
                            }
                            else
                            {
                                Console.WriteLine("参数接收失败");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //Log.WriteLog(ex, "");//往TXT写入异常信息
                throw;
            }
        }
示例#2
0
        public void runing(object param)
        {
            //try
            {
                ///初始化
                for (int n = 0; n < 20; n++)
                {
                    CollectData colle = new CollectData();
                    collectData.Add(colle);
                    last_onehr_index_CPos.Add(0);
                    last_onehr_index_CNeg.Add(0);
                    last_onehr_index_Speed.Add(0);
                    last_onehr_index_Speed_up.Add(0);
                    last_onehr_index_Speed_down.Add(0);
                    last_onehr_index_Density.Add(0);

                    last_i64time.Add(0);
                    last_detetime.Add(DateTime.Now.Second * 1000 + DateTime.Now.Millisecond);
                    last_detetime_min.Add(DateTime.Now.Minute);
                }
                int    last_min       = DateTime.Now.Minute;
                bool   calculate_flag = true;
                byte[] writebuffer    = new byte[20480];
                string strPipeName    = "\\\\.\\pipe\\HST_Output_Pip_Gpu_1";
                Console.WriteLine(strPipeName);

                DataRec dr = new DataRec(Convert.ToInt32(param));
                while (true)
                {
                    Thread.Sleep(1000);
                    if (dr.PipeFlag)
                    {
                        while (true)//连接管道
                        {
                            //dr.hPipe = PipeNative.WaitNamedPipe
                            dr.hPipe = PipeNative.CreateFile(
                                strPipeName,                                                      //管道名称
                                FileDesiredAccess.GENERIC_READ | FileDesiredAccess.GENERIC_WRITE, //访问模式,读模式或写模式
                                FileShareMode.Zero,                                               //0表示不共享,共享模式
                                IntPtr.Zero,                                                      //一个只读字段,代表已初始化为零的指针或句柄。指向安全属性的指针
                                FileCreationDisposition.OPEN_EXISTING,                            //如何创建。文件必须已经存在。由设备提出要求
                                0,                                                                //文件属性
                                0);                                                               //用于复制文件句柄,不使用模板
                            if (dr.hPipe.ToInt32() != PipeNative.INVALID_HANDLE_VALUE)
                            {
                                break;                                                     //PipeNative.INVALID_HANDLE_VALUE = -1.管道创建失败
                            }
                            if (PipeNative.GetLastError() != PipeNative.ERROR_PIPE_BUSY || //PipeNative.ERROR_PIPE_BUSY = 231
                                PipeNative.WaitNamedPipe(strPipeName, 5 * 1000))           //在超时时间前管道的一个实例有效则返回非0,在超时时间内没有一个有效的实例,则返回0
                            {
                                Console.WriteLine("无法连接管道:{0} ERROR:{1}", strPipeName, PipeNative.GetLastError());
                                continue;
                            }
                            else
                            {
                                Console.WriteLine("管道连接成功:{0}", strPipeName);
                            }
                        }

                        //start read pipe thread
                        ThreadStart childref    = new ThreadStart(ReadPipeThread);
                        Thread      childThread = new Thread(childref);
                        m_bExitReadPipe = false;
                        m_hPipe         = dr.hPipe;
                        childThread.Start();

                        while (dr.PipeFlag)
                        {
                            #region [接收数据]

                            //通过线程异步读取
                            SHstPipeInfo sPipeInfo = null;
                            int          iRes      = 0;

                            lock (m_oReadPipeLock)
                            {
                                if (m_pipeInfoQueue.Count > 0)
                                {
                                    sPipeInfo = (SHstPipeInfo)m_pipeInfoQueue.Dequeue();
                                }
                            }

                            if (sPipeInfo == null)
                            {
                                Thread.Sleep(10);
                                continue;
                            }

                            ////////////////////////////
                            string mtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff");
                            Log    log   = new Log();
                            string msg   = "ID:" + sPipeInfo.szVideoInfo[0].szObjInfo[0].ID + "读取时间:" + DateTime.Now + "毫秒:" + mtime;
                            //log.WriteLog(msg);
                            ////////////////////////////
                            //continue; //测试用,需删除 吴超

                            if (iRes == 0)
                            {
                                //todo 参数处理
                                //Console.WriteLine("\r ReadPipeInfo videocount: {0} time: {1} \t v0:{2}:{3} \t  v1:{4}:{5} \t  v2:{6}:{7} \t  v3:{8}:{9} \t"
                                //    , sPipeInfo.iVideoCount, sPipeInfo.szVideoInfo[0].i64Time
                                //    , sPipeInfo.szVideoInfo[0].iVideoID, sPipeInfo.szVideoInfo[0].iObjCount
                                //    , sPipeInfo.szVideoInfo[1].iVideoID, sPipeInfo.szVideoInfo[1].iObjCount
                                //    , sPipeInfo.szVideoInfo[2].iVideoID, sPipeInfo.szVideoInfo[2].iObjCount
                                //    , sPipeInfo.szVideoInfo[3].iVideoID, sPipeInfo.szVideoInfo[3].iObjCount
                                //    );

                                //管道收发同步机制
                                for (int l = 0; l < sPipeInfo.iVideoCount; l++)
                                {
                                    int misec           = DateTime.Now.Second * 1000 + DateTime.Now.Millisecond;
                                    int dif_time_stamp  = Convert.ToInt32(sPipeInfo.szVideoInfo[l].i64Time - last_i64time[l]);
                                    int dif_time_detect = misec - last_detetime[l];
                                    if (dif_time_detect - dif_time_stamp > 500)
                                    {
                                        i64time_flag = false;
                                        Console.WriteLine("计算时长超时,处理下一组数据");
                                        Console.WriteLine("时间间隔为:{0}", dif_time_detect - dif_time_stamp);
                                        last_i64time[l]      = sPipeInfo.szVideoInfo[l].i64Time;
                                        last_detetime[l]     = misec;
                                        last_detetime_min[l] = DateTime.Now.Minute;
                                        break;
                                    }
                                    else
                                    {
                                        i64time_flag = true;
                                    }
                                }

                                if (i64time_flag)
                                {
                                    bool caculateflag = true;
                                    if (simulation_flag)
                                    {
                                        //模拟计算
                                        calculate2();//模拟数据计算
                                    }
                                    else
                                    {
                                        //实际计算
                                        caculateflag = pcalculate.calculate(sPipeInfo);
                                    }

                                    if (caculateflag)
                                    {
                                        bool statistical_flage = false;
                                        int  now_min           = DateTime.Now.Minute;
                                        int  now_hour          = DateTime.Now.Hour;
                                        if ((now_min == 0) && (now_min != last_min))
                                        {
                                            statistical_flage = true;
                                        }
                                        else
                                        {
                                            statistical_flage = false;
                                        }
                                        for (int i = 0; i < pcalculate.AllOutputData.Count; i++)
                                        {
                                            resultParam.CamID             = pcalculate.AllOutputData[i].CamID;
                                            resultParam.CPos              = pcalculate.AllOutputData[i].UpHumanVolume;
                                            resultParam.CNeg              = pcalculate.AllOutputData[i].DownHumanVolume;
                                            resultParam.CPos_incr         = pcalculate.AllOutputData[i].DeltUpHuman;
                                            resultParam.CNeg_incr         = pcalculate.AllOutputData[i].DeltDownHuman;
                                            resultParam.DetectTime        = DateTime.Now;
                                            resultParam.Speed             = pcalculate.AllOutputData[i].AverageSpeed;
                                            resultParam.AverageUpSpeed    = pcalculate.AllOutputData[i].AverageUpSpeed;
                                            resultParam.AverageDownSfpeed = pcalculate.AllOutputData[i].AverageDownSfpeed;
                                            resultParam.Density           = pcalculate.AllOutputData[i].AverageDensity;
                                            if (resultParam.CamID != 0)
                                            {
                                                mp.insertData(resultParam);//5s插入数据库
                                            }

                                            //存储历史数据,第i路数据
                                            collectData[i].list_sec_CPos.Add(resultParam.CPos);
                                            collectData[i].list_sec_CNeg.Add(resultParam.CNeg);
                                            collectData[i].list_sec_Speed.Add(resultParam.Speed);
                                            collectData[i].list_sec_Speed_up.Add(resultParam.AverageUpSpeed);
                                            collectData[i].list_sec_Speed_down.Add(resultParam.AverageDownSfpeed);
                                            collectData[i].list_sec_Density.Add(resultParam.Density);

                                            ////////统计一小时数据////////
                                            if (statistical_flage)
                                            {
                                                if ((now_hour == 0) && (now_min == 0))
                                                {
                                                    statistical.oneHorSta(2, resultParam.CamID, collectData[i], last_onehr_index_CPos[i], last_onehr_index_CNeg[i], last_onehr_index_Speed[i], last_onehr_index_Speed_up[i], last_onehr_index_Speed_down[i], last_onehr_index_Density[i]);
                                                }
                                                else
                                                {
                                                    statistical.oneHorSta(1, resultParam.CamID, collectData[i], last_onehr_index_CPos[i], last_onehr_index_CNeg[i], last_onehr_index_Speed[i], last_onehr_index_Speed_up[i], last_onehr_index_Speed_down[i], last_onehr_index_Density[i]);
                                                }
                                                last_onehr_index_CPos[i]       = collectData[i].list_sec_CPos.Count;
                                                last_onehr_index_CNeg[i]       = collectData[i].list_sec_CNeg.Count;
                                                last_onehr_index_Speed[i]      = collectData[i].list_sec_Speed.Count;
                                                last_onehr_index_Speed_up[i]   = collectData[i].list_sec_Speed_up.Count;
                                                last_onehr_index_Speed_down[i] = collectData[i].list_sec_Speed_down.Count;
                                                last_onehr_index_Density[i]    = collectData[i].list_sec_Density.Count;

                                                collectData[i].list_sec_CPos.Clear();
                                                collectData[i].list_sec_CNeg.Clear();
                                                collectData[i].list_sec_Speed.Clear();
                                                collectData[i].list_sec_Speed_up.Clear();
                                                collectData[i].list_sec_Speed_down.Clear();
                                                collectData[i].list_sec_Density.Clear();
                                                last_onehr_index_CPos[i]       = 0;
                                                last_onehr_index_CNeg[i]       = 0;
                                                last_onehr_index_Speed[i]      = 0;
                                                last_onehr_index_Speed_up[i]   = 0;
                                                last_onehr_index_Speed_down[i] = 0;
                                                last_onehr_index_Density[i]    = 0;
                                            }
                                            ////////统计一天数据////////
                                            if ((now_hour == 23) && (now_min == 50) && (now_min != last_min))
                                            {
                                                CollectData cData = new CollectData();//不存储23-00数据
                                                mp.loadHorData(cData, resultParam.CamID);
                                                string table = "pflow_tb_data_day";
                                                statistical.Sta(resultParam.CamID, cData, table);

                                                //数据库表的状态检测
                                                CreatTable dt_man = new CreatTable();
                                                dt_man.creat_table();


                                                if (DateTime.Now.DayOfWeek == DayOfWeek.Sunday)//周日汇总本周的数据
                                                {
                                                    CollectData cseveData = new CollectData();
                                                    mp.load7DayData(cseveData, resultParam.CamID);
                                                    table = "pflow_tb_data_week";
                                                    statistical.Sta(resultParam.CamID, cseveData, table);
                                                }
                                                if (DateTime.Now.AddDays(1).Day == 1)//每月一号汇总前一个月的数据
                                                {
                                                    CollectData cseveData = new CollectData();
                                                    mp.load1MonthData(cseveData, resultParam.CamID);//会查询到后于当前时间的数据
                                                    table = "pflow_tb_data_month";
                                                    statistical.Sta(resultParam.CamID, cseveData, table);
                                                }
                                                if ((DateTime.Now.Month == 12) && (DateTime.Now.AddDays(1).Day == 1))//每年12月最后一天汇总当年的数据
                                                {
                                                    CollectData cseveData = new CollectData();
                                                    mp.load1YearData(cseveData, resultParam.CamID);
                                                    table = "pflow_tb_data_year";
                                                    statistical.Sta(resultParam.CamID, cseveData, table);
                                                }
                                            }
                                            last_min = DateTime.Now.Minute;//reset last time
                                        }

                                        if (simulation_flag)
                                        {
                                            //模拟参数插入数据库
                                            //resultParam.CamID = 123;
                                            //resultParam.CPos += 1;
                                            //resultParam.CNeg += 1;
                                            //resultParam.CPos_incr = 1;
                                            //resultParam.CNeg_incr = 1;
                                            //Random rad = new Random();
                                            //double d = rad.NextDouble();//double本来就是产生0-1之间小数的
                                            //resultParam.Density = Convert.ToDouble(d.ToString("#0.00"));//这里输出是控制输出几位数,0.00表示小数点后两位!
                                            //resultParam.Speed = rad.Next(5, 10);
                                            //resultParam.DetectTime = DateTime.Now;
                                            //mp.insertData(resultParam);//5s插入数据库
                                        }
                                    }
                                    /////////////////////////////插入原始数据////////////////////////
                                    for (int i = 0; i < sPipeInfo.szVideoInfo.Length; i++)           //第i个摄像头
                                    {
                                        for (int j = 0; j < sPipeInfo.szVideoInfo[i].iObjCount; j++) //第j个轨迹点
                                        {
                                            if (lastCarId == sPipeInfo.szVideoInfo[i].szObjInfo[j].ID)
                                            {
                                                result.center_x = sPipeInfo.szVideoInfo[i].szObjInfo[j].center_x;
                                                result.center_y = sPipeInfo.szVideoInfo[i].szObjInfo[j].center_y;
                                                //listinfo.Add(result);
                                                str += result.center_x.ToString() + "," + result.center_y.ToString() + "|";
                                            }
                                            if (lastCarId != 999 && lastCarId != sPipeInfo.szVideoInfo[i].szObjInfo[j].ID && sPipeInfo.szVideoInfo[i].szObjInfo[j].ID != 0)//不同ID表示轨迹信息为下一辆车的,则开始计算上一辆车的轨迹数据
                                            {
                                                //if (listinfo.Count != 0)
                                                //{
                                                //tracker.Add(listinfo);
                                                //listinfo.Clear();
                                                //flag_2 = 1;
                                                Points point = new Points();
                                                point.CamID      = sPipeInfo.szVideoInfo[i].iVideoID;
                                                point.points     = str;
                                                point.DetectTime = DateTime.Now;
                                                point.track_id   = lastCarId;
                                                if (str != "")    //
                                                {
                                                    //mp.insertPoint(point);
                                                }

                                                str = "";
                                                tracker.Clear();
                                                //}
                                            }
                                            if (sPipeInfo.szVideoInfo[i].szObjInfo[j].ID != 0)
                                            {
                                                lastCarId = sPipeInfo.szVideoInfo[i].szObjInfo[j].ID;//替换上一个carID
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                Console.WriteLine("参数接收失败");
                            }

                            sPipeInfo = null;
                        }

                        //stop read pipe thread
                        m_bExitReadPipe = true;
                    }
                }
            }
            //catch (Exception ex)
            //{
            //    //Log.WriteLog(ex, "");//往TXT写入异常信息
            //    throw;
            //}
        }
    static void PInvokeNativePipeClient()
    {
        /////////////////////////////////////////////////////////////////////
        // Try to open a named pipe.
        //

        // Prepare the pipe name
        String strPipeName = String.Format(@"\\{0}\pipe\{1}",
                                           ".",         // Server name
                                           "HelloWorld" // Pipe name
                                           );

        IntPtr hPipe;

        while (true)
        {
            hPipe = PipeNative.CreateFile(
                strPipeName,                     // Pipe name
                FileDesiredAccess.GENERIC_READ | // Read and write access
                FileDesiredAccess.GENERIC_WRITE,

                FileShareMode.Zero,                    // No sharing
                IntPtr.Zero,                           // Default security attributes
                FileCreationDisposition.OPEN_EXISTING, // Opens existing pipe
                0,                                     // Default attributes
                0);                                    // No template file

            // Break if the pipe handle is valid.
            if (hPipe.ToInt32() != PipeNative.INVALID_HANDLE_VALUE)
            {
                break;
            }

            if (// Exit if an error other than ERROR_PIPE_BUSY occurs
                PipeNative.GetLastError() != PipeNative.ERROR_PIPE_BUSY
                ||
                // All pipe instances are busy, so wait for five seconds
                !PipeNative.WaitNamedPipe(strPipeName, 5000))
            {
                Console.WriteLine("Unable to open named pipe {0} w/err 0x{1:X}",
                                  strPipeName, PipeNative.GetLastError());
                return;
            }
        }
        Console.WriteLine("The named pipe, {0}, is connected.", strPipeName);


        /////////////////////////////////////////////////////////////////////
        // The pipe connected; change to message-read mode.
        //

        PipeMode mode    = PipeMode.PIPE_READMODE_MESSAGE;
        bool     bResult = PipeNative.SetNamedPipeHandleState(
            hPipe, ref mode, IntPtr.Zero, IntPtr.Zero);

        if (!bResult)
        {
            Console.WriteLine("SetNamedPipeHandleState failed w/err 0x{0:X}",
                              PipeNative.GetLastError());
            return;
        }


        /////////////////////////////////////////////////////////////////////
        // Send a message to the pipe server and receive its response.
        //

        // A byte buffer of BUFFER_SIZE bytes. The buffer should be big
        // enough for ONE request to the server.

        string strMessage;

        byte[] bRequest;                        // Client -> Server
        uint   cbBytesWritten, cbRequestBytes;

        byte[] bReply = new byte[BUFFER_SIZE];  // Server -> Client
        uint   cbBytesRead, cbReplyBytes;

        // Send one message to the pipe.

        // '\0' is appended in the end because the client may be a native
        // C++ program.
        strMessage     = "Default request from client\0";
        bRequest       = Encoding.Unicode.GetBytes(strMessage);
        cbRequestBytes = (uint)bRequest.Length;

        bResult = PipeNative.WriteFile(         // Write to the pipe.
            hPipe,                              // Handle of the pipe
            bRequest,                           // Message to be written
            cbRequestBytes,                     // Number of bytes to write
            out cbBytesWritten,                 // Number of bytes written
            IntPtr.Zero);                       // Not overlapped

        if (!bResult /*Failed*/ || cbRequestBytes != cbBytesWritten /*Failed*/)
        {
            Console.WriteLine("WriteFile failed w/err 0x{0:X}",
                              PipeNative.GetLastError());
            return;
        }

        Console.WriteLine("Sends {0} bytes; Message: \"{1}\"",
                          cbBytesWritten, strMessage.TrimEnd('\0'));

        // Receive the response from the server.

        cbReplyBytes = BUFFER_SIZE;
        do
        {
            bResult = PipeNative.ReadFile(      // Read from the pipe.
                hPipe,                          // Handle of the pipe
                bReply,                         // Buffer to receive the reply
                cbReplyBytes,                   // Size of buffer
                out cbBytesRead,                // Number of bytes read
                IntPtr.Zero);                   // Not overlapped

            if (!bResult &&
                PipeNative.GetLastError() != PipeNative.ERROR_MORE_DATA)
            {
                Console.WriteLine("ReadFile failed w/err 0x{0:X}",
                                  PipeNative.GetLastError());
                break;
            }

            strMessage = Encoding.Unicode.GetString(bReply).TrimEnd('\0');
            Console.WriteLine("Receives {0} bytes; Message: \"{1}\"",
                              cbBytesRead, strMessage);
        } while (!bResult);  // Repeat loop if ERROR_MORE_DATA


        /////////////////////////////////////////////////////////////////////
        // Close the pipe.
        //

        PipeNative.CloseHandle(hPipe);
    }