/*if the camera is OpenIdle, it will put it in AquidleMode. Finished*/
        public override int StartAquisition()
        {
            int toreturn;

            if (nowState == State.OpenIdle)
            {
                try
                {
                    Camera.StartAcquisition();
                    nowState = State.AquiIdle;
                    toreturn = 1;
                }
                catch (Exception exception)
                {
                    toreturn = -1;
                    Logging.Add("Exception occured when starting aquisition in camera with serial " + SerialNumber +
                                " in CameraXimea, exception is: " + exception.Message);
                }
            }
            else if (nowState == State.AquiIdle)
            {
                toreturn = 1;
                Logging.Add("Tried to start aquisition for camera with serial number " + SerialNumber + "but the state is already AquiIdle, continuing");
            }
            else
            {
                Logging.Add("Starting aquisition failed for camera with serial number " + SerialNumber + "State should be OpenIdle, but it is " + nowState);
                toreturn = 0;
            }
            return(toreturn);
        }
        /*if the camera is AquiIdle, it will put it in OpenleMode. Finished*/
        public override int StopAquisition()
        {
            int toreturn;

            if (nowState == State.AquiIdle)
            {
                try
                {
                    Camera.StopAcquisition();
                    nowState = State.OpenIdle;
                    toreturn = 1;
                }
                catch (Exception exception)
                {
                    Logging.Add("Exception occured when trying to stop aquisition in Ximea camera with serial number " + SerialNumber + "Exception is " + exception.Message);
                    toreturn = -1;
                }
            }
            else
            {
                toreturn = 0;
                Logging.Add("Failed to Stop aquisition, camera should be in a state AquiIdle, but it is" + nowState);
            }
            return(toreturn);
        }
        /*If the camera is closed, opens a camera using an index. Finished*/
        public override int Open(int i)
        {
            int toreturn;

            if (nowState == State.Closed)
            {
                try
                {
                    Camera.OpenDevice(i);
                    nowState = State.OpenIdle;
                    Initialise();
                    toreturn = 1;
                }
                catch (Exception exception)
                {
                    Logging.Add("Exception occured in opening camera with index " + i +
                                " in CameraXimea, exception is: " + exception.Message);
                    toreturn = -1;
                }
            }
            else
            {
                Logging.Add("Failed to open Ximea camera number" + i + "camera device should be clsoed but is in state" + nowState);
                toreturn = 0;
            }

            return(toreturn);
        }
        /*returns 0 if the camera is in the wrong state, -1 for exceptionand +1 for success */
        public override int DirectlyUpdateSettings(int exposureUs, float gainDb = 0)
        {
            int toreturn = 0;

            if (nowState == State.OpenIdle)
            {
                try
                { ////EDIT THIS NEEDS to BE CHANGED TO AFFECT BOTH GAIN AND EXPOSURE!!!!!!!
                    //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                    Camera.SetParam(PRM.EXPOSURE_DIRECT_UPDATE, (int)(exposureUs * expCorrection + 0.5));
                    _exposure = exposureUs;
                    Camera.SetParam(PRM.GAIN_DIRECT_UPDATE, gainDb);
                    _gain = gainDb;
                }
                catch (Exception exception)
                {
                    toreturn = -1;
                    Logging.Add("Expection in CameraXimea when trying to update settings :" + exception.Message);
                }
            }
            else
            {
                toreturn = 0;
            }

            return(toreturn);
        }
        protected override int Close()
        {
            int toreturn = 0;

            if (nowState != State.Closed)
            {
                try
                {
                    Camera.CloseDevice();
                }
                catch (Exception exception)
                {
                    Logging.Add(exception.Message + "in" + nowCameraType.ToString() + "when trying to close device");
                    toreturn = -1;
                }
                finally
                {
                    nowState = State.Closed;
                }
            }
            else
            {
                Logging.Add("Closing camera failed, Ximea camera with serial number" + SerialNumber + "is already closed");
                toreturn = 0;
            }

            return(toreturn);
        }
        /*returns 0 if the camera is in the wrong state, -1 for exceptionand +1 for success */
        public override int UpdateSettings(int exposureUs, float gainDb = 0, float gammaY = 1, float gammaC = 1)
        {
            int toreturn = 0;

            if (nowState == State.OpenIdle)
            {
                try
                {////EDIT THIS NEEDS to BE CHANGED TO AFFECT BOTH GAIN AND EXPOSURE!!!!!!!
                    //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                    _exposure = (int)(exposureUs * expCorrection + 0.5);
                    Camera.SetParam(PRM.EXPOSURE, _exposure);

                    Camera.SetParam(PRM.GAIN, gainDb);
                    _gain = gainDb;

                    Camera.SetParam(PRM.GAMMAY, gammaY);
                    _gammaY = gammaY;
                    Camera.SetParam(PRM.GAMMAC, gammaC);
                    _gammaC  = gammaC;
                    toreturn = 1;
                    nowState = State.OpenIdle;
                }
                catch (Exception exception)
                {
                    toreturn = -1;
                    Logging.Add("Expection in CameraXimea when trying to update settings :" + exception.Message);
                }
            }
            else
            {
                toreturn = 0;
            }

            return(toreturn);
        }
Exemplo n.º 7
0
        /* IN USE  - packaging*/
        public byte[] GetResourceContents(ItemIdentifier itemId, Type itemType, Resource resource, string revisionAlias)
        {
            if (revisionAlias != null)
            {
                //check if the resource has already been packaged before
                resource.ResourceContents =
                    resource.ToByteArray(Core.Settings.revisionsPath + "/" + revisionAlias + "/" +
                                         Core.Settings.ResourcesFolderName);
                if (resource.ResourceContents != null)
                {
                    return(resource.ResourceContents);
                }
            }

            ItemProvider provider = null;

            if (!string.IsNullOrEmpty(resource.ExtractToPath) && itemType != null)
            {
                provider = Umbraco.Courier.Core.ProviderModel.ItemProviderCollection.Instance.GetProvider(itemId.ProviderId);
                provider.ExecutionContext = establishPackagingContext(ContextManager.Instance.Get(SessionKey));
                ResolutionManager.Instance.PackagingResource(itemId, itemType, resource, provider);
            }

            resource.ResourceContents = resource.ToByteArray("~/");
            Logging.Add("nulls", (resource.ResourceContents == null).ToString() + " < " + resource.ExtractToPath);

            //if (!string.IsNullOrEmpty(resource.ExtractToPath) && itemType != null)
            //    ResolutionManager.Instance.PackagedResource(itemId, itemType, resource, provider);

            Logging.Add("nulls", (resource.ResourceContents == null).ToString() + " > " + resource.ExtractToPath);

            return(resource.ResourceContents);
        }
Exemplo n.º 8
0
        /*returns a 2D arra., in thue format array [y][x], if the parameters are wrong it returns arrays full of zeros */
        public static ushort[][] ByteToUshort2D(byte [] data, int width, int height)
        {
            ushort[][] scaledImage = new ushort[height][];

            //allocate space for data in the 2D array
            for (int i = 0; i < height; i++)
            {
                scaledImage[i] = new ushort[width];
            }


            if (data.Length == (height * width * 2))
            {
                for (int i = 0; i < data.Length / 2; i++)
                {
                    int lowernumber  = data[2 * i];
                    int highernumber = data[((2 * i) + 1)];
                    scaledImage[i / width][i % width] = (ushort)(((lowernumber + highernumber * 256) * Image10To16bit_scaler));
                }
            }
            else
            {
                Logging.Add("Can't perform ByteToUshort2D, dimentions are wrong, image is" + width + ":" + height + "but the data is of length" + data.Length);
            }

            return(scaledImage);
        }
        /*if the camera is closed, opens a camera using a serial number. Finished*/
        public override int Open(string serial)
        {
            int toreturn;

            if (nowState == State.Closed)
            {
                try
                {
                    Camera.OpenDevice(xiCam.OpenDevBy.SerialNumber, serial);
                    nowState = State.OpenIdle;
                    Initialise();
                    toreturn = 1;
                }
                catch (Exception exception)
                {
                    Logging.Add("Exception occured in opening camera with serial " + serial +
                                " in CameraXimea, exception is: " + exception.Message);
                    toreturn = -1;
                }
            }
            else
            {
                toreturn = 0;
                Logging.Add("Failed to open camera by serial" + serial + "Camera should be closed, but is in state" + nowState);
            }

            return(toreturn);
        }
Exemplo n.º 10
0
        private static void Main(string[] args)
        {
            Logging.Add(CalculatorLog, typeof(Calculator));

            new Sample().Run();
            Logging.Complete();

            Console.WriteLine("[Enter] to exit");
            Console.ReadLine();
        }
Exemplo n.º 11
0
        public static ushort[][] BitmapToUShort2DArray(Bitmap image, int truebitPerPixel, float correction)
        {
            UInt16[][] destination = null;
            if (image == null)
            {
                Logging.Add("BitmapToUShortArray Bitmap is null");
            }
            else if ((truebitPerPixel <= 16) && (truebitPerPixel >= 8))
            {
                destination = new UInt16[image.Height][];
                for (int i = 0; i < destination.Length; i++)
                {
                    destination[i] = new ushort[image.Width];
                }

                ushort shift = (ushort)(16 - truebitPerPixel);
                // Lock the bitmap's bits.
                Rectangle  rect    = new Rectangle(0, 0, image.Width, image.Height);
                BitmapData bmpData = image.LockBits(rect, ImageLockMode.ReadWrite, image.PixelFormat);

                // Get the address of the first line.
                IntPtr ptr = bmpData.Scan0;

                // Declare an array to hold the bytes of the bitmap. The returned value is in bytes, and we are storing ushort, so we need to divide by 2
                int length = (Math.Abs(bmpData.Stride) * image.Height) / 2;

                if (image.PixelFormat == PixelFormat.Format16bppGrayScale)
                {
                    unsafe
                    {
                        var sourcePtr = (ushort *)ptr;
                        for (int i = 0; i < destination.Length; i++)
                        {
                            for (int n = 0; n < destination[i].Length; n++)
                            {
                                destination[i][n] = (ushort)((*sourcePtr << shift) * correction);
                                sourcePtr++;
                            }
                        }
                    }
                }
                else
                {
                    Logging.Add("BitmapToUShortArray failed because Pixelformat should be 16bpp grayscale, but it is " +
                                image.PixelFormat);
                }
            }
            else
            {
                Logging.Add("BitmapToUShortArray failed because truebitPerPixel value is " + truebitPerPixel + " but it should be between 8 and 16");
            }

            return(destination);
        }
Exemplo n.º 12
0
        protected override int Initialise()
        {
            int toreturn;

            if (nowState != State.OpenIdle)
            {
                Logging.Add("Can't initialise the camera with SN " + SerialNumber + "because the state should be OpenIdle and it is " + nowState);
                toreturn = 0;
            }
            else
            {
                nowState = State.OpenUpdating;
                try
                {
                    /*get static camera parameters */
                    Camera.GetParam(PRM.DEVICE_SN, out SerialNumber);

                    //Resolution
                    // image width must be divisible by 4
                    Camera.GetParam(PRM.WIDTH, out _width);
                    _width = _width - (_width % 4);
                    Camera.SetParam(PRM.WIDTH, _width);
                    Camera.GetParam(PRM.HEIGHT, out _height);
                    _height = _height - (_height % 4);
                    Camera.SetParam(PRM.HEIGHT, _height);

                    Camera.SetParam(PRM.IMAGE_DATA_FORMAT, IMG_FORMAT.RAW16);
                    Camera.SetParam(PRM.OUTPUT_DATA_BIT_DEPTH, _bitdepth);

                    //control
                    Camera.SetParam(PRM.BUFFER_POLICY, BUFF_POLICY.UNSAFE);
                    Camera.SetParam(PRM.TRG_SOURCE, TRG_SOURCE.SOFTWARE);
                    nowTrigger = Trigger.Software;
                    toreturn   = 1;


                    nowState = State.OpenIdle;
                }
                catch (Exception exception)
                {
                    toreturn = -1;
                    Logging.Add("Updating camera settings failed: " + exception.Message);
                }
            }
            return(0);
        }
Exemplo n.º 13
0
        public static CameraXimea[] InitAllXimeaCameras()
        {
            int NofXimeaCameras = getNOfXimeaCameras();

            CameraXimea[] allCameras = new CameraXimea[NofXimeaCameras];
            try
            {
                for (int i = 0; i < NofXimeaCameras; i++)
                {
                    allCameras[i] = new CameraXimea(i);
                }
            }
            catch (Exception exception)
            {
                Logging.Add(exception.ToString() + exception.Message);
            }
            return(allCameras);
        }
Exemplo n.º 14
0
        /*Returns null if taking the image fails*/
        protected override Bitmap TakeImage()
        {
            Bitmap tempImage = null;

            if (nowState != State.AquiIdle)
            {
                Logging.Add("Taking Image failed on camera with SN" + SerialNumber + "Mode should be AquiIdle, but is " + nowState);
            }
            else
            {
                int timeout = _exposure * 2 + 200;

                try
                {
                    nowState = State.AquiExposure;
                    Camera.SetParam(PRM.TRG_SOFTWARE, 1);
                    nowState = State.AquiReading;
                    Camera.GetImage(out tempImage, timeout);
                    nowState = State.AquiIdle;
                }
                catch (Exception exception)
                {
                    nowState = State.AquiIdle;

                    if (exception.Message.Equals("Error 1", StringComparison.OrdinalIgnoreCase))
                    {
                        Logging.Add("Camera SN " + SerialNumber + "Handle became invalid. Did you unplug it?");
                        nowState = State.Closed;
                        Dispose();
                    }
                    else if (exception.Message.Contains("Error 10"))
                    {
                        Logging.Add("Camera SN " + SerialNumber + "Experienced timeout and failed to aquire a frame");
                    }
                    else
                    {
                        Logging.Add("Exception occured when trying to image, camera SN " + SerialNumber +
                                    "Exception message " + exception.Message);
                    }
                }
            }

            return(tempImage);
        }
Exemplo n.º 15
0
 private static void SendNetworkUpdate()
 {
     lock (_network)
     {
         lock (Logic.Status)
         {
             if (Logic.Status != null)
             {
                 foreach (Servlet connection in _network)
                 {
                     connection.SendData(Logic.Status);
                 }
                 Logic.Status.LogChanges = "";   //clears the log-changes, as the changes were submitted to clients
             }
             else
             {
                 Logging.Add("Tried To send an empty frame!");
             }
         }
     }
 }
Exemplo n.º 16
0
Arquivo: IO.cs Projeto: jayvin/Courier
        public static void SaveFile(string path, byte[] contents, bool overwrite = true)
        {
            if (contents == null)
            {
                Logging.Add("nulls", path + " is null");
            }

            string file   = "";
            string folder = "";

            try
            {
                file = Core.Context.Current.MapPath(path);
                CreateFolder(new FileInfo(file).Directory.FullName.TrimEnd('\\'));

                System.IO.File.WriteAllBytes(path, contents);
            }
            catch (Exception ex)
            {
                Logging._Error("Tried saving " + path + " to: " + Environment.NewLine + file + Environment.NewLine + "Folder: " + folder + Environment.NewLine + ex.ToString());
            }
        }
Exemplo n.º 17
0
        private static async void StartHostedNetwork()
        {
            Logging.Add("Attempting to start hosted network");
            bool success = false;

            String netshOutput;

            pHostedNet.StartInfo.FileName               = "netsh.exe";
            pHostedNet.StartInfo.Arguments              = "wlan start hostednetwork";
            pHostedNet.StartInfo.UseShellExecute        = false;
            pHostedNet.StartInfo.RedirectStandardOutput = true;
            pHostedNet.StartInfo.WindowStyle            = System.Diagnostics.ProcessWindowStyle.Hidden;

            while (!success)
            {
                pHostedNet.Start();
                StandardOutput = pHostedNet.StandardOutput;
                netshOutput    = await StandardOutput.ReadLineAsync();

                if (netshOutput.Contains(hNetworkSuccess))
                {
                    //good
                    success = true;
                    Logging.Add("Hosted Network Started");
                    break;
                }

                else
                {//something happened, wait and do it again
                    hostNetworkStartAttempts++;
                    Logging.Add("Tried to start HostedNetwork, failed and got " + netshOutput);
                    await Task.Delay(1000);
                }
            }

            updateConnections();
        }
Exemplo n.º 18
0
        private static void updateConnections()
        {
            lock (_network)
            {
                //Start and/or update network IP list

                List <IPAddress> newIpAdresses     = new List <IPAddress>(); //for storing IP adresses that the programm did not yet start listening on
                List <IPAddress> presentIpAdresses = new List <IPAddress>(); //for storing all IP addresses of the right type


                foreach (NetworkInterface netInterface in NetworkInterface.GetAllNetworkInterfaces())
                {
                    if (netInterface.Description.Contains("Microsoft Hosted Network Virtual Adapter"))              //find the HostedNet adapter
                    {
                        if (netInterface.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Down) // if it's down'
                        {
                            HostedNetUp = false;
                            StartHostedNetwork();  ///start it
                        }
                        else
                        {
                            HostedNetUp = true;
                        }
                    }
                    if (netInterface.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up) //check if the interface is up
                    {
                        IPInterfaceProperties ipProps = netInterface.GetIPProperties();

                        foreach (UnicastIPAddressInformation addr in ipProps.UnicastAddresses)
                        {
                            if (addr.Address.AddressFamily == AddressFamily.InterNetwork) //checks if the adress is an IPv4 one
                            {
                                presentIpAdresses.Add(addr.Address);

                                if (_network.Length > 0)
                                {
                                    if (Array.Exists(_network, p => p.LocalIp.Equals(addr.Address)))
                                    {
                                        //IP address is already on the list
                                    }
                                    else
                                    {
                                        newIpAdresses.Add(addr.Address); //add it to the list, it's not there
                                    }
                                }
                                else
                                {
                                    newIpAdresses.Add(addr.Address);
                                    //networking is not initialised, put everything on the list
                                }
                            }
                        }
                    }
                }


                List <Servlet> newlist = new List <Servlet>();

                int    removedAddresses = 0;
                String listofIpAdresses = ""; //string that stores every IP address that hte programm is working with

                foreach (var connection in _network)
                {
                    if (presentIpAdresses.Exists(p => p.Equals(connection.LocalIp))) //check if the connection still exists
                    {
                        newlist.Add(connection);
                        //this is a bad way to retry connections, but I have no better ideas at het moment!
                        if (!connection.IsActive())  //try resetting the connection a bit!
                        {
                            Logging.Add("Resetting connection " + connection.LocalIp);
                            connection.Reset();
                        }

                        listofIpAdresses += connection.LocalIp.ToString() + ", ";
                    }
                    else
                    {
                        removedAddresses++;
                        connection.Dispose(); //if it is not, dispose of it
                    }
                }

                if (newIpAdresses.Count > 0 || removedAddresses > 0)
                {
                    foreach (var connection in newIpAdresses)
                    {
                        var newconnection = new Servlet(connection);
                        newconnection.Readnetwork();
                        newlist.Add(newconnection);
                        listofIpAdresses += connection.ToString() + ", ";
                    }


                    Logging.Add("IP addresses changed: the connections are " + listofIpAdresses);

                    _network = newlist.ToArray <Servlet>();
                }
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// 添加任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            //判断是否是“粘贴并添加”
            if (txtInput.Text.Trim() == "" && Clipboard.ContainsText())             //如果文本框为空则为“粘贴并添加”
            {
                txtInput.Text = Clipboard.GetText();
            }


            string url = txtInput.Text;

            this.Cursor = Cursors.WaitCursor;

            IPlugin selectedPlugin = null;

            //如果有可用插件
            if (supportedPlugins.Count > 0)
            {
                selectedPlugin = supportedPlugins[cboPlugins.SelectedIndex];

                //取得此url的hash
                string hash = selectedPlugin.GetHash(url);
                //检查是否有已经在进行的相同任务
                foreach (TaskInfo task in _taskMgr.TaskInfos)
                {
                    if (hash == task.Hash)
                    {
                        toolTip.Show("当前任务已经存在", txtInput, 4000);
                        this.Cursor = Cursors.Default;
                        return;
                    }
                }
                try
                {
                    //取得[代理设置]
                    AcDownProxy selectedProxy = null;
                    if (Config.setting.Proxy_Settings != null)
                    {
                        foreach (AcDownProxy item in Config.setting.Proxy_Settings)
                        {
                            if (item.Name == cboProxy.SelectedItem.ToString())
                            {
                                selectedProxy = item;
                            }
                        }
                    }

                    //取得[AutoAnswer设置]
                    List <AutoAnswer> aa = new List <AutoAnswer>();
                    if (chkAutoAnswer.Checked)
                    {
                        if (selectedPlugin.Feature.ContainsKey("AutoAnswer"))
                        {
                            aa = (List <AutoAnswer>)selectedPlugin.Feature["AutoAnswer"];
                            if (aa.Count > 0)
                            {
                                FormAutoAnswer faa = new FormAutoAnswer(aa);
                                faa.TopMost = this.TopMost;
                                var result = faa.ShowDialog();
                                if (result == System.Windows.Forms.DialogResult.Cancel)
                                {
                                    this.Cursor = Cursors.Default;
                                    return;
                                }
                            }
                        }
                    }

                    //添加任务
                    TaskInfo task = _taskMgr.AddTask(selectedPlugin,
                                                     url,
                                                     (selectedProxy == null) ? null : selectedProxy.ToWebProxy());
                    //设置[保存目录]
                    task.SaveDirectory = new DirectoryInfo(txtPath.Text);
                    //设置[字幕]
                    DownloadSubtitleType ds = DownloadSubtitleType.DownloadSubtitle;
                    if (cboDownSub.SelectedIndex == 1)
                    {
                        ds = DownloadSubtitleType.DontDownloadSubtitle;
                    }
                    if (cboDownSub.SelectedIndex == 2)
                    {
                        ds = DownloadSubtitleType.DownloadSubtitleOnly;
                    }
                    task.DownSub = ds;
                    //设置[提取浏览器缓存]
                    task.ExtractCache = chkExtractCache.Checked;
                    //设置[解析关联视频]
                    task.ParseRelated = chkParseRelated.Checked;
                    //设置[自动应答]
                    task.AutoAnswer = aa;
                    //设置注释
                    task.Comment = txtComment.Text;


                    //开始下载
                    _taskMgr.StartTask(task);


                    this.Cursor = Cursors.Default;
                    this.Close();
                }
                catch (Exception ex)
                {
                    Logging.Add(ex);
                    toolTip.Show("新建任务出现错误:\n" + ex.Message, btnAdd, 4000);
                }
            }
            else
            {
                toolTip.Show("您所输入的网络地址(URL)不符合规则。\n没有支持解析此网址的插件,请您检查后重新输入", txtInput, 3000);
                txtInput.SelectAll();
            }
            this.Cursor = Cursors.Default;
        }
Exemplo n.º 20
0
        static void Main(string[] args)
        {
            int choice = 0;

            do
            {
                var table = new List <HRD>();
                Console.WriteLine("\n Выберите пункт");
                Console.WriteLine("1 - Просмотр таблицы");
                Console.WriteLine("2 - Добавить запись");
                Console.WriteLine("3 - Удалить запись");
                Console.WriteLine("4 - Обновить запись");
                Console.WriteLine("5 - Поиск записей");
                Console.WriteLine("6 - Просмотреть лог");
                Console.WriteLine("7 - Записать в файл");
                Console.WriteLine("8 - Сортировка");
                Console.WriteLine("9 - Выход");
                choice = int.Parse(Console.ReadLine());
                string path = @"D:\lab.dat";
                switch (choice)
                {
                case WATCH_TABLE:

                    for (int list_item = 0; list_item < list.Count; list_item++)
                    {
                        HRD t = list[list_item];
                        Console.WriteLine("----------------------------------------------------------------------------");
                        t.ShowTable(t.Name, t.Postion, t.Yers, t.Salary);
                    }
                    StreamReader fstream = new StreamReader(path);
                    string       line;
                    while (!fstream.EndOfStream)
                    {
                        line = fstream.ReadLine();
                        Console.Write(line);
                    }
                    fstream.Close();
                    Logging.Add(DateTime.Now, Operations.LOOK, "Просмотрена таблица");
                    break;

                case ADD_RAW:
                    HRD t1;
                    Console.WriteLine("Введите Фамилию");
                    t1.Name = Console.ReadLine();
                    Console.WriteLine("ВведитеДолжность");
                    t1.Postion = Console.ReadLine();

Found1:
                    Console.WriteLine("Введите год рождения");
                    try
                    {
                        int blabla = Convert.ToInt32(Console.ReadLine());     //вводим данные, и конвертируем в целое число
                        t1.Yers = blabla;
                        if ((blabla < 1895) || (blabla > 2030))
                        {
                            Console.WriteLine("Error. (Введите повторно)");
                            goto Found1;
                        }
                    }
                    catch (FormatException)
                    {
                        t1.Yers = 000;
                        Console.WriteLine("Error. (Введите повторно)");
                        goto Found1;
                    }
                    Pos pro;
Found3:
                    Console.WriteLine("Введите оклад");
                    try
                    {
                        string blabla3 = Console.ReadLine();
                        t1.Salary = blabla3;
                        pro       = (Pos)Enum.Parse(typeof(Pos), blabla3);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error. (Введите повторно)");
                        pro = Pos.None;
                        goto Found3;
                    }

                    list.Add(t1);
                    Console.WriteLine("Строка была добавлена!");
                    Console.WriteLine();
                    Logging.Add(DateTime.Now, Operations.ADD, "Строка добавлена в таблицу!");
                    break;

                case REMOVE_RAW:
                    string       linel = String.Empty;
                    string       delet = Console.ReadLine();
                    StreamReader sr    = new StreamReader(path);
                    while (sr.Peek() >= 0)
                    {
                        String temp = sr.ReadLine();
                        if (temp.IndexOf(delet) != -1)
                        {
                        }
                        else
                        {
                            linel += temp;
                        }
                    }
                    sr.Close();
                    StreamWriter sw = new StreamWriter(path);
                    sw.Write(linel);
                    sw.Close();
                    Logging.Add(DateTime.Now, Operations.ADD, "строка удалена!");
                    break;

                case UPDATE_RAW:
                    StreamReader readf    = new StreamReader(path);
                    string       surname  = readf.ReadLine();
                    string       pos      = readf.ReadLine();
                    var          position = Pos.None;
                    if (pos == "П")
                    {
                        position = Pos.П;
                    }
                    else if (pos == "С")
                    {
                        position = Pos.С;
                    }
                    else if (pos == "А")
                    {
                        position = Pos.А;
                    }
                    int    year   = int.Parse(readf.ReadLine());
                    string salary = readf.ReadLine();
                    HRD    newWorker;
                    newWorker.Name    = surname;
                    newWorker.Postion = Convert.ToString(position);
                    newWorker.Yers    = year;
                    newWorker.Salary  = salary;
                    table.Add(newWorker);
                    Logging.Add(DateTime.Now, Operations.ADD, "Строка обновлена!");
                    break;

                case FIND_RAW:
                    Console.WriteLine("Введите фамилию");
                    string text = Console.ReadLine();
                    HRD    FindRaw;
                    for (int item_list = 0; item_list < list.Count; item_list++)
                    {
                        FindRaw = list[item_list];
                        if (FindRaw.Name.ToLower().Equals(text.ToLower()))
                        {
                            Console.Write("{0,10}", FindRaw.Name);
                            Console.Write("{0,10}", FindRaw.Postion);
                            Console.Write("{0,10}", FindRaw.Yers);
                            Console.Write("{0,10}", FindRaw.Salary);
                            Console.WriteLine();
                        }
                    }
                    Logging.Add(DateTime.Now, Operations.ADD, "Строка найдена!");
                    break;

                case SHOW_LOG:
                    Logging.Add(DateTime.Now, Operations.ADD, "Логи просмотрены!");
                    Logging.ShowInfo();
                    break;

                case ADD_WRITE:
                    var encod = System.Text.Encoding.GetEncoding(1251);

                    //Для чтения текста из файла:
                    var    Reader = new StreamReader(path, encod);
                    String text1  = Reader.ReadToEnd();
                    String text2  = Reader.ReadToEnd();
                    Reader.Close();

                    StreamWriter write      = new StreamWriter(@"D:\lab.dat");
                    int          list_item1 = 0;
                    HRD          d          = list[list_item1];
                    write.WriteLine("{0,10} {1,10} {2,10} {3,10}", d.Name, d.Postion, d.Yers, d.Salary);
                    list_item1++;
                    write.Close();
                    //Для записи в файл:
                    var Writer = new StreamWriter(path, true, encod);
                    if (text1 != text2)
                    {
                        Writer.Write(text1);
                    }
                    Writer.Close();

                    Logging.Add(DateTime.Now, Operations.ADD, "Запись в файл");

                    break;

                case Sort:
                    for (int i = 0; i < list.Count; i++)
                    {
                        int j   = i - 1;
                        var tmp = list[i];
                        while (j >= 0 && tmp.Yers < list[j].Yers)
                        {
                            list[j + 1] = list[j];
                            j--;
                        }
                        list[j + 1] = tmp;
                    }
                    using (StreamWriter newText = new StreamWriter(path, false))
                    {
                        for (int i = 0; i < list.Count; i++)
                        {
                            newText.WriteLine("{0,10} {1,10} {2,10} {3,10}", list[i].Name, list[i].Postion, list[i].Yers, list[i].Salary);
                        }
                    }
                    Console.WriteLine("Таблица готова");
                    Logging.Add(DateTime.Now, Operations.ADD, "Сортировка");

                    break;

                case EXIT:

                    break;
                }
            } while (choice != 9);
        }
Exemplo n.º 21
0
        /// <summary>
        /// 添加任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            string url = txtInput.Text;

            this.Cursor = Cursors.WaitCursor;

            IPlugin selectedPlugin = null;

            //如果有可用插件
            if (supportedPlugins.Count > 0)
            {
                selectedPlugin = supportedPlugins[cboPlugins.SelectedIndex];

                //取得此url的hash
                string hash = selectedPlugin.GetHash(url);
                //检查是否有已经在进行的相同任务
                foreach (TaskInfo task in CoreManager.TaskManager.TaskInfos)
                {
                    if (hash.Equals(task.Hash, StringComparison.InvariantCultureIgnoreCase))
                    {
                        toolTip.Show("当前任务已经存在", txtInput, 4000);
                        this.Cursor = Cursors.Default;
                        return;
                    }
                }
                try
                {
                    //取得[代理设置]
                    WebProxy selectedProxy = null;
                    if (cboProxy.SelectedIndex == 0)                     //IE设置
                    //将WebProxy设置为null可以使用默认IE设置
                    //与WebRequest.DefaultWebProxy的区别在于设置为null时不会自动检测代理设置
                    //详情请见 http://msdn.microsoft.com/en-us/library/fze2ytx2.aspx
                    {
                        selectedProxy = null;
                    }
                    else if (cboProxy.SelectedIndex == 1)                     //直接连接
                    {
                        selectedProxy = new WebProxy();
                    }
                    else if (CoreManager.ConfigManager.Settings.Proxy_Settings != null)
                    {
                        foreach (AcDownProxy item in CoreManager.ConfigManager.Settings.Proxy_Settings)
                        {
                            if (item.Name == cboProxy.SelectedItem.ToString())
                            {
                                selectedProxy = item.ToWebProxy();
                                break;
                            }
                        }
                    }

                    //取得[AutoAnswer设置]
                    List <AutoAnswer> aa = new List <AutoAnswer>();
                    if (chkAutoAnswer.Checked)
                    {
                        if (selectedPlugin.Feature != null)
                        {
                            if (selectedPlugin.Feature.ContainsKey("AutoAnswer"))
                            {
                                aa = (List <AutoAnswer>)selectedPlugin.Feature["AutoAnswer"];
                                if (aa.Count > 0)
                                {
                                    FormAutoAnswer faa = new FormAutoAnswer(aa);
                                    faa.TopMost = this.TopMost;
                                    var result = faa.ShowDialog();
                                    if (result == System.Windows.Forms.DialogResult.Cancel)
                                    {
                                        this.Cursor = Cursors.Default;
                                        return;
                                    }
                                }
                            }
                        }
                    }

                    //添加任务
                    TaskInfo task = CoreManager.TaskManager.AddTask(selectedPlugin, url.Trim(), selectedProxy);
                    //设置[保存目录]
                    task.SaveDirectory = new DirectoryInfo(cboPath.Text);
                    //设置[下载类型]
                    DownloadType ds = DownloadType.None;
                    if (lstDownloadType.GetItemChecked(0))
                    {
                        ds = ds | DownloadType.Video;
                    }
                    if (lstDownloadType.GetItemChecked(1))
                    {
                        ds = ds | DownloadType.Audio;
                    }
                    if (lstDownloadType.GetItemChecked(2))
                    {
                        ds = ds | DownloadType.Picture;
                    }
                    if (lstDownloadType.GetItemChecked(3))
                    {
                        ds = ds | DownloadType.Text;
                    }
                    if (lstDownloadType.GetItemChecked(4))
                    {
                        ds = ds | DownloadType.Subtitle;
                    }
                    if (lstDownloadType.GetItemChecked(5))
                    {
                        ds = ds | DownloadType.Comment;
                    }
                    task.DownloadTypes = ds;
                    //设置[提取浏览器缓存]
                    task.ExtractCache = chkExtractCache.Checked;
                    //设置[解析关联视频]
                    task.ParseRelated = chkParseRelated.Checked;
                    //设置[自动应答]
                    task.AutoAnswer = aa;
                    //设置注释
                    task.Comment = txtComment.Text;


                    //开始下载
                    CoreManager.TaskManager.StartTask(task);


                    this.Cursor = Cursors.Default;
                    this.Close();
                }
                catch (Exception ex)
                {
                    Logging.Add(ex);
                    toolTip.Show("新建任务出现错误:\n" + ex.Message, btnAdd, 4000);
                }
            }
            else
            {
                toolTip.Show("您所输入的网络地址(URL)不符合规则。\n没有支持解析此网址的插件,请您检查后重新输入", txtInput, 3000);
                txtInput.SelectAll();
            }
            this.Cursor = Cursors.Default;
        }
Exemplo n.º 22
0
        static void Main(string[] args)
        {
            int choice = 0;

            do
            {
                Console.WriteLine("Выберите пункт");
                Console.WriteLine("1 - Просмотр таблицы");
                Console.WriteLine("2 - Добавить запись");
                Console.WriteLine("3 - Удалить запись");
                Console.WriteLine("4 - Обновить запись");
                Console.WriteLine("5 - Поиск записей");
                Console.WriteLine("6 - Просмотреть лог");
                Console.WriteLine("7 - Выход");
                choice = int.Parse(Console.ReadLine());
                string path = @"D:\lab.dat";
                switch (choice)
                {
                case WATCH_TABLE:
                    Console.WriteLine("{0,10} {1,10} {2,10} {3,10}", "Фамилия", "Должность", "Год рождения", "Оклад");
                    for (int list_item = 0; list_item < list.Count; list_item++)
                    {
                        HRD t = list[list_item];
                        Console.WriteLine("----------------------------------------------------------------------------");
                        t.ShowTable(t.Name, t.Postion, t.Yers, t.Salary);
                    }
                    FileStream fstream = File.OpenRead(path);

                    // преобразуем строку в байты
                    byte[] array = new byte[fstream.Length];
                    // считываем данные
                    fstream.Read(array, 0, array.Length);
                    // декодируем байты в строку
                    string textFromFile = System.Text.Encoding.Default.GetString(array);
                    Console.WriteLine(textFromFile);
                    Logging.Add(DateTime.Now, Operations.LOOK, "Просмотрена таблица");
                    break;

                case ADD_RAW:
                    HRD t1;
                    Console.WriteLine("Введите Фамилию");
                    t1.Name = Console.ReadLine();
                    Console.WriteLine("ВведитеДолжность");
                    t1.Postion = Console.ReadLine();

Found1:
                    Console.WriteLine("Введите год рождения");
                    try
                    {
                        int blabla = Convert.ToInt32(Console.ReadLine());     //вводим данные, и конвертируем в целое число
                        t1.Yers = blabla;
                        if ((blabla < 1895) || (blabla > 2030))
                        {
                            Console.WriteLine("Error. (Введите повторно)");
                            goto Found1;
                        }
                    }
                    catch (FormatException)
                    {
                        t1.Yers = 000;
                        Console.WriteLine("Error. (Введите повторно)");
                        goto Found1;
                    }
                    Pos pro;
Found3:
                    Console.WriteLine("Введите оклад");
                    try
                    {
                        string blabla3 = Console.ReadLine();
                        t1.Salary = blabla3;
                        pro       = (Pos)Enum.Parse(typeof(Pos), blabla3);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error. (Введите повторно)");
                        pro = Pos.None;
                        goto Found3;
                    }

                    list.Add(t1);
                    Console.WriteLine("Строка была добавлена!");
                    Console.WriteLine();
                    Logging.Add(DateTime.Now, Operations.ADD, "Строка добавлена в таблицу!");
                    break;

                case REMOVE_RAW:


                    Console.WriteLine("Введите номер строки, которую хотите удалить");
                    int number = int.Parse(Console.ReadLine());
                    try
                    {
                        list.RemoveAt(number - 1);
                    }
                    catch (Exception e) { Console.WriteLine("Строки с таким номером нет!"); }
                    Console.WriteLine();
                    Logging.Add(DateTime.Now, Operations.ADD, "Строка удалена!");
                    break;

                case UPDATE_RAW:
                    Console.WriteLine("Введите номер строки, которую хотите изменить");
                    int UpdateIndex = int.Parse(Console.ReadLine());
                    try
                    {
                        HRD t2 = list[UpdateIndex - 1];

                        //Выводим старые значения

                        t2.ShowTable(t2.Name, t2.Postion, t2.Yers, t2.Salary);


                        //Вводим новые значения

                        Console.WriteLine("Введите новое фамилию");
                        t2.Name = Console.ReadLine();
                        Console.WriteLine("Введите новую должность");
                        t2.Postion = Console.ReadLine();
                        Console.WriteLine("Введите новый год рождения");
Found2:
                        t2.Yers = int.Parse(Console.ReadLine());
                        try
                        {
                            int blabla2 = Convert.ToInt32(Console.ReadLine());     //вводим данные, и конвертируем в целое число
                            t2.Yers = blabla2;
                            if ((blabla2 < 1895) || (blabla2 > 2030))
                            {
                                Console.WriteLine("Error. (Введите повторно)");
                                goto Found2;
                            }
                        }
                        catch (FormatException)
                        {
                            t2.Yers = 000;
                            Console.WriteLine("Error. (Введите повторно)");
                            goto Found2;
                        }
                        Console.WriteLine("Введите новый Тип");
                        Pos pro2;
Found4:
                        try
                        {
                            string blabla4 = Console.ReadLine();
                            t2.Salary = blabla4;
                            pro2      = (Pos)Enum.Parse(typeof(Pos), blabla4);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error. (Введите повторно)");
                            pro2 = Pos.None;
                            goto Found4;
                        }
                        list[UpdateIndex - 1] = t2;
                    }
                    catch (Exception e) { Console.WriteLine("Нет строки с таким номером!"); }
                    Logging.Add(DateTime.Now, Operations.ADD, "Строка обновлена!");
                    break;

                case FIND_RAW:
                    Console.WriteLine("Введите фамилию");
                    string text = Console.ReadLine();
                    HRD    FindRaw;
                    for (int item_list = 0; item_list < list.Count; item_list++)
                    {
                        FindRaw = list[item_list];
                        if (FindRaw.Name.ToLower().Equals(text.ToLower()))
                        {
                            Console.Write("{0,10}", FindRaw.Name);
                            Console.Write("{0,10}", FindRaw.Postion);
                            Console.Write("{0,10}", FindRaw.Yers);
                            Console.Write("{0,10}", FindRaw.Salary);
                            Console.WriteLine();
                        }
                    }
                    Logging.Add(DateTime.Now, Operations.ADD, "Строка найдена!");
                    break;

                case SHOW_LOG:
                    Logging.Add(DateTime.Now, Operations.ADD, "Логи просмотрены!");
                    Logging.ShowInfo();
                    break;

                case EXIT:

                    StreamWriter write = new StreamWriter(@"D:\lab.dat");
                    for (int list_item = 0; list_item < list.Count; list_item++)
                    {
                        HRD t = list[list_item];
                        write.WriteLine("----------------------------------------------------------------------------");
                        write.WriteLine("{0,10} {1,10} {2,10} {3,10}", t.Name, t.Postion, t.Yers, t.Salary);
                    }

                    write.Close();
                    break;
                }
            } while (choice != 7);
        }
Exemplo n.º 23
0
            private static void ex1()
            {
                Console.WriteLine("Введите номер подзадания (1 или 2) , который хотите увидеть  ");
                int tmp = Convert.ToInt32(Console.ReadLine());

                if (tmp == 1)
                {
                    int choice = 0;
                    do
                    {
                        Console.WriteLine("Выберите пункт");
                        Console.WriteLine("1 - Просмотр таблицы");
                        Console.WriteLine("2 - добавить запись");
                        Console.WriteLine("3 - Удалить запись");
                        Console.WriteLine("4 - обновить запись");
                        Console.WriteLine("5 - поиск записей");
                        Console.WriteLine("6 - просмотреть лог");
                        Console.WriteLine("7 - Выход");
                        choice = int.Parse(Console.ReadLine());
                        switch (choice)
                        {
                        case WATCH_TABLE:
                            Console.WriteLine("{0,10} {1,10} {2,10} {3,10}", "Фамилия", "Должность", "Год рождения", "Оклад");
                            for (int list_item = 0; list_item < list.Count; list_item++)
                            {
                                HRD t = list[list_item];
                                Console.WriteLine("----------------------------------------------------------------------------");
                                t.ShowTable(t.Name, t.Postion, t.Yers, t.Salary);
                            }
                            Logging.Add(DateTime.Now, Operations.LOOK, "Просмотрена таблица");
                            break;

                        case ADD_RAW:
                            HRD t1;
                            Console.WriteLine("Введите Фамилию");
                            t1.Name = Console.ReadLine();
                            Console.WriteLine("Введите Должность");
                            t1.Postion = Console.ReadLine();

Found1:
                            Console.WriteLine("Введите год рождения");
                            try
                            {
                                int blabla = Convert.ToInt32(Console.ReadLine());     //вводим данные, и конвертируем в целое число
                                t1.Yers = blabla;
                                if ((blabla < 1895) || (blabla > 2030))
                                {
                                    Console.WriteLine("Error. (Введите повторно)");
                                    goto Found1;
                                }
                            }
                            catch (FormatException)
                            {
                                t1.Yers = 000;
                                Console.WriteLine("Error. (Введите повторно)");
                                goto Found1;
                            }
                            Pos pro;
Found3:
                            Console.WriteLine("Введите оклад");
                            try
                            {
                                string blabla3 = Console.ReadLine();
                                t1.Salary = blabla3;
                                pro       = (Pos)Enum.Parse(typeof(Pos), blabla3);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Error. (Введите повторно)");
                                pro = Pos.None;
                                goto Found3;
                            }

                            list.Add(t1);
                            Console.WriteLine("Строка была добавлена!");
                            Console.WriteLine();
                            Logging.Add(DateTime.Now, Operations.ADD, "Строка добавлена в таблицу!");
                            break;

                        case REMOVE_RAW:
                            Console.WriteLine("Введите номер строки, которую хотите удалить");
                            int number = int.Parse(Console.ReadLine());
                            try
                            {
                                list.RemoveAt(number - 1);
                            }
                            catch (Exception e) { Console.WriteLine("Строки с таким номером нет!"); }
                            Console.WriteLine();
                            Logging.Add(DateTime.Now, Operations.ADD, "Строка удалена!");
                            break;

                        case UPDATE_RAW:
                            Console.WriteLine("Введите номер строки, которую хотите изменить");
                            int UpdateIndex = int.Parse(Console.ReadLine());
                            try
                            {
                                HRD t2 = list[UpdateIndex - 1];

                                //Выводим старые значения

                                t2.ShowTable(t2.Name, t2.Postion, t2.Yers, t2.Salary);


                                //Вводим новые значения

                                Console.WriteLine("Введите новое фамилию");
                                t2.Name = Console.ReadLine();
                                Console.WriteLine("Введите новую должность");
                                t2.Postion = Console.ReadLine();
                                Console.WriteLine("Введите новый год рождения");
Found2:
                                t2.Yers = int.Parse(Console.ReadLine());
                                try
                                {
                                    int blabla2 = Convert.ToInt32(Console.ReadLine());     //вводим данные, и конвертируем в целое число
                                    t2.Yers = blabla2;
                                    if ((blabla2 < 1895) || (blabla2 > 2030))
                                    {
                                        Console.WriteLine("Error. (Введите повторно)");
                                        goto Found2;
                                    }
                                }
                                catch (FormatException)
                                {
                                    t2.Yers = 000;
                                    Console.WriteLine("Error. (Введите повторно)");
                                    goto Found2;
                                }
                                Console.WriteLine("Введите новый Тип");
                                Pos pro2;
Found4:
                                try
                                {
                                    string blabla4 = Console.ReadLine();
                                    t2.Salary = blabla4;
                                    pro2      = (Pos)Enum.Parse(typeof(Pos), blabla4);
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine("Error. (Введите повторно)");
                                    pro2 = Pos.None;
                                    goto Found4;
                                }
                                list[UpdateIndex - 1] = t2;
                            }
                            catch (Exception e) { Console.WriteLine("Нет строки с таким номером!"); }
                            Logging.Add(DateTime.Now, Operations.ADD, "Строка обновлена!");
                            break;

                        case FIND_RAW:
                            Console.WriteLine("Введите фамилию");
                            string text = Console.ReadLine();
                            HRD    FindRaw;
                            for (int item_list = 0; item_list < list.Count; item_list++)
                            {
                                FindRaw = list[item_list];
                                if (FindRaw.Name.ToLower().Equals(text.ToLower()))
                                {
                                    Console.Write("{0,10}", FindRaw.Name);
                                    Console.Write("{0,10}", FindRaw.Postion);
                                    Console.Write("{0,10}", FindRaw.Yers);
                                    Console.Write("{0,10}", FindRaw.Salary);
                                    Console.WriteLine();
                                }
                            }
                            Logging.Add(DateTime.Now, Operations.ADD, "Строка найдена!");
                            break;

                        case SHOW_LOG:
                            Logging.Add(DateTime.Now, Operations.ADD, "Логи просмотрены!");
                            Logging.ShowInfo();
                            break;

                        case EXIT:
                            break;
                        }
                    } while (choice != 7);
                }
                if (tmp == 2)
                {
                    int choice = 0;
                    do
                    {
                        var logOfSession = new DoublyLinkedList <Log>();
                        var table        = new DoublyLinkedList <WR>();
                        int salary;
                        int year;
                        Console.WriteLine("Выберите пункт");
                        Console.WriteLine("1 - Просмотр таблицы");
                        Console.WriteLine("2 - добавить запись");
                        Console.WriteLine("3 - Удалить запись");
                        Console.WriteLine("4 - обновить запись");
                        Console.WriteLine("5 - поиск записей");
                        Console.WriteLine("6 - просмотреть лог");
                        Console.WriteLine("7 - Выход");
                        choice = int.Parse(Console.ReadLine());
                        switch (choice)
                        {
                        case WATCH_TABLE:
                            Console.WriteLine("{0,10} {1,10} {2,10} {3,10}", "Фамилия", "Должность", "Год рождения", "Оклад");
                            for (int list_item = 0; list_item < list.Count; list_item++)
                            {
                                foreach (var item in table)
                                {
                                    item.showTable();
                                }
                            }
                            Log newLog;
                            newLog.time      = DateTime.Now;
                            newLog.operation = "Просмотр таблицы";
                            logOfSession.Add(newLog);
                            break;

                        case ADD_RAW:
                            string name;
                            Pos    position = new Pos();
                            Console.WriteLine("Введите Фамилию");
                            name = Console.ReadLine();
                            Console.WriteLine("Введите Должность");
                            string pos = Console.ReadLine();
                            if (pos == "П")
                            {
                                position = Pos.П;
                            }
                            else if (pos == "С")
                            {
                                position = Pos.С;
                            }
                            else if (pos == "А")
                            {
                                position = Pos.А;
                            }
                            else
                            {
                                Console.WriteLine("УПС!\n-_-");
                            }
Found1:
                            Console.WriteLine("Введите год рождения");
                            try
                            {
                                int blabla = Convert.ToInt32(Console.ReadLine());     //вводим данные, и конвертируем в целое число
                                year = blabla;
                                if ((blabla < 1895) || (blabla > 2030))
                                {
                                    Console.WriteLine("Error. (Введите повторно)");
                                    goto Found1;
                                }
                            }
                            catch (FormatException)
                            {
                                year = 000;
                                Console.WriteLine("Error. (Введите повторно)");
                                goto Found1;
                            }
                            Pos pro;
Found3:
                            Console.WriteLine("Введите оклад");
                            try
                            {
                                int blabla3 = Convert.ToInt32(Console.ReadLine());
                                salary = blabla3;
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Error. (Введите повторно)");
                                pro = Pos.None;
                                goto Found3;
                            }
                            WR newWr;
                            newWr.name     = name;
                            newWr.position = position;
                            newWr.salary   = salary;
                            newWr.year     = year;
                            Console.WriteLine("Строка была добавлена!");
                            Console.WriteLine();

                            newLog.time      = DateTime.Now;
                            newLog.operation = "Строка добавлена";
                            logOfSession.Add(newLog); break;

                        case REMOVE_RAW:
                            Console.WriteLine("Введите номер строки, которую хотите удалить");
                            int number = int.Parse(Console.ReadLine());
                            try
                            {
                                list.RemoveAt(number - 1);
                            }
                            catch (Exception e) { Console.WriteLine("Строки с таким номером нет!"); }
                            Console.WriteLine();
                            newLog.time      = DateTime.Now;
                            newLog.operation = "Строка delet";
                            logOfSession.Add(newLog);  break;

                        case UPDATE_RAW:
                            Console.WriteLine("Введите номер строки, которую хотите изменить");
                            int UpdateIndex = int.Parse(Console.ReadLine());
                            try
                            {
                                HRD t2 = list[UpdateIndex - 1];

                                //Выводим старые значения

                                t2.ShowTable(t2.Name, t2.Postion, t2.Yers, t2.Salary);


                                //Вводим новые значения

                                Console.WriteLine("Введите новое фамилию");
                                t2.Name = Console.ReadLine();
                                Console.WriteLine("Введите новую должность");
                                t2.Postion = Console.ReadLine();
                                Console.WriteLine("Введите новый год рождения");
Found2:
                                t2.Yers = int.Parse(Console.ReadLine());
                                try
                                {
                                    int blabla2 = Convert.ToInt32(Console.ReadLine());     //вводим данные, и конвертируем в целое число
                                    t2.Yers = blabla2;
                                    if ((blabla2 < 1895) || (blabla2 > 2030))
                                    {
                                        Console.WriteLine("Error. (Введите повторно)");
                                        goto Found2;
                                    }
                                }
                                catch (FormatException)
                                {
                                    t2.Yers = 000;
                                    Console.WriteLine("Error. (Введите повторно)");
                                    goto Found2;
                                }
                                Console.WriteLine("Введите новый Тип");
                                Pos pro2;
Found4:
                                try
                                {
                                    string blabla4 = Console.ReadLine();
                                    t2.Salary = blabla4;
                                    pro2      = (Pos)Enum.Parse(typeof(Pos), blabla4);
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine("Error. (Введите повторно)");
                                    pro2 = Pos.None;
                                    goto Found4;
                                }
                                list[UpdateIndex - 1] = t2;
                            }
                            catch (Exception e) { Console.WriteLine("Нет строки с таким номером!"); }
                            newLog.time      = DateTime.Now;
                            newLog.operation = "Строка обновлена";
                            logOfSession.Add(newLog); break;

                        case FIND_RAW:
                            Console.WriteLine("Введите фамилию");
                            string text = Console.ReadLine();
                            HRD    FindRaw;
                            for (int item_list = 0; item_list < list.Count; item_list++)
                            {
                                FindRaw = list[item_list];
                                if (FindRaw.Name.ToLower().Equals(text.ToLower()))
                                {
                                    Console.Write("{0,10}", FindRaw.Name);
                                    Console.Write("{0,10}", FindRaw.Postion);
                                    Console.Write("{0,10}", FindRaw.Yers);
                                    Console.Write("{0,10}", FindRaw.Salary);
                                    Console.WriteLine();
                                }
                            }
                            newLog.time      = DateTime.Now;
                            newLog.operation = "Строка найдена";
                            logOfSession.Add(newLog);                                 newLog.time = DateTime.Now;
                            newLog.operation = "Логи просмотрены";
                            logOfSession.Add(newLog);
                            break;

                        case EXIT:
                            break;
                        }
                    } while (choice != 7);
                }
            }
Exemplo n.º 24
0
        static void Main(string[] args)
        {
            int choice = 0;

            do
            {
                Console.WriteLine("Выберите пункт");
                Console.WriteLine("1 - Просмотр таблицы");
                Console.WriteLine("2 - Добавить запись");
                Console.WriteLine("3 - Удалить запись");
                Console.WriteLine("4 - Обновить запись");
                Console.WriteLine("5 - Поиск записей");
                Console.WriteLine("6 - Просмотреть лог");
                Console.WriteLine("7 - Выход");
                choice = int.Parse(Console.ReadLine());
                switch (choice)
                {
                case WATCH_TABLE:
                    Console.WriteLine("{0,10} {1,10} {2,10} {3,10}", "Вид транспорта", "№ маршрута", "Протяженность маршрута (км) ", "Время в дороге (мин)");
                    for (int list_item = 0; list_item < list.Count; list_item++)
                    {
                        HRD t = list[list_item];
                        Console.WriteLine("----------------------------------------------------------------------------\n");
                        t.ShowTable(t.Transport, t.number, t.Length, t.RoadTime);
                    }

                    string textFromFile = FileExpert.ReadFromRelativePath("lab.dat");
                    Console.WriteLine(textFromFile);
                    Logging.Add(DateTime.Now, Operations.LOOK, "Просмотрена таблица");
                    break;

                case ADD_RAW:
                    HRD t1;
                    Console.WriteLine("Введите Вид транспорта");
                    t1.Transport = Console.ReadLine();
                    Console.WriteLine("Введите Номер маршрута");
                    t1.number = Console.ReadLine();

Found1:
                    Console.WriteLine("Введите Протяженность маршрута (км) ");
                    try
                    {
                        int enter_length = Convert.ToInt32(Console.ReadLine());     //вводим данные, и конвертируем в целое число
                        t1.Length = enter_length;
                        if ((enter_length <= 0) || (enter_length >= 250))
                        {
                            Console.WriteLine("Error. (Введите повторно)");
                            goto Found1;
                        }
                    }
                    catch (FormatException)
                    {
                        t1.Length = 000;
                        Console.WriteLine("Error. (Введите повторно)");
                        goto Found1;
                    }
                    Pos pro;
Found3:
                    Console.WriteLine("Время в дороге (мин)");
                    try
                    {
                        string enter_length3 = Console.ReadLine();
                        t1.RoadTime = enter_length3;
                        pro         = (Pos)Enum.Parse(typeof(Pos), enter_length3);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error. (Введите повторно)");
                        pro = Pos.None;
                        goto Found3;
                    }

                    list.Add(t1);
                    Console.WriteLine("Строка была добавлена!");
                    Console.WriteLine();
                    Logging.Add(DateTime.Now, Operations.ADD, "Строка добавлена в таблицу!");
                    break;

                case REMOVE_RAW:


                    Console.WriteLine("Введите номер строки, которую хотите удалить");
                    int number = int.Parse(Console.ReadLine());
                    try
                    {
                        list.RemoveAt(number - 1);
                    }
                    catch (Exception e) { Console.WriteLine("Строки с таким номером нет!"); }
                    Console.WriteLine();
                    Logging.Add(DateTime.Now, Operations.ADD, "Строка удалена!");
                    break;

                case UPDATE_RAW:
                    Console.WriteLine("Введите номер строки, которую хотите изменить");
                    int UpdateIndex = int.Parse(Console.ReadLine());
                    try
                    {
                        HRD t2 = list[UpdateIndex - 1];

                        //Выводим старые значения

                        t2.ShowTable(t2.Transport, t2.number, t2.Length, t2.RoadTime);


                        //Вводим новые значения

                        Console.WriteLine("Введите новый вид транспорта");
                        t2.Transport = Console.ReadLine();
                        Console.WriteLine("Введите новый № маршрута ");
                        t2.number = Console.ReadLine();
                        Console.WriteLine("Введите новую протяженность маршрута (км) ");
Found2:
                        t2.Length = int.Parse(Console.ReadLine());
                        try
                        {
                            int enter_length2 = Convert.ToInt32(Console.ReadLine());     //вводим данные, и конвертируем в целое число
                            t2.Length = enter_length2;
                            if ((enter_length2 < 1895) || (enter_length2 > 2030))
                            {
                                Console.WriteLine("Error. (Введите повторно)");
                                goto Found2;
                            }
                        }
                        catch (FormatException)
                        {
                            t2.Length = 000;
                            Console.WriteLine("Error. (Введите повторно)");
                            goto Found2;
                        }
                        Console.WriteLine("Введите новый Тип");
                        Pos pro2;
Found4:
                        try
                        {
                            string enter_length4 = Console.ReadLine();
                            t2.RoadTime = enter_length4;
                            pro2        = (Pos)Enum.Parse(typeof(Pos), enter_length4);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error. (Введите повторно)");
                            pro2 = Pos.None;
                            goto Found4;
                        }
                        list[UpdateIndex - 1] = t2;
                    }
                    catch (Exception e) { Console.WriteLine("Нет строки с таким номером!"); }
                    Logging.Add(DateTime.Now, Operations.ADD, "Строка обновлена!");
                    break;

                case FIND_RAW:
                    Console.WriteLine("Введите фамилию");
                    string text = Console.ReadLine();
                    HRD    FindRaw;
                    for (int item_list = 0; item_list < list.Count; item_list++)
                    {
                        FindRaw = list[item_list];
                        if (FindRaw.Transport.ToLower().Equals(text.ToLower()))
                        {
                            Console.Write("{0,10}", FindRaw.Transport);
                            Console.Write("{0,10}", FindRaw.number);
                            Console.Write("{0,10}", FindRaw.Length);
                            Console.Write("{0,10}", FindRaw.RoadTime);
                            Console.WriteLine();
                        }
                    }
                    Logging.Add(DateTime.Now, Operations.ADD, "Строка найдена!");
                    break;

                case SHOW_LOG:
                    Logging.Add(DateTime.Now, Operations.ADD, "Логи просмотрены!");
                    Logging.ShowInfo();
                    break;

                case EXIT:

                    String file = string.Empty;
                    foreach (var t in list)
                    {
                        file += "----------------------------------------------------------------------------";
                        file += t.Transport + "\t" + t.number + "\t" + t.Length + "\t" + t.RoadTime;
                    }
                    //for (int list_item = 0; list_item < list.Count; list_item++)
                    //{
                    //    HRD t = list[list_item];
                    //    write.WriteLine("----------------------------------------------------------------------------");
                    //    write.WriteLine("{0,10} {1,10} {2,10} {3,10}" , t.Transport, t.number, t.Length, t.RoadTime);
                    // }

                    FileExpert.SaveToRelativePath("lab.dat", file);
                    break;
                }
            } while (choice != 7);
        }