public OperationResult<DetailedConfiguration> GetDetailedConfiguration()
        {
            OperationResult<DetailedConfiguration> opResult = new OperationResult<DetailedConfiguration>();
            var configOpResult = GetConfiguration();
            if (configOpResult.Success)
            {
                List<ConfigurationParameterDetail> details = new List<ConfigurationParameterDetail>();
                foreach (var param in configOpResult.Result.Parameters)
                {

                    var detailOpResult = _connectionManager.SendMessage<ConfigDetailResponseMessage>(new RequestMessageWithParam
                    {
                        MessageId = (int)MessageTypeId.ConfigurationGet,
                        Param = param.Name,
                    });

                    if (detailOpResult.Success)
                    {
                        details.Add(Helpers.GetParameterDetailFromMessage(detailOpResult.Result));
                        details.Last().Value = param.Value;
                    }
                    else
                    {
                        return opResult.SetFail(detailOpResult.ResultMessage);
                        //return OperationResult<List<ConfigParameterDetail>>.GetFail(detailOpResult.ResultMessage);
                    }
                }

                //return OperationResult<List<ConfigParameterDetail>>.GetSucces(details);
                return opResult.SetSucces(new DetailedConfiguration { Parameters = details });
            }

            return opResult.SetFail(configOpResult.ResultMessage);
            //return OperationResult<List<ConfigParameterDetail>>.GetFail(configOpResult.ResultMessage);
        }
		public void OnInit(OperationResult status)
		{
			if (status == OperationResult.Success) {
				speech.Speak(lastText, QueueMode.Flush, new Dictionary<string,string>());
				lastText = null;
			}
		}
        public IOperationResult Check(MutationContext context)
        {
            var result = new OperationResult();

              CheckNoClassesInheritFromRole(context, result);

              CheckNoInstancesAreCreatedForRole(context, result);

              CheckRoleDoesntComposeItself(result);

              CheckRoleDoesntImplementInterfacesExplicitly(result);

              CheckRoleHasNoPInvokeMethods(result);

              CheckRoleHasNoPlaceholders(result);

              /* TODO Checks:
            * a role can't be a struct
            * static members? right now it's being checked in the wrong class!
            * cannot have parameterized constructors - where is this being checked?
              * only a single parameterless constructor is supported
            * cannot have base classes (other than object), but can have base interfaces
            */

              return result;
        }
Example #4
0
        /// <summary>
        /// 获取文章详情
        /// </summary>
        /// <param name="articleId"></param>
        /// <returns></returns>
        public async Task<OperationResult<Article>> GetArticleInfo(string articleId)
        {
            FormData.Clear();

            FormData["articleid"] = articleId;

            var result = new OperationResult<Article>();

            var response = await GetResponse(ServiceURL.Article_GetArticleInfo);
            result.Retcode = response?.GetNamedString("retcode");

            if (response != null && result.Retcode?.CheckSuccess() == true)
            {
                var data = response.GetNamedValue("data");
                var article = JsonConvert.DeserializeObject<Article>(data.ToString());

                var buffer = await GetBytesResponse(article.content);
                using (var memoryStream = new MemoryStream(buffer.ToArray()))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(mutilmedia));
                    article.mutilmedias = ((mutilmedia)serializer.Deserialize(memoryStream)).Items;
                }

                result.Data = article;
            }

            return result;
        }
Example #5
0
        public override void ExecuteCommand(ClientManager clientManager, Alachisoft.NCache.Common.Protobuf.Command command)
        {
            CommandInfo cmdInfo;

            try
            {
                cmdInfo = ParseCommand(command, clientManager);
                if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("RemCmd.Exec", "cmd parsed");

            }
            catch (Exception exc)
            {
                _removeResult = OperationResult.Failure;
                if (!base.immatureId.Equals("-2"))
                {
                    //PROTOBUF:RESPONSE
                    _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponse(exc, command.requestID));
                }
                return;
            }
            NCache nCache = clientManager.CmdExecuter as NCache;
            try
            {
                CallbackEntry cbEntry = null;

                CompressedValueEntry flagValueEntry = null;

                OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
                flagValueEntry = nCache.Cache.Remove(cmdInfo.Key, cmdInfo.FlagMap, cbEntry, cmdInfo.LockId, cmdInfo.LockAccessType, operationContext);

                UserBinaryObject ubObject = (flagValueEntry == null) ? null : (UserBinaryObject) flagValueEntry.Value;

                //PROTOBUF:RESPONSE
                Alachisoft.NCache.Common.Protobuf.Response response = new Alachisoft.NCache.Common.Protobuf.Response();
                Alachisoft.NCache.Common.Protobuf.RemoveResponse removeResponse =
                    new Alachisoft.NCache.Common.Protobuf.RemoveResponse();
                response.responseType = Alachisoft.NCache.Common.Protobuf.Response.Type.REMOVE;
                response.remove = removeResponse;
                response.requestId = Convert.ToInt64(cmdInfo.RequestId);
                if (ubObject != null)
                {
                    removeResponse.value.AddRange(ubObject.DataList);
                    removeResponse.flag = flagValueEntry.Flag.Data;
                }
                _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeResponse(response));
            }
            catch (Exception exc)
            {
                _removeResult = OperationResult.Failure;

                //PROTOBUF:RESPONSE
                _serializedResponsePackets.Add(
                    Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponse(exc, command.requestID));
            }
            finally
            {
                if (ServerMonitor.MonitorActivity)
                    ServerMonitor.LogClientActivity("RemCmd.Exec", "cmd executed on cache");
            }
        }
Example #6
0
        public async Task<OperationResult<List<Comment>>> GetComments(string articleid, string type, string sort,int pageIndex,int pageSize)
        {
            FormData.Clear();

            FormData["articleid"] = articleid;
            FormData["userid"] = LocalSetting.Current.GetValue<string>("userid"); ;
            FormData["sid"] = LocalSetting.Current.GetValue<string>("sessionid"); ;
            FormData["type"] = type;
            FormData["sort"] = sort;
            FormData["deviceid"] = DeviceHelper.GetDeviceId().ToString();
            FormData["pindex"] = pageIndex.ToString();
            FormData["psize"] = pageSize.ToString();

            var result = new OperationResult<List<Comment>>();

            var response = await GetResponse(ServiceURL.Comment_CommentList);
            result.Retcode = response?.GetNamedString("retcode");

            if (response != null && result.Retcode?.CheckSuccess() == true)
            {
                var data = response.GetNamedValue("data");

                result.Data = JsonConvert.DeserializeObject<List<Comment>>(data.ToString());
            }

            return result;
        }
Example #7
0
        /// <summary>
        /// 获取用户作品列表
        /// </summary>
        /// <param name="otherUserId"></param>
        /// <param name="type"></param>
        /// <param name="tag"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<OperationResult<List<UArticle>>> GetUArticles(string otherUserId, string type, string tag, int pageIndex, int pageSize)
        {
            FormData.Clear();

            FormData["userid"] = otherUserId;
            FormData["sid"] = LocalSetting.Current.GetValue<string>("sessionid") ?? "";
            FormData["deviceId"] = DeviceHelper.GetDeviceId().ToString();
            FormData["type"] = type;
            FormData["tag"] = tag;
            FormData["pindex"] = pageIndex.ToString();
            FormData["psize"] = pageSize.ToString();

            var result = new OperationResult<List<UArticle>>();

            var response = await GetResponse(ServiceURL.UArticle_UArticleList);
            result.Retcode = response?.GetNamedString("retcode");

            if (response != null && result.Retcode?.CheckSuccess() == true)
            {
                var data = response.GetNamedValue("data");

                result.Data = JsonConvert.DeserializeObject<List<UArticle>>(data.ToString());
            }

            return result;
        }
Example #8
0
        /// <summary>
        /// 创建用户作业
        /// </summary>
        /// <param name="title"></param>
        /// <param name="tags"></param>
        /// <param name="tool"></param>
        /// <param name="fileData"></param>
        /// <returns></returns>
        public async Task<OperationResult> CreateUArticle(string title, string tags, string tool, IEnumerable<KeyValuePair<string, byte[]>> fileData)
        {
            FormData.Clear();

            FormData["userid"] = LocalSetting.Current.GetValue<string>("userid");
            FormData["sid"] = LocalSetting.Current.GetValue<string>("sessionid");
            FormData["deviceId"] = DeviceHelper.GetDeviceId().ToString();
            FormData["tags"] = tags;
            FormData["tool"] = tool;
            FormData["title"] = title;

            var result = new OperationResult<string>();

            var response = await GetResponse(ServiceURL.UArticle_CreateUArticle, fileData);
            result.Retcode = response?.GetNamedString("retcode");

            if (response != null && result.Retcode?.CheckSuccess() == true)
            {
                var data = response.GetNamedObject("data");

                //result.Data = data.GetNamedString("articleid");
            }

            return result;
        }
Example #9
0
        public OperationResult<Message> InvokeMethod(Phrase phrase)
        {
            var res = new OperationResult<Message>();
            var msg = new Message();

            try
            {
                object mres = phrase.Method.Invoke("dummy", phrase.Params != null? phrase.Params.ToArray():null);

                var mStream = new MemoryStream();
                var formatter = new BinaryFormatter();
                formatter.Serialize(mStream, mres);
                mStream.Close();

                //var marshall = new XmlSerializer(mres.GetType());
                //var mStream = new MemoryStream();

                //marshall.Serialize(mStream, mres);

                using (var reader = new StreamReader(mStream))
                {
                    msg.Value = reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                res.HasError = true;
                res.Message = ex.Message;
            }

            res.Result = msg;

            return res;
        }
		public void OnInit (OperationResult status)
		{
			if (status.Equals (OperationResult.Success))
				Console.WriteLine ("spoke");
			else
				Console.WriteLine ("was quiet");
		}
        public void MinusMatrixInverseMatrixMultiply_MAPLE_Test2()
        {
            var tileSize = 5;
            var delta = 0.000000001;

            var a = new Matrix<double>(new double[,] { { -32, 9, 25, 50, -40, 3, 66, -11, 73 }, { -92, 71, 80, 26, 95, 31, -23, -70, -88 }, { -60, -59, 87, 16, 63, -45, -78, 25, -69 }, { 19, 57, -34, 22, -64, 75, -53, -61, -98 }, { 43, 64, -59, 51, -24, -84, -35, -79, -9 }, { -16, -74, -77, 91, 32, -88, -28, 39, -16 }, { -49, -91, -11, 78, 40, -21, -32, -98, 11 }, { 95, -30, -39, 90, -6, -65, 86, -76, 49 }, { 29, 17, 72, -90, -10, 41, 56, -14, -52 } });
            var b = new Matrix<double>(new double[,] { { 77, 63, -62, -66, -6, -56, 80, -14, -65 }, { 4, -53, -65, -36, 42, 15, 34, 78, -5 }, { -30, 82, -1, 68, -62, 3, 17, -75, -10 }, { 84, 60, 16, 63, 67, 45, 53, -42, 2 }, { 87, 95, 92, 79, -63, 64, -36, 62, -1 }, { -8, -41, 82, -89, -54, 51, 96, -61, -73 }, { -38, -38, -45, 40, -75, 86, 75, 68, 28 }, { -7, 37, -36, 65, -88, -61, -6, -99, -79 }, { 98, 8, -37, 39, 91, 86, -27, -63, -72 } });

            // MinusMatrixInverseMatrix expects its second argument to be LU Factorized
            b = b.GetLU();

            var expected = MatrixHelpers.Tile(new Matrix<double>(new[,] { { 0.01984508466, 0.9042399904, 0.3995515772, -0.7745771722, 0.2994725178, 0.1084556411, -0.6575886106, -0.05301668731, 0.5444903099 }, { 1.855372611, -5.371281536, -4.104553393, -0.1121640216, -0.7296221045, -1.180498074, 3.045677622, 0.1386335471, 0.2821013684 }, { 1.929588849, -4.235913487, -1.189842573, -0.4245090055, -0.7875419486, -0.8542334129, 2.365695716, -1.087624087, 0.7376953336 }, { -0.3015200144, 0.06444804897, -1.093050084, 1.295819257, -0.3278095393, -0.09936130892, -0.08586242003, 0.2752136949, -1.135640896 }, { -0.6678456488, 1.635971997, 0.7408829678, -0.03480275626, 0.3196134418, 0.6555494623, -0.4839099415, -0.3891630982, -0.1698423028 }, { 0.9195999547, -1.811264799, 0.7645929720, -0.9267010695, -0.04031193539, 0.2576350183, 0.4513746375, -1.641684280, 0.6576041476 }, { 0.8358290298, 0.4796609017, 0.9546484769, -0.7810311114, 0.6595774182, 0.08541865288, -0.1904549301, -0.9345738811, 0.06621834781 }, { -0.6369792740, 3.263015949, 3.301792682, -1.825297016, 0.8801089887, 0.6821136696, -1.785435645, -1.226781234, 0.4676272889 }, { -0.2239907182, -0.3318901401, -0.4804214610, 0.2182583930, -0.2667527668, -0.6941578781, 0.3641733215, 0.4656006742, -0.08591310567 } }), tileSize);

            var opData1 = new OperationResult<double>(MatrixHelpers.Tile(a, tileSize));
            var opData2 = new OperationResult<double>(MatrixHelpers.Tile(b, tileSize));

            OperationResult<double> actual;
            var nmimmProducer = new MinusMatrixInverseMatrixMultiply<double>(opData1, opData2, out actual);
            var pm = new Manager(nmimmProducer);
            pm.Start();
            pm.Join();

            MatrixHelpers.IsDone(actual);
            MatrixHelpers.Diff(expected, actual.Data, delta);
            MatrixHelpers.Compare(expected, actual.Data, delta);
        }
		public void OnInit (OperationResult status)
		{
			if (status.Equals (OperationResult.Success)) {
				var p = new Dictionary<string, string> ();
				textToSpeech.Speak (toSpeak, QueueMode.Flush, p);
			}
		}
    protected void btnSim_Click(object sender, EventArgs e)
    {
        DataFieldCollection lFields = new DataFieldCollection();
        OperationResult lreturn = new OperationResult();

        try
        {
            lFields.Add(DEFENSORITINERANCIAQD._DEF_ID, ddlDefensores.SelectedValue);
            lFields.Add(DEFENSORITINERANCIAQD._DEFI_DISPOSICAO, rblItinerancia.SelectedValue);
            lFields.Add(DEFENSORITINERANCIAQD._DEFI_USUARIOS, Session["_SessionUser"].ToString());
            lFields.Add(DEFENSORITINERANCIAQD._DEFI_REGDATE, DateTime.Now);
            lFields.Add(DEFENSORITINERANCIAQD._DEFI_STATUS, "A");

            lreturn = DEFENSORITINERANCIADo.Insert(lFields, LocalInstance.ConnectionInfo);

            if (!lreturn.IsValid)
            {
                Exception exc = new Exception(lreturn.OperationException.Message.ToString());
                throw exc;
            }
            else
            {
                MessageBox1.wuc_ShowMessage("Registro efetuado com sucesso!", 1);
                LoadDefensor();
            }

        }
        catch (Exception err)
        {
            (new UnknownException(err)).TratarExcecao(true);
        }
    }
Example #14
0
        public ConnectResult(OperationResult operationResult)
            : base(operationResult.IsSuccessful,
			operationResult.StatusCode,
			operationResult.StatusName,
			operationResult.StatusDescription)
        {
        }
        protected void WaitForResultOfRequest(ILog logger, string workerTypeName, IOperation operation, Guid subscriptionId, string certificateThumbprint, string requestId)
        {
            OperationResult operationResult = new OperationResult();
            operationResult.Status = OperationStatus.InProgress;
            bool done = false;
            while (!done)
            {
                operationResult = operation.StatusCheck(subscriptionId, certificateThumbprint, requestId);
                if (operationResult.Status == OperationStatus.InProgress)
                {
                    string logMessage = string.Format(CultureInfo.CurrentCulture, "{0} '{1}' submitted a deployment request with ID '{2}', the operation was found to be in process, waiting for '{3}' seconds.", workerTypeName, this.Id, requestId, FiveSecondsInMilliseconds / 1000);
                    logger.Info(logMessage);
                    Thread.Sleep(FiveSecondsInMilliseconds);
                }
                else
                {
                    done = true;
                }
            }

            if (operationResult.Status == OperationStatus.Failed)
            {
                string logMessage = string.Format(CultureInfo.CurrentCulture, "{0} '{1}' submitted a deployment request with ID '{2}' and it failed. The code was '{3}' and message '{4}'.", workerTypeName, this.Id, requestId, operationResult.Code, operationResult.Message);
                logger.Error(logMessage);
            }
            else if (operationResult.Status == OperationStatus.Succeeded)
            {
                string logMessage = string.Format(CultureInfo.CurrentCulture, "{0} '{1}' submitted a deployment request with ID '{2}' and it succeeded. The code was '{3}' and message '{4}'.", workerTypeName, this.Id, requestId, operationResult.Code, operationResult.Message);
                logger.Info(logMessage);
            }
        }
Example #16
0
        public override bool Execute()
        {
            var timer = new Stopwatch();
              timer.Start();
              Log.LogMessage("NRoles v" + _Metadata.Version);

              if (ShowTrace) {
            SetUpTraceListener();
              }

              IOperationResult result;
              try {
            result = new RoleEngine().Execute(
              new RoleEngineParameters(AssemblyPath) {
            TreatWarningsAsErrors = TreatWarningsAsErrors,
            RunPEVerify = false,
            References = References.Split(';')
              });
            LogMessages(result);
              }
              catch (Exception ex) {
            result = new OperationResult();
            result.AddMessage(Error.InternalError());
            LogMessages(result);
            Log.LogErrorFromException(ex);
              }

              timer.Stop();
              Log.LogMessage("NRoles done, took {0}s", (timer.ElapsedMilliseconds / 1000f));
              return result.Success;
        }
Example #17
0
        public async Task<OperationResult<List<UArticle>>> GetUArticles(Dictionary<string, string> dict, int pageIndex, int pageSize)
        {
            FormData.Clear();

            foreach (var item in dict.Keys)
            {
                FormData[item] = dict[item];
            }
            //FormData["pindex"] = pageIndex.ToString();
            //FormData["psize"] = pageSize.ToString();

            FormData["pindex"] = pageIndex.ToString();
            FormData["psize"] = pageSize.ToString();

            var result = new OperationResult<List<UArticle>>();

            var response = await GetResponse(ServiceURL.UArticle_UArticleList);
            result.Retcode = response?.GetNamedString("retcode");

            if (response != null && result.Retcode?.CheckSuccess() == true)
            {
                var data = response.GetNamedValue("data");

                result.Data = JsonConvert.DeserializeObject<List<UArticle>>(data.ToString());
            }

            return result;
        }
Example #18
0
 static ArithmeticValidateCodeBuilder()
 {
     // 定义加减法
     Operations = new Tuple<string, Func<int, int, OperationResult>>[2];
     Operations[0] = new Tuple<string, Func<int, int, OperationResult>>(Plus, (x, y) =>
     {
         var result = new OperationResult
         {
             X = x,
             Y = y,
             Result = x + y
         };
         return result;
     });
     Operations[1] = new Tuple<string, Func<int, int, OperationResult>>(Subtract, (x, y) =>
     {
         // 如果 x 小于 y,则将 x 和 y 值互换,以免出现负数的情况
         if (y > x)
         {
             int tempX = y;
             y = x;
             x = tempX;
         }
         var result = new OperationResult
         {
             X = x,
             Y = y,
             Result = x - y
         };
         return result;
     });
 }
        public bool ValidateManifest(AddonManifest manifest, out OperationResult testResult)
        {
            testResult = new OperationResult();

            var prop =
                    manifest.Properties.FirstOrDefault(
                        p => p.Key.Equals("requireDevCredentials", StringComparison.InvariantCultureIgnoreCase));

            if (prop == null || !prop.HasValue)
            {
                testResult.IsSuccess = false;
                testResult.EndUserMessage = "Missing required property 'requireDevCredentials'. This property needs to be provided as part of the manifest";
                return false;
            }

            if (string.IsNullOrWhiteSpace(manifest.ProvisioningUsername) ||
                string.IsNullOrWhiteSpace(manifest.ProvisioningPassword))
            {
                testResult.IsSuccess = false;
                testResult.EndUserMessage = "Missing credentials 'provisioningUsername' & 'provisioningPassword' . These values needs to be provided as part of the manifest";
                return false;
            }

            return true;
        }
		public void SetOperationResult(OperationResult result)
		{
			lastStream?.Dispose();
			lastStream = null;
			if (result != OperationResult.Ok)
				Success = false;
		}
Example #21
0
 public void OnInit(OperationResult status)
 {
     if (status.Equals (OperationResult.Success)) {
         var p = new Dictionary<string,string> ();
         speaker.Speak (textAFalar, QueueMode.Flush, p);
     }
 }
        // Testing Instance
        // Input: AddonTestRequest request
        // Output: OperationResult
        public override OperationResult Test(AddonTestRequest request)
        {
            var testResult = new OperationResult {IsSuccess = false};
            var apr = new AddonProvisionRequest
            {
                DeveloperParameters = request.DeveloperParameters,
                Manifest = request.Manifest
            };

            var dpr = new AddonDeprovisionRequest
            {
                DeveloperParameters = request.DeveloperParameters,
                Manifest = request.Manifest
            };
            var provisionTest = Provision(apr);
            if (!provisionTest.IsSuccess)
            {
                return provisionTest;
            }
            var testProgress = provisionTest.EndUserMessage;
            var deprovisionTest = Deprovision(dpr);
            if (!deprovisionTest.IsSuccess)
            {
                return deprovisionTest;
            }
            testProgress += deprovisionTest.EndUserMessage;
            testResult.IsSuccess = true;
            testResult.EndUserMessage = testProgress;
            return testResult;
        }
Example #23
0
        public async Task<OperationResult<string>> CreateComment(Comment comment)
        {
            FormData.Clear();

            FormData["userid"] = comment.userid;
            FormData["sid"] = comment.sid;
            FormData["deviceid"] = comment.deviceid;
            FormData["type"] = comment.type;
            FormData["articleid"] = comment.articleid;
            FormData["comment"] = comment.comment;
            //FormData["atuserid"] = comment.atuserid;
            //FormData["atcommentid"] = comment.atcommentid;
            //FormData["commentstyle"] = comment.commentstyle;
            //FormData["floor"] = comment.floor.ToString();

            var result = new OperationResult<string>();

            var response = await GetResponse(ServiceURL.Comment_CreateComment);
            result.Retcode = response?.GetNamedString("retcode");

            if (response != null && result.Retcode?.CheckSuccess() == true)
            {
                var data = response.GetNamedObject("data");

                result.Data = data.GetNamedString("commentid");
            }

            return result;
        }
		public void OnInit(OperationResult status)
		{
			if (_speakerSpeech == null)
			{
				Task.Run(() =>
				{
					_initMutex.WaitOne();
					LazyResolver<IDispatcherService>.Service.InvokeOnUIThread(() => OnInit(status));
				});

				return;
			}
			_speakerSpeech.SetLanguage(Locale.Default);
			_speakerSpeech.SetOnUtteranceCompletedListener(this);

			Dictionary<string, string> speakParameters = new Dictionary<string, string>
			{
				{TextToSpeech.Engine.KeyParamUtteranceId, INITIALIZE_UTTERANCE_ID}
			};

			string word = "india rose";
#if __ANDROID_11__
			if (Build.VERSION.SdkInt >= BuildVersionCodes.Honeycomb)
			{
				word = "a";
				speakParameters.Add(TextToSpeech.Engine.KeyParamVolume, "0");
			}
#endif
			_speakerSpeech.Speak(word, QueueMode.Add, speakParameters);
			Log.Error("TTS", "Engine initialized");
		}
Example #25
0
        public ActionResult Create(Banka model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    using (ButceTakipContext context = new ButceTakipContext())
                    {
                        var count = context.Bankalar.Count();
                        context.Bankalar.Add(model);
                        context.SaveChanges();
                    }
                    TempData["OperationResult"] = new OperationResult()
                    {
                        Message = string.Format("{0} {1} başarıyla yaratıldı.", model.Aciklama, model.Sube),
                        Success = true,
                    };
                    return RedirectToAction("Index");
                }
                catch (Exception)
                {

                    TempData["OperationResult"] = new OperationResult()
                    {
                        Message = string.Format("{0} {1} hata oluştu.", model.Aciklama, model.Sube),
                        Success = false,
                    };
                }

            }
            return View(model);
        }
Example #26
0
 public ActionResult Delete(Banka model)
 {
     try
     {
         using (ButceTakipContext context = new ButceTakipContext())
         {
             context.Entry<Banka>(model).State = System.Data.EntityState.Deleted;
             context.SaveChanges();
             TempData["OperationResult"] = new OperationResult()
             {
                 Message = string.Format("{0} {1} başarıyla silindi.", model.Aciklama, model.Sube),
                 Success = true,
             };
             return RedirectToActionPermanent("Index");
         }
     }
     catch (Exception)
     {
         TempData["OperationResult"] = new OperationResult()
         {
             Message = string.Format("{0} {1} silinemedi!", model.Aciklama, model.Sube),
             Success = false,
         };
         return RedirectToAction("Delete", model.Id);
     }
 }
 public void GetGroupById(Action<OperationResult<Model.Group>> callBack, int groupId)
 {
     Group group = new Group("Test group", "Test projects group.");
     group.GroupId = groupId;
     var result = new OperationResult<Model.Group>(group);
     callBack(result);
 }
Example #28
0
 public OperationResult<Contact> GetContact(int id)
 {
     var result = new OperationResult<Contact>();
     var dyn = table.Single(id);
     result.Data = new Contact() { Id = dyn.Id, Dob = dyn.Dob, Name = dyn.Name, Phone = dyn.Phone };
     return result;
 }
Example #29
0
        public void OnInit(OperationResult status)
        {
            if (status != OperationResult.Success)
            {
                Log.Error("TTS error", "Initialization Failed!");
                OnTtsFailed();
                return;
            }
            if (mTts.Language == null || string.IsNullOrEmpty(mTts.Language.Language))
            {
                try
                {
                    var result = mTts.SetLanguage(Java.Util.Locale.Default);
                    if (result == LanguageAvailableResult.MissingData || result == LanguageAvailableResult.NotSupported)
                    {
                        result = mTts.SetLanguage(Java.Util.Locale.Us);
                        if (result == LanguageAvailableResult.MissingData)
                        {
                            OnTtsError();
                        }
                        else if (result == LanguageAvailableResult.NotSupported)
                        {
                            OnTtsFailed();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(TAG, string.Format("Failed to set TTS langauage. {0}", ex.Message));
                    OnTtsFailed();
                }
            }

            ttsLoaded = mTts.Language != null && !string.IsNullOrEmpty(mTts.Language.Language);
        }
        public void PlusMultiply_GENDATA_Test1()
        {
            var tileSize = 50;
            var blockMatrix1 = MatrixHelpers.Tile(Matrix<double>.CreateNewRandomDoubleMatrix(200, 200), tileSize);
            var blockMatrix2 = MatrixHelpers.Tile(Matrix<double>.CreateNewRandomDoubleMatrix(200, 200), tileSize);
            var blockMatrix3 = MatrixHelpers.Tile(Matrix<double>.CreateNewRandomDoubleMatrix(200, 200), tileSize);
            var clonedBlockMatrix1 = blockMatrix1.Clone();
            var clonedBlockMatrix2 = blockMatrix2.Clone();
            var clonedBlockMatrix3 = blockMatrix3.Clone();

            var opData1 = new OperationResult<double>(blockMatrix1);
            var opData2 = new OperationResult<double>(blockMatrix2);
            var opData3 = new OperationResult<double>(blockMatrix3);

            Matrix<Matrix<double>> expected = clonedBlockMatrix1.PlusMultiply(clonedBlockMatrix2, clonedBlockMatrix3);
            OperationResult<double> actual;
            var plusMultProducer = new PlusMultiply<double>(opData1, opData2, opData3, out actual);
            var pm = new Manager(plusMultProducer);
            pm.Start();
            pm.Join();

            MatrixHelpers.IsDone(actual);
            MatrixHelpers.Diff(expected, actual.Data);
            MatrixHelpers.Compare(expected, actual.Data);
        }
Example #31
0
        public OperationResult <Nothing> Handle(CreateDocumentToProcess command)
        {
            using (var context = new ImageProcessingContext(_persistenceConfiguration))
            {
                try
                {
                    var document = new DocumentToProcessPersistenceModel
                    {
                        Id = command.Id,
                        RequesterIdentifier          = command.RequesterIdentifier,
                        TemplateDefinitionIdentifier = command.TemplateDefinitionIdentifier
                    };

                    context.DocumentsToProcess.Add(document);
                    context.SaveChanges();

                    return(OperationResult <Nothing> .Success(new Nothing()));
                }
                catch (Exception ex)
                {
                    return(OperationResult <Nothing> .Failure(new UncaughtException(ex)));
                }
            }
        }
Example #32
0
        public bool AnyMissngTables(ref OperationResult op)
        {
            if (!HasFileInfoTable || !HasMp3InfoTable || !HasArtistTable)
            {
                op.AddInformation("Missing Table)s:\n");

                if (!HasFileInfoTable)
                {
                    op.AddInformation("Missing tbFileInfo table.\n");
                }

                if (!HasMp3InfoTable)
                {
                    op.AddInformation("Missing tbMp3Info table.\n");
                }

                if (!HasArtistTable)
                {
                    op.AddInformation("Missing tbArtist table.\n");
                }
                return(true);
            }
            return(false);
        }
        public async Task <OperationResult <bool> > Handle(ChangePasswordUserCommand request, CancellationToken cancellationToken)
        {
            var getUser = await unitOfWork.UsersRepository.GetUserByIdAsync(request.Id, cancellationToken);

            if (getUser.Result != null)
            {
                getUser.Result.ChangePassword(request.Password);
                var addUser = unitOfWork.UsersRepository.Update(getUser.Result, cancellationToken);
                if (addUser.Success)
                {
                    try
                    {
                        await unitOfWork.CommitSaveChangeAsync();

                        return(OperationResult <bool> .BuildSuccessResult(true));
                    }
                    catch (Exception ex)
                    {
                        return(OperationResult <bool> .BuildFailure(ex.Message));
                    }
                }
            }
            return(OperationResult <bool> .BuildFailure(getUser.ErrorMessage));
        }
Example #34
0
        public async Task <OperationResult> DeleteAllByCompany(int companyId)
        {
            var valid = await _companyService.IsValid(companyId);

            if (valid)
            {
                return(OperationResult.FailureResult("Invalid company id!"));
            }

            var jobs = this.jobsRepository.Set()
                       .Where(j => j.CompanyId == companyId)
                       .ToList();

            if (jobs.Count > 0)
            {
                foreach (var item in jobs)
                {
                    await jobsRepository.DeleteAsync(item);
                }
            }
            return(null);
            // var success = this.jobsRepository.SaveChanges() > 0;
            //return success ? OperationResult.SuccessResult() : OperationResult.FailureResult("Job post can't create, try again later or contact with support !");
        }
Example #35
0
        /// <summary>
        /// update payment term
        /// </summary>
        /// <param name="paymentTerm"></param>
        /// <returns></returns>
        public OperationResult UpdatePaymentTerm(PaymentTerm paymentTerm)
        {
            var operationResult = new OperationResult();

            var existingPaymentTerm = GetPaymentTerm(paymentTerm.PaymentTermId);

            if (existingPaymentTerm != null)
            {
                logger.Debug("PaymentTerm is being updated.");

                try
                {
                    _db.PaymentTerm.Attach(existingPaymentTerm);

                    _db.Entry(existingPaymentTerm).CurrentValues.SetValues(paymentTerm);

                    _db.SaveChanges();

                    operationResult.Success = true;
                    operationResult.Message = "Success";
                }
                catch (Exception ex)
                {
                    operationResult.Success = false;
                    operationResult.Message = "Error";
                    logger.ErrorFormat("Error while updating payment term: { 0} ", ex.ToString());
                }
            }
            else
            {
                operationResult.Success = false;
                operationResult.Message = "Unable to find selected payment term.";
            }

            return(operationResult);
        }
Example #36
0
        public override void ExecuteCommand(ClientManager clientManager, Alachisoft.NCache.Common.Protobuf.Command command)
        {
            CommandInfo cmdInfo;

            try
            {
                cmdInfo = ParseCommand(command, clientManager);
            }
            catch (System.Exception exc)
            {
                _syncEventResult = OperationResult.Failure;
                if (!base.immatureId.Equals("-2"))
                {
                    //PROTOBUF:RESPONSE
                    _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponse(exc, command.requestID, command.commandID));
                }
                return;
            }

            byte[] data = null;

            try
            {
                NCache nCache = clientManager.CmdExecuter as NCache;

                EventStatus eventStatus = nCache.GetEventsStatus();
                List <Alachisoft.NCache.Persistence.Event> syncEventResult = nCache.Cache.GetFilteredEvents(clientManager.ClientID, cmdInfo.EventsList, eventStatus);
                SyncEventResponseBuilder.BuildResponse(syncEventResult, cmdInfo.RequestId, _serializedResponsePackets, clientManager.ClientID, command.commandID, nCache.Cache);
            }
            catch (System.Exception exc)
            {
                _syncEventResult = OperationResult.Failure;
                //PROTOBUF:RESPONSE
                _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponse(exc, command.requestID, command.commandID));
            }
        }
Example #37
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="product"></param>
        /// <param name="quantity"></param>
        /// <returns></returns>
        public OperationResult PlaceOrder(Product product, int quantity)
        {
            bool   sent    = false;
            string message = "";

            if (product == null)
            {
                throw new ArgumentNullException(nameof(product));
            }
            if (quantity < 1)
            {
                throw new ArgumentOutOfRangeException(nameof(quantity));
            }

            var orderText = $"product {product.ProductName} from Acme in quantity of {quantity} ";


            var emailService = new EmailService();
            var subject      = $"Hello, you have sent an order";
            var recepit      = "*****@*****.**";
            var confirmation = emailService.SendMessage(subject, orderText, recepit);

            if (confirmation.Contains("Message sent"))
            {
                sent    = true;
                message = "successfully processed the order";
            }
            else
            {
                sent    = false;
                message = "unable to process the order";
            }
            var operationResult = new OperationResult(sent, message);

            return(operationResult);
        }
Example #38
0
        /// <summary>
        /// save payment term
        /// </summary>
        /// <param name="newPaymentTerm"></param>
        /// <returns></returns>
        public OperationResult SavePaymentTerm(PaymentTerm newPaymentTerm)
        {
            var operationResult = new OperationResult();

            try
            {
                var existingPaymentTerm = _db.PaymentTerm.FirstOrDefault(x => x.Description.ToLower() == newPaymentTerm.Description.ToLower());

                if (existingPaymentTerm == null)
                {
                    logger.Debug("PaymentTerm is being created...");

                    newPaymentTerm.IsActive = true;

                    _db.PaymentTerm.Add(newPaymentTerm);

                    _db.SaveChanges();

                    operationResult.Success = true;
                    operationResult.Message = "Success";
                }
                else
                {
                    operationResult.Success = false;
                    operationResult.Message = "Duplicate Entry";
                }
            }
            catch (Exception ex)
            {
                operationResult.Success = false;
                operationResult.Message = "Error";
                logger.ErrorFormat("Error saving new payment term: {0} ", ex.ToString());
            }

            return(operationResult);
        }
Example #39
0
        public string AddDiseases(ref OperationResult pobjOperationResult, diseasesDto pobjDtoEntity, List <string> ClientSession)
        {
            //mon.IsActive = true;
            string NewId = "(No generado)";

            try
            {
                SigesoftEntitiesModel dbContext = new SigesoftEntitiesModel();
                diseases objEntity = diseasesAssembler.ToEntity(pobjDtoEntity);

                objEntity.d_InsertDate   = DateTime.Now;
                objEntity.i_InsertUserId = Int32.Parse(ClientSession[2]);
                objEntity.i_IsDeleted    = 0;
                // Autogeneramos el Pk de la tabla
                int intNodeId = int.Parse(ClientSession[0]);
                NewId = Common.Utils.GetNewId(intNodeId, Utils.GetNextSecuentialId(intNodeId, 27), "DD");
                objEntity.v_DiseasesId = NewId;


                dbContext.AddTodiseases(objEntity);
                dbContext.SaveChanges();

                pobjOperationResult.Success = 1;
                // Llenar entidad Log
                LogBL.SaveLog(ClientSession[0], ClientSession[1], ClientSession[2], LogEventType.CREACION, "ENFERMEDAD", "v_Diseases=" + NewId.ToString(), Success.Ok, null);
                return(NewId);
            }
            catch (Exception ex)
            {
                pobjOperationResult.Success          = 0;
                pobjOperationResult.ExceptionMessage = Common.Utils.ExceptionFormatter(ex);
                // Llenar entidad Log
                LogBL.SaveLog(ClientSession[0], ClientSession[1], ClientSession[2], LogEventType.CREACION, "ENFERMEDAD", "v_Diseases=" + NewId.ToString(), Success.Failed, pobjOperationResult.ExceptionMessage);
                return(null);
            }
        }
Example #40
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="product"></param>
        /// <param name="quantity"></param>
        /// <param name="deliveryBy"></param>
        /// <returns></returns>
        public OperationResult PlaceOrder(Product product, int quantity, DateTimeOffset deliveryBy)
        {
            if (product == null)
            {
                throw new NullReferenceException(nameof(product));
            }
            if (quantity < 1)
            {
                throw new ArgumentOutOfRangeException(nameof(quantity));
            }
            if (deliveryBy >= DateTimeOffset.Now)
            {
                throw new ArgumentOutOfRangeException(nameof(deliveryBy));
            }

            bool   sent      = false;
            string message   = "";
            var    orderText = $"Order {product.ProductName} delivered by {deliveryBy}";

            var emailService = new EmailService();
            var email        = emailService.SendMessage("new order", orderText, this.Email);

            if (email.Contains("Message sent"))
            {
                sent    = true;
                message = "successfully processed the order";
            }
            else
            {
                sent    = false;
                message = "unable to process the order";
            }
            var operationResult = new OperationResult(sent, message);

            return(operationResult);
        }
Example #41
0
        public override OperationResult <string> Process(DirectoryInfo directory)
        {
            var result   = new OperationResult <string>();
            var data     = string.Empty;
            var found    = 0;
            var modified = 0;
            var metaDatasForFilesInFolder = GetAudioMetaDatasForDirectory(directory);

            if (metaDatasForFilesInFolder.Any())
            {
                found = metaDatasForFilesInFolder.Count();
                var firstMetaData = metaDatasForFilesInFolder.OrderBy(x => x.Filename ?? string.Empty).ThenBy(x => SafeParser.ToNumber <short>(x.TrackNumber)).FirstOrDefault();
                if (firstMetaData == null)
                {
                    return(new OperationResult <string>("Error Getting First MetaData")
                    {
                        Data = $"Unable to read Metadatas for Directory [{ directory.FullName }]"
                    });
                }
                var artist = firstMetaData.Artist;
                foreach (var metaData in metaDatasForFilesInFolder.Where(x => x.Artist != artist))
                {
                    modified++;
                    Console.WriteLine($"╟ Setting Artist to [{ artist }], was [{ metaData.Artist }] on file [{ metaData.FileInfo.Name}");
                    metaData.Artist = artist;
                    if (!Configuration.Inspector.IsInReadOnlyMode)
                    {
                        TagsHelper.WriteTags(metaData, metaData.Filename);
                    }
                }
                data = $"Found [{ found }] files, Modified [{ modified }] files";
            }
            result.Data      = data;
            result.IsSuccess = true;
            return(result);
        }
Example #42
0
        public void Delete()
        {
            OwaStoreObjectId owaStoreObjectId = (OwaStoreObjectId)base.GetParameter("id");

            if (owaStoreObjectId.IsOtherMailbox || owaStoreObjectId.IsGSCalendar)
            {
                throw new OwaInvalidRequestException("Cannot perform delete on shared folder");
            }
            ExTraceGlobals.MailCallTracer.TraceDebug((long)this.GetHashCode(), "TreeEventHandler.Delete");
            if (Utilities.IsDefaultFolderId(base.UserContext, owaStoreObjectId, DefaultFolderType.SearchFolders))
            {
                throw new OwaInvalidRequestException("Cannot Delete Search Folders");
            }
            bool flag  = (bool)base.GetParameter("fSrcD");
            bool flag2 = flag || owaStoreObjectId.IsPublic || (bool)base.GetParameter("pd");
            NavigationTreeDirtyFlag flag3 = NavigationTreeDirtyFlag.None;

            using (Folder folder = Utilities.GetFolder <Folder>(base.UserContext, owaStoreObjectId, new PropertyDefinition[]
            {
                StoreObjectSchema.ContainerClass,
                FolderSchema.IsOutlookSearchFolder,
                FolderSchema.AdminFolderFlags,
                StoreObjectSchema.ParentEntryId
            }))
            {
                string className = folder.ClassName;
                if (Utilities.IsOutlookSearchFolder(folder))
                {
                    throw new OwaInvalidRequestException("Cannot Delete Search Folders");
                }
                if (Utilities.IsELCFolder(folder))
                {
                    throw new OwaInvalidRequestException("Cannot Delete ELC folders.");
                }
                if (Utilities.IsOneOfTheFolderFlagsSet(folder, new ExtendedFolderFlags[]
                {
                    ExtendedFolderFlags.RemoteHierarchy
                }))
                {
                    throw new OwaInvalidRequestException("Cannot delete a folder that is controlled remotely.");
                }
                if (!flag2 || (!owaStoreObjectId.IsPublic && !flag))
                {
                    flag3 = this.CheckNavigationTreeDirtyFlag(folder, true);
                }
            }
            OperationResult operationResult = Utilities.Delete(base.UserContext, flag2, new OwaStoreObjectId[]
            {
                owaStoreObjectId
            }).OperationResult;

            if (operationResult == OperationResult.Failed)
            {
                Strings.IDs localizedId = flag2 ? -1691273193 : 1041829989;
                throw new OwaEventHandlerException("Delete returned an OperationResult.Failed", LocalizedStrings.GetNonEncoded(localizedId));
            }
            if (operationResult == OperationResult.PartiallySucceeded)
            {
                throw new OwaAccessDeniedException(LocalizedStrings.GetNonEncoded(995407892));
            }
            if (!flag2)
            {
                this.RenderFolderTreeChangedNode(base.UserContext.GetDeletedItemsFolderId((MailboxSession)owaStoreObjectId.GetSession(base.UserContext)), owaStoreObjectId, false, false, FolderTreeRenderType.None);
            }
            RenderingUtilities.RenderNavigationTreeDirtyFlag(this.Writer, base.UserContext, flag3, (NavigationModule[])base.GetParameter("cms"));
        }
Example #43
0
        // Token: 0x06002FA1 RID: 12193 RVA: 0x0011436C File Offset: 0x0011256C
        private void CopyOrMoveFolder(bool isCopy)
        {
            ExTraceGlobals.MailCallTracer.TraceDebug((long)this.GetHashCode(), "TreeEventHandler." + (isCopy ? "Copy" : "Move"));
            OwaStoreObjectId owaStoreObjectId  = (OwaStoreObjectId)base.GetParameter("id");
            OwaStoreObjectId owaStoreObjectId2 = (OwaStoreObjectId)base.GetParameter("destId");
            bool             isExpanded        = (bool)base.GetParameter("exp");

            if (owaStoreObjectId.IsOtherMailbox || owaStoreObjectId2.IsOtherMailbox)
            {
                throw new OwaInvalidRequestException("Cannot copy or move a shared folder");
            }
            if (Utilities.IsDefaultFolderId(base.UserContext, owaStoreObjectId, DefaultFolderType.SearchFolders) || Utilities.IsDefaultFolderId(base.UserContext, owaStoreObjectId2, DefaultFolderType.SearchFolders))
            {
                throw new OwaInvalidRequestException("Cannot Copy or Move Search Folder");
            }
            NavigationTreeDirtyFlag navigationTreeDirtyFlag = NavigationTreeDirtyFlag.None;
            string displayName;

            using (Folder folder = Utilities.GetFolder <Folder>(base.UserContext, owaStoreObjectId, new PropertyDefinition[]
            {
                FolderSchema.DisplayName,
                StoreObjectSchema.ContainerClass,
                FolderSchema.IsOutlookSearchFolder,
                FolderSchema.AdminFolderFlags,
                StoreObjectSchema.ParentEntryId
            }))
            {
                displayName = folder.DisplayName;
                string className = folder.ClassName;
                if (Utilities.IsOutlookSearchFolder(folder))
                {
                    throw new OwaInvalidRequestException("Cannot Copy or Move Search Folders");
                }
                if (!this.CanFolderHaveSubFolders(owaStoreObjectId2))
                {
                    throw new OwaInvalidRequestException("Cannot Copy or Move a folder to this destination");
                }
                if (Utilities.IsELCFolder(folder))
                {
                    throw new OwaInvalidRequestException(string.Format("Cannot {0} ELC folders.", isCopy ? "Copy" : "Move"));
                }
                if (!isCopy && ((!owaStoreObjectId.IsPublic && Utilities.IsSpecialFolderForSession(folder.Session as MailboxSession, owaStoreObjectId.StoreObjectId)) || Utilities.IsOneOfTheFolderFlagsSet(folder, new ExtendedFolderFlags[]
                {
                    ExtendedFolderFlags.RemoteHierarchy
                })))
                {
                    throw new OwaInvalidRequestException("Cannot move folders that are special or controlled remotely.");
                }
                if (base.UserContext.IsPublicFolderRootId(owaStoreObjectId.StoreObjectId))
                {
                    throw new OwaEventHandlerException("Copy/move public root folder is not supported", LocalizedStrings.GetNonEncoded(-177785786), true);
                }
                bool flag  = owaStoreObjectId.IsPublic || (bool)base.GetParameter("fSrcD");
                bool flag2 = owaStoreObjectId2.IsPublic || (bool)base.GetParameter("fDstD");
                bool flag3 = !isCopy && owaStoreObjectId.IsArchive != owaStoreObjectId2.IsArchive;
                if (((!flag || !flag2) && (!isCopy || !flag2) && (isCopy || flag || flag2)) || flag3)
                {
                    navigationTreeDirtyFlag = this.CheckNavigationTreeDirtyFlag(folder, true);
                    if (isCopy || flag)
                    {
                        navigationTreeDirtyFlag &= ~NavigationTreeDirtyFlag.Favorites;
                    }
                }
            }
            if (owaStoreObjectId2.IsArchive)
            {
                navigationTreeDirtyFlag |= NavigationTreeDirtyFlag.Favorites;
            }
            OperationResult operationResult = Utilities.CopyOrMoveFolder(base.UserContext, isCopy, owaStoreObjectId2, new OwaStoreObjectId[]
            {
                owaStoreObjectId
            }).OperationResult;

            if (operationResult == OperationResult.Failed)
            {
                throw new OwaEventHandlerException(isCopy ? "Copy returned an OperationResult.Failed" : "Move returned an OperationResult.Failed", LocalizedStrings.GetNonEncoded(-1597406995));
            }
            if (operationResult == OperationResult.PartiallySucceeded)
            {
                throw new OwaEventHandlerException((isCopy ? "Copy" : "Move") + " returned an OperationResult.PartiallySucceeded", LocalizedStrings.GetNonEncoded(2109230231));
            }
            bool flag4 = true;

            if (!isCopy && owaStoreObjectId.IsPublic == owaStoreObjectId2.IsPublic && owaStoreObjectId.IsArchive == owaStoreObjectId2.IsArchive && StringComparer.InvariantCultureIgnoreCase.Equals(owaStoreObjectId.MailboxOwnerLegacyDN, owaStoreObjectId2.MailboxOwnerLegacyDN))
            {
                flag4 = false;
            }
            OwaStoreObjectId newFolderId;

            if (flag4)
            {
                newFolderId = this.GetSubFolderIdByName(owaStoreObjectId2, displayName);
            }
            else
            {
                newFolderId = owaStoreObjectId;
            }
            this.RenderFolderTreeChangedNode(owaStoreObjectId2, newFolderId, isExpanded, owaStoreObjectId2.IsArchive, (FolderTreeRenderType)base.GetParameter("rdt"));
            RenderingUtilities.RenderNavigationTreeDirtyFlag(this.Writer, base.UserContext, navigationTreeDirtyFlag, (NavigationModule[])base.GetParameter("cms"));
        }
 public ActionResult Delete(int Id)
 {
     OperationResult result = PermissionService.Delete(Id);
     return Json(result);
 }
Example #45
0
        public OperationResult RunTest(Jumper Jumper)
        {
            var testOp = new OperationResult();

            ///For testing
            //Jumper.results.InsertionLoss1550SCA = 0.15;
            //Jumper.results.ReturnLoss1550SCA = 70;
            //Jumper.results.LengthInMeters = 9;
            //return true;
            ///----------------------

            this.Jumper = this.Jumper ?? Jumper;

            if (pctConnection.Initialized)
            {
            }
            else
            {
                Initialize();
            }

            AssignInterfaces();

            if (isReadyToTest)
            {
                try
                {
                    ISetup.Type = MAP200_PCTMeasurementTypeEnum.MAP200_PCTMeasurementTypeDUT;
                    IMeas.Initiate();

                    do
                    {
                        Thread.Sleep(100);
                    } while (IMeas.State == MAP200_PCTMeasurementStateEnum.MAP200_PCTMeasurementState_Busy);

                    string msg = ISystem.GetWarning();
                    if (!msg.Equals("No Warning"))
                    {
                        logger.Debug(msg);
                    }

                    Jumper.Results.InsertionLoss1550SCA = IMeas.GetIL();
                    Jumper.Results.ReturnLoss1550SCA    = IMeas.GetORL(Method: ReturnLossMethod, Origin: ReturnLossOrigin, Aoffset: Aoffset, Boffset: Boffset);
                    Jumper.Results.LengthInMeters       = IMeas.GetLength();
                    testOp.Success = true;
                }
                catch (Exception ex)
                {
                    //jumper.postMessage.Response.Message = ex.Message;
                    testOp.Success = false;
                    testOp.ErrorMessages.Add(ex.Message);
                }
                finally
                {
                    closeConnection();
                }
            }
            else
            {
                //Jumper.postMessage.Response.Message = "PCT not ready to test";
                testOp.ErrorMessages.Add("PCT not ready to test");
                testOp.Success = false;
            }

            return(testOp);
        }
Example #46
0
 public override ValueTask <OperationResult> HandleAsync(object caller, MessageQueueMessage request, CancellationToken cancellation = default)
 {
     Console.WriteLine(Zongsoft.Serialization.Serializer.Json.Serialize(request));
     return(ValueTask.FromResult(OperationResult.Success()));
 }
Example #47
0
        //获取线状图数据
        /// <summary>
        ///
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="typeID"></param>
        /// <param name="searchType">0:销售统计,1订单总数统计,2 已支付统计,3未支付统计</param>
        /// <returns></returns>
        public JsonResult GetLineData(string startTime, string endTime, int typeID = 0, int searchType = 0)
        {
            var      result = new JsonResultObject();
            DateTime sTime  = DateTime.Now;
            DateTime eTime  = DateTime.Now;
            //例:100: 111,111,111,111,111,111,111
            Dictionary <string, string> allData = new Dictionary <string, string>();

            GetTime(startTime, endTime, typeID, ref sTime, ref eTime);
            OperationResult <IList <OrderDailyInfo> > ort = OrderDailyBLL.Instance.OrderDaily_GetStationePrice(sTime, eTime);

            //生成y轴时间点

            if (ort.ResultType == OperationResultType.Success)
            {
                IList <OrderDailyInfo> odInfoList = ort.AppendData;
                foreach (var item in odInfoList)
                {
                    item.SourceName = Enum.GetName(typeof(OrderSource), item.Source);
                }

                //设置指定天数
                IList <string> timeList = new List <string>();
                while (true)
                {
                    timeList.Add(sTime.ToShortDateString());
                    sTime = sTime.AddDays(1);
                    if (sTime > Convert.ToDateTime(eTime.ToShortDateString()))
                    {
                        break;
                    }
                }

                var web     = odInfoList.Where(p => p.Source == (int)OrderSource.WEB);
                var ios     = odInfoList.Where(p => p.Source == (int)OrderSource.IOS);
                var android = odInfoList.Where(p => p.Source == (int)OrderSource.Android);
                var h5      = odInfoList.Where(p => p.Source == (int)OrderSource.H5);

                string webStr     = string.Empty;
                string iosStr     = string.Empty;
                string androidStr = string.Empty;
                string h5Str      = string.Empty;

                #region 数据整合
                for (int i = 0; i < timeList.Count; i++)
                {
                    var webdata = web.Where(p => p.CreateDate.ToShortDateString() == timeList[i] && p.Source == (int)OrderSource.WEB);
                    if (webdata.Count() != 0)
                    {
                        foreach (var t in webdata)
                        {
                            switch (searchType)
                            {
                            case 0:
                                webStr += t.PayAmount + ",";
                                break;

                            case 1:
                                webStr += t.OrderQuan + ",";
                                break;

                            case 2:
                                webStr += t.PayQuan + ",";
                                break;

                            case 3:
                                webStr += t.OrderQuan - t.PayQuan + ",";
                                break;
                            }
                        }
                    }
                    else
                    {
                        webStr += "0,";
                    }

                    var iosdata = ios.Where(p => p.CreateDate.ToShortDateString() == timeList[i] && p.Source == (int)OrderSource.IOS);
                    if (iosdata.Count() != 0)
                    {
                        foreach (var t in iosdata)
                        {
                            switch (searchType)
                            {
                            case 0:
                                iosStr += t.PayAmount + ",";
                                break;

                            case 1:
                                iosStr += t.OrderQuan + ",";
                                break;

                            case 2:
                                iosStr += t.PayQuan + ",";
                                break;

                            case 3:
                                iosStr += t.OrderQuan - t.PayQuan + ",";
                                break;
                            }
                        }
                    }
                    else
                    {
                        iosStr += "0,";
                    }
                    var androiddata = android.Where(p => p.CreateDate.ToShortDateString() == timeList[i] && p.Source == (int)OrderSource.Android);
                    if (androiddata.Count() != 0)
                    {
                        foreach (var t in androiddata)
                        {
                            switch (searchType)
                            {
                            case 0:
                                androidStr += t.PayAmount + ",";
                                break;

                            case 1:
                                androidStr += t.OrderQuan + ",";
                                break;

                            case 2:
                                androidStr += t.PayQuan + ",";
                                break;

                            case 3:
                                androidStr += t.OrderQuan - t.PayQuan + ",";
                                break;
                            }
                        }
                    }
                    else
                    {
                        androidStr += "0,";
                    }
                    var h5data = h5.Where(p => p.CreateDate.ToShortDateString() == timeList[i] && p.Source == (int)OrderSource.H5);
                    if (h5data.Count() != 0)
                    {
                        foreach (var t in h5data)
                        {
                            switch (searchType)
                            {
                            case 0:
                                h5Str += t.PayAmount + ",";
                                break;

                            case 1:
                                h5Str += t.OrderQuan + ",";
                                break;

                            case 2:
                                h5Str += t.PayQuan + ",";
                                break;

                            case 3:
                                h5Str += t.OrderQuan - t.PayQuan + ",";
                                break;
                            }
                        }
                    }
                    else
                    {
                        h5Str += "0,";
                    }
                }

                //去除多余逗号
                if (webStr.EndsWith(","))
                {
                    webStr = webStr.Substring(0, webStr.Length - 1);
                }
                if (iosStr.EndsWith(","))
                {
                    iosStr = iosStr.Substring(0, iosStr.Length - 1);
                }
                if (androidStr.EndsWith(","))
                {
                    androidStr = androidStr.Substring(0, androidStr.Length - 1);
                }
                if (h5Str.EndsWith(","))
                {
                    h5Str = h5Str.Substring(0, h5Str.Length - 1);
                }
                allData.Add("WEB", webStr);
                allData.Add("IOS", iosStr);
                allData.Add("ANDROID", androidStr);
                allData.Add("H5", h5Str);
                #endregion


                result.data   = JsonHelper.ConvertToJson(allData);
                result.status = true;
            }
            else
            {
                result.status = false;
                result.msg    = "数据获取失败,未能连接至网络!";
            }
            return(Json(result));
        }
Example #48
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (cboMedico.SelectedValue.ToString() == "-1")
            {
                MessageBox.Show("Seleccionar un médico tratante", " ¡ VALIDACIÓN!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            if (_auxiliaryExams == null)
            {
                _auxiliaryExams = new List <ServiceComponentList>();
            }

            // Save ListView / recorrer la lista de examenes seleccionados
            foreach (ListViewItem item in lvExamenesSeleccionados.Items)
            {
                var fields           = item.SubItems;
                var ComponentId      = fields[1].Text.Split('|');
                var NombreComponente = fields[0].Text.Split('|');



                MedicalExamBL objComponentBL  = new MedicalExamBL();
                componentDto  objComponentDto = new componentDto();

                OperationResult objOperationResult = new OperationResult();
                foreach (var scid in ComponentId)
                {
                    var conCargoA = -1;
                    if (_type == "Hospi")
                    {
                        var oFrmType = new frmType();
                        oFrmType.ShowDialog();

                        if (oFrmType._conCargoA == "Médico")
                        {
                            conCargoA = 1;
                        }
                        else
                        {
                            conCargoA = 2;
                        }
                    }

                    objComponentDto = objComponentBL.GetMedicalExam(ref objOperationResult, scid);
                    SystemParameterBL oSp = new SystemParameterBL();
                    var o = oSp.GetSystemParameter(ref objOperationResult, 116, int.Parse(objComponentDto.i_CategoryId.ToString()));
                    //Lógica de Aumento de Precio Base

                    var porcentajes = o.v_Field.Split('-');

                    float p1 = porcentajes[0] == null ? 0 : float.Parse(porcentajes[0].ToString());

                    float p2 = porcentajes[1] == null ? 0 : float.Parse(porcentajes[1].ToString());

                    float pb          = objComponentDto.r_BasePrice.Value;
                    var   precio_base = pb + (pb * p1 / 100) + (pb * p2 / 100);
                    //FormPrecioComponente frm = new FormPrecioComponente("", "", "");
                    //frmConfigSeguros frm1 = new frmConfigSeguros(0, 0, 0, "", "");
                    ServiceComponentList auxiliaryExam          = new ServiceComponentList();
                    servicecomponentDto  objServiceComponentDto = new servicecomponentDto();
                    ServiceBL            _ObjServiceBL          = new ServiceBL();
                    TicketBL             oTicketBL = new TicketBL();
                    if (_modo == "ASEGU")
                    {
                        #region OLD Logica antigua
                        #region Conexion SAM
                        //ConexionSigesoft conectasam = new ConexionSigesoft();
                        //conectasam.opensigesoft();
                        #endregion
                        #region Query
                        //var componente = NombreComponente[0].ToString();
                        //var cadena1 = "select PL.i_EsDeducible, PL.i_EsCoaseguro, PL.d_Importe, PL.d_ImporteCo from [dbo].[plan] PL where PL.v_IdUnidadProductiva='" + lineId + "' and PL.v_ProtocoloId='" + _protocolId + "' ";
                        //SqlCommand comando = new SqlCommand(cadena1, connection: conectasam.conectarsigesoft);
                        //SqlDataReader lector = comando.ExecuteReader();
                        //int deducible = 0;
                        //int coaseguro = 0;
                        //decimal? importe = 0;
                        //decimal? importeCo = 0;
                        //while (lector.Read())
                        //{
                        //    deducible = int.Parse(lector.GetValue(0).ToString()); coaseguro = int.Parse(lector.GetValue(1).ToString()); importe = decimal.Parse(lector.GetValue(2).ToString()); importeCo = decimal.Parse(lector.GetValue(3).ToString());
                        //}
                        //lector.Close();
                        //string factores = ""; string aseguradoraName = ""; string organizationId = "";
                        //var factorGlobal = "";
                        //var cadena2 = "select PR.r_PriceFactor, OO.v_Name, PR.v_CustomerOrganizationId from Organization OO inner join protocol PR On PR.v_AseguradoraOrganizationId = OO.v_OrganizationId where PR.v_ProtocolId ='" + _protocolId + "'";
                        //comando = new SqlCommand(cadena2, connection: conectasam.conectarsigesoft);
                        //lector = comando.ExecuteReader();
                        //while (lector.Read())
                        //{
                        //    factores = lector.GetValue(0).ToString();
                        //    var factorArray = factores.Split('|');// factores[0].ToString().Split('|');
                        //    factorGlobal = factorArray[0];
                        //    aseguradoraName = lector.GetValue(1).ToString();
                        //    organizationId = lector.GetValue(2).ToString();
                        //}
                        //lector.Close();
                        //string empresa = "";
                        //var cadena3 = "select v_Name from Organization OO  where OO.v_OrganizationId ='" + organizationId + "'";
                        //comando = new SqlCommand(cadena3, connection: conectasam.conectarsigesoft);
                        //lector = comando.ExecuteReader();
                        //while (lector.Read())
                        //{
                        //    empresa = lector.GetValue(0).ToString();
                        //}
                        //lector.Close();
                        #endregion
                        #region Lógica PARA SABER SI ES DEDUCIBLE O COASEGURO
                        //if (rbNuevaConsulta.Checked)// QUIERE DECIR QUE ES UNA NUEVA ATENCION Y DEBE SER CONSIDERADO COMO DEDUCIBLE SIN FACTOR
                        //{
                        //    factorGlobal = "1";
                        //    coaseguro = 0;
                        //    importeCo = null;
                        //}
                        //else if (rbAdicional.Checked) // QUIERE DECIR QUE ES UN COMPONENTE ADICIONAL Y DEBE SER CONSIDERADO COMO COASEGURO CON FACTOR
                        //{
                        //    deducible = 0;
                        //    importe = null;
                        //}
                        #endregion
                        #region Formulario
                        //precio_base = (float)objComponentDto.r_PriceSegus;// se cambia el precio inicial por el SEGUS
                        //frmConfigSeguros frm1 = new frmConfigSeguros(deducible, coaseguro, importe, precio_base.ToString(), factorGlobal, importeCo);
                        //frm1.Text = aseguradoraName + " / " + empresa;
                        //frm1.ShowDialog();
                        #endregion
                        #endregion

                        #region Obteniendo los campos de la BD
                        ConexionSigesoft conectasam = new ConexionSigesoft();
                        conectasam.opensigesoft();
                        var           componente      = NombreComponente[0].ToString();
                        var           cadena          = "select i_KindOfService from  component where v_ComponentId='" + objComponentDto.v_ComponentId + "'";
                        SqlCommand    comando         = new SqlCommand(cadena, connection: conectasam.conectarsigesoft);
                        SqlDataReader lector          = comando.ExecuteReader();
                        int           i_KindOfService = 0;
                        while (lector.Read())
                        {
                            try
                            {
                                i_KindOfService = int.Parse(lector.GetValue(0).ToString());
                            }
                            catch (Exception exception)
                            {
                                MessageBox.Show(exception.Message, " ¡ ERROR !", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }
                        }
                        lector.Close();
                        var cadena1 = "select PL.i_PlanId, PL.i_EsCoaseguro, PL.d_Importe, PL.d_ImporteCo " +
                                      "from [dbo].[plan] PL " +
                                      "where PL.v_IdUnidadProductiva='" + lineId + "' and PL.v_ProtocoloId='" + _protocolId + "' ";
                        comando = new SqlCommand(cadena1, connection: conectasam.conectarsigesoft);
                        lector  = comando.ExecuteReader();
                        string PlanId = ""; int coaseguro = 0; decimal?importe = 0; decimal?importeCo = 0;
                        while (lector.Read())
                        {
                            try
                            {
                                PlanId    = lector.GetValue(0).ToString();
                                coaseguro = int.Parse(lector.GetValue(1).ToString());
                                importe   = decimal.Parse(lector.GetValue(2).ToString());
                                importeCo = decimal.Parse(lector.GetValue(3).ToString());
                            }
                            catch (Exception exception)
                            {
                                MessageBox.Show(exception.Message, " ¡ ERROR !", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }
                        }
                        lector.Close();
                        string factores = ""; string aseguradoraName = ""; string organizationId = ""; var factorGlobal = "";
                        var    cadena2 = "select PR.r_PriceFactor, OO.v_Name, PR.v_CustomerOrganizationId " +
                                         "from Organization OO " +
                                         "inner join protocol PR On PR.v_AseguradoraOrganizationId = OO.v_OrganizationId " +
                                         "where PR.v_ProtocolId ='" + _protocolId + "'";
                        comando = new SqlCommand(cadena2, connection: conectasam.conectarsigesoft);
                        lector  = comando.ExecuteReader();
                        while (lector.Read())
                        {
                            try
                            {
                                factores = lector.GetValue(0).ToString();
                                var factorArray = factores.Split('|');// factores[0].ToString().Split('|');
                                factorGlobal    = factorArray[0];
                                aseguradoraName = lector.GetValue(1).ToString();
                                organizationId  = lector.GetValue(2).ToString();
                            }
                            catch (Exception exception)
                            {
                                MessageBox.Show(exception.Message, " ¡ ERROR !", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }
                        }
                        lector.Close();
                        #endregion

                        #region Según el tipo de componente se hace el calculo
                        switch (i_KindOfService)
                        {
                        //CLINICA
                        case 1:
                        {
                            if (objComponentDto.r_PriceSegus != 0)
                            {
                                objServiceComponentDto.r_Price            = objComponentDto.r_PriceSegus;
                                objServiceComponentDto.d_SaldoPaciente    = importe;
                                objServiceComponentDto.d_SaldoAseguradora = (decimal)objComponentDto.r_PriceSegus - importe;
                            }
                            else
                            {
                                frmConfigSeguros frm1 = new frmConfigSeguros("1");
                                frm1.ShowDialog();
                                objServiceComponentDto.r_Price            = (float)frm1.nuevoPrecio;
                                objServiceComponentDto.d_SaldoPaciente    = importe;
                                objServiceComponentDto.d_SaldoAseguradora = frm1.nuevoPrecio - importe;
                            }
                        }
                        break;

                        //SERVICIOS AUXILIARES
                        case 2:
                        {
                            if (objComponentDto.r_PriceSegus != 0)
                            {
                                objServiceComponentDto.r_Price            = objComponentDto.r_PriceSegus * float.Parse(factorGlobal);
                                objServiceComponentDto.d_SaldoPaciente    = importeCo * (decimal)objServiceComponentDto.r_Price / 100;
                                objServiceComponentDto.d_SaldoAseguradora = (100 - importeCo) * (decimal)objServiceComponentDto.r_Price / 100;
                            }
                            else
                            {
                                frmConfigSeguros frm1 = new frmConfigSeguros(factorGlobal);
                                frm1.ShowDialog();
                                objServiceComponentDto.r_Price            = (float)frm1.nuevoPrecio;
                                objServiceComponentDto.d_SaldoPaciente    = importeCo * frm1.nuevoPrecio / 100;
                                objServiceComponentDto.d_SaldoAseguradora = (100 - importeCo) * frm1.nuevoPrecio / 100;
                            }
                        }
                        break;

                        //HONORARIOS MÉDICOS Y/O QUIRURGICOS
                        case 3:
                        {
                            if (objComponentDto.r_PriceSegus != 0)
                            {
                                objServiceComponentDto.r_Price            = objComponentDto.r_PriceSegus * float.Parse(factorGlobal);
                                objServiceComponentDto.d_SaldoPaciente    = importeCo * (decimal)objServiceComponentDto.r_Price / 100;
                                objServiceComponentDto.d_SaldoAseguradora = (100 - importeCo) * (decimal)objServiceComponentDto.r_Price / 100;
                            }
                            else
                            {
                                frmConfigSeguros frm1 = new frmConfigSeguros(factorGlobal);
                                frm1.ShowDialog();
                                objServiceComponentDto.r_Price            = (float)frm1.nuevoPrecio;
                                objServiceComponentDto.d_SaldoPaciente    = importeCo * frm1.nuevoPrecio / 100;
                                objServiceComponentDto.d_SaldoAseguradora = (100 - importeCo) * frm1.nuevoPrecio / 100;
                            }
                        }
                        break;
                        }
                        #endregion



                        objServiceComponentDto.v_ServiceId              = _serviceId;
                        objServiceComponentDto.i_ExternalInternalId     = (int)Common.ComponenteProcedencia.Interno;
                        objServiceComponentDto.i_ServiceComponentTypeId = 1;
                        objServiceComponentDto.i_IsVisibleId            = 1;
                        objServiceComponentDto.i_IsInheritedId          = (int)Common.SiNo.NO;
                        objServiceComponentDto.d_StartDate              = null;
                        objServiceComponentDto.d_EndDate                  = null;
                        objServiceComponentDto.i_index                    = 1;
                        objServiceComponentDto.v_ComponentId              = scid;
                        objServiceComponentDto.i_IsInvoicedId             = (int)Common.SiNo.NO;
                        objServiceComponentDto.i_ServiceComponentStatusId = (int)Common.ServiceStatus.PorIniciar;
                        objServiceComponentDto.i_QueueStatusId            = (int)Common.QueueStatusId.LIBRE;
                        objServiceComponentDto.i_Iscalling                = (int)Common.Flag_Call.NoseLlamo;
                        objServiceComponentDto.i_Iscalling_1              = (int)Common.Flag_Call.NoseLlamo;
                        objServiceComponentDto.i_IsManuallyAddedId        = (int)Common.SiNo.NO;
                        objServiceComponentDto.i_IsRequiredId             = (int)Common.SiNo.SI;
                        objServiceComponentDto.v_IdUnidadProductiva       = txtUnidProdId.Text;
                        objServiceComponentDto.i_MedicoTratanteId         = int.Parse(cboMedico.SelectedValue.ToString());
                        if (rbNuevaConsulta.Checked)
                        {
                            objServiceComponentDto.i_TipoDesc = 1;
                        }
                        else if (rbAdicional.Checked)
                        {
                            objServiceComponentDto.i_TipoDesc = 2;
                        }

                        _ObjServiceBL.AddServiceComponent(ref objOperationResult, objServiceComponentDto, Globals.ClientSession.GetAsList());
                        #region Update a service agrega el PlanId
                        cadena1 = "update service set " +
                                  "i_PlanId = '" + PlanId + "' " +
                                  "where v_ServiceId = '" + _serviceId + "' ";
                        comando = new SqlCommand(cadena1, connection: conectasam.conectarsigesoft);
                        lector  = comando.ExecuteReader();
                        lector.Close();
                        #endregion
                    }
                    else
                    {
                        FormPrecioComponente frm = new FormPrecioComponente(NombreComponente[0].ToString(), precio_base.ToString(), "");
                        frm.ShowDialog();
                        objServiceComponentDto.i_ConCargoA              = conCargoA;
                        objServiceComponentDto.v_ServiceId              = _serviceId;
                        objServiceComponentDto.i_ExternalInternalId     = (int)Common.ComponenteProcedencia.Interno;
                        objServiceComponentDto.i_ServiceComponentTypeId = 1;
                        objServiceComponentDto.i_IsVisibleId            = 1;
                        objServiceComponentDto.i_IsInheritedId          = (int)Common.SiNo.NO;
                        objServiceComponentDto.d_StartDate              = null;
                        objServiceComponentDto.d_EndDate                  = null;
                        objServiceComponentDto.i_index                    = 1;
                        objServiceComponentDto.r_Price                    = frm.Precio;
                        objServiceComponentDto.v_ComponentId              = scid;
                        objServiceComponentDto.i_IsInvoicedId             = (int)Common.SiNo.NO;
                        objServiceComponentDto.i_ServiceComponentStatusId = (int)Common.ServiceStatus.PorIniciar;
                        objServiceComponentDto.i_QueueStatusId            = (int)Common.QueueStatusId.LIBRE;
                        //objServiceComponentDto.i_IsRequiredId = (int)Common.SiNo.SI;
                        objServiceComponentDto.i_Iscalling          = (int)Common.Flag_Call.NoseLlamo;
                        objServiceComponentDto.i_Iscalling_1        = (int)Common.Flag_Call.NoseLlamo;
                        objServiceComponentDto.i_IsManuallyAddedId  = (int)Common.SiNo.NO;
                        objServiceComponentDto.i_IsRequiredId       = (int)Common.SiNo.SI;
                        objServiceComponentDto.v_IdUnidadProductiva = objComponentDto.v_IdUnidadProductiva;
                        objServiceComponentDto.i_MedicoTratanteId   = int.Parse(cboMedico.SelectedValue.ToString());
                        objServiceComponentDto.d_SaldoPaciente      = 0;
                        objServiceComponentDto.d_SaldoAseguradora   = 0;
                        _ObjServiceBL.AddServiceComponent(ref objOperationResult, objServiceComponentDto, Globals.ClientSession.GetAsList());
                    }
                }

                //Actualizo si son examenes adicionales
                if (_DataSource.Count > 0)
                {
                    new AdditionalExamBL().UpdateAdditionalExamByComponentIdAndServiceId(ComponentId[0], _serviceId,
                                                                                         Globals.ClientSession.i_SystemUserId);
                }
            }

            MessageBox.Show("Se grabo correctamente", " ¡ INFORMACIÓN !", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.DialogResult = DialogResult.OK;
        }
Example #49
0
 private static void PrintChange(string @event, OperationResult result)
 {
     Console.Out.WriteLine($"{@event} {result.Timestamp} Changed: {result.Tag.Name} {result.StatusCode}");
 }
Example #50
0
        public async Task <OperationResult <bool> > Process(FileInfo fileInfo, bool doJustInfo = false)
        {
            var result = new OperationResult <bool>();

            try
            {
                // Determine what type of file this is
                var fileType = DetermineFileType(fileInfo);

                OperationResult <bool> pluginResult = null;
                foreach (var p in Plugins)
                {
                    // See if there is a plugin
                    if (p.HandlesTypes.Contains(fileType))
                    {
                        pluginResult = await p.Process(fileInfo, doJustInfo, SubmissionId).ConfigureAwait(false);

                        break;
                    }
                }

                if (!doJustInfo)
                {
                    // If no plugin, or if plugin not successfull and toggle then move unknown file
                    if ((pluginResult?.IsSuccess != true) && DoMoveUnknowns)
                    {
                        var uf = UnknownFolder;
                        if (!string.IsNullOrEmpty(uf))
                        {
                            if (!Directory.Exists(uf))
                            {
                                Directory.CreateDirectory(uf);
                            }
                            if (!fileInfo.DirectoryName.Equals(UnknownFolder) && File.Exists(fileInfo.FullName))
                            {
                                var df = Path.Combine(UnknownFolder,
                                                      string.Format("{0}~{1}~{2}", Guid.NewGuid(), fileInfo.Directory.Name, fileInfo.Name));
                                Logger.LogDebug("Moving Unknown/Invalid File [{0}] -> [{1}] to UnknownFolder", fileInfo.FullName, df);
                                fileInfo.MoveTo(df);
                            }
                        }
                    }
                }

                result = pluginResult;
            }
            catch (PathTooLongException ex)
            {
                Logger.LogError(ex, "Error Processing File. File Name Too Long. Deleting.");
                if (!doJustInfo)
                {
                    fileInfo.Delete();
                }
            }
            catch (Exception ex)
            {
                var willMove = !fileInfo.DirectoryName.Equals(UnknownFolder);
                Logger.LogError(ex,
                                string.Format("Error Processing File [{0}], WillMove [{1}]\n{2}", fileInfo.FullName, willMove,
                                              ex.Serialize()));
                string newPath = null;
                try
                {
                    newPath = Path.Combine(UnknownFolder, fileInfo.Directory.Parent.Name, fileInfo.Directory.Name,
                                           fileInfo.Name);
                    if (willMove && !doJustInfo)
                    {
                        var directoryPath = Path.GetDirectoryName(newPath);
                        if (!Directory.Exists(directoryPath))
                        {
                            Directory.CreateDirectory(directoryPath);
                        }
                        fileInfo.MoveTo(newPath);
                    }
                }
                catch (Exception ex1)
                {
                    Logger.LogError(ex1,
                                    string.Format("Unable to move file [{0}] to [{1}]", fileInfo.FullName, newPath));
                }
            }

            return(result);
        }
Example #51
0
        private void frmAddAdditionalExam_Load(object sender, EventArgs e)
        {
            OperationResult objOperationResult = new OperationResult();

            if (_DataSource.Count > 0)
            {
                grdDataServiceComponent.DataSource = _DataSource;
                ultraGrid1.DataSource = _DataSource;
                groupBox1.Visible     = false;
                cbLine.Visible        = false;
                this.Height           = 458;
                ultraGrid1.Height     = 360;
                ultraGrid1.Location   = new Point(3, 3);
            }
            else
            {
                var ListServiceComponent = objServiceBL.GetAllComponents(ref objOperationResult, null, "");
                grdDataServiceComponent.DataSource = ListServiceComponent;
                ultraGrid1.DataSource = ListServiceComponent;
            }


            if (_modo == "HOSPI" || _modo == "ASEGU")
            {
                cboMedico.Enabled = true;
                Utils.LoadDropDownList(cboMedico, "Value1", "Id", BLL.Utils.GetProfessionalName(ref objOperationResult), DropDownListAction.Select);
                cboMedico.SelectedValue = "11";
                if (_modo == "ASEGU")
                {
                    #region Conexion SIGESOFT Obtener nombre del protocolo
                    ConexionSigesoft conectasam = new ConexionSigesoft();
                    conectasam.opensigesoft();
                    var cadena1 = "select PR.v_Name, OO.v_Name " +
                                  "from protocol PR " +
                                  "inner join [dbo].[plan] PL on PR.v_ProtocolId=PL.v_ProtocoloId " +
                                  "inner join organization OO on PL.v_OrganizationSeguroId=OO.v_OrganizationId " +
                                  "where v_ProtocolId='" + _protocolId + "' " +
                                  "group by PR.v_Name, OO.v_Name ";
                    SqlCommand    comando         = new SqlCommand(cadena1, connection: conectasam.conectarsigesoft);
                    SqlDataReader lector          = comando.ExecuteReader();
                    string        protocolName    = "";
                    string        aseguradoraName = "";
                    while (lector.Read())
                    {
                        protocolName    = lector.GetValue(0).ToString();
                        aseguradoraName = lector.GetValue(1).ToString();
                    }
                    lector.Close();
                    //conectasam.closesigesoft();
                    lblPlan.Text = "Añadir plan de: " + aseguradoraName + "\n" + "Protocolo de Atención: " + protocolName;
                    if (lblPlan.Text.Length > 50)
                    {
                        lblPlan.Font = new Font("Microsoft Sans Serif", 6.25f);
                    }
                    #endregion

                    cbLine.Select();
                    object listaLine = LlenarLines();
                    cbLine.DataSource            = listaLine;
                    cbLine.DisplayMember         = "v_Nombre";
                    cbLine.ValueMember           = "v_IdLinea";
                    cbLine.AutoCompleteMode      = Infragistics.Win.AutoCompleteMode.Suggest;
                    cbLine.AutoSuggestFilterMode = Infragistics.Win.AutoSuggestFilterMode.Contains;
                    this.cbLine.DropDownWidth    = 590;
                    cbLine.DisplayLayout.Bands[0].Columns[0].Width = 20;
                    cbLine.DisplayLayout.Bands[0].Columns[1].Width = 335;
                    #region Colocar el Plan en el combo y bloquearlo
                    cadena1 = "select SR.i_PlanId, PL.v_IdUnidadProductiva, LN.v_Nombre " +
                              "from service SR " +
                              "inner join [dbo].[plan] PL on SR.v_ProtocolId=PL.v_ProtocoloId and SR.i_PlanId=PL.i_PlanId " +
                              "inner join [20505310072].[dbo].[linea] LN on PL.v_IdUnidadProductiva= LN.v_IdLinea " +
                              "where v_ServiceId = '" + _serviceId + "' and SR.i_PlanId <> ''";
                    comando = new SqlCommand(cadena1, connection: conectasam.conectarsigesoft);
                    lector  = comando.ExecuteReader();
                    string i_PlanId, v_IdUnidadProductiva, v_Nombre = "";
                    bool   resultPlan = false;
                    while (lector.Read())
                    {
                        i_PlanId             = lector.GetValue(0).ToString();
                        v_IdUnidadProductiva = lector.GetValue(1).ToString();
                        v_Nombre             = lector.GetValue(2).ToString();
                        resultPlan           = true;
                    }
                    lector.Close();
                    conectasam.closesigesoft();
                    if (resultPlan)
                    {
                        cbLine.Text    = v_Nombre;
                        cbLine.Enabled = false;
                    }
                    #endregion
                }
                else
                {
                    gbExamenesSeleccionados.Size     = new Size(337, 430);
                    gbExamenesSeleccionados.Location = new Point(626, 12);
                    gbTipoAtencion.Visible           = false;
                    lblPlan.Visible = false;
                    cbLine.Visible  = false;
                }
            }
            else
            {
                Utils.LoadDropDownList(cboMedico, "Value1", "Id", BLL.Utils.GetProfessionalName(ref objOperationResult), DropDownListAction.Select);
                cboMedico.SelectedValue = "11";
                cboMedico.Enabled       = false;
            }
        }
Example #52
0
 void TextToSpeech.IOnInitListener.OnInit(OperationResult status)
 {
     _lastStatus = status;
     Log.Debug(TAG, "OnInit() status = " + status);
     _event1.Set();
 }
Example #53
0
        private OperationResult ValidarAccesoUsuarioSistemaEmpresa(BEUsuarioValidoResponse objUsuarioValidado, string pKeySistema)
        {
            var operationResult = new OperationResult();

            operationResult.isValid = false;
            if (string.IsNullOrEmpty(objUsuarioValidado.codEmpresaNombre) && objUsuarioValidado.codEmpleado != "EXT")
            {
                operationResult.brokenRulesCollection.Add(new BrokenRule
                {
                    description = WebConstants.ValidacionDatosSEGURIDAD.FirstOrDefault(x => x.Key == 2006).Value,
                    severity    = RuleSeverity.Warning
                });
                return(operationResult);
            }
            else if (string.IsNullOrEmpty(objUsuarioValidado.codSistemaNombre))
            {
                operationResult.brokenRulesCollection.Add(new BrokenRule
                {
                    description = WebConstants.ValidacionDatosSEGURIDAD.FirstOrDefault(x => x.Key == 2007).Value,
                    severity    = RuleSeverity.Warning
                });
                return(operationResult);
            }
            else if (string.IsNullOrEmpty(objUsuarioValidado.codRolNombre))
            {
                operationResult.brokenRulesCollection.Add(new BrokenRule
                {
                    description = WebConstants.ValidacionDatosSEGURIDAD.FirstOrDefault(x => x.Key == 2008).Value,
                    severity    = RuleSeverity.Warning
                });
                return(operationResult);
            }

            //Validar si esta asignado a una empresa
            //365A01B7-6C8E-460E-90F4-29C52D6CADD7|1|Sistema SIS|10181980325,
            //0E48ADC1-21B7-465B-858E-F3A3C608CEB1|2|Sistema GC|10181980327
            bool     blnEmpresaEsValido = false;
            string   strEmpresa         = string.Empty;
            string   strnumRUC          = string.Empty;
            DateTime?fecLicenciaVenc    = null;
            int      numCodigoError     = 0;

            if (objUsuarioValidado.codEmpleado != "EXT")
            {
                //HelpLogging.Write(TraceLevel.Warning, string.Concat(GetType().Name, ".", MethodBase.GetCurrentMethod().Name),
                //                  objUsuarioValidado.codEmpresaNombre,
                //                  string.Format("Empresa:[{0}], Usuario:[{1}]", "00", objUsuarioValidado.desLogin));

                string[] arrEmpresas = objUsuarioValidado.codEmpresaNombre.Split(',');
                foreach (string itemEmpresa in arrEmpresas)
                {
                    string[] arrDatoEmpresa = itemEmpresa.Split('|');

                    //HelpLogging.Write(TraceLevel.Info, string.Concat(GetType().Name,".", MethodBase.GetCurrentMethod().Name),
                    //              string.Format("arrDatoEmpresa[{0}].Trim() == pKeySistema({1})", arrDatoEmpresa[0].Trim(), pKeySistema),
                    //              string.Format("Empresa:[{0}], Usuario:[{1}]", "00", objUsuarioValidado.desLogin));

                    if (arrDatoEmpresa[0].Trim() == pKeySistema)
                    {
                        //HelpLogging.Write(TraceLevel.Info, string.Concat(GetType().Name, ".", MethodBase.GetCurrentMethod().Name),
                        //          string.Format("ConvertYYYYMMDDToDate:[ {0} ] == DateTime.Now=[ {1} ]", HelpTime.ConvertYYYYMMDDToDate(arrDatoEmpresa[1].Trim()),
                        //                                                                                 DateTime.Now.AddHours(GlobalSettings.GetDEFAULT_HorasFechaActualCloud())),
                        //          string.Format("Empresa:[{0}], Usuario:[{1}]", "00", objUsuarioValidado.desLogin));

                        if (HelpTime.ConvertYYYYMMDDToDate(arrDatoEmpresa[1].Trim()) > DateTime.Now.AddHours(GlobalSettings.GetDEFAULT_HorasFechaActualCloud()))
                        {
                            blnEmpresaEsValido            = true;
                            numCodigoError                = 0;
                            objUsuarioValidado.codEmpresa = Extensors.CheckInt(arrDatoEmpresa[2]);
                            strEmpresa = arrDatoEmpresa[3].Trim();
                            strnumRUC  = arrDatoEmpresa[4].Trim();
                            break;
                        }
                        else
                        {
                            numCodigoError  = 2011;
                            strEmpresa      = arrDatoEmpresa[3].Trim();
                            fecLicenciaVenc = HelpTime.ConvertYYYYMMDDToDate(arrDatoEmpresa[1].Trim());
                            HelpLogging.Write(TraceLevel.Warning, string.Concat(GetType().Name, ".", MethodBase.GetCurrentMethod().Name),
                                              string.Format("numCodigoError:[ {0} ] == DateTime.Now=[ {1} ]", numCodigoError,
                                                            DateTime.Now.AddHours(GlobalSettings.GetDEFAULT_HorasFechaActualCloud())),
                                              string.Format("Empresa:[{0}], Usuario:[{1}]", "00", objUsuarioValidado.desLogin));
                            break;
                        }
                    }
                    else
                    {
                        numCodigoError = 2010;
                        HelpLogging.Write(TraceLevel.Warning, string.Concat(GetType().Name, MethodBase.GetCurrentMethod().Name),
                                          string.Format("numCodigoError:[ {0} ] == DateTime.Now=[ {1} ]", numCodigoError,
                                                        DateTime.Now.AddHours(GlobalSettings.GetDEFAULT_HorasFechaActualCloud())),
                                          string.Format("Empresa:[{0}], Usuario:[{1}]", "00", objUsuarioValidado.desLogin));
                    }
                }

                if (!blnEmpresaEsValido)
                {
                    if (numCodigoError == 2011)
                    {
                        operationResult.brokenRulesCollection.Add(new BrokenRule
                        {
                            description = string.Format(WebConstants.ValidacionDatosSEGURIDAD.FirstOrDefault(x => x.Key == numCodigoError).Value,
                                                        strEmpresa, fecLicenciaVenc.Value.ToShortDateString()),
                            severity = RuleSeverity.Warning
                        });
                    }
                    else
                    {
                        operationResult.brokenRulesCollection.Add(new BrokenRule
                        {
                            description = WebConstants.ValidacionDatosSEGURIDAD.FirstOrDefault(x => x.Key == numCodigoError).Value,
                            severity    = RuleSeverity.Warning
                        });
                    }
                    return(operationResult);
                }

                objUsuarioValidado.codEmpresaNombre = strEmpresa;
                objUsuarioValidado.numRUC           = strnumRUC;
            }

            //Validar si esta asignado al sistema
            //365A01B7-6C8E-460E-90F4-29C52D6CADD7|1|Sistema SIS,
            //0E48ADC1-21B7-465B-858E-F3A3C608CEB1|2|Sistema GC
            bool   blnSistemaEsValido = false;
            string strSistema         = string.Empty;

            string[] arrSistemas = objUsuarioValidado.codSistemaNombre.Split(',');
            foreach (string itemSistema in arrSistemas)
            {
                string[] strValoresSistema = itemSistema.Split('|');
                if (strValoresSistema[0].Trim() == pKeySistema)
                {
                    strSistema = strValoresSistema[2].Trim();
                    objUsuarioValidado.codSistema = strValoresSistema[1].Trim();
                    blnSistemaEsValido            = true;
                    break;
                }
            }
            if (!blnSistemaEsValido)
            {
                operationResult.brokenRulesCollection.Add(new BrokenRule
                {
                    description = WebConstants.ValidacionDatosSEGURIDAD.FirstOrDefault(x => x.Key == 2009).Value,
                    severity    = RuleSeverity.Warning
                });
                return(operationResult);
            }
            objUsuarioValidado.codSistemaNombre = strSistema;
            //Validar si esta asignado a un rol
            //365A01B7-6C8E-460E-90F4-29C52D6CADD7|1|Administrador,
            //0E48ADC1-21B7-465B-858E-F3A3C608CEB1|15|Administrador
            bool   blnUsuarioEsValido = false;
            string strRol             = string.Empty;

            string[] arrRolesUsuario = objUsuarioValidado.codRolNombre.Split(',');
            foreach (string itemRolesUsuario in arrRolesUsuario)
            {
                string[] strValoresRolesUsuario = itemRolesUsuario.Split('|');
                if (strValoresRolesUsuario[0].Trim() == pKeySistema)
                {
                    strRol = strValoresRolesUsuario[2].Trim();
                    objUsuarioValidado.codRol = strValoresRolesUsuario[1].Trim();
                    blnUsuarioEsValido        = true;
                    break;
                }
            }
            if (!blnUsuarioEsValido)
            {
                operationResult.brokenRulesCollection.Add(new BrokenRule
                {
                    description = WebConstants.ValidacionDatosSEGURIDAD.FirstOrDefault(x => x.Key == 2012).Value,
                    severity    = RuleSeverity.Warning
                });
                return(operationResult);
            }

            objUsuarioValidado.codRolNombre = strRol;
            operationResult.isValid         = true;
            return(operationResult);
        }
Example #54
0
        /// <summary>
        /// Metodo                  :DetectarUsuario
        /// Propósito               :Permite detectar la existencia del usuario con Login y Contrasenia
        /// Retorno                 :Verdadero o Falso
        /// Autor                   :OCR - Orlando Carril R.
        /// Fecha/Hora de Creación  :22/10/2015
        /// Modificado              :N/A
        /// Fecha/Hora Modificación :N/A
        /// </summary>
        /// <param name="pdesLogin">Login del usuario</param>
        /// <param name="pclvContrasenia">Contraseña del usuario</param>
        /// <returns></returns>
        public OperationResult ValidarUsuario(string pdesLogin, string pclvContrasenia, string pKeySistema, string numIP)
        {
            BEUsuarioValidoResponse objUsuarioValidado = null;
            SeguridadData           objSeguridadDataNx = null;

            try
            {
                objSeguridadDataNx = new SeguridadData();

                var pUserSeek = ValidarDataAccesoUsuario(pdesLogin, pclvContrasenia);

                if (pUserSeek.brokenRulesCollection.Count == 0)
                {
                    string pMessage = string.Empty;
                    if (!DetectLoginPasswordExterno(pdesLogin, pclvContrasenia, out pMessage))
                    {
                        var operationResult = new OperationResult();
                        operationResult.isValid = false;
                        operationResult.brokenRulesCollection.Add(new BrokenRule
                        {
                            description = pMessage,
                            severity    = RuleSeverity.Warning
                        });

                        return(operationResult);
                    }
                    objUsuarioValidado = objSeguridadDataNx.FindLoginValidated(pdesLogin);

                    if (objUsuarioValidado == null)
                    {
                        /* Guardar auditoria de los ingresos FALLIDOS al sistema  */
                        int codigoRetorno = InsertAuditoria(new BEAuditoria
                        {
                            desLogin       = pdesLogin,
                            codRol         = null,
                            codSistema     = pKeySistema,
                            desMensaje     = WebConstants.ValidacionDatosSEGURIDAD.FirstOrDefault(x => x.Key == 2004).Value,
                            desTipo        = RuleSeverity.Warning.ToString(),
                            fecRegistroApp = DateTime.Now.AddHours(GlobalSettings.GetDEFAULT_HorasFechaActualCloud()),
                            nomMaquinaIP   = numIP
                        });

                        var operationResult = new OperationResult();
                        if (codigoRetorno <= 3)
                        {
                            operationResult.brokenRulesCollection.Add(new BrokenRule
                            {
                                description = WebConstants.ValidacionDatosSEGURIDAD.FirstOrDefault(x => x.Key == 2004).Value,
                                severity    = RuleSeverity.Warning
                            });
                        }
                        else
                        {
                            operationResult.brokenRulesCollection.Add(new BrokenRule
                            {
                                description = string.Format(WebConstants.ValidacionDatosSEGURIDAD.FirstOrDefault(x => x.Key == 2013).Value,
                                                            codigoRetorno),
                                severity = RuleSeverity.Warning
                            });
                        }
                        return(operationResult);
                    }
                    else /* Guardar auditoria de los ingresos SATISFACTORIOS al sistema  */
                    {
                        var operationResult = new OperationResult();
                        operationResult = ValidarAccesoUsuarioSistemaEmpresa(objUsuarioValidado, pKeySistema);

                        if (operationResult.isValid)
                        {
                            objUsuarioValidado.Token           = GetToken(objUsuarioValidado);
                            objUsuarioValidado.ResultIndValido = true;

                            var auditoria = new BEAuditoria
                            {
                                desLogin       = pdesLogin,
                                codRol         = objUsuarioValidado.codRol,
                                codEmpresa     = objUsuarioValidado.codEmpresa,
                                codSistema     = pKeySistema,
                                desTipo        = RuleSeverity.Success.ToString(),
                                fecRegistroApp = DateTime.Now.AddHours(GlobalSettings.GetDEFAULT_HorasFechaActualCloud()),
                                nomMaquinaIP   = numIP
                            };
                            auditoria.desMensaje = WebConstants.ValidacionDatosSEGURIDAD.FirstOrDefault(x => x.Key == 2000).Value;
                            int codigoRetorno = InsertAuditoria(auditoria);
                        }
                        else
                        {
                            return(operationResult);
                        }
                    }
                }
                else
                {
                    objUsuarioValidado = new BEUsuarioValidoResponse();
                    objUsuarioValidado.ResultIMessage  = pUserSeek.brokenRulesCollection[0].description;
                    objUsuarioValidado.ResultIndValido = false;
                }
                return(OK(objUsuarioValidado));
            }
            catch (Exception ex)
            {
                return(Error(GetType().Name, MethodBase.GetCurrentMethod().Name, ex, "", ""));
            }
        }
        public async Task <OperationResult> CreateFolder(string requestedVirtualPath, string folderName)
        {
            OperationResult result;

            if (string.IsNullOrEmpty(folderName))
            {
                result         = new OperationResult(false);
                result.Message = _sr["Folder name not provided"];
                _log.LogWarning($"CreateFolder: Folder name not provided");
                return(result);
            }

            await EnsureProjectSettings().ConfigureAwait(false);

            if (string.IsNullOrEmpty(requestedVirtualPath))
            {
                requestedVirtualPath = _rootPath.RootVirtualPath;
            }

            var    isRoot = (requestedVirtualPath == _rootPath.RootVirtualPath);
            string requestedFsPath;

            if (!isRoot)
            {
                if (!requestedVirtualPath.StartsWith(_rootPath.RootVirtualPath))
                {
                    result         = new OperationResult(false);
                    result.Message = _sr["Invalid path"];
                    _log.LogWarning($"CreateFolder: {requestedVirtualPath} was not valid for root path {_rootPath.RootVirtualPath}");
                    return(result);
                }

                var virtualSubPath = requestedVirtualPath.Substring(_rootPath.RootVirtualPath.Length);
                var segments       = virtualSubPath.Split('/');
                if (segments.Length > 0)
                {
                    requestedFsPath = Path.Combine(_rootPath.RootFileSystemPath, Path.Combine(segments));
                    if (!Directory.Exists(requestedFsPath))
                    {
                        result         = new OperationResult(false);
                        result.Message = _sr["Invalid path"];
                        _log.LogWarning($"CreateFolder: {requestedVirtualPath} was not valid for root path {_rootPath.RootVirtualPath}");
                        return(result);
                    }
                }
                else
                {
                    requestedFsPath = _rootPath.RootFileSystemPath;
                }
            }
            else
            {
                requestedFsPath = _rootPath.RootFileSystemPath;
            }

            var newFolderFsPath = Path.Combine(requestedFsPath, _nameRules.GetCleanFolderName(folderName));

            if (Directory.Exists(newFolderFsPath))
            {
                result         = new OperationResult(false);
                result.Message = _sr["Folder already exists"];
                _log.LogWarning($"CreateFolder: {requestedVirtualPath} already exists");
                return(result);
            }

            try
            {
                Directory.CreateDirectory(newFolderFsPath);
                result = new OperationResult(true);
                return(result);
            }
            catch (IOException ex)
            {
                _log.LogError(MediaLoggingEvents.FOLDER_CREATION, ex, ex.Message + " " + ex.StackTrace);
                result         = new OperationResult(false);
                result.Message = _sr["Server error"];
                return(result);
            }
        }
Example #56
0
        private void AddAuxiliaryExam()
        {
            var findResult = lvExamenesSeleccionados.FindItemWithText(MedicalExamId);

            // El examen ya esta agregado
            if (findResult != null)
            {
                MessageBox.Show("Por favor seleccione otro examen.", "Error de validación", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            var res = _ListaComponentes.Find(p => p == MedicalExamId);

            if (res != null)
            {
                var DialogResult = MessageBox.Show("El paciente ya cuenta con este examen, ¿Desea crear nuevo servicio?", "Error de Valicación", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                if (DialogResult == System.Windows.Forms.DialogResult.Yes)
                {
                    #region Agenda Automática
                    CalendarBL      calendarBl         = new CalendarBL();
                    OperationResult objOperationResult = new OperationResult();

                    var protocolId = Constants.Prot_Hospi_Adic;

                    var objCalendarDto = new calendarDto();
                    objCalendarDto.v_PersonId         = new PacientBL().GetPersonByNroDocument(ref objOperationResult, _dni).v_PersonId;// item.PersonId;
                    objCalendarDto.d_DateTimeCalendar = DateTime.Now;
                    objCalendarDto.d_CircuitStartDate = DateTime.Now;
                    objCalendarDto.d_EntryTimeCM      = DateTime.Now;
                    objCalendarDto.i_ServiceTypeId    = (int)ServiceType.Particular;
                    objCalendarDto.i_ServiceId        = (int)MasterService.Hospitalizacion;

                    objCalendarDto.i_CalendarStatusId  = (int)CalendarStatus.Agendado;
                    objCalendarDto.i_LineStatusId      = (int)LineStatus.EnCircuito;
                    objCalendarDto.v_ProtocolId        = protocolId;
                    objCalendarDto.i_NewContinuationId = 1;
                    objCalendarDto.i_LineStatusId      = (int)LineStatus.EnCircuito;
                    objCalendarDto.i_IsVipId           = (int)SiNo.NO;

                    var serviceId = calendarBl.AddShedule(ref objOperationResult, objCalendarDto, Globals.ClientSession.GetAsList(), protocolId, objCalendarDto.v_PersonId, (int)MasterService.Eso, "Nuevo");

                    serviceDto objServiceDto = new serviceDto();
                    objServiceDto = new ServiceBL().GetService(ref objOperationResult, serviceId);
                    objServiceDto.d_ServiceDate = DateTime.Now;

                    objServiceDto.i_ServiceStatusId = (int)Common.ServiceStatus.Iniciado;
                    new ServiceBL().UpdateService(ref objOperationResult, objServiceDto, Globals.ClientSession.GetAsList());


                    var servicesComponents = new ServiceBL().GetServiceComponents(ref objOperationResult, serviceId);

                    foreach (var servicesComponent in servicesComponents)
                    {
                        servicecomponentDto oservicecomponentDto = new servicecomponentDto();
                        oservicecomponentDto = new ServiceBL().GetServiceComponent(ref objOperationResult,
                                                                                   servicesComponent.v_ServiceComponentId);
                        oservicecomponentDto.i_MedicoTratanteId   = 11;
                        oservicecomponentDto.i_IsVisibleId        = 1;
                        oservicecomponentDto.v_ServiceComponentId = servicesComponent.v_ServiceComponentId;
                        new ServiceBL().UpdateServiceComponent(ref objOperationResult, oservicecomponentDto, Globals.ClientSession.GetAsList());
                    }



                    var oHospitalizacionserviceDto = new hospitalizacionserviceDto();

                    oHospitalizacionserviceDto.v_HopitalizacionId = _nroHospitalizacion;
                    oHospitalizacionserviceDto.v_ServiceId        = serviceId;

                    new HospitalizacionBL().AddHospitalizacionService(ref objOperationResult, oHospitalizacionserviceDto, Globals.ClientSession.GetAsList());
                    #endregion

                    MessageBox.Show("Se generó el servicio: " + serviceId, " ¡ INFORMACIÓN !", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //var DialogResult = DialogResult.OK;
                    //var frm = new frmCalendar(_nroHospitalizacion, _dni, _serviceId);
                    //frm.ShowDialog();
                }
                else
                {
                    return;
                }
            }


            var row = new ListViewItem(new[] { MedicalExamName, MedicalExamId, ServiceComponentConcatId });

            lvExamenesSeleccionados.Items.Add(row);

            gbExamenesSeleccionados.Text = string.Format("Examenes Seleccionados {0}", lvExamenesSeleccionados.Items.Count);
        }
        public async Task <OperationResult> RenameFile(string requestedVirtualPath, string newNameSegment)
        {
            OperationResult result;

            if (string.IsNullOrEmpty(requestedVirtualPath))
            {
                result         = new OperationResult(false);
                result.Message = _sr["Path not provided"];
                return(result);
            }

            if (string.IsNullOrEmpty(newNameSegment))
            {
                result         = new OperationResult(false);
                result.Message = _sr["New name not provided"];
                return(result);
            }

            await EnsureProjectSettings().ConfigureAwait(false);

            if (!requestedVirtualPath.StartsWith(_rootPath.RootVirtualPath))
            {
                result         = new OperationResult(false);
                result.Message = _sr["Invalid path"];
                _log.LogWarning($"RenameFile: {requestedVirtualPath} was not valid for root path {_rootPath.RootVirtualPath}");
                return(result);
            }

            var virtualSubPath = requestedVirtualPath.Substring(_rootPath.RootVirtualPath.Length);
            var segments       = virtualSubPath.Split('/');

            if (segments.Length == 0)
            {
                // don't allow delete the root folder
                result         = new OperationResult(false);
                result.Message = _sr["Invalid path"];
                _log.LogWarning($"RenameFile: {requestedVirtualPath} was not valid for root path {_rootPath.RootVirtualPath}");
                return(result);
            }

            var currentFsPath = Path.Combine(_rootPath.RootFileSystemPath, Path.Combine(segments));
            var ext           = Path.GetExtension(currentFsPath);

            if (!File.Exists(currentFsPath))
            {
                result         = new OperationResult(false);
                result.Message = _sr["Invalid path"];
                _log.LogWarning($"RenameFile: {requestedVirtualPath} does not exist");
                return(result);
            }

            // pop the last segment
            segments = segments.Take(segments.Count() - 1).ToArray();

            if (Path.HasExtension(newNameSegment) && Path.GetExtension(newNameSegment) == ext)
            {
                // all good
            }
            else
            {
                newNameSegment = Path.GetFileNameWithoutExtension(newNameSegment) + ext;
            }
            var cleanFileName = _nameRules.GetCleanFileName(newNameSegment);

            string newFsPath;

            if (segments.Length > 0)
            {
                newFsPath = Path.Combine(Path.Combine(_rootPath.RootFileSystemPath, Path.Combine(segments)), cleanFileName);
            }
            else
            {
                newFsPath = Path.Combine(_rootPath.RootFileSystemPath, cleanFileName);
            }


            if (File.Exists(newFsPath))
            {
                result         = new OperationResult(false);
                result.Message = _sr["Directory already exists"];
                return(result);
            }

            try
            {
                File.Move(currentFsPath, newFsPath);
                result = new OperationResult(true);
                return(result);
            }
            catch (IOException ex)
            {
                _log.LogError(MediaLoggingEvents.FOLDER_RENAME, ex, ex.Message + " " + ex.StackTrace);
                result         = new OperationResult(false);
                result.Message = _sr["A error was logged while processing the request"];
                return(result);
            }
        }
Example #58
0
        /// <summary>
        ///  查询对比值
        /// </summary>
        /// <param name="typeID">类型: 0:当天 1:昨天 2:7天 3:30天 4:自定义时间 5:90天</param>
        /// <returns></returns>
        public JsonResult GetDataContrast(string startTime, string endTime, int typeID = 2)
        {
            //同比:由时间控制
            //环比:开始时间 对比的数据是上一个月数据,被对比的数据,是由时间提供,本月数据不作对比


            //设定时间
            var result = new JsonResultObject();
            IList <DataContrastInfo> dcInfoList = new List <DataContrastInfo>();

            //当前时间
            DateTime sTime = DateTime.Now;
            DateTime eTime = DateTime.Now;

            GetTime(startTime, endTime, typeID, ref sTime, ref eTime);

            //同比时间
            DateTime anSTime = sTime.AddYears(-1);
            DateTime anETime = eTime.AddYears(-1);

            //被环比的时间
            DateTime adjStime = sTime.AddDays(-1);
            DateTime adjEtime = eTime.AddDays(-1);


            TimeSpan ts = sTime - DateTime.Parse(eTime.ToShortDateString());

            adjStime = adjStime.Add(ts);
            adjEtime = adjEtime.Add(ts);

            //同比数据
            OperationResult <IList <OrderDailyInfo> > anInfo =
                OrderDailyBLL.Instance.OrderDaily_GetSUMAll(anSTime, anETime);

            //环比数据
            OperationResult <IList <OrderDailyInfo> > adjInfo =
                OrderDailyBLL.Instance.OrderDaily_GetSUMAll(adjStime, adjEtime);

            //获取本年同比数据
            OperationResult <IList <OrderDailyInfo> > currentAnInfo =
                OrderDailyBLL.Instance.OrderDaily_GetSUMAll(sTime, eTime);

            if (anInfo.ResultType != OperationResultType.Success ||
                adjInfo.ResultType != OperationResultType.Success ||
                currentAnInfo.ResultType != OperationResultType.Success)
            {
                result.status = false;
                result.msg    = "展示异常,数据库连接异常!";
                return(Json(result));
            }
            IList <OrderDailyInfo> cInfoList = currentAnInfo.AppendData;

            for (int i = 0; i < cInfoList.Count; i++)
            {
                OrderDailyInfo   cInfo  = cInfoList[i];
                DataContrastInfo dcInfo = new DataContrastInfo();
                dcInfo.Source      = cInfo.Source;
                dcInfo.SourceName  = Enum.GetName(typeof(OrderSource), dcInfo.Source);
                dcInfo.OrderAmount = cInfo.OrderAmount;
                dcInfo.OrderQuan   = cInfo.OrderQuan;
                dcInfo.PayQuan     = cInfo.PayQuan;
                dcInfo.NoPayQuan   = cInfo.OrderQuan - cInfo.PayQuan;
                dcInfoList.Add(dcInfo);
            }

            foreach (var cInfo in dcInfoList)
            {
                foreach (var aInfo in anInfo.AppendData)
                {
                    //同比值
                    if (cInfo.Source == aInfo.Source)
                    {
                        cInfo.AnOrderAmount = GetPercent(cInfo.OrderAmount, aInfo.OrderAmount);                             //总订单额
                        cInfo.AnOrderQuan   = GetPercent(cInfo.OrderQuan, aInfo.OrderQuan);                                 //总订单数
                        cInfo.AnPayQuan     = GetPercent(cInfo.PayQuan, aInfo.PayQuan);                                     //支付订单
                        cInfo.AnNoPayQuan   = GetPercent(cInfo.OrderQuan - cInfo.PayQuan, aInfo.OrderQuan - aInfo.PayQuan); //未支付订单量
                    }
                }
                foreach (var adInfo in adjInfo.AppendData)
                {
                    //环比值
                    if (cInfo.Source == adInfo.Source)
                    {
                        cInfo.AdjOrderAmount = GetPercent(cInfo.OrderAmount, adInfo.OrderAmount);                              //总订单额
                        cInfo.AdjOrderQuan   = GetPercent(cInfo.OrderQuan, adInfo.OrderQuan);                                  //总订单数
                        cInfo.AdjPayQuan     = GetPercent(cInfo.PayQuan, adInfo.PayQuan);                                      //支付订单
                        cInfo.AdjNoPayQuan   = GetPercent(cInfo.OrderQuan - cInfo.PayQuan, adInfo.OrderQuan - adInfo.PayQuan); //未支付订单量
                    }
                }
            }
            result.data   = JsonHelper.ConvertToJson(dcInfoList);
            result.msg    = null;
            result.status = true;
            return(Json(result));
        }
Example #59
0
 private static void TagChanged(OperationResult result)
 {
     PrintChange("TagChanged", result);
 }
Example #60
0
        public OperationResult <MenuTreeData> GetWebTreeMenus()
        {
            var result = new OperationResult <MenuTreeData>();

            try
            {
                var menus     = GetMenus();
                var rolemenus = menus.PageRight;

                result.Body           = new MenuTreeData();
                result.Body.PageRight = new List <MenuTreeItemData>();
                foreach (var menu in rolemenus)
                {
                    var child = new MenuTreeItemData();
                    child.id = menu.MID;
                    if (menu.PID == 0)
                    {
                        child.parent = "#";
                    }
                    else
                    {
                        child.parent = menu.PID + "";
                    }

                    child.icon  = menu.MIcon;
                    child.state = new MenuTreeStateData()
                    {
                        opened = true
                    };
                    child.text    = menu.MName;
                    child.li_attr = new Dictionary <string, string>()
                    {
                        { "dtype", menu.MType + "" }
                    };
                    child.url = menu.Url;
                    result.Body.PageRight.Add(child);
                }

                var extends = menus.PageRightExtend;

                if (extends != null && extends.Count > 0)
                {
                    result.Body.PageRightExtend = new List <MenuTreeItemData>();
                    foreach (var menu in extends)
                    {
                        var parentPage = result.Body.PageRight.FirstOrDefault(c => c.id == menu.MID);
                        if (parentPage == null)
                        {
                            continue;
                        }

                        if (result.Body.PageRightExtend.Exists(c => c.id == parentPage.id) == false)
                        {
                            var pagePar = new MenuTreeItemData()
                            {
                                parent  = "#",
                                id      = parentPage.id,
                                icon    = parentPage.icon,
                                li_attr = parentPage.li_attr,
                                text    = parentPage.text,
                                state   = parentPage.state,
                            };
                            result.Body.PageRightExtend.Add(pagePar);
                        }
                        var child = new MenuTreeItemData();
                        child.id      = menu.ExtendID;
                        child.parent  = menu.MID + "";
                        child.icon    = "fa fa-chain";
                        child.li_attr = new Dictionary <string, string>()
                        {
                            { "dtype", "2" }
                        };
                        child.text = menu.ExtendName;
                        result.Body.PageRightExtend.Add(child);
                    }
                }


                result.ErrCode = 0;
                result.Message = "ok";
            }
            catch (Exception ex)
            {
                Logger.WriteException("GetWebTreeMenusV2", ex, "");
                result.ErrCode = -1;
                result.Message = ex.Message;
            }

            return(result);
        }