Example #1
0
 public void SetDragonCurve()
 {
     WorkingState = InitialState;
     ReverseWorkingState();
     InvertWorkingState();
     DragonCurve = InitialState + '0' + WorkingState.ToString();
 }
        void HandleSend(SendIOEventCode sendEventCode)
        {
            //throw new NotImplementedException();
            switch (sendEventCode)
            {
            case SendIOEventCode.SocketError:
            {
                UnBindSocket(true);
            }
            break;

            case SendIOEventCode.SendComplete:
            {
                //save when send complete here
                Action tmpWhenSendComplete = whenSendCompleted;
                //clear handler
                whenSendCompleted = null;
                _workingState     = WorkingState.Rest;
                if (tmpWhenSendComplete != null)
                {
                    //just invoke it
                    tmpWhenSendComplete();
                }
            }
            break;
            }
        }
Example #3
0
        /// <summary>
        /// Searches for compatible archives in the given directory
        /// </summary>
        /// <param name="path">path to the directory</param>
        /// <returns>Reading Status: Status code whether the search threw an error or if a cancellation request was made</returns>
        private ReadingStatus addDirectoryToSearchList(string path)
        {
            // if the directory doesn't exist, it's not a big problem so we can continue with whatever we want to.
            if (!Directory.Exists(path))
            {
                return(ReadingStatus.OK);
            }

            CurrentWorkingState = WorkingState.DirectorySearch;
            this.InvokeIfRequired(() => setStatus($"Listing files in directories.. { path }", true, true, 0, true));

            // Get all matching compressed files we can get in the given directory
            (Boolean errorOccured, List <string> results)search = Utils.SearchDirectory(path);
            string[] files = search.results.ToArray();

            CurrentWorkingState = WorkingState.FileScan;
            this.InvokeIfRequired(() => setStatus("Read files in directories.. ", true, true, 0, true));

            // Loop through each file ..
            ReadingStatus fileReadingStatus = addFilesToSearchList(files);

            // if the search threw an error, return that.
            if (search.errorOccured)
            {
                return(ReadingStatus.Error);
            }
            else
            {
                return(fileReadingStatus);
            }
        }
Example #4
0
        private void SetFollowUpWorkingState(WorkingState state)
        {
            tableLayoutPanel11.Enabled = true;
            this.FollowUpWorkingState  = state;

            if (WorkingState.Add == state)
            {
                DTPDate.Enabled             = true;
                ComboBoxState.SelectedIndex = 0;
                TxtBoxBriefing.Text         = "";
                RichTxtBoxContent.Text      = "";

                BtnLogSave.Text    = "添加";
                BtnLogSave.Enabled = false;
                BtnLogSave.Visible = true;
            }
            else
            {
                DTPDate.Enabled = false;

                BtnLogSave.Text    = "更新";
                BtnLogSave.Enabled = false;
                BtnLogSave.Visible = true;
            }
        }
        public override void SpawnSetup(Map map, bool respawningAfterLoad)
        {
            base.SpawnSetup(map, respawningAfterLoad);
            this.mapManager = map.GetComponent <MapTickManager>();

            if (readyOnStart)
            {
                this.State = WorkingState.Ready;
                this.Reset();
                MapManager.AfterAction(Rand.Range(0, this.startCheckIntervalTicks), this.Ready);
            }
            else
            {
                if (this.State == WorkingState.Ready)
                {
                    MapManager.AfterAction(Rand.Range(0, this.startCheckIntervalTicks), this.Ready);
                }
                else if (this.State == WorkingState.Working)
                {
                    MapManager.NextAction(this.StartWork);
                }
                else if (this.State == WorkingState.Placing)
                {
                    MapManager.NextAction(this.Placing);
                }
            }
        }
        /// <summary>
        /// close conncetion, +/- blocking
        /// </summary>
        /// <param name="nextAction"></param>
        public void Disconnect(Action nextAction = null)
        {
            _writer.Reset();
            ComQuitPacket quitPacket = new ComQuitPacket(new PacketHeader());

            quitPacket.WritePacket(_writer);
            byte[] data = _writer.ToArray();
            //-------------------------------------
            InitWait();
            StartSend(data, 0, data.Length, () =>
            {
                socket.Shutdown(SocketShutdown.Both);
                _workingState = WorkingState.Disconnected;
                UnWait();
                if (nextAction != null)
                {
                    nextAction();
                }
            });
            if (nextAction == null)
            {
                Wait(); //block
            }
            else
            {
                UnWait();
            }
        }
    void Start()
    {
        //Por defecto, al principio el zoom está alejado
        zoomState          = ZommState.far;
        camera.fieldOfView = fovFar;

        //Cámara en reposo
        workingSate = WorkingState.idle;

        //Asigno los transforms
        tr       = this.gameObject.transform;
        trPlayer = player.transform;

        if (viewType == ViewType.custom)
        {
            //Me posiciono con respecto al player
            tr.position = new Vector3(trPlayer.position.x, trPlayer.position.y + height, trPlayer.position.z + distance);
        }

        //Calculo la dirección al player
        diff = trPlayer.position - tr.position;

        if (viewType == ViewType.custom)
        {
            //Miro al player
            tr.LookAt(trPlayer);
        }
    }
Example #8
0
 public ModbusClient(ResultData resultData,
                     ConfigurationSettingsModel configurationSettings, WorkingState workingState)
 {
     _resultData            = resultData;
     _configurationSettings = configurationSettings;
     _workingState          = workingState;
 }
        public void StartConnection(TcpConnectionSettings connectionSettings)
        {
            if (this.State == WorkingState.Enabled)
            {
                _logger.UpdateLog("TCP connection starting aborted - connection is already enabled!");
                return;
            }

            _connectionSettings = connectionSettings;

            try
            {
                ConnectionData connData = connectionSettings.ToConnectionData();
                //TcpServer.SetContainerSize(5);
                _tcpServerInstance = TcpServer.RunServer(connData, _logger);
                this.State         = WorkingState.Enabled;

                HandleClientCommandsAsync();
                HandleClientActivityCheckAsync();
            }
            catch (Exception exception)
            {
                _logger.UpdateLog($"TCP connection - connection starting error: {exception.Message}");
                this.State = WorkingState.Error;
            }
        }
Example #10
0
 protected override void OnChangeState(WorkingState before, WorkingState after)
 {
     if (after == WorkingState.Ready)
     {
         this.consumer.ReleaseEnergy();
     }
 }
Example #11
0
 public ViewModel()
 {
     StatusBar             = new StatusBar();
     WorkingState          = new WorkingState(StatusBar);
     ConfigurationSettings = ConfigurationSettingsModel.Deserialize(StormbusDirectory.ConfigurationFilePath);
     ResultData            = new ResultData(ConfigurationSettings);
     ModbusClient          = new ModbusClient(ResultData, ConfigurationSettings, WorkingState);
 }
Example #12
0
        /// <summary>
        /// Handle end of compressed file search
        /// </summary>
        private void bw_loadFiles_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            setStatus(DefaultStatusText, true);

            btn_abort.Visible            = false;
            CurrentWorkingState          = WorkingState.None;
            requestedTimesOfCancellation = 0;
        }
Example #13
0
 // Start is called before the first frame update
 void Start()
 {
     _state       = WorkingState.Child;
     _gameManager = GameObject.FindWithTag("GameManager").GetComponent <GameManager>();
     _jobManager  = GameObject.FindWithTag("GameManager").GetComponent <JobManager>();
     InvokeRepeating("Age", 30.0f, 15.0f);
     //InvokeRepeating("ConsumeRessources", 60.0f, 60.0f);
 }
Example #14
0
 private void Retire()
 {
     if (_job != null)
     {
         _job.RemoveWorker(this);
     }
     _jobManager.RemoveWorker(this);
     _state = WorkingState.Retired;
 }
Example #15
0
        private void ReverseWorkingState()
        {
            var characters = WorkingState.ToCharArray();
            var newState   = new StringBuilder();

            for (var i = characters.Length - 1; i > -1; i--)
            {
                newState.Append(characters[i]);
            }
            WorkingState = newState.ToString();
        }
        protected void ForceStartWork(T working, float workAmount)
        {
            this.Reset();
            this.ClearActions();

            this.State           = WorkingState.Working;
            this.working         = working;
            this.totalWorkAmount = workAmount;
            this.workStartTick   = Find.TickManager.TicksAbs;
            MapManager.NextAction(StartWork);
        }
        }         // Week

        // ----------------------------------------------------------------------
        public DateTime CalculateNextStateChange(DateTime moment, WorkingState state)
        {
            DateTime?nextDate = null;

            while (nextDate.HasValue == false)
            {
                ITimePeriod           weekPeriod         = week.GetWeekPeriod(moment);
                ITimePeriodCollection weekExcludePeriods = GetWeekExcludePeriods(moment);

                // setup moment for the next search
                ITimePeriod nextExcludePeriod = FindNextPeriod(weekExcludePeriods, moment);
                if (nextExcludePeriod == null)
                {
                    moment = weekPeriod.End;
                    continue;
                }
                moment = nextExcludePeriod.End;

                // search next availabe date by adding zero
                DateAdd dateAdd = new DateAdd();
                dateAdd.IncludePeriods.Add(weekPeriod);
                dateAdd.ExcludePeriods.AddAll(weekExcludePeriods);

                // calculate the next avialable time
                nextDate = dateAdd.Add(moment, TimeSpan.Zero);
                if (!nextDate.HasValue)                   // not found in this week
                {
                    moment = weekPeriod.End.AddTicks(1);
                    continue;
                }

                switch (state)
                {
                case WorkingState.On:
                    break;

                case WorkingState.Off:
                    ITimePeriod nextPeriod = FindSuccessorPeriod(weekExcludePeriods, nextDate.Value);
                    if (nextPeriod == null)                               // search in next week
                    {
                        nextDate = null;
                        moment   = weekPeriod.End.AddTicks(1);
                    }
                    else
                    {
                        nextDate = nextPeriod.Start;
                    }
                    break;
                }
            }

            return(nextDate.Value);
        }         // CalculateNextStateChange
Example #18
0
        /// <summary>
        /// Start search for a string in the given files
        /// </summary>
        private void btn_search_Click(object sender, EventArgs e)
        {
            // Variables and current status declaration
            tsm_searchText.Enabled = false;
            btn_abort.Visible      = true;
            CurrentWorkingState    = WorkingState.StringSearch;

            // Start search on all files currently listed in the lv_files (pass only the tags to the background worker)
            bw_search.RunWorkerAsync(lv_files.Items.Cast <ListViewItem>()
                                     .Select(item => item.Tag)
                                     .ToList());
        }
Example #19
0
        public void Init()
        {
            State = WorkingState.Working;
            PhantomJSDriverService service = PhantomJSDriverService.CreateDefaultService(@"D:\");

            service.IgnoreSslErrors         = true;
            service.LoadImages              = false;
            service.ProxyType               = "none";
            service.HideCommandPromptWindow = hide;
            driver = new PhantomJSDriver(service);
            driver.Manage().Window.Size = new System.Drawing.Size(1920, 1080);
            State = WorkingState.Idle;
        }
Example #20
0
        public IHttpActionResult GetWorkingStateByDate(string date, Guid userID)
        {
            WorkingState  workingState = WorkingState.NoRegister;
            string        query        = $"select * from JobBooking where Date = '{date}' and UserID = '{userID.ToString()}'";
            SqlDataReader reader       = executeQuery(query);

            if (reader.Read())
            {
                workingState = (WorkingState)reader["WorkingState"];
            }
            sqlConnection.Close();
            return(Ok(workingState));
        }
Example #21
0
 public void StopConnection()
 {
     try
     {
         this.State = WorkingState.Disabled;
         TcpServer.StopServer();
         _logger.UpdateLog("TCP connection stopped successfully!");
     }
     catch (Exception exception)
     {
         this.State = WorkingState.Error;
         _logger.UpdateLog($"TCP connection - connection stopping error: {exception.Message}");
     }
 }
Example #22
0
 public void Navigate(string URL)
 {
     State = WorkingState.Working;
     if (Navigates >= TotalAllowed)
     {
         driver.Quit();
         Init();
         Thread.Sleep(250);
         Navigates = 0;
     }
     //driver.Manage().Window.Position = new System.Drawing.Point(1000000, 1000000);
     driver.Navigate().GoToUrl(URL);
     Navigates += 1;
     State      = WorkingState.Idle;
 }
    void Update()
    {
        if (Input.GetButtonDown("Zoom") && workingSate == WorkingState.idle)
        {
            //El usuario ha pulsado el botón de zoom

            //Cámara ocupada
            workingSate = WorkingState.busy;
            StartCoroutine(makeZoom());
        }
        // Me desplazo con el player
        if (trPlayer)
        {
            tr.position = trPlayer.position - diff;
        }
    }
        public void StartReceive(Action <MySqlResult> whenCompleteAction)
        {
            //must be in opened state
            if (_workingState != WorkingState.Rest)
            {
                throw new Exception("sending error: state is not= opened");
            }
            //--------------------------------------------------------------
#if DEBUG
            if (this.whenRecvData != null)
            {
                //must be null
                throw new Exception("receving something?...");
            }
#endif
            this.whenRecvData  = whenCompleteAction;
            this._workingState = WorkingState.Receiving;
            recvIO.StartReceive();
        }
Example #25
0
        public static WorkingState ParseWorkMess(string[] inforColl)
        {
            WorkingState state = null;

            try
            {
                state = new WorkingState();
                state.carVidiconState  = inforColl[1];
                state.carVidiconTemp   = float.Parse(inforColl[2]);
                state.conConnStateVSIO = inforColl[3];
                state.roadNumber       = inforColl[4];
                state.inputState       = inforColl[5];
            }
            catch (Exception e)
            {
                FileWorker.LogHelper.WriteLog("解析D01记录失败," + e.Message);
            }
            return(state);
        }
Example #26
0
        private TimeSpan CalculateTimeSpan(TimeStamp[] timeStamps, WorkingState workingState)
        {
            TimeSpan result = new TimeSpan();

            for (int index = 0; index < timeStamps.Length; index++)
            {
                TimeStamp current = timeStamps[index];
                if (current.WorkingState != workingState)
                {
                    continue;
                }

                DateTime endTime = GetIntervalEndTimeByIndex(timeStamps, index);
                TimeSpan span    = endTime - current.DateTime;
                result = result.Add(span);
            }

            return(result);
        }
        public void StartSend(byte[] sendBuffer, int start, int len, Action whenSendCompleted)
        {
            //must be in opened state
            if (_workingState != WorkingState.Rest)
            {
                throw new Exception("sending error: state is not= opened");
            }
            //--------------------------------------------------------------
#if DEBUG
            if (this.whenSendCompleted != null)
            {
                //must be null
                throw new Exception("sending something?...");
            }
#endif
            this.whenSendCompleted = whenSendCompleted;
            this._workingState     = WorkingState.Sending;
            sendIO.EnqueueOutputData(sendBuffer, len);
            sendIO.StartSendAsync();
        }
 protected virtual void Reset()
 {
     if (this.State != WorkingState.Ready)
     {
         this.products.ForEach(t =>
         {
             if (!t.Spawned)
             {
                 GenPlace.TryPlaceThing(t, this.Position, this.Map, ThingPlaceMode.Near);
             }
         });
     }
     this.CleanupWorkingEffect();
     this.State           = WorkingState.Ready;
     this.totalWorkAmount = 0;
     this.workStartTick   = 0;
     Option(this.working).ForEach(h => workingSet.Remove(h));
     this.working = null;
     this.products.Clear();
 }
Example #29
0
        public void StartConnection(TcpConnectionSettings connectionSettings)
        {
            _connectionSettings = connectionSettings;
            _logger.UpdateLog($"Starting connection with IP [{connectionSettings.Ip}] port [{connectionSettings.Port}]");

            try
            {
                ConnectionData connData = connectionSettings.ToConnectionData();
                //TcpServerClient.SetCommandInsertionTimeLimit(15);
                _tcpClientInstance = TcpServerClient.RunServerClient(connData, _logger);
                this.State         = WorkingState.Enabled;

                HandleServerCommandsAsync();
            }
            catch (Exception exception)
            {
                _logger.UpdateLog($"TCP connection - connection starting error: {exception.Message} | {exception.StackTrace}");
                this.State = WorkingState.Error;
            }
        }
 protected virtual void FinishWork()
 {
     if (this.State != WorkingState.Working || !this.Spawned)
     {
         return;
     }
     MapManager.RemoveAfterAction(this.CheckWork);
     MapManager.RemoveAfterAction(this.FinishWork);
     if (!this.IsActive())
     {
         this.ForceReady();
         return;
     }
     if (this.WorkInterruption(this.working))
     {
         this.ForceReady();
         return;
     }
     if (this.FinishWorking(this.working, out this.products))
     {
         this.State = WorkingState.Placing;
         this.CleanupWorkingEffect();
         this.working = null;
         if (this.products == null || this.products.Count == 0)
         {
             this.Reset();
             MapManager.NextAction(this.Ready);
         }
         else
         {
             MapManager.NextAction(this.Placing);
         }
     }
     else
     {
         this.Reset();
         MapManager.NextAction(this.Ready);
     }
 }
 /// <summary>
 /// open connection, +/- blocking
 /// </summary>
 /// <param name="nextAction"></param>
 public void Connect(Action nextAction = null)
 {
     if (State == ConnectionState.Connected)
     {
         throw new NotSupportedException("already connected");
     }
     _mysqlParserMx.UseConnectionParser();
     this._workingState = WorkingState.Rest;
     //--------------
     var endpoint = new IPEndPoint(IPAddress.Parse(config.host), config.port);
     socket.Connect(endpoint);
     this._workingState = WorkingState.Rest;
     //--------------
     //**start listen after connect
     InitWait();
     StartReceive(mysql_result =>
     {
         //when complete1
         //create handshake packet and send back
         var handshakeResult = mysql_result as MySqlHandshakeResult;
         if (handshakeResult == null)
         {
             //error
             throw new Exception("err1");
         }
         HandshakePacket handshake_packet = handshakeResult.packet;
         this.threadId = handshake_packet.threadId;
         byte[] token = MakeToken(config.password,
            GetScrollbleBuffer(handshake_packet.scrambleBuff1, handshake_packet.scrambleBuff2));
         _writer.IncrementPacketNumber();
         //----------------------------
         //send authen packet to the server
         var authPacket = new ClientAuthenticationPacket(new PacketHeader());
         authPacket.SetValues(config.user, token, config.database, isProtocol41 = handshake_packet.protocol41);
         authPacket.WritePacket(_writer);
         byte[] sendBuff = _writer.ToArray();
         _writer.Reset();
         //------------------------------------
         //switch to result packet parser  
         _mysqlParserMx.SetProtocol41(isProtocol41);
         _mysqlParserMx.UseResultParser();
         //------------------------------------
         StartSend(sendBuff, 0, sendBuff.Length, () =>
         {
             StartReceive(mysql_result2 =>
             {
                 var ok = mysql_result2 as MySqlOkResult;
                 if (ok != null)
                 {
                     this._workingState = WorkingState.Rest;
                 }
                 else
                 {
                     //TODO: review here
                     //error  
                     _workingState = WorkingState.Error;
                 }
                 //set max allow of the server ***
                 //todo set max allow packet***
                 UnWait();
                 if (nextAction != null)
                 {
                     nextAction();
                 }
             });
         });
     });
     if (nextAction == null)
     {
         //block ....
         Wait();
     }
     else
     {
         UnWait();
     }
 }
        void HandleReceive(RecvEventCode recvEventCode)
        {
            switch (recvEventCode)
            {
                default: throw new NotSupportedException();
                case RecvEventCode.SocketError:
                    {
                        UnBindSocket(true);
                    }
                    break;
                case RecvEventCode.NoMoreReceiveData:
                    {
                    }
                    break;
                case RecvEventCode.HasSomeData:
                    {
                        //process some data
                        //there some data to process  
                        //parse the data    
#if DEBUG
                        if (dbugPleaseBreak)
                        {
                        }
#endif

                        bool needMoreData = _mysqlParserMx.ParseData(recvIO);
                        //please note that: result packet may not ready in first round
                        //but parser mx may 'release' some part of the result (eg. large table)
                        MySqlResult result = _mysqlParserMx.ParseResult; //'release' result 
                        //---------------------------------------------------------------
                        if (result != null)
                        {
                            //if we has some 'release' result from parser mx
                            if (needMoreData)
                            {
                                //this is 'partial result'
                                if (whenRecvData == null)
                                {
                                    //?
                                }
                                //-------------------------
                                //partial release data here
                                //before recv next
                                //because we want to 'sync'
                                //the series of result
                                whenRecvData(result);
                                //-------------------------
                            }
                            else
                            {
                                //when recv complete***
                                Action<MySqlResult> tmpWhenRecvData = whenRecvData;
                                //delete recv handle **before** invoke it, and
                                //reset state to 'rest' state
                                this.whenRecvData = null;
                                this._workingState = WorkingState.Rest;
                                tmpWhenRecvData(result);
                            }
                        }
                        //--------------------------
                        if (needMoreData)
                        {
                            //so if it need more data then start receive next
                            recvIO.StartReceive();//***
                        }
                        else
                        {

                        }
                        //--------------------------
                    }
                    break;
            }
        }
        void HandleSend(SendIOEventCode sendEventCode)
        {
            //throw new NotImplementedException();
            switch (sendEventCode)
            {
                case SendIOEventCode.SocketError:
                    {
                        UnBindSocket(true);
                    }
                    break;
                case SendIOEventCode.SendComplete:
                    {
                        //save when send complete here
                        Action tmpWhenSendComplete = whenSendCompleted;
                        //clear handler
                        whenSendCompleted = null;
                        _workingState = WorkingState.Rest;
                        if (tmpWhenSendComplete != null)
                        {
                            //just invoke it
                            tmpWhenSendComplete();
                        }

                    }
                    break;
            }
        }
 /// <summary>
 /// close conncetion, +/- blocking
 /// </summary>
 /// <param name="nextAction"></param>
 public void Disconnect(Action nextAction = null)
 {
     _writer.Reset();
     ComQuitPacket quitPacket = new ComQuitPacket(new PacketHeader());
     quitPacket.WritePacket(_writer);
     byte[] data = _writer.ToArray();
     //-------------------------------------
     InitWait();
     StartSend(data, 0, data.Length, () =>
     {
         socket.Shutdown(SocketShutdown.Both);
         _workingState = WorkingState.Disconnected;
         UnWait();
         if (nextAction != null)
         {
             nextAction();
         }
     });
     if (nextAction == null)
     {
         Wait(); //block
     }
     else
     {
         UnWait();
     }
 }
        public void StartSend(byte[] sendBuffer, int start, int len, Action whenSendCompleted)
        {
            //must be in opened state
            if (_workingState != WorkingState.Rest)
            {
                throw new Exception("sending error: state is not= opened");
            }
            //--------------------------------------------------------------
#if DEBUG
            if (this.whenSendCompleted != null)
            {
                //must be null 
                throw new Exception("sending something?...");
            }
#endif
            this.whenSendCompleted = whenSendCompleted;
            this._workingState = WorkingState.Sending;
            sendIO.EnqueueOutputData(sendBuffer, len);
            sendIO.StartSendAsync();
        }
        public void StartReceive(Action<MySqlResult> whenCompleteAction)
        {

            //must be in opened state
            if (_workingState != WorkingState.Rest)
            {
                throw new Exception("sending error: state is not= opened");
            }
            //--------------------------------------------------------------
#if DEBUG
            if (this.whenRecvData != null)
            {
                //must be null 
                throw new Exception("receving something?...");
            }
#endif
            this.whenRecvData = whenCompleteAction;
            this._workingState = WorkingState.Receiving;
            recvIO.StartReceive();
        }
Example #37
0
        private bool WorkDirectMessageCore()
        {
            try
            {
                try
                {
                    var match = RegularExpressions.DirectMessageSendRegex.Match(body);
                    if (!match.Success)
                        throw new InvalidOperationException("アサーション失敗(DM-postcheck)");
                    String target = match.Groups[1].Value;
                    body = match.Groups[2].Value;
                    // build text

                    // attach image
                    if (!String.IsNullOrEmpty(this.attachImagePath))
                    {
                        if (File.Exists(this.attachImagePath))
                        {
                            try
                            {
                                var upl = UploaderManager.GetSuggestedUploader();
                                if (upl == null)
                                    throw new InvalidOperationException("画像のアップローダ―が指定されていません。");
                                body += " " + upl.UploadImage(this.accountInfo, this.attachImagePath, this.body);
                            }
                            catch (Exception e)
                            {
                                throw new WebException("画像のアップロードに失敗しました。", e);
                            }
                        }
                        else
                        {
                            throw new FileNotFoundException("添付ファイルが見つかりません。");
                        }
                    }

                    if (TweetTextCounter.Count(body) > TwitterDefine.TweetMaxLength)
                    {
                        if (Setting.Instance.InputExperienceProperty.TrimExceedChars)
                        {
                            while (TweetTextCounter.Count(body) > TwitterDefine.TweetMaxLength)
                            {
                                body = body.Substring(0, body.Length - 1);
                            }
                        }
                        else
                        {
                            throw new Exception("ツイートが140文字を超えました。");
                        }
                    }

                    this.TweetSummary = body;

                    PostOffice.UpdateDirectMessage(this.accountInfo, target, body);

                    this.WorkingState = InputBlock.WorkingState.Updated;

                    return true;
                }
                catch (TweetFailedException tfex)
                {
                    var acc = AccountStorage.Get(this.accountInfo.AccountProperty.FallbackAccount);
                    if (tfex.ErrorKind != TweetFailedException.TweetErrorKind.Controlled ||
                        acc == null)
                    {
                        throw;
                    }
                    else
                    {
                        // fallbacking
                        WorkerAddRequired(new TweetWorker(this.parent, acc, this.body, this.inReplyToId, this.attachImagePath, this.tags));
                        throw new TweetAnnotationException(TweetAnnotationException.AnnotationKind.Fallbacked);
                    }
                }
            }
            catch (Exception ex)
            {
                this.WorkingState = ex is TweetAnnotationException ? InputBlock.WorkingState.Annotated : InputBlock.WorkingState.Failed;
                this.ExceptionString = ex.ToString();
                ParseFailException(ex);
                this.RecentPostCount = -1;
                return this.WorkingState == InputBlock.WorkingState.Annotated;
            }
        }
Example #38
0
        private bool WorkCore()
        {
            try
            {
                try
                {
                    // build text

                    // attach image
                    if (!String.IsNullOrEmpty(this.attachImagePath))
                    {
                        if (File.Exists(this.attachImagePath))
                        {
                            try
                            {
                                var upl = UploaderManager.GetSuggestedUploader();
                                if (upl == null)
                                    throw new InvalidOperationException("画像のアップローダ―が指定されていません。");
                                body += " " + upl.UploadImage(this.accountInfo, this.attachImagePath, this.body);
                            }
                            catch (Exception e)
                            {
                                throw new WebException("画像のアップロードに失敗しました。", e);
                            }
                        }
                        else
                        {
                            throw new FileNotFoundException("添付ファイルが見つかりません。");
                        }
                    }

                    if (TweetTextCounter.Count(body) > TwitterDefine.TweetMaxLength)
                    {
                        if (Setting.Instance.InputExperienceProperty.TrimExceedChars)
                        {
                            while (TweetTextCounter.Count(body) > TwitterDefine.TweetMaxLength)
                            {
                                body = body.Substring(0, body.Length - 1);
                            }
                        }
                        else
                        {
                            throw new Exception("ツイートが140文字を超えました。");
                        }
                    }

                    // is Unoffocial RT
                    bool isQuoting = false;
                    string quoteBody = String.Empty;
                    // split "unofficial RT"
                    var quoteindex = -1;

                    var rtidx = body.IndexOf("RT @");
                    if (rtidx >= 0)
                        quoteindex = rtidx;

                    var qtidx = body.IndexOf("QT @");
                    if (qtidx >= 0 && (quoteindex == -1 || qtidx < quoteindex))
                        quoteindex = qtidx;

                    if (quoteindex >= 0)
                    {
                        isQuoting = true;
                        quoteBody = body.Substring(quoteindex);
                        body = body.Substring(0, quoteindex);
                    }

                    // add footer (when is in not "unofficial RT")
                    if (!isQuoting &&
                        !String.IsNullOrEmpty(accountInfo.AccountProperty.FooterString) &&
                        TweetTextCounter.Count(body) + TweetTextCounter.Count(accountInfo.AccountProperty.FooterString) + 1 <= TwitterDefine.TweetMaxLength)
                        body += " " + accountInfo.AccountProperty.FooterString;

                    // bind tag
                    if (tags != null && tags.Count() > 0)
                    {
                        foreach (var tag in tags.Select(t => t.StartsWith("#") ? t : "#" + t))
                        {
                            if (TweetTextCounter.Count(body) + TweetTextCounter.Count(quoteBody) +  tag.Length + 1 <= TwitterDefine.TweetMaxLength)
                                body += " " + tag;
                        }
                        if (isQuoting)
                            body += " ";
                    }

                    // join quote
                    body += quoteBody;

                    this.TweetSummary = body;

                    // ready

                    if (this.inReplyToId != 0)
                        this.RecentPostCount = PostOffice.UpdateTweet(this.accountInfo, body, this.inReplyToId);
                    else
                        this.RecentPostCount = PostOffice.UpdateTweet(this.accountInfo, body);

                    this.WorkingState = InputBlock.WorkingState.Updated;

                    return true;
                }
                catch (TweetFailedException tfex)
                {
                    var acc = AccountStorage.Get(this.accountInfo.AccountProperty.FallbackAccount);
                    if (tfex.ErrorKind != TweetFailedException.TweetErrorKind.Controlled ||
                        acc == null)
                    {
                        throw;
                    }
                    else
                    {
                        // fallbacking
                        WorkerAddRequired(new TweetWorker(this.parent, acc, this.body, this.inReplyToId, this.attachImagePath, this.tags));
                        throw new TweetAnnotationException(TweetAnnotationException.AnnotationKind.Fallbacked);
                    }
                }
            }
            catch (Exception ex)
            {
                this.WorkingState = ex is TweetAnnotationException ? InputBlock.WorkingState.Annotated : InputBlock.WorkingState.Failed;
                this.ExceptionString = ex.ToString();
                ParseFailException(ex);
                this.RecentPostCount = -1;
                return this.WorkingState == InputBlock.WorkingState.Annotated;
            }
        }
Example #39
0
 public Task<bool> DoWork()
 {
     this.WorkingState = InputBlock.WorkingState.Updating;
     if (RegularExpressions.DirectMessageSendRegex.IsMatch(body))
     {
         return Task.Factory.StartNew(() => WorkDirectMessageCore());
     }
     else
     {
         return Task.Factory.StartNew(() => WorkCore());
     }
 }
Example #40
0
        private bool WorkDirectMessageCore()
        {
            string originalBody = body; // 元の投稿文を取っておく
            try
            {
                var pmatch = RegularExpressions.DirectMessageSendRegex.Match(body);
                if (!pmatch.Success)
                    throw new InvalidOperationException("プレチェック失敗(DM-precheck)");
                // build text

                // attach image
                if (!String.IsNullOrEmpty(this.attachImagePath) && !isImageAttached)
                {
                    if (File.Exists(this.attachImagePath))
                    {
                        try
                        {
                            var upl = UploaderManager.GetSuggestedUploader();
                            if (upl == null)
                                throw new InvalidOperationException("画像のアップローダ―が指定されていません。");
                            body += " " + upl.UploadImage(this.accountInfo, this.attachImagePath, this.body);
                            isImageAttached = true;
                        }
                        catch (Exception e)
                        {
                            throw new WebException("画像のアップロードに失敗しました。", e);
                        }
                    }
                    else
                    {
                        throw new FileNotFoundException("添付ファイルが見つかりません。");
                    }
                }

                // generate body string
                var match = RegularExpressions.DirectMessageSendRegex.Match(body);
                if (!match.Success)
                    throw new InvalidOperationException("ポストアサーション失敗(DM-postcheck)");
                String target = pmatch.Groups[1].Value;
                body = pmatch.Groups[2].Value;

                if (TweetTextCounter.Count(body) > TwitterDefine.TweetMaxLength)
                {
                    if (Setting.Instance.InputExperienceProperty.TrimExceedChars)
                    {
                        while (TweetTextCounter.Count(body) > TwitterDefine.TweetMaxLength)
                        {
                            body = body.Substring(0, body.Length - 1);
                        }
                    }
                    else
                    {
                        throw new Exception("ツイートが140文字を超えました。");
                    }
                }

                this.TweetSummary = body;

                PostOffice.UpdateDirectMessage(this.accountInfo, target, body);

                this.WorkingState = InputBlock.WorkingState.Updated;

                return true;
            }
            catch (Exception ex)
            {
                body = originalBody; // 元に戻しておく
                this.TweetSummary = originalBody;
                this.WorkingState = ex is TweetAnnotationException ? InputBlock.WorkingState.Annotated : InputBlock.WorkingState.Failed;
                this.ExceptionString = ex.ToString();
                ParseFailException(ex);
                this.RecentPostCount = -1;
                return this.WorkingState == InputBlock.WorkingState.Annotated;
            }
        }