Пример #1
0
        private string SendRequest(GenericRequest request, string httpMethod, bool isAuth = true)
        {
            string json   = JsonConvert.SerializeObject(request);
            string json64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(json));

            byte[] data      = Encoding.UTF8.GetBytes(json64);
            byte[] hash      = hashMaker.ComputeHash(data);
            string signature = GetHexString(hash);

            HttpWebRequest wr = WebRequest.Create("https://api.bitfinex.com" + request.request) as HttpWebRequest;

            wr.Headers.Add("X-BFX-APIKEY", Key);
            wr.Headers.Add("X-BFX-PAYLOAD", json64);
            wr.Headers.Add("X-BFX-SIGNATURE", signature);
            wr.Method = httpMethod;

            string response = null;

            try
            {
                HttpWebResponse resp = wr.GetResponse() as HttpWebResponse;
                StreamReader    sr   = new StreamReader(resp.GetResponseStream());
                response = sr.ReadToEnd();
                sr.Close();
            }
            catch (WebException ex)
            {
                StreamReader sr = new StreamReader(ex.Response.GetResponseStream());
                response = sr.ReadToEnd();
                sr.Close();
                throw new BitfinexException(ex, response);
            }
            return(response);
        }
Пример #2
0
        private GenericRequest CreateRequest()
        {
            GenericRequest request = new GenericRequest();

            request.UserName = "******";
            return(request);
        }
Пример #3
0
        public virtual async Task <GenericResponse <TDto> > UpdateAsync(GenericRequest <TDto> request)
        {
            var response = await ValidateAsync(request);

            if (response.IsError())
            {
                return(response);
            }

            try
            {
                var dto = await _repository.UpdateAsync(request.Data);

                if (dto == null)
                {
                    response.AddErrorMessage(GeneralResource.Item_Update_NotFound);
                    return(response);
                }

                response.Data = dto;
                response.AddInfoMessage(GeneralResource.Info_Saved);
            }
            catch (Exception e)
            {
                response.AddErrorMessage(e.InnerException?.Message ?? e.Message);
            }

            return(response);
        }
Пример #4
0
        protected virtual async Task <GenericResponse <TDto> > ValidateAsync(GenericRequest <TDto> request)
        {
            var response = new GenericResponse <TDto>();
            await Task.CompletedTask;

            return(response);
        }
Пример #5
0
        public async Task <List <GenreResponse> > FetchGenres()
        {
            var Request  = new GenericRequest(EndPoints.GenreList);
            var Response = await DoGet <GenericRequest, GenreListResponse>(Request);

            return(Response?.Genres ?? new List <GenreResponse>());
        }
Пример #6
0
        public async Task <List <MovieResponse> > FetchMovies(int Page)
        {
            var Request  = new GenericRequest(string.Format(EndPoints.MoviesList, Page));
            var Response = await DoGet <GenericRequest, MovieListResponse>(Request);

            return(Response?.Movies ?? new List <MovieResponse>());
        }
Пример #7
0
        public override GenericResponse <T> GetByExpression(GenericRequest <T> Request)
        {
            GenericResponse <T> response = new GenericResponse <T>();

            try
            {
                response.EntityList = _context.Set <T>()
                                      .Where(Request.Expression)
                                      .ToList();

                if (response.EntityList.Count <= 0)
                {
                    response.Result_Type = CoreEnum.Result_Type.NoData;
                }
                else
                {
                    response.Result_Type = CoreEnum.Result_Type.Success;
                }
            }
            catch (Exception ex)
            {
                response.Result_Type = CoreEnum.Result_Type.Failed;
                response.Message     = ex.Message.ToString();
            }
            return(response);
        }
Пример #8
0
        public override GenericResponse <T> DisableEntity(GenericRequest <T> Request)
        {
            GenericResponse <T> response = new GenericResponse <T>();

            try
            {
                GenericRequest <T> EntityRequest = new GenericRequest <T>();
                EntityRequest.ID = Request.ID;
                T willUpdated = this.GetByID(EntityRequest).Entity;
                willUpdated.Status = Status_Type.Passive;

                Request.Entity = willUpdated;

                _context.Entry(willUpdated).CurrentValues.SetValues(Request.Entity);
                _context.SaveChanges();
                response.Result_Type = Result_Type.Success;
            }
            catch (Exception ex)
            {
                response.Result_Type = AppCore.CoreEnum.Result_Type.Failed;
                response.Entity      = null;
                response.Message     = ex.Message.ToString();
            }

            return(response);
        }
Пример #9
0
        public override GenericResponse <T> Update(GenericRequest <T> Request)
        {
            GenericResponse <T> response = new GenericResponse <T>();

            try
            {
                GenericRequest <T> EntityRequest = new GenericRequest <T>();
                EntityRequest.ID = Request.Entity.ID;
                T willUpdated = this.GetByID(EntityRequest).Entity;

                _context.Entry(willUpdated).CurrentValues.SetValues(Request.Entity);
                _context.SaveChanges();
                response.Result_Type = CoreEnum.Result_Type.Success;
            }
            catch (Exception ex)
            {
                response.Result_Type = CoreEnum.Result_Type.Failed;
                response.Message     = ex.Message.ToString();
            }
            finally
            {
                response.Entity = Request.Entity;
            }
            return(response);
        }
Пример #10
0
        protected async Task CallGenericMessagesCore(JsonServer js, JsonClient jc, ICredentials credentials = null)
        {
            js.Start();
            await jc.ConnectAsync();

            var intMsg = new GenericRequest <int> {
                Value = 1
            };
            var intResult = await jc.Call(intMsg);

            Assert.AreEqual(2, intResult.Result);

            var dtMsg = new GenericRequest <DateTime> {
                Value = new DateTime(2018, 12, 18)
            };
            var dtResult = await jc.Call(dtMsg);

            Assert.AreEqual(new DateTime(2019, 12, 18), dtResult.Result);

            var strMsg = new GenericRequest <string> {
                Value = "World"
            };
            var strResult = await jc.Call(strMsg);

            Assert.AreEqual("Hello World!", strResult.Result);

            var boolMsg = new GenericRequest <bool> {
                Value = true
            };

            Assert.ThrowsAsync <MethodNotFoundException>(async() => await jc.Call(boolMsg));

            // make sure all incoming messages are processed
            Assert.AreEqual(0, jc.PendingMessages.Count);
        }
Пример #11
0
        public async Task <ActionResult <Operation> > Get(GenericRequest request)
        {
            var ChallengeClient = await _context.Clients.FindAsync(request.ClientId);

            if (ChallengeClient == null)
            {
                return(NotFound());
            }

            ChallengeClient.Balance -= request.Value;

            var operation = new Operation {
                Client = ChallengeClient.Id.ToString(),
                Type   = "TakeOut",
                Value  = request.Value.ToString(),
                Date   = DateTime.Now
            };

            _context.Operations.Add(operation);

            if (Hasher.Verify(request.Password, ChallengeClient.Password))
            {
                await _context.SaveChangesAsync();

                return(operation);
            }

            return(Unauthorized());
        }
        //Receiving the token from DB
        private async Task <DeviceToken> GetTokenAsync(GenericRequest request)
        {
            var json = JsonConvert.SerializeObject(request);

            HttpContent httpContent = new StringContent(json);

            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            var result = await _client.PostAsync(getTokenUrl(), httpContent);

            if (result.IsSuccessStatusCode)
            {
                var content = await result.Content.ReadAsStringAsync();

                try
                {
                    return(JsonConvert.DeserializeObject <DeviceToken>(content));
                }
                catch
                {
                    //Log the exception from this service
                    return(new DeviceToken());
                }
            }
            else
            {
                return(new DeviceToken());
            }
        }
Пример #13
0
        private static void ThreeDSAuthorization0Dictionary(GenericRequest request, OrderedDictionary dictionary)
        {
            var specificRequest = (ThreeDSAuthorization0RequestXML)request;

            dictionary.Add("ORDERID", specificRequest.OrderID);
            AddCommonParameters(specificRequest, dictionary);
            dictionary.Add("PAN", specificRequest.PAN);
            dictionary.Add("CVV2", specificRequest.CVV2);
            dictionary.Add("EXPDATE", specificRequest.ExpDate);
            dictionary.Add("AMOUNT", specificRequest.Amount);
            dictionary.Add("CURRENCY", specificRequest.Currency);
            dictionary.Add("EXPONENT", specificRequest.Exponent);
            dictionary.Add("ACCOUNTINGMODE", specificRequest.AccountingMode);
            dictionary.Add("NETWORK", specificRequest.Network);
            dictionary.Add("EMAILCH", specificRequest.EmailCH);
            dictionary.Add("USERID", specificRequest.Userid);
            dictionary.Add("ACQUIRER", specificRequest.Acquirer);
            dictionary.Add("IPADDRESS", specificRequest.IpAddress);
            dictionary.Add("USRAUTHFLAG", specificRequest.UsrAuthFlag);
            dictionary.Add("OPDESCR", specificRequest.OpDescr);
            dictionary.Add("OPTIONS", specificRequest.Options);
            dictionary.Add("ANTIFRAUD", specificRequest.Antifraud);
            dictionary.Add("PRODUCTREF", specificRequest.ProductRef);
            dictionary.Add("NAME", specificRequest.Name);
            dictionary.Add("SURNAME", specificRequest.Surname);
            dictionary.Add("TAXID", specificRequest.TaxID);
            dictionary.Add("THREEDSDATA", specificRequest.ThreeDSData);
            dictionary.Add("NAMECH", specificRequest.NameCH);
            dictionary.Add("NOTIFURL", specificRequest.NotifUrl);
            dictionary.Add("THREEDSMTDNOTIFURL", specificRequest.ThreeDSMtdNotifUrl);
            dictionary.Add("CHALLENGEWINSIZE", specificRequest.ChallengeWinSize);
        }
Пример #14
0
        public UnitConsumptionGraph <string> GetGraph(GenericRequest input, SearchParam criteria)
        {
            PagedData <GenericRequest> inp = new PagedData <GenericRequest>();

            inp.NumberOfRecords = -1;
            inp.Data            = input;
            var fullData = this.GetTodayData(inp, criteria);
            var first    = fullData.Data.Where(m => m.consumptioninmcube != null && m.consumptioninmcube.Trim() != "" && m.consumptioninmcube.Trim() != "N/C" && m.consumptioninmcube.Trim() != "###")
                           .Select(us => new point <string>()
            {
                X = us.unitid, Y = Convert.ToDecimal(us.consumptioninmcube)
            });
            var second = fullData.Data.Where(m => m.dayconsumption != null && m.dayconsumption.Trim() != "" && m.dayconsumption.Trim() != "N/C" && m.dayconsumption.Trim() != "###")
                         .Select(us => new point <string>()
            {
                X = us.unitid, Y = Convert.ToDecimal(us.dayconsumption)
            });
            var result = new UnitConsumptionGraph <string>();

            result.Cumalative          = new Graph <string>();
            result.DayConsumption      = new Graph <string>();
            result.Cumalative.Data     = first.ToList();
            result.DayConsumption.Data = second.ToList();
            return(result);
        }
Пример #15
0
        private static void Auth3DSDictionary(GenericRequest request, OrderedDictionary dictionary)
        {
            var specificRequest = (AuthorizationRequest)request;

            dictionary.Add("ORDERID", specificRequest.OrderID);
            AddCommonParameters(specificRequest, dictionary);
            dictionary.Add("PAN", specificRequest.PAN);
            dictionary.Add("CVV2", specificRequest.CVV2);
            dictionary.Add("EXPDATE", specificRequest.ExpDate);
            dictionary.Add("AMOUNT", specificRequest.Amount);
            dictionary.Add("CURRENCY", specificRequest.Currency);
            dictionary.Add("EXPONENT", specificRequest.Exponent);
            dictionary.Add("ACCOUNTINGMODE", specificRequest.AccountingMode);
            dictionary.Add("NETWORK", specificRequest.Network);
            dictionary.Add("EMAILCH", specificRequest.EmailCH);
            dictionary.Add("USERID", specificRequest.Userid);
            dictionary.Add("ACQUIRER", specificRequest.Acquirer);
            dictionary.Add("IPADDRESS", specificRequest.IpAddress);
            dictionary.Add("OPDESCR", specificRequest.OpDescr);
            dictionary.Add("USRAUTHFLAG", specificRequest.UsrAuthFlag);
            dictionary.Add("OPTIONS", specificRequest.Options);
            dictionary.Add("ANTIFRAUD", specificRequest.Antifraud);
            dictionary.Add("PRODUCTREF", specificRequest.ProductRef);
            dictionary.Add("NAME", specificRequest.Name);
            dictionary.Add("SURNAME", specificRequest.Surname);
            dictionary.Add("TAXID", specificRequest.TaxID);
        }
Пример #16
0
 private void OnGenericRequestReceived(GenericRequest request)
 {
     if (GenericRequestReceived != null)
     {
         GenericRequestReceived(this, request.ExtractInnerMessage());
     }
 }
        public override GenericResponse <T> DisableEntity(GenericRequest <T> Request)
        {
            Response = Repository.DisableEntity(Request);


            return(Response);
        }
Пример #18
0
 /// <summary>
 /// This is an attempt by another object to interact with this object directly
 /// </summary>
 public virtual void Interact()
 {
     GenericRequest?.Invoke(gameObject, GameActions.Interact, new GenericMessage()
     {
         values = new string[] { id.ToString() }
     });
 }
Пример #19
0
 private void ValidateRequest(GenericRequest request)
 {
     if (String.IsNullOrWhiteSpace(request.UserName))
     {
         throw new Exception("Please enter a valid Username.");
     }
 }
Пример #20
0
        private static void ThreeDSAuthorization2Dictionary(GenericRequest request, OrderedDictionary dictionary)
        {
            var specificRequest = (ThreeDSAuthorization2RequestXML)request;

            AddCommonParameters(specificRequest, dictionary);
            dictionary.Add("THREEDSTRANSID", specificRequest.ThreeDSTransId);
        }
Пример #21
0
        public GenericResponse SaveDataSiswa(GenericRequest @params)
        {
            var response  = false;
            var container = new CompleteDataSiswa(@params)
            {
                repository = _unitOfWork
            };

            CompleteDataOperationsSiswa.Initialize(ref container);

            var similarity = _similarity.proximity(container.siswa.nama_siswa.Trim(), container.siswa_data.nama_siswa.Trim()) * 100;

            try
            {
                if (container != null)
                {
                    if (similarity > 0)
                    {
                        response = true;
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }

            var output = JsonConvert.SerializeObject(response);

            return(new GenericResponse()
            {
                data = output
            });
        }
Пример #22
0
        public void DeclineInvitation(ulong invitationId, EntityId channelId, RPCContextDelegate callback)
        {
            GenericRequest genericRequest = new GenericRequest();

            genericRequest.SetInvitationId(invitationId);
            this.m_rpcConnection.QueueRequest(ChannelAPI.m_channelInvitationService.Id, 5u, genericRequest, callback, 0u);
        }
Пример #23
0
 protected virtual void OnGenericRequestReceived(GenericRequest request)
 {
     if (GenericRequestReceived != null)
     {
         GenericRequestReceived(this, request.ExtractInnerMessage());
     }
 }
Пример #24
0
        public ActionResult DeclineRequest(int?id)
        {
            GenericRequest req = db.Requests.Find(id);

            if (req.Type == "JoinCourse")
            {
                db.Requests.Remove(req);
                db.SaveChanges();
                return(RedirectToAction("JoinRequests", "Home"));
            }
            else if (req.Type == "ParentStudent")
            {
                db.Requests.Remove(req);
                db.SaveChanges();
                return(RedirectToAction("AcceptParentRequests", "Home"));
            }
            else
            {
                ApplicationUser deleted = db.Users.Find(req.User1id);
                try
                {
                    db.Users.Remove(deleted);
                    db.Requests.Remove(req);
                    db.SaveChanges();
                }
                catch (Exception e)
                {
                    throw e;
                }
                return(RedirectToAction("AdminRoleRequests", "Home"));
            }
        }
Пример #25
0
        public ActionResult AcceptRequest(int?id)
        {
            GenericRequest req        = db.Requests.Find(id);
            UserRepository repository = new UserRepository();

            if (req.Type == "JoinCourse")
            {
                repository.AcceptJoinRequest(req);
                return(RedirectToAction("JoinRequests", "Home"));
            }
            else if (req.Type == "ParentStudent")
            {
                repository.AcceptParentRequest(req);
                return(RedirectToAction("AcceptParentRequests", "Home"));
            }
            else
            {
                ApplicationUser user = db.Users.Find(req.User1id);
                user.Validated = true;
                try
                {
                    db.Entry(user).State = EntityState.Modified;
                    db.Requests.Remove(req);
                    db.SaveChanges();
                    UserRepository.BuildEmailTemplate("Your Account was successfully validated!You are allowed to login!", user.Email);
                }
                catch (Exception e)
                {
                    throw e;
                }
                return(RedirectToAction("AdminRoleRequests", "Home"));
            }
        }
Пример #26
0
        /// <summary>
        /// Accepts and erases a join request
        /// </summary>
        /// <param name="req">the request</param>
        public void AcceptJoinRequest(GenericRequest req)
        {
            GenericRequest  request = db.Requests.Find(req.ReqId);
            Course          course  = db.Courses.Find(req.Courseid);
            ApplicationUser student = db.Users.Find(req.User2id);

            db.Courses.Attach(course);

            Enrollment enrol = new Enrollment();

            enrol.Grade    = -1;
            enrol.Absences = -1;
            enrol.CourseId = course.CourseId;
            enrol.Course   = course;
            enrol.UserId   = student.Id;
            enrol.User     = student;

            try
            {
                db.Entry(course).State = EntityState.Modified;
                db.Requests.Remove(request);
                db.Enrollments.Add(enrol);
                db.SaveChanges();
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Пример #27
0
        //public GenericResponse ConfirmDataSiswa(GenericRequest @params)
        //{
        //    var output = "";

        //    var se = new SiswaEntity();
        //    se = JsonConvert.DeserializeObject<SiswaEntity>(@params.json_data);

        //    CompleteDataOperationsSiswa.Initialize2(se, _unitOfWork, @params);

        //    output = JsonConvert.SerializeObject(se);
        //    return new GenericResponse() { data = output };
        //}

        public GenericResponse DeleteSiswa(GenericRequest @params)
        {
            var response  = false;
            var container = new CompleteDataSiswa(@params)
            {
                repository = _unitOfWork
            };

            CompleteDataOperationsSiswa.Remove(ref container);

            try
            {
                if (container != null)
                {
                    response = true;
                }
            }
            catch (Exception)
            {
                throw;
            }

            var output = JsonConvert.SerializeObject(response);

            return(new GenericResponse()
            {
                data = output
            });
        }
        public override async Task <MessageResult> SyncOrgbookToAccounts(GenericRequest request, ServerCallContext context)
        {
            _logger.LogInformation("Starting SyncOrgbookToAccounts.");
            IList <MicrosoftDynamicsCRMaccount> result;

            try
            {
                var select = new List <string> {
                    "adoxio_bcincorporationnumber", "accountid"
                };
                string filter = $"adoxio_orgbookorganizationlink eq null and adoxio_businessregistrationnumber eq null and adoxio_bcincorporationnumber ne null and adoxio_bcincorporationnumber ne 'BC1234567'";
                result = _dynamics.Accounts.Get(filter: filter, select: select).Value;
            }
            catch (HttpOperationException odee)
            {
                _logger.LogError(odee, "Error getting accounts");

                // fail if we can't get results.
                return(new MessageResult()
                {
                    Success = false
                });
            }

            _logger.LogInformation($"Found {result.Count} organizations to query orgbook for.");

            // now for each one process it.
            foreach (var item in result)
            {
                string registrationId = item.AdoxioBcincorporationnumber;
                string accountId      = item.Accountid;
                int?   orgbookTopicId = await _orgbookClient.GetTopicId(registrationId);

                if (orgbookTopicId != null)
                {
                    string orgbookLink = _orgbookClient.ORGBOOK_BASE_URL + "/en/organization/registration.registries.ca/" + item.AdoxioBcincorporationnumber;
                    _dynamics.Accounts.Update(accountId, new MicrosoftDynamicsCRMaccount()
                    {
                        AdoxioOrgbookorganizationlink = orgbookLink,
                        AdoxioIsorgbooklinkfound      = 845280000
                    });
                    _logger.LogInformation($"Successfully added orgbook link to account with registration id {registrationId}.");
                }
                else
                {
                    _dynamics.Accounts.Update(accountId, new MicrosoftDynamicsCRMaccount()
                    {
                        AdoxioIsorgbooklinkfound = 845280001
                    });
                    _logger.LogError($"Failed to add orgbook link to account with registration id {registrationId}.");
                }
            }

            _logger.LogInformation($"Ending SyncOrgbookToAccounts");
            return(new MessageResult()
            {
                Success = true
            });
        }
Пример #29
0
        public Search GetInitialSearchLists(GenericRequest request)
        {
            var req    = Mapper.Map <DataModels.GenericRequest>(request);
            var data   = Repository.GetInitialSearchLists(req);
            var result = Mapper.Map <BusinessModels.UnitReport.Search>(data);

            return(result);
        }
Пример #30
0
        public virtual ActionResult Index()
        {
            GenericResponse <T> response = new GenericResponse <T>();
            GenericRequest <T>  request  = new GenericRequest <T>();

            response = _business.GetActives(request);
            return(View("Index", response));
        }
Пример #31
0
 public AuthProcessor(AccountDBContext context, GenericRequest request)
 {
     this.request = request;
     this.context = context;
     context.Configuration.ProxyCreationEnabled = false;
     users = new GenericRepository<User>(new StorageContext<User>(context));
     roles = new GenericRepository<Role>(new StorageContext<Role>(context));
     userroles = new GenericRepository<UserRoles>(new StorageContext<UserRoles>(context));
 }
 public SolutionMessageResponse SendNewPassword(GenericRequest request)
 {
     SolutionMessageResponse response = new SolutionMessageResponse();
     ImardaCRMBusiness.IImardaCRM service = ImardaProxyManager.Instance.IImardaCRMProxy;
     ChannelInvoker.Invoke(delegate(out IClientChannel channel)
     {
         channel = service as IClientChannel;
         service.SendNotificationEmail(request);
     });
     response.Status = true;
     return response;
 }
Пример #33
0
        BusinessMessageResponse SendSMS(GenericRequest req)
        {
            try
            {
                var response = new BusinessMessageResponse();

                return response;
            }
            catch (Exception ex)
            {
                return ErrorHandler.Handle(ex);
            }
        }
Пример #34
0
 private void Connect_Click(object sender, EventArgs e)
 {
     _Result.Clear();
     var req = new GenericRequest(
         Guid.Empty,
         _MicrosoftReportingSvc.Text.Trim(),
         _Network.Checked ? "network" : "default",
         _User.Text.Trim(),
         _Password.Text.Trim(),
         _Domain.Text.Trim()
         );
     Cursor = Cursors.WaitCursor;
     ThreadPool.QueueUserWorkItem(Connect, req);
 }
 public MessageProcessor(CourseDBContext context, GenericRequest request)
 {
     this.request = request;
     this.context = context;
     context.Configuration.ProxyCreationEnabled = false;
     courses = new GenericRepository<Course>(new StorageContext<Course>(context));
     degreePrograms = new GenericRepository<DegreeProgram>(new StorageContext<DegreeProgram>(context));
     prerequisiteCourses = new GenericRepository<PrerequisiteCourse>(new StorageContext<PrerequisiteCourse>(context));
     electiveCourses = new GenericRepository<ElectiveCourse>(new StorageContext<ElectiveCourse>(context));
     electiveLists = new GenericRepository<ElectiveList>(new StorageContext<ElectiveList>(context));
     electiveListCourses = new GenericRepository<ElectiveListCourse>(new StorageContext<ElectiveListCourse>(context));
     plans = new GenericRepository<Plan>(new StorageContext<Plan>(context));
     planCourses = new GenericRepository<PlanCourse>(new StorageContext<PlanCourse>(context));
     requiredCourses = new GenericRepository<RequiredCourse>(new StorageContext<RequiredCourse>(context));
     semesters = new GenericRepository<Semester>(new StorageContext<Semester>(context));
 }
Пример #36
0
 public BusinessMessageResponse SendPlan(GenericRequest req)
 {
     try
     {
         var response = new BusinessMessageResponse();
         //separate delivery method from request
         //call SendEmail(req1);
         //call SendSMS(req2);
         //call other methods;
         return response;// always return successful response
     }
     catch (Exception ex)
     {
         return ErrorHandler.Handle(ex);
     }
 }
Пример #37
0
        BusinessMessageResponse SendEmail(GenericRequest req)
        {
            try
            {
                var response = new BusinessMessageResponse();
                //for each recipient in req
                //build a new Email object
                //SaveToPending();
                //SendSingleEmail(Email e);

                return response;
            }
            catch (Exception ex)
            {
                return ErrorHandler.Handle(ex);
            }
        }
        public SimpleResponse<string> HttpPost(GenericRequest request)
        {
            try
            {
                _Log.InfoFormat("HttpPost - enter");

                Guid companyID = request.ID;
                string url = (string)request[0];
                Guid templateID = (Guid)request[1];
                string data = (string)request[2];
                string tzid = (string)request[3];

                var resp1 = GetNotificationItem(new IDRequest(templateID));
                ErrorHandler.Check(resp1);

                NotificationItem item = resp1.Item;

                //ask for Notification service
                IImardaNotification service = ImardaProxyManager.Instance.IImardaNotificationProxy;

                SimpleResponse<string> resp2 = null;
                ChannelInvoker.Invoke(delegate(out IClientChannel channel)
                {
                    channel = service as IClientChannel;
                    var param = new string[] {
                        url,
                        item.Content,
                        tzid,
                    };
                    GenericRequest reqSingle = new GenericRequest(companyID, url, item.Content, data, tzid);
                    _Log.InfoFormat("Before HttpPost");
                    resp2 = service.HttpPost(reqSingle);
                    _Log.Info("After HttpPost");
                });
                ErrorHandler.CheckItem(resp1);
                return resp2;
            }
            catch (Exception ex)
            {
                return ErrorHandler.Handle<SimpleResponse<string>>(ex);
            }
        }
        /// <summary>
        /// Get the text of a notification, localized and filled in with parameters.
        /// </summary>
        /// <param name="request">.ID = notification item ID, [0]=companyID, [1]=typedData, [2]=tzid, [4]=force default date fmt</param>
        /// <returns></returns>
        public SimpleResponse<string> GetNotification(GenericRequest request)
        {
            try
            {
                Guid templateID = request.ID;
                Guid companyID = (Guid)request[0];
                string data = (string)request[1];
                string tzid = (string)request[2];
                bool forceDefaultDateFormat = (bool)request[3];

                var resp = GetNotificationItem(new IDRequest(templateID));
                ErrorHandler.Check(resp);

                NotificationItem item = resp.Item;
                string msg = FillInTemplate(item.CRMID, companyID, tzid, item.Content, data, forceDefaultDateFormat);

                return new SimpleResponse<string>(msg);
            }
            catch (Exception ex)
            {
                return ErrorHandler.Handle<SimpleResponse<string>>(ex);
            }
        }
        public BusinessMessageResponse SendNotificationSMS(GenericRequest request)
        {
            try
            {
                _Log.InfoFormat("SendNotificationSMS - enter");

                Guid personID = request.ID;
                Guid templateID = (Guid)request[0];
                Guid companyID = (Guid)request[1];
                string data = (string)request[2];
                string tzid = (string)request[3];

                Person p = GetPerson(new IDRequest(personID)).Item;
                _Log.InfoFormat("Person = {0}", p);

                if (!p.Deleted)
                {
                    var resp = GetNotificationItem(new IDRequest(templateID));
                    ErrorHandler.Check(resp);

                    NotificationItem item = resp.Item;

                    //ask for Notification service
                    IImardaNotification service = ImardaProxyManager.Instance.IImardaNotificationProxy;

                    ChannelInvoker.Invoke(delegate(out IClientChannel channel)
                    {
                        channel = service as IClientChannel;
                        string[] param = new string[8];

                        param[0] = companyID.ToString();
                        param[1] = personID.ToString();
                        param[2] = item.Content;
                        param[3] = "i360 - Alert Notification";
                        param[4] = p.FullName + '|' + p.MobilePhone + "||";
                        param[5] = new StringBuilder(data).AppendKV("RecipientName", p.FullName).ToString();
                        param[6] = p.Email;
                        param[7] = tzid;

                        //no cc and bcc for now
                        GenericRequest reqSingle = new GenericRequest(personID, param);
                        _Log.InfoFormat("Before SendSMS, personID: {0}", personID);
                        service.SendSMS(reqSingle);
                        _Log.Info("After SendSMS");
                    });
                }
                else
                {
                    _Log.InfoFormat("The Person {0} has been deleted, so no alert sending", p);
                }
                return new BusinessMessageResponse();
            }
            catch (Exception ex)
            {
                return ErrorHandler.Handle(ex);
            }
        }
Пример #41
0
        public BusinessMessageResponse SetScheduledTaskStatus(GenericRequest request)
        {
            var count = 1;
            int retry = ConfigUtils.GetInt("retry", 1); ;
            try
            {

                var brResponse = SetScheduledTaskStatus_mth(request);
                return brResponse;
            }
            catch (SqlException e)
            {
                while (count <= retry)
                {
                    try
                    {
                        DebugLog.Write("Retry for scheduled task");
                        var brResponse = SetScheduledTaskStatus_mth(request);
                        return brResponse;
                    }
                    catch (Exception)
                    {
                        if (e.Number == -2 || e.Number == 1205)
                            // if (e.Message == "SQL Timeout")
                            count++;
                        else
                        {
                            return ErrorHandler.Handle(e);
                        }
                    }
                }
                return ErrorHandler.Handle(e);
            }
        }
        /// <summary>
        /// Send email 
        /// </summary>
        /// <param name="req">[0]=CompanyID, [1]=UserID, [2]=Content, [3]=Subject, 
        /// [4]=AttachmentFilesFullPaths, in format "c:\attach1.doc;c:\attach2.kml;...",
        /// [5]=list of recipients, in format "name1|destination1||name2|destination2||name3|destination3||..."
        /// [6]=CC addresses for email, [7]=Bcc addresses for email [8] is mailmerge parameters [9] timezone [10] priority</param>
        /// <returns>always return a response with status = ok</returns>
        public BusinessMessageResponse SendEmail(GenericRequest req)
        {
            try
            {
                _Log.Debug("Enter SendEmail");
                var p = req.Parameters;
                string companyID = GetString(p, 0);
                string userID = GetString(p, 1);
                string content = GetString(p, 2);
                string subject = GetString(p, 3);
                string attachments = GetString(p, 4);
                string recipientList = GetString(p, 5);
                string cc = GetString(p, 6);
                string bcc = GetString(p, 7);
                string data = GetString(p, 8);
                string tzid = GetString(p, 9);
                string priority = GetString(p, 10);
                byte prio;
                if (!byte.TryParse(priority, out prio)) prio = 1;

                _Log.DebugFormat("SendEmail comp={0} content={1} subject={2} attach={3} recip={4}, data={5}, tzid={6}",
                    companyID, content, subject, attachments.Truncate(30),
                    recipientList, data.Truncate(100), tzid);

                //IM-5884 check recipient list on sending email
                return SendEmailInternal(content, recipientList, null, subject, SequentialGuid.NewDbGuid(), companyID, userID, cc, bcc, attachments, tzid, data, prio);
            }
            catch (Exception ex)
            {
                return ErrorHandler.Handle(ex);
            }
        }
        private void NotifyRecipients(ReportTask task, string path)
        {
            _Log.Info("Notify Recipients");

            NotificationDef ndef = task.Notification;
            ReportDef rdef = task.Definition;

            //# IM-3927
            List<string> users = new List<string>();
            List<string> addresses = new List<string>();
            List<Guid> planIDs = new List<Guid>();
            string server = "";
            string port = "22";
            string username = "";
            string password = "";
            string psk = "";
            string destinationPath = "";

            switch (ndef.Delivery.ToUpper())
            {
                case "SMTP":
                    ndef.GetRecipients(out users, out addresses, out planIDs); // user IDs currently not used
                    if (users.Count == 0 && addresses.Count == 0 && planIDs.Count == 0)
                    {
                        Attention(new Guid("79b09d0b-0a0a-badd-a0ef-386d5dedf1fc"), "No recipients for ReportTask.ID=" + task.ID);
                        return; // no notifications required
                    }
                    break;

                case "SFTP":
                    ndef.GetFTPDetails(out server, out port, out username, out password, out psk, out destinationPath);
                    if (server == "" || username == "" || password == "")  // || destinationFolder == "")
                    {
                        Attention(new Guid("79b09d0b-0a0a-badd-a0ef-386d5dedf1fc"), "No sFTP details for ReportTask.ID=" + task.ID);
                        return; // no notifications required
                    }
                    break;
            }
            //. IM-3927

            // Download report
            string attachment = null;
            if (!String.IsNullOrEmpty(path))
            {
                try
                {
                    attachment = Path.GetFileName(path) + "|" + Convert.ToBase64String(File.ReadAllBytes(path));
                    _Log.InfoFormat("Attachment {0} bytes, {1} chars", new FileInfo(path).Length, attachment.Length);
                }
                catch (Exception ex)
                {
                    _Log.ErrorFormat("Error reading attachment file {0}: {1}", path, ex.Message);
                }
            }
            //Priority: have to make string to pass to service methods
            byte priority = task.Notification.Priority;

            StringBuilder sb = GetParametersForTemplate(task);

            //# IM-3927
            switch (ndef.Delivery.ToUpper())
            {
                case "SMTP":
                    // Send notification plans
                    if (planIDs.Count > 0)
                    {
                        _Log.InfoFormat("Send {0} Notification Plan(s)", planIDs.Count);

                        // The Comment field contains a message that may contain <...> or $(...) placeholders for parameters
                        //    therefore we have to instantiate it here to create a message.
                        // Add the instantiated message to the list of parameters
                        //    This can be expanded in a NotificationItem template where <Message> or $(Message) is found,
                        //    but it is also the body for single Emails
                        string message = FillInTemplate(rdef.Locale, task.TimeZoneID, task.Notification.Comment, sb.ToString());
                        sb.AppendKV("Message", message);
                        string allParameters = sb.ToString();
                        _Log.InfoFormat("All parameters for notification plan: {0}", allParameters);

                        IImardaCRM crmService = ImardaProxyManager.Instance.IImardaCRMProxy;
                        ChannelInvoker.Invoke(delegate(out IClientChannel channel)
                        {
                            channel = crmService as IClientChannel;
                            foreach (Guid planID in planIDs)
                            {
                                var crmreq = new GenericRequest(planID, task.CompanyID, allParameters, task.TimeZoneID,
                                                                                                attachment, priority);
                                BusinessMessageResponse crmresp = crmService.SendNotificationPlan(crmreq);
                                _Log.InfoFormat("After send notification plan {0} -> {1}", planID, crmresp.Status);
                            }
                        });
                    }

                    // Send to addresses that were entered in the UI
                    if (addresses.Count > 0)
                    {
                        _Log.InfoFormat("Send {0} Notification Email(s)", addresses.Count);
                        string allParameters = sb.ToString();
                        // we don't know the user names, therefore use the address as user name; (we must fill in unique address)
                        string recipients = String.Join("||", addresses.Select(addr => addr + "|" + addr).ToArray());

                        var param = new string[11];

                        string emptyID = Guid.Empty.ToString();
                        param[0] = task.CompanyID.ToString();
                        param[1] = emptyID;
                        param[2] = task.Notification.Comment; // template to be instantiated in the SendEmail
                        param[3] = "i360 - Report - " + rdef.Description; // subject
                        param[4] = attachment;
                        param[5] = recipients;
                        param[6] = ""; // cc
                        param[7] = ""; // bcc
                        param[8] = allParameters; // parameters that go optionally into the template
                        param[9] = task.TimeZoneID;
                        param[10] = priority.ToString();

                        IImardaNotification notifService = ImardaProxyManager.Instance.IImardaNotificationProxy;
                        ChannelInvoker.Invoke(delegate(out IClientChannel channel)
                        {
                            channel = notifService as IClientChannel;

                            var nreq = new GenericRequest(Guid.Empty, param);
                            var nresp = notifService.SendEmail(nreq);

                            //IM-5884 now checks response from SendSingle and returns it
                            if (!nresp.Status)
                            {
                                _Log.WarnFormat("{0} - Error on sending email: {1}", MethodBase.GetCurrentMethod().Name, nresp.Status);
                            }
                            _Log.InfoFormat("After send email to {0} : {1} -> {2}", recipients ?? "recipients is null", param[3], nresp.Status);
                        });
                    }
                    break;

                case "SFTP":
                    if (server == "" || username == "" || password == "")  // || destinationPath == "")
                        break;

                    _Log.InfoFormat("Send {0} Notification via sFTP", server + "," + username);
                    var ftpParam = new string[10];

                    string emptyUserID = Guid.Empty.ToString();
                    ftpParam[0] = task.CompanyID.ToString();
                    ftpParam[1] = emptyUserID;
                    ftpParam[2] = server;
                    ftpParam[3] = port;
                    ftpParam[4] = username;
                    ftpParam[5] = password;
                    ftpParam[6] = psk;
                    ftpParam[7] = destinationPath;
                    ftpParam[8] = attachment;
                    ftpParam[9] = priority.ToString();

                    IImardaNotification notifyService = ImardaProxyManager.Instance.IImardaNotificationProxy;
                    ChannelInvoker.Invoke(delegate(out IClientChannel channel)
                    {
                        channel = notifyService as IClientChannel;
                        var nreq = new GenericRequest(Guid.Empty, ftpParam);
                        BusinessMessageResponse nresp = notifyService.SendsFTP(nreq);
                        _Log.InfoFormat("After send report via sFTP to {0} : {1} -> {2} {3}", server, username, nresp.Status, rdef.Description);
                    });
                    break;
            }

            if (!String.IsNullOrEmpty(path))
            {
                try
                {
                    if (_CleanUpAttachments)
                    {
                        File.Delete(path);
                        _Log.Info("Attachment deleted");
                    }
                }
                catch (Exception ex)
                {
                    _Log.ErrorFormat("Error deleting attachment file {0}: {1}", path, ex.Message);
                }
            }

            //. IM-3927
        }
Пример #44
0
		public void TestGetCategoryReports()
		{
			Guid catID = new Guid("209ab46d-b226-4936-a6a5-e854fde802f5");
			IImardaReport channel = ImardaProxyManager.Instance.IImardaReportProxy;
			var service = ImardaProxyManager.Instance.${Proxy};
				ChannelInvoker.Invoke(delegate(out IClientChannel channel)
				{
					channel = service as IC				var req = new GenericRequest(catID);
				GetListResponse<ReportType> resp = channel.GetCategoryReports(req);
				Assert.IsTrue(resp != null);
				Assert.IsTrue(resp.Status);
				Assert.IsTrue(resp.List != null);
				foreach (ReportType rt in resp.List) Console.WriteLine("{0}: '{1}' {2}", rt.ID, rt.Name, rt.OwnerID);
			}
		}
Пример #45
0
 public BusinessMessageResponse RequeuePendingMessages(GenericRequest request)
 {
     try
     {
         var db = ImardaDatabase.CreateDatabase(Util.GetConnName<ScheduledTask>());
         byte managerID = (byte)request[0];
         int n = db.ExecuteNonQuery("SPRequeuePendingMessages", managerID);
         Execute.Later(ConfigUtils.GetTimeSpan("SystemTaskDelay", TimeSpan.FromMinutes(1.0)), () => db.ExecuteNonQuery("SPReinstallSystemTasks"));
         return new BusinessMessageResponse { Status = true, StatusMessage = n.ToString(CultureInfo.InvariantCulture) };
     }
     catch (Exception ex)
     {
         return ErrorHandler.Handle(ex);
     }
 }
Пример #46
0
		public void TestCreateSnapshot()
		{
			//GetItemResponse<Report> CreateSnapshot(GenericRequest req);
			//Guid rtID = new Guid("FFF2F38A-E5C3-4BA5-B9BA-977543C89123");
			Guid rtID = new Guid("51eda16f-724b-466e-82ad-85b2f2104fc6");
			IImardaReport channel = ImardaProxyManager.Instance.IImardaReportProxy;
			var service = ImardaProxyManager.Instance.${Proxy};
				ChannelInvoker.Invoke(delegate(out IClientChannel channel)
				{
					channel = service as IC				var req = new GenericRequest(rtID);
				GetItemResponse<Report> resp = channel.CreateSnapshot(req);
				Assert.IsTrue(resp != null);
				Assert.IsTrue(resp.Status);
				Assert.IsTrue(resp.Item != null);
				var report = resp.Item;
				Assert.AreEqual("http://MSREPORTSVC/ReportServer", report.BaseUrl);
				string pattern = "yyyy-MM-ddTHH:mm:ss";
				string path, historyID;
				report.GetPathAndHistoryID(out path, out historyID);
				Assert.AreEqual(pattern.Length, historyID.Length);

				Assert.AreEqual("/Instances/08c46d66-b886-44d0-a3c2-3aa9b12c4d98/Travel", path);
				Assert.LessOrEqual(DateTime.Now.ToString(pattern), historyID);
				Assert.AreEqual("administrator", report.LoginUser.ToLower());
				Assert.AreEqual("imarda1234", report.Password);
				Assert.IsNull(report.Domain);
			}
		}
Пример #47
0
		public void TestCreateTypeAndSnapshot()
		{
			var companyID = new Guid("e649e5e1-98c4-4601-a83c-4657028d0e17");
			var userID = new Guid("1b477f9a-1170-4a53-af28-12eec6fb1310");
			var ownerID = companyID;

			IImardaReport channel = ImardaProxyManager.Instance.IImardaReportProxy;
			var service = ImardaProxyManager.Instance.${Proxy};
				ChannelInvoker.Invoke(delegate(out IClientChannel channel)
				{
					channel = service as IC				var parameters = new ParamsForCreateLinkedReportType
				{
					CompanyID = companyID,
					UserID = userID,
					Name = "Travel",
					Version = "1",
					OwnerID = ownerID,
					ReportParameters = "hello|world"
				};

				GetItemResponse<ReportType> resp1 = channel.CreateLinkedReportType(parameters.AsGenericRequest());
				Assert.IsTrue(resp1 != null);
				Assert.IsTrue(resp1.Status);
				Assert.IsTrue(resp1.Item != null);

				Guid rtID = resp1.Item.ID;
				var req = new GenericRequest(rtID);
				GetItemResponse<Report> resp2 = channel.CreateSnapshot(req);
				Assert.IsTrue(resp2 != null);
				Assert.IsTrue(resp2.Status);
				Assert.IsTrue(resp2.Item != null);
				var report = resp2.Item;
				string url = report.GetReportURL("60.234.77.199");
				Process.Start(url);
			}
		}
Пример #48
0
 public SessionObject CheckPermissions(GenericRequest request, Guid authToken)
 {
     var session = CheckPermissions(request.SessionID, authToken);
     return session;
 }
Пример #49
0
		public void TestGetOwnerReports()
		{
			Guid ownerID = new Guid("e649e5e1-98c4-4601-a83c-4657028d0e17");
			IImardaReport channel = ImardaProxyManager.Instance.IImardaReportProxy;
			var service = ImardaProxyManager.Instance.${Proxy};
				ChannelInvoker.Invoke(delegate(out IClientChannel channel)
				{
					channel = service as IC				var req = new GenericRequest(ownerID, "%");
				GetListResponse<ReportType> resp = channel.GetOwnerReports(req);
				Console.WriteLine(resp);
				Assert.IsTrue(resp != null);
				Assert.IsTrue(resp.Status);
				Assert.IsTrue(resp.List != null);
				Assert.IsTrue(resp.List.Count > 0);
				foreach (ReportType rt in resp.List) Console.WriteLine("{0}: '{1}' {2}", rt.ID, rt.Name, rt.OwnerID);
			}
		}
Пример #50
0
        public SimpleResponse<string> GetCulturePreferences(GenericRequest req)
        {
            try
            {
                Guid personID = req.ID;
                Guid companyID = (Guid)req[0];

                RemoveCachedCulture(new IDRequest(companyID));

                var config = new CultureConfigGroup();
                Guid[] ids = ConfigGroup.GetIDs(config);
                ConfigListRequest request2;
                if (personID != Guid.Empty)
                {
                    request2 = new ConfigListRequest(ids, companyID, personID);
                }
                else
                {
                    request2 = new ConfigListRequest(ids, companyID);
                }
                request2.IgnoreCache = true;
                var resp2 = GetConfigValueList(request2);
                ConfigValue[] values = resp2.List.ToArray();
                ConfigGroup.SetValues(config, values);
                string preferences = CultureHelper.CalcPreferences(config, this);
                return new SimpleResponse<string>(preferences);
            }
            catch (Exception ex)
            {
                return ErrorHandler.Handle<SimpleResponse<string>>(ex);
            }
        }
        /// <summary>
        /// Send email or SMS or Fax for a NotificationItem
        /// </summary>
        /// <param name="req">[0]=NotificationPlan ID, [1]=CompanyID, [2]=UserID, [3]=NotificationPlan Name, 
        /// [4]=Content, [5]=Delivery Method (Email, SMS, Fax etc), 
        /// [6]=recipient, in format "name1|destination1||"
        /// [7]=CC addresses for email, [8]=Bcc addresses for email, [9]=attachment, [10]=parameters, [11]=from [12]=tzid [13]=priority</param>
        /// <returns>always return a response with status = ok</returns>
        public BusinessMessageResponse SendSingle(GenericRequest req)
        {
            try
            {
                _Log.InfoFormat("SendSingle - enter");
                var p = req.Parameters;
                string planID = GetString(p, 0);
                string companyID = GetString(p, 1);
                string userID = GetString(p, 2);
                string subject = GetString(p, 3);
                string content = GetString(p, 4);
                string deliveryMethod = GetString(p, 5);
                string recipientList = GetString(p, 6);
                string cc = "";//GetString(p, 7);
                string bcc = "";//GetString(p, 8);
                string attachments = GetString(p, 9);
                string data = GetString(p, 10);
                string fromAddress = GetString(p, 11);
                string tzid = GetString(p, 12);
                string priority = GetString(p, 13);
                byte prio;
                if (!byte.TryParse(priority, out prio)) prio = 1;
                Guid notifyID = Guid.Empty;
                _Log.InfoFormat("SendSingle: plan {0}, to {1}, by {2}, data {3}", planID, recipientList, deliveryMethod, data);

                if (planID != Guid.Empty.ToString())
                {
                    notifyID = CreateNotification(planID, subject, companyID, userID);
                }
                //IM-5884 check recipient list on sending email
                var response = new BusinessMessageResponse();
                switch (deliveryMethod.ToUpperInvariant())
                {
                    case "EMAIL":
                        response = SendEmailInternal(content, recipientList, null, subject, notifyID, companyID, userID, cc, bcc, attachments, tzid, data, prio);
                        break;

                    case "SMS":
                        subject = null;
                        SendSMSInternal(content, recipientList, fromAddress, subject, notifyID, companyID, userID, tzid, data);
                        break;

                    case "FAX":
                        SendFaxInternal(content, recipientList, subject, notifyID, companyID, userID, tzid, data);
                        break;
                }
                _Log.InfoFormat("SendSingle end.");
                return response;
            }
            catch (Exception ex)
            {
                _Log.ErrorFormat("Exception caught in SendSingle: {0}", ex);
                return ErrorHandler.Handle(ex);
            }
        }
Пример #52
0
 public GetListResponse<ScheduledTask> GetScheduledTaskListForProcessing(GenericRequest request)
 {
     try
     {
         byte managerID = (byte)request[0];
         int topN = (int)request[1];
         return ImardaDatabase.GetList<ScheduledTask>("SPGetScheduledTaskListForProcessing", managerID, topN);
     }
     catch (Exception ex)
     {
         return ErrorHandler.Handle<GetListResponse<ScheduledTask>>(ex);
     }
 }
        //. IM-3927
        /// <summary>
        /// Send SMS 
        /// </summary>
        /// <param name="req">[0]=CompanyID, [1]=UserID, [2]=Content, [3]=Subject, 
        /// [4]=list of recipients, in format "name1|destination1||name2|destination2||name3|destination3||..."</param>
        /// <returns>always return a response with status = ok</returns>
        public BusinessMessageResponse SendSMS(GenericRequest req)
        {
            var p = req.Parameters;
            string companyID = GetString(p, 0);
            string userID = GetString(p, 1);
            string content = GetString(p, 2);
            string subject = GetString(p, 3);
            string recipientList = GetString(p, 4);
            string data = GetString(p, 5);
            string fromAddress = GetString(p, 6);
            string tzid = GetString(p, 7);

            SendSMSInternal(content, recipientList, fromAddress, subject, SequentialGuid.NewDbGuid(), companyID, userID, tzid, data);
            return new BusinessMessageResponse();
        }
Пример #54
0
 public override void IgnoreInvitation(IRpcController controller, GenericRequest request, Action<NoData> done)
 {
     throw new NotImplementedException();
 }
Пример #55
0
 public override void IgnoreInvitation(IRpcController controller, GenericRequest request, Action<NoData> done)
 {
     ProtoOutputBuffer.Write(request.GetType(), request.ToString());
 }
Пример #56
0
        /// <summary>
        /// Puts the new tasks that were read from the task service into a memory queue for later execution.
        /// </summary>
        /// <returns></returns>
        private int TaskProcessingInnerLoop()
        {
            int n = 0;
            try
            {
                IImardaTask service = _Proxy.GetChannel();
                ChannelInvoker.Invoke(delegate(out IClientChannel channel)
                {
                    channel = service as IClientChannel;

                    // Log Entry Point
                    var request = new GenericRequest(Guid.Empty, _TaskManagerID, Chunk);
                    var response = service.GetScheduledTaskListForProcessing(request);
                    n = response.List.Count;
                    if (n > 0)
                    {
                        _Log.Info("Enqueue " + n + " pending ScheduledTasks");
                        foreach (ScheduledTask task in response.List)
                        {
                            if (_QueueCache.Enqueue(task, Schedule, ProcessOneTask))
                            {
                                SaveStatus(task.ID, TaskStatus.Queued, task.QueueID);
                            }
                            else
                            {
                                SaveStatus(task.ID, TaskStatus.QueueError, null);
                            }
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                ErrorHandler.HandleInternal(ex);
                _Log.InfoFormat("Exception caught inside ProcessMessages...", ex);
            }
            return n;
        }
        //& IM-3927
        public BusinessMessageResponse SendsFTP(GenericRequest req)
        {
            try
            {
                _Log.Debug("Enter SendsFTP");
                var p = req.Parameters;
                string companyID = GetString(p, 0);
                string userID = GetString(p, 1);
                string server = GetString(p, 2);
                string port = GetString(p, 3);
                string username = GetString(p, 4);
                string password = GetString(p, 5);
                string psk = GetString(p, 6);
                string destinationPath = GetString(p, 7);
                string attachments = GetString(p, 8);
                string priority = GetString(p, 9);
                byte prio;
                if (!byte.TryParse(priority, out prio)) prio = 1;

                _Log.DebugFormat("SendsFTP comp={0} server={1} username={2} attachments={3}",
                    companyID, server, username, attachments.Truncate(30));

                SendFtpInternal(companyID, userID, server, port, username, password, psk, destinationPath, attachments, prio);
                return new BusinessMessageResponse();
            }
            catch (Exception ex)
            {
                return ErrorHandler.Handle(ex);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="request">ID=notifPlanID, [0]=companyID, [1]=parameters, [2]=tzid [3]=attachments [4]=(byte)priority</param>
        /// <returns></returns>
        public BusinessMessageResponse SendNotificationPlan(GenericRequest request)
        {
            try
            {
                NotificationPlan plan = null;
                Guid planID = request.ID;
                _Log.InfoFormat("SendNotificationPlan - enter, planID: {0}", planID);
                var response = GetNotificationPlan(new IDRequest(planID));
                _Log.InfoFormat("GetNotificationPlan response = {0}", response);
                //IM-5359
                if (response.Item == null)
                {
                    _Log.WarnFormat("Could not retrieve Notification Item. PlanID{0}", planID);
                    return new BusinessMessageResponse();
                }//IM-5359
                plan = response.Item;

                Guid companyID = (Guid)request[0];
                string data = (string)request[1];
                string tzid = (string)request[2];
                string priority = "0";
                string attachments = null;
                if (request.Parameters.Length > 4)
                {
                    attachments = (string)request[3];
                    priority = ((byte)request[4]).ToString();
                }

                _Log.InfoFormat("GetNotificationPlan data = {0}", data);

                var preq = new IDRequest(planID);
                preq.CompanyID = companyID;
                var listResponse = GetNotificationItemListByNotificationPlanID(preq);
                _Log.InfoFormat("GetNotificationItemListByNotificationPlanID response = {0}", listResponse);
                ErrorHandler.Checklist<NotificationItem>(listResponse);
                List<NotificationItem> notificationItems = listResponse.List;

                string[] param = new string[14];
                param[0] = planID.ToString();//NotificationPlanID
                param[1] = plan.CompanyID.ToString();//CompanyID
                param[2] = plan.UserID.ToString();//UserID
                param[3] = "i360 - Alert Notification";

                foreach (NotificationItem item in notificationItems)
                {
                    Person p = GetPerson(new IDRequest(item.CRMID)).Item;
                    _Log.InfoFormat("Person = {0}", p);
                    string recipientSpec = p.FullName;
                    if (p != null && !p.Deleted)
                    {
                        switch (item.DeliveryMethod.ToUpperInvariant())
                        {
                            case "EMAIL":
                                recipientSpec = p.FullName + "|" + p.Email + "||";
                                break;
                            case "SMS":
                                recipientSpec = p.FullName + "|" + p.MobilePhone + "||";
                                break;
                            case "FAX":
                                recipientSpec = p.FullName + "|" + p.Phone + "||";
                                break;
                        }
                        //ask for Notification service
                        IImardaNotification service = ImardaProxyManager.Instance.IImardaNotificationProxy;
                        //send email plan
                        ChannelInvoker.Invoke(delegate(out IClientChannel channel)
                        {
                            channel = service as IClientChannel;
                            param[4] = item.Content; // body
                            param[5] = item.DeliveryMethod;//Method Name, Email, SMS, Fax
                            param[6] = recipientSpec;
                            //param[7]
                            //param[8]
                            param[9] = attachments;
                            param[10] = new StringBuilder(data).AppendKV("RecipientName", p.FullName).ToString();
                            param[11] = p.Email;
                            param[12] = tzid;
                            param[13] = priority.ToString();
                            //no cc and bcc for now
                            GenericRequest reqSingle = new GenericRequest(SequentialGuid.NewDbGuid(), param);

                            _Log.InfoFormat("Before SendSingle, planID: {0}", planID);
                            service.SendSingle(reqSingle);
                            _Log.Info("After SendSingle");
                        });
                    }
                    else
                    {
                        _Log.InfoFormat("No notification sent for CRMID = {0}, Person not found or been deleted.", item.CRMID);
                    }
                }
                return new BusinessMessageResponse();
            }
            catch (Exception ex)
            {
                _Log.ErrorFormat("Error: {0}", ex);
                return ErrorHandler.Handle(ex);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="request">action.Link1, action.Link2, unit.CompanyID, fmtdata;</param>
        /// <returns></returns>
        public BusinessMessageResponse SendNotificationEmail(GenericRequest request)
        {
            try
            {
                var result = new BusinessMessageResponse();
                _Log.InfoFormat("SendNotificationEmail - enter");

                Guid personID = request.ID;
                Guid templateID = (Guid)request[0];
                Guid companyID = (Guid)request[1];
                string data = (string)request[2];
                string tzid = (string)request[3];

                Person p = GetPerson(new IDRequest(personID)).Item;
                //IM-5359
                if (p == null)
                {
                    _Log.WarnFormat("Person with ID {0} not found", request.ID);
                    return new BusinessMessageResponse();
                }//IM-5359
                _Log.InfoFormat("Person = {0}", p);

                if (!p.Deleted)
                {
                    var resp = GetNotificationItem(new IDRequest(templateID));
                    ErrorHandler.Check(resp);

                    NotificationItem item = resp.Item;

                    //ask for Notification service
                    IImardaNotification service = ImardaProxyManager.Instance.IImardaNotificationProxy;

                    ChannelInvoker.Invoke(delegate(out IClientChannel channel)
                    {
                        channel = service as IClientChannel;
                        string[] param = new string[10];

                        param[0] = companyID.ToString();
                        param[1] = personID.ToString();
                        param[2] = item.Content;
                        param[3] = string.IsNullOrEmpty(item.Subject) ? null : item.Subject;
                        param[4] = "";
                        param[5] = p.FullName + '|' + p.Email + "||";
                        param[6] = "";
                        param[7] = "";
                        param[8] = new StringBuilder(data).AppendKV("RecipientName", p.FullName).ToString();
                        param[9] = tzid;

                        //no cc and bcc for now
                        GenericRequest reqSingle = new GenericRequest(personID, param);
                        _Log.InfoFormat("Before SendEmail, personID: {0}", personID);
                        result = service.SendEmail(reqSingle);
                        //IM-5884 now checks response from SendEmail and returns it
                        if (!result.Status)
                        {
                            _Log.WarnFormat("{0} - Error on sending email: {1}", MethodBase.GetCurrentMethod().Name, result.Status);
                        }
                        _Log.Info("After SendEmail");
                    });
                }
                else
                {
                    _Log.InfoFormat("The Person {0} has been deleted, so no alert sending", p);
                }
                return result;
            }
            catch (Exception ex)
            {
                return ErrorHandler.Handle(ex);
            }
        }
Пример #60
0
        public BusinessMessageResponse SetScheduledTaskStatus_mth(GenericRequest request)
        {
            try
            {
                var db = ImardaDatabase.CreateDatabase(Util.GetConnName<ScheduledTask>());
                byte status = (byte)request[0];
                string queueID = request.Parameters.Length > 1 ? (string)request[1] : null;
                db.ExecuteNonQuery("SPSetScheduledTaskStatus", request.ID, status, queueID);

                //   throw new Exception("SQL Timeout");
                return new BusinessMessageResponse();

            }
            catch (SqlException)
            {
                throw;
            }
        }