Beispiel #1
0
        public void OnMessageReceived(Action <dynamic>[] actions, string customer)
        {
            this.MessageReceived += (message, client) =>
            {
                LastActiveTime = DateTime.Now;
                if (string.IsNullOrWhiteSpace(message))
                {
                    return;
                }

                if (message.Contains("keep") && message.Contains("alive"))
                {
                    if (DateTime.Now > lastKeepaliveWriteTime.AddMinutes(15))
                    {
                        LogUnit?.LogInformation($"Websocket Event: {message}");
                        lastKeepaliveWriteTime = DateTime.Now;
                    }
                }
                else
                {
                    LogUnit?.LogInformation($"Websocket Event: {message}");
                }

                if (actions == null)
                {
                    return;
                }

                foreach (var action in actions)
                {
                    action?.Invoke(Newtonsoft.Json.JsonConvert.DeserializeObject <dynamic>(message));
                }
            };
        }
Beispiel #2
0
        private void lbInfo_Click(object sender, EventArgs e)
        {
            if (lbInfo.SelectedIndex == -1)
            {
                return;
            }
            LogUnit  logUnit  = (LogUnit)updateService.GetLog()[lbInfo.SelectedIndex];
            Film     film     = logUnit.film;
            FilmInfo filmInfo = logUnit.filmInfo;

            tbRussianTitle.Text  = film.russianTitle;
            tbOriginalTitle.Text = film.originalTitle;
            tbYear.Text          = film.year;
            tbCountry.Text       = film.country;
            tbGenre.Text         = film.genre;
            tbDirector.Text      = film.director;
            rtbActors.Text       = film.actors;
            tbWorldDate.Text     = film.worldDate;
            tbRussianDate.Text   = film.russianDate;
            tbDiscDate.Text      = film.discDate;
            tbRusTitle.Text      = filmInfo.russianTitle;
            tbOrigTitle.Text     = filmInfo.originalTitle;
            tbY.Text             = filmInfo.year;
            tbC.Text             = filmInfo.country;
            tbG.Text             = filmInfo.genre;
            tbD.Text             = filmInfo.director;
            rtbA.Text            = filmInfo.actors;
            tbWDate.Text         = filmInfo.worldPremiere;
            tbRDate.Text         = filmInfo.russianPremiere;
            tbDDate.Text         = filmInfo.discPremiere;
        }
Beispiel #3
0
        void DoMyWindow(int windowID)
        {
            int RealHight = mBtRealHight;

            GUI.contentColor = Color.white;
            GUI.DragWindow(new Rect(0, 0, mBtWidget, RealHight * 2 + 20));

            GUI.skin.box.alignment   = TextAnchor.MiddleLeft;
            GUI.skin.button.fontSize = mBtWidget / 7;
            GUI.skin.label.fontSize  = mBtWidget / 6;
            GUI.skin.box.fontSize    = mBtWidget / 7;
            //GUILayout.Label
            GUI.Box(new Rect(5, 20, mBtWidget, RealHight), mGuiFPSTex);
            //GUI.Box(new Rect(5, 20 + mBtHight, mBtWidget, RealHight), mGuiCPUTex);
            //GUI.Box(new Rect(5, 20 + mBtHight * 2, mBtWidget, RealHight), mGuiMoTex);

            for (int i = 0; i < mLogBufs.Count; i++)
            {
                LogUnit lu = mLogBufs[i];
                GUI.contentColor = lu.color;
                GUI.Label(new Rect(5 + mBtWidget / 3 * i, 20 + mBtHight, mBtWidget, RealHight), "(" + lu.mLogInfos.Count.ToString("00") + ")");
            }
            GUI.contentColor = Color.white;
            if (GUI.Button(new Rect(5, 20 + mBtHight * 2, mBtWidget / 2, RealHight), "关闭"))
            {
                CloseLog();
            }
            if (GUI.Button(new Rect(5 + mBtWidget / 2, 20 + mBtHight * 2, mBtWidget / 2, RealHight), "展开"))
            {
                mIsScale = false;
            }
        }
Beispiel #4
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="unit">Unit.</param>
        public LogUnitNode(LogUnit unit)
        {
            if (unit == null)
            {
                throw new ArgumentNullException("unit");
            }

            Unit = unit;
        }
Beispiel #5
0
 void ShowListLog(int index)
 {
     mSelectLogUnity = mLogBufs[index];
     mhSbarValue     = 0;
     mhSbarSize      = 0;
     mDetailInfo     = null;
     mPauseLogInfo   = null;
     mScrollPosition = Vector2.zero;
 }
Beispiel #6
0
        /// <summary>
        /// Select the text that corresponds to the given unit.
        /// </summary>
        /// <param name="unit">The unit to select the text for.</param>
        public void SelectText(LogUnit unit)
        {
            if (unit == null)
            {
                throw new ArgumentNullException("unit");
            }

            View.SelectLine(unit.LineNumber);
        }
Beispiel #7
0
        private void btnItemClear_Click(object sender, RoutedEventArgs e)
        {
            if (lineDataGrid.SelectedItems != null)
            {
                LogUnit startUnit = lineDataGrid.SelectedItems[0] as LogUnit;
                LogUnit endUnit   = lineDataGrid.SelectedItems[lineDataGrid.SelectedItems.Count - 1] as LogUnit;

                logUnitViewModel.SelectedClear(startUnit, endUnit);
            }
        }
Beispiel #8
0
        private void RegLog(string keyName, List <LogInfo> log, Rect rt, Color c)
        {
            LogUnit lu = new LogUnit();

            lu.keyName   = keyName;
            lu.mLogInfos = log;
            lu.mRect     = rt;
            lu.color     = c;
            mLogBufs.Add(lu);
        }
Beispiel #9
0
        /// <summary>
        /// 建立请求,以模拟远程HTTP的POST请求方式构造并获取支付宝的处理结果
        /// </summary>
        /// <param name="sParaTemp">请求参数数组</param>
        /// <returns>支付宝处理结果</returns>
        public static string BuildRequest(SortedDictionary <string, string> sParaTemp)
        {
            Encoding code = Encoding.GetEncoding(_input_charset);

            //待请求参数数组字符串
            string strRequestData = BuildRequestParaToString(sParaTemp, code);

            LogUnit.Write("请求入参:" + strRequestData);
            //把数组转换成流中所需字节数组类型
            byte[] bytesRequestData = code.GetBytes(strRequestData);

            //构造请求地址
            string strUrl = GATEWAY_NEW + "_input_charset=" + _input_charset;

            //请求远程HTTP
            string strResult = "";

            try
            {
                //设置HttpWebRequest基本信息
                HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strUrl);
                myReq.Method      = "post";
                myReq.ContentType = "application/x-www-form-urlencoded";

                //填充POST数据
                myReq.ContentLength = bytesRequestData.Length;
                Stream requestStream = myReq.GetRequestStream();
                requestStream.Write(bytesRequestData, 0, bytesRequestData.Length);
                requestStream.Close();

                //发送POST数据请求服务器
                HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
                Stream          myStream  = HttpWResp.GetResponseStream();

                //获取服务器返回信息
                StreamReader  reader       = new StreamReader(myStream, code);
                StringBuilder responseData = new StringBuilder();
                String        line;
                while ((line = reader.ReadLine()) != null)
                {
                    responseData.Append(line);
                }

                //释放
                myStream.Close();

                strResult = responseData.ToString();
            }
            catch (Exception exp)
            {
                strResult = "报错:" + exp.Message;
            }
            LogUnit.Write("请求出参:" + strResult);
            return(strResult);
        }
Beispiel #10
0
        private void btnEnter_Click(object sender, EventArgs e)
        {
            if (lbInfo.SelectedIndex == -1)
            {
                return;
            }
            LogUnit logUnit = (LogUnit)updateService.GetLog()[lbInfo.SelectedIndex];
            Film    film    = logUnit.film;
            int     index   = films.GetFilmIndex(film);

            if (index == -1)
            {
                MessageBox.Show(@"Данный фильм не найден в базе!");
                return;
            }
            film.russianTitle  = tbRusTitle.Text;
            film.originalTitle = tbOrigTitle.Text;
            film.year          = tbY.Text;
            film.country       = tbC.Text;
            film.genre         = tbG.Text;
            film.director      = tbD.Text;
            film.actors        = rtbA.Text;
            film.worldDate     = tbWDate.Text;
            film.russianDate   = tbRDate.Text;
            film.discDate      = tbDDate.Text;
            film.dataCheck     = DateTime.Now.ToString();
            films.Edit(film, index);
            updateService.GetLog().RemoveAt(lbInfo.SelectedIndex);
            frMain.UpdateEvent();
            frMain.FilmUpdateEvent(index);
            lbInfo.Items.RemoveAt(lbInfo.SelectedIndex);
            tbRussianTitle.Clear();
            tbOriginalTitle.Clear();
            tbYear.Clear();
            tbCountry.Clear();
            tbGenre.Clear();
            tbDirector.Clear();
            rtbActors.Clear();
            tbWorldDate.Clear();
            tbRussianDate.Clear();
            tbDiscDate.Clear();
            tbRusTitle.Clear();
            tbOrigTitle.Clear();
            tbY.Clear();
            tbC.Clear();
            tbG.Clear();
            tbD.Clear();
            rtbA.Clear();
            tbWDate.Clear();
            tbRDate.Clear();
            tbDDate.Clear();
        }
Beispiel #11
0
        public async Task <string> OnFirstEvent(string customer, CancellationToken token)
        {
            waitFirstEvent        = new EventWaitHandle(false, EventResetMode.ManualReset);
            this.MessageReceived += WebSocket_FirstEvent;
            if (await OpenWebSocket(token))
            {
                if (waitFirstEvent.WaitOne(2000))
                {
                    LogUnit?.LogInformation($"Websocket Subscribe: {firstEvent}");
                    this.MessageReceived -= WebSocket_FirstEvent;
                    return(firstEvent);
                }
            }

            throw new TimeoutException("WebSocket timed out after 2 seconds waiting for subscription event.");
        }
Beispiel #12
0
        private void WriteToHistory(string message, LogType type)
        {
            if (_deviceInfoService.IsIgorPhone)
            {
                if (IsDuplicateMessages(message))
                {
                    _lastLogUnit.DuplicateMessagesCounter++;
                    _lastLogUnit.Date = DateTime.UtcNow;
                    return;
                }

                var logUnit = new LogUnit {
                    Message = message, Type = type
                };
                _lastLogUnit = logUnit;
                _history.Add(logUnit);
            }
        }
Beispiel #13
0
 private void DoPrintLogCache()
 {
     if (!Debug.get_logger().get_logEnabled())
     {
         return;
     }
     if (this.IsOutputLock)
     {
         return;
     }
     DebugUIView.LogString = string.Empty;
     LogUnit[] array = RemoteLogSender.Instance.LogCacheUnits.ToArray();
     for (int i = 0; i < array.Length; i++)
     {
         LogUnit logUnit = array[i];
         DebugUIView.AddToLogString(logUnit.logString, logUnit.stackTrace, logUnit.logType);
     }
     this.SetOutput(DebugUIView.LogString);
 }
Beispiel #14
0
        public void LogError(string message, Exception exception = null, string fileName = "")
        {
            LogUnit logUnit = new LogUnit
            {
                Moment = DateTime.Now,
                Head   = message,
                Author = _user
            };

            if (exception != null)
            {
                logUnit.Head    = exception.GetType().Name;
                logUnit.Message = exception.PrintAllExceptions();
                while (exception != null)
                {
                    logUnit.Head = exception.GetType().ToString();
                    exception    = exception.InnerException;
                }
            }

            _unitOfWork.SaveEntity(logUnit);
        }
Beispiel #15
0
    private static void onThreadLogHandler()
    {
        while (LogEnable)
        {
            _autoResetEvent.WaitOne();//等待信号(开启绿灯)
            try
            {
                while (_logWaitingQueue.Count > 0)
                {
                    StringBuilder stringBuilder = GetStringBuilder();
                    LogUnit       logUnit       = _logWaitingQueue.Dequeue();
                    LogFormat(ref stringBuilder, logUnit.LogLevel, logUnit.Log.TrimStart(), logUnit.StackTrace, logUnit.Timer.ToString(TIME_FORMAT_HMSF));
                    WriteToLocalTxt(stringBuilder.ToString(), null);
                }
            }
            catch (System.Exception)
            {
                throw;
            }

            _autoResetEvent.Reset();//开启红灯
            Thread.Sleep(1);
        }
    }
Beispiel #16
0
    public static void WriteLog(LogUnit logUnit)
    {
#if DEBUG_LOG || LOG_ONLY_EXCEPTION || UNITY_EDITOR
        if (!LogEnable)
        {
            return;
        }
        if (string.IsNullOrEmpty(logUnit.Log))
        {
            return;
        }
#if !CSHARP_LOGIC
        if (_limitOutputType != eLogOutputType.Txt && (logUnit.OutputType == eLogOutputType.Debug || logUnit.OutputType == eLogOutputType.All))
        {
            StringBuilder stringBuilder = GetStringBuilder();
            if (logUnit.Color != eLogColor.Default)
            {
                stringBuilder.Append("<color=#");
                stringBuilder.Append(LogColor[(int)logUnit.Color]);
                stringBuilder.Append(">");
            }

#if !UNITY_2019_1_OR_NEWER
            stringBuilder.Append("[");
            stringBuilder.Append(logUnit.Timer.ToString(TIME_FORMAT_HMSF));
            stringBuilder.Append("] ");
#else
            stringBuilder.Append("[");
            stringBuilder.Append(logUnit.Timer.ToString("fff"));
            stringBuilder.Append("] ");
#endif

            if (logUnit.Color != eLogColor.Default)
            {
                StringBuilder temp = GetStringBuilder();
                temp.Append("\r</color><color=#");
                temp.Append(LogColor[(int)logUnit.Color]);
                temp.Append(">");
                stringBuilder.Append(logUnit.Log.Replace("\r", temp.ToString()));
                if (!string.IsNullOrEmpty(logUnit.StackTrace))
                {
                    stringBuilder.AppendLine();
                    stringBuilder.Append(logUnit.StackTrace.Replace("\r", temp.ToString()));
                }
                stringBuilder.Append("</color>");
            }
            else
            {
                stringBuilder.Append(logUnit.Log);
                if (!string.IsNullOrEmpty(logUnit.StackTrace))
                {
                    stringBuilder.AppendLine();
                    stringBuilder.Append(logUnit.StackTrace);
                }
            }

            switch (logUnit.LogLevel)
            {
            case eLogLevel.Log:
                UnityEngine.Debug.Log(stringBuilder.ToString());
                break;

            case eLogLevel.Warning:
                UnityEngine.Debug.LogWarning(stringBuilder.ToString());
                break;

            case eLogLevel.Error:
                UnityEngine.Debug.LogError(stringBuilder.ToString());
                break;

            case eLogLevel.Exception:
                UnityEngine.Debug.LogError(stringBuilder.ToString());
                break;
            }
        }
#endif

        if (logUnit.OutputType == eLogOutputType.Debug)
        {
            return;
        }

        _logWaitingQueue.Enqueue(logUnit);
        _autoResetEvent.Set();//开启绿灯
#endif
    }
Beispiel #17
0
        public async Task CreateWebSocket(string uri, string customer, TimeSpan expire,
                                          Action openAction              = null,
                                          Action closeAction             = null,
                                          Action <Exception> errorAction = null,
                                          Action renewAction             = null,
                                          bool keepAliveEnabled          = false, TimeSpan?keepAliveInterval = null,
                                          List <KeyValuePair <string, string> > header = null)
        {
            if (WebSocket?.State == System.Net.WebSockets.WebSocketState.Open)
            {
                return;
            }

            this.uri = new Uri(uri);

            await CloseWebSocket(CancellationToken.None);

            WebSocket = new ClientWebSocket();

            if (header != null)
            {
                foreach (var h in header)
                {
                    WebSocket.Options.SetRequestHeader(h.Key, h.Value);
                }
            }

            if (keepAliveEnabled && keepAliveInterval.HasValue)
            {
                WebSocket.Options.KeepAliveInterval = keepAliveInterval.Value;
            }

            //WebSocket.EnableAutoSendPing = keepAliveEnabled;
            //WebSocket.AutoSendPingInterval = (int)keepAliveInterval?.TotalSeconds;

            this.Opened = (client) => {
                if (client.WebSocket.State == System.Net.WebSockets.WebSocketState.Open)
                {
                    LogUnit?.LogInformation($"Websocket Opened");
                    openAction?.Invoke();
                    Task.Factory.StartNew(async() =>
                    {
                        bool done = false;
                        while (!done)
                        {
                            await Task.Delay(expire, cancelSource.Token);

                            if (cancelSource.IsCancellationRequested)
                            {
                                done = true;
                                LogUnit?.LogInformation($"Websocket Expire - Cancelled");
                            }
                            else if (IsWebSocketOpen)
                            {
                                if (keepAliveEnabled && client.LastActiveTime < DateTime.Now.Subtract(keepAliveInterval.Value.Add(keepAliveInterval.Value).Add(keepAliveInterval.Value)))
                                {
                                    done = true;
                                    LogUnit?.LogInformation($"Websocket Expire - Closing");
                                    await client?.CloseWebSocket(CancellationToken.None);
                                }
                                else
                                {
                                    renewAction?.Invoke();
                                }
                            }
                            else
                            {
                                done = true;
                                LogUnit?.LogInformation($"Websocket Expire - Not Open");
                            }
                        }
                    }, cancelSource.Token);

                    StartListen(cancelSource.Token);
                }
            };

            this.Closed = (client) =>
            {
                cancelSource.Cancel();
                LogUnit?.LogInformation($"Websocket Closed");
                closeAction?.Invoke();
            };

            this.Error = (client, e) =>
            {
                cancelSource.Cancel();
                LogUnit?.LogError($"Websocket Error", e);
                errorAction?.Invoke(e);
            };

            CancellationToken token = new CancellationToken();
            await WebSocket.ConnectAsync(this.uri, token);

            this.Opened(this);
            OnOpen?.Invoke(this, null);
        }
Beispiel #18
0
        void OnGUIEx()
        {
            GUI.skin.box.alignment   = TextAnchor.MiddleLeft;
            GUI.skin.button.fontSize = mBtWidget / 7;
            GUI.skin.label.fontSize  = mBtWidget / 6;
            GUI.skin.box.fontSize    = mBtWidget / 7;
            //GUILayout.Label()
            GUI.Box(new Rect(Screen.width - mBtWidget - 10, 10, mBtWidget, mBtRealHight), mGuiFPSTex);
            GUI.Box(new Rect(Screen.width - mBtWidget - 10, 10 + mBtHight, mBtWidget, mBtRealHight), mGuiCPUTex);
            GUI.Box(new Rect(Screen.width - mBtWidget - 10, 10 + mBtHight * 2, mBtWidget, mBtRealHight), mGuiMoTex);
            if (mIsScale)
            {
                if (GUI.Button(new Rect(10, 10, mBtWidget, mBtRealHight), "展开(↓↓)"))
                {
                    mIsScale = false;
                }
                return;
            }
            if (GUI.Button(new Rect(10, 10 + mBtHight * 3, mBtWidget, mBtRealHight), "收起(↑↑)"))
            {
                mIsScale = true;
            }


            GUI.contentColor = Color.white;
            for (int i = 0; i < mLogBufs.Count; i++)
            {
                LogUnit lu = mLogBufs[i];
                GUI.contentColor = lu.color;
                if (GUI.Button(lu.mRect, lu.keyName + "(" + lu.mLogInfos.Count + ")"))
                {
                    mSelectLogUnity = lu;
                    mhSbarValue     = 0;
                    mhSbarSize      = 0;
                    mDetailInfo     = null;
                    mPauseLogInfo   = null;
                    mScrollPosition = Vector2.zero;
                }
            }

            if (mDetailInfo != null)
            {
                GUI.Box(new Rect(mBtWidget + 20, 10 + mBtHight, (int)(mBtWidget * 4.5 * mButtonDp), mBtHight * 10), "");
                GUILayout.BeginArea(new Rect(mBtWidget + 20, 10 + mBtHight, (int)(mBtWidget * 4.5 * mButtonDp), mBtHight * 10));
                mScrollPosition  = GUILayout.BeginScrollView(mScrollPosition, GUILayout.Width((int)(mBtWidget * 4.5 * mButtonDp)), GUILayout.Height(mBtHight * 10));
                GUI.contentColor = GetColor(mDetailInfo.logType);
                GUILayout.Label("打印信息: \n" + mDetailInfo.logName + "\n\n堆栈信息:\n" + mDetailInfo.logStack);
                GUILayout.EndScrollView();
                GUILayout.EndArea();
                GUI.contentColor = GetColor(mDetailInfo.logType);
                if (GUI.Button(new Rect(mBtWidget + 20, 10, (int)(mBtWidget * 4.5 * mButtonDp), mBtRealHight), mDetailInfo.logName))
                {
                    mDetailInfo = null;
                }
            }
            else if (mSelectLogUnity != null)
            {
                List <LogInfo> infos   = mPauseLogInfo != null ? mPauseLogInfo : mSelectLogUnity.mLogInfos;
                int            logCout = infos.Count;

                int curYe = 0;
                if (logCout > 10)
                {
                    float bb = mhSbarValue / (1 - mhSbarSize);;
                    mhSbarSize  = 10 / (float)logCout;
                    curYe       = (int)((logCout - 10) / (1 - mhSbarSize) * mhSbarValue);
                    mhSbarValue = (1 - mhSbarSize) * bb;
                    mhSbarValue = GUI.VerticalScrollbar(new Rect((int)(mBtWidget * 5.5 * mButtonDp) + 35, 10 + mBtHight, mBtWidget / 4, mBtHight * 10 - (mBtHight - mBtRealHight)), mhSbarValue, mhSbarSize, 0.0f, 1.0f);
                }

                int index = 0;
                for (int i = curYe; i < infos.Count && i < curYe + 10; i++)
                {
                    LogInfo li = infos[i];
                    GUI.contentColor = GetColor(li.logType);
                    if (GUI.Button(new Rect(mBtWidget + 20, 10 + mBtHight + mBtHight * index++, (int)(mBtWidget * 4.5 * mButtonDp), mBtRealHight), li.logName))
                    {
                        mDetailInfo = li;
                    }
                }

                GUI.contentColor = Color.white;
                if (mPauseLogInfo != null)
                {
                    GUI.contentColor = Color.blue;
                    if (GUI.Button(new Rect(mBtWidget + 20, 10, mBtWidget * 2 * mButtonDp, mBtRealHight), "开启日志"))
                    {
                        mPauseLogInfo = null;
                    }
                }
                else if (GUI.Button(new Rect(mBtWidget + 20, 10, mBtWidget * 2 * mButtonDp, mBtRealHight), "暂停日志"))
                {
                    mPauseLogInfo = new List <LogInfo>(mSelectLogUnity.mLogInfos.ToArray());
                }
                GUI.contentColor = Color.red;
                if (GUI.Button(new Rect(mBtWidget * 2 * mButtonDp + mBtWidget + 40, 10, mBtWidget * 2 * mButtonDp, mBtRealHight), "清空日志"))
                {
                    mSelectLogUnity.mLogInfos.Clear();
                    mPauseLogInfo = null;
                }
            }
        }
Beispiel #19
0
        public IActionResult NewLog(NewLogView model, IFormCollection form, ICollection <IFormFile> files)
        {
            PopulateLogViewModel(model);

            if (model.LogType == LogTypes.Work && String.IsNullOrWhiteSpace(form["nonUnitPersonnel"]))
            {
                model.ErrorMessage = "You need to specify at least 1 person to be part of the work log.";
                return(View(model));
            }

            try
            {
                try
                {
                    if (files != null && files.Any())
                    {
                        foreach (var file in files)
                        {
                            if (file != null && !String.IsNullOrWhiteSpace(file.FileName))
                            {
                                string extension = Path.GetExtension(file.FileName);

                                if (!String.IsNullOrWhiteSpace(extension))
                                {
                                    extension = extension.ToLower();
                                }

                                if (extension != ".jpg" && extension != ".jpeg" && extension != ".png" && extension != ".gif" && extension != ".pdf" &&
                                    extension != ".doc" && extension != ".docx" && extension != ".ppt" && extension != ".pptx" && extension != ".pps" &&
                                    extension != ".ppsx" && extension != ".odt" && extension != ".xls" && extension != ".xlsx" && extension != ".txt" && extension != ".rtf")
                                {
                                    model.ErrorMessage = string.Format("File type ({0}) is not importable.", extension);
                                }

                                if (file.Length > 10000000)
                                {
                                    model.ErrorMessage = "Document is too large, must be smaller then 10MB.";
                                }
                            }
                        }
                    }
                }
                catch { }

                if (!String.IsNullOrWhiteSpace(model.ErrorMessage))
                {
                    return(View(model));
                }

                // Get all unit blocks in the report
                List <int> unitsInReport = (from object key in form.Keys where key.ToString().StartsWith("unit_personnel_") select int.Parse(key.ToString().Replace("unit_personnel_", ""))).ToList();

                model.Log.LoggedByUserId = UserId;
                model.Log.DepartmentId   = model.Department.DepartmentId;
                model.Log.Narrative      = System.Net.WebUtility.HtmlDecode(model.Log.Narrative);
                model.Log.Cause          = System.Net.WebUtility.HtmlDecode(model.Log.Cause);
                model.Log.InitialReport  = System.Net.WebUtility.HtmlDecode(model.Log.InitialReport);
                model.Log.LogType        = (int)model.LogType;

                if (model.Log.StationGroupId == 0)
                {
                    model.Log.StationGroupId = null;
                }

                model.Log.Units = new Collection <LogUnit>();
                model.Log.Users = new Collection <LogUser>();

                if (String.IsNullOrWhiteSpace(model.Log.InvestigatedByUserId))
                {
                    model.Log.InvestigatedByUserId = null;
                }

                if (model.Log.StationGroupId.HasValue && model.Log.StationGroupId.Value == 0)
                {
                    model.Log.StationGroupId = null;
                }

                if (model.LogType == LogTypes.Run)
                {
                    if (model.CallId == 0)
                    {
                        model.Call.DepartmentId    = DepartmentId;
                        model.Call.ReportingUserId = UserId;
                        model.Call.Priority        = (int)model.CallPriority;

                        if (model.Call.Type == "No Type")
                        {
                            model.Call.Type = null;
                        }

                        model.Call          = _callsService.SaveCall(model.Call);
                        model.Log.CallId    = model.Call.CallId;
                        model.Log.StartedOn = model.Call.LoggedOn;
                    }
                    else
                    {
                        var call = _callsService.GetCallById(model.CallId);
                        call.Priority     = (int)model.CallPriority;
                        call.NatureOfCall = model.Call.NatureOfCall;
                        call.Address      = model.Call.Address;
                        call.LoggedOn     = model.Call.LoggedOn;
                        call.Name         = model.Call.Name;

                        model.Call       = _callsService.SaveCall(call);
                        model.Log.CallId = model.Call.CallId;
                    }
                }

                if (model.LogType == LogTypes.Work)
                {
                    var startedOn = form["Log.StartedOn"];
                    var endedOn   = form["Log.EndedOn"];

                    if (!String.IsNullOrWhiteSpace(startedOn))
                    {
                        model.Log.StartedOn = DateTime.Parse(startedOn);
                    }

                    if (!String.IsNullOrWhiteSpace(endedOn))
                    {
                        model.Log.EndedOn = DateTime.Parse(endedOn);
                    }
                }

                if (model.LogType == LogTypes.Meeting)
                {
                    var startedOn = form["Log.StartedOn"];
                    var endedOn   = form["Log.EndedOn"];

                    if (!String.IsNullOrWhiteSpace(startedOn))
                    {
                        model.Log.StartedOn = DateTime.Parse(startedOn);
                    }

                    if (!String.IsNullOrWhiteSpace(endedOn))
                    {
                        model.Log.EndedOn = DateTime.Parse(endedOn);
                    }
                }

                if (model.LogType == LogTypes.Coroner)
                {
                    var startedOn          = form["coronerDate"];
                    var caseNumber         = form["caseNumber"];
                    var coronerInstructors = form["coronerInstructors"];
                    var coronerDestination = form["coronerDestination"];
                    var coronerOthers      = form["coronerOthers"];

                    if (!String.IsNullOrWhiteSpace(startedOn))
                    {
                        model.Log.StartedOn = DateTime.Parse(startedOn);
                    }

                    if (!String.IsNullOrWhiteSpace(caseNumber))
                    {
                        model.Log.ExternalId = caseNumber;
                    }

                    if (!String.IsNullOrWhiteSpace(coronerInstructors))
                    {
                        model.Log.Instructors = coronerInstructors;
                    }

                    if (!String.IsNullOrWhiteSpace(coronerDestination))
                    {
                        model.Log.Location = coronerDestination;
                    }

                    if (!String.IsNullOrWhiteSpace(coronerOthers))
                    {
                        model.Log.OtherPersonnel = coronerOthers;
                    }
                }

                foreach (var i in unitsInReport)
                {
                    var unit = new LogUnit();
                    unit.UnitId = i;

                    if (!string.IsNullOrWhiteSpace(form["unit_dispatchtime_" + i]))
                    {
                        unit.Dispatched = DateTime.Parse(form["unit_dispatchtime_" + i]);
                    }

                    if (!string.IsNullOrWhiteSpace(form["unit_enroutetime_" + i]))
                    {
                        unit.Enroute = DateTime.Parse(form["unit_enroutetime_" + i]);
                    }

                    if (!string.IsNullOrWhiteSpace(form["unit_onscenetime_" + i]))
                    {
                        unit.OnScene = DateTime.Parse(form["unit_onscenetime_" + i]);
                    }

                    if (!string.IsNullOrWhiteSpace(form["unit_releasedtime_" + i]))
                    {
                        unit.Released = DateTime.Parse(form["unit_releasedtime_" + i]);
                    }

                    if (!string.IsNullOrWhiteSpace(form["unit_inquarterstime_" + i]))
                    {
                        unit.InQuarters = DateTime.Parse(form["unit_inquarterstime_" + i]);
                    }

                    model.Log.Units.Add(unit);

                    if (!string.IsNullOrWhiteSpace(form["unit_personnel_" + i]))
                    {
                        var personnelIds = form["unit_personnel_" + i].ToString().Split(char.Parse(","));

                        foreach (var personnelId in personnelIds)
                        {
                            var logUser = new LogUser();
                            logUser.UserId = personnelId;
                            logUser.UnitId = i;

                            model.Log.Users.Add(logUser);
                        }
                    }
                }

                if (!string.IsNullOrWhiteSpace(form["nonUnitPersonnel"]))
                {
                    var personnelIds = form["nonUnitPersonnel"].ToString().Split(char.Parse(","));

                    foreach (var personnelId in personnelIds)
                    {
                        var logUser = new LogUser();
                        logUser.UserId = personnelId;

                        model.Log.Users.Add(logUser);
                    }
                }

                var savedLog = _workLogsService.SaveLog(model.Log);

                try
                {
                    if (files != null)
                    {
                        foreach (var file in files)
                        {
                            if (file != null && file.Length > 0)
                            {
                                LogAttachment attachment = new LogAttachment();
                                attachment.LogId    = savedLog.LogId;
                                attachment.Type     = file.ContentType;
                                attachment.FileName = file.FileName;

                                byte[] uploadedFile = new byte[file.OpenReadStream().Length];
                                file.OpenReadStream().Read(uploadedFile, 0, uploadedFile.Length);

                                attachment.Data      = uploadedFile;
                                attachment.UserId    = UserId;
                                attachment.Timestamp = DateTime.UtcNow;

                                _workLogsService.SaveLogAttachment(attachment);
                            }
                        }
                    }
                }
                catch { }

                _eventAggregator.SendMessage <LogAddedEvent>(new LogAddedEvent()
                {
                    DepartmentId = DepartmentId, Log = model.Log
                });
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);

                model.ErrorMessage = "We encountered an error trying to save your log. Please check your form to ensure it's properly filled out and try again.";
                return(View(model));
            }

            return(RedirectToAction("Index"));
        }