public async Task Handler_Return_True_Create_Success() { Mock <IDataAuthorityRepository> repositoryMock = new Mock <IDataAuthorityRepository>(); repositoryMock.Setup(a => a.AddPayLoad(It.IsAny <PayLoad>())) .Callback((PayLoad payload) => { PayLoad newPayLoad = new PayLoad(payload.Id + 1, payload.ProvidedPayLoadId, "Left", payload.Data); _payLoadList.Add(newPayLoad); }) .Returns(() => { return(_payLoadList.OrderBy(a => a.Id).FirstOrDefault()); }); CreatePayLoadCommand fakeCommand = new CreatePayLoadCommand(1, "Left", "dGVzdGU="); var handler = new CreatePayLoadCommandHandler(repositoryMock.Object); var canToken = new System.Threading.CancellationToken(); var result = await handler.Handle(fakeCommand, canToken); Assert.True(result); }
static async System.Threading.Tasks.Task Main(string[] args) { Payment payment = new Payment(); var key = payment.GetEncryptionKey(Secretkey); var json = JsonConvert.SerializeObject(GetData()); var encryptedData = payment.EncryptData(key, json); PayLoad postData = GetPayLoad(encryptedData); var jsondata = JsonConvert.SerializeObject(postData); ChargeResponse chargeReponse = await payment.SuggestCardType(chargeEndpoint, jsondata); if (chargeReponse != null && chargeReponse.status == "success" && chargeReponse.data.suggested_auth == "PIN") { var rawJsonDataInit = JsonConvert.SerializeObject(GetData(chargeReponse.data.suggested_auth, "3310")); var encryptedDataInit = payment.EncryptData(key, rawJsonDataInit); PayLoad payloadInit = GetPayLoad(encryptedDataInit); var encrptedjsondataInit = JsonConvert.SerializeObject(payloadInit); CardResponse cardReponse = await payment.InitializePayment(chargeEndpoint, encrptedjsondataInit); if (cardReponse != null && cardReponse.data.chargeResponseCode == "02" && cardReponse.data.authModelUsed == "PIN") { var dataRf = new { PBFPubKey = PublicKey, transaction_reference = cardReponse.data.txRef, otp = "12345" }; var jsondf = JsonConvert.SerializeObject(dataRf); ValidateResponse valReps = await payment.ValidatePayment(validationEndpoint, jsondf); } } else if (chargeReponse.status == "error") { } }
public PayLoad AddPayLoad(PayLoad payLoad) { int id = 0; DataModels.PayLoadDataModel payLoadEntity = _dataBase.GetPaylod(payLoad.ProvidedPayLoadId, payLoad.Origin); if (payLoadEntity != null) { id = payLoadEntity.Id; payLoadEntity.Data = payLoad.Data; _dataBase.UpdatePayLoad(payLoadEntity); } else { id = _dataBase.AddPayLoad(new DataModels.PayLoadDataModel() { ProvidedPayLoadId = payLoad.ProvidedPayLoadId, Origin = payLoad.Origin, Data = payLoad.Data }); } _mediator.DispatchDomainEvents(payLoad); DataModels.PayLoadDataModel newlyEntity = _dataBase.GetPaylodById(id); if (newlyEntity == null) { return(null); } else { return(new PayLoad(newlyEntity.Id, newlyEntity.ProvidedPayLoadId, newlyEntity.Origin, newlyEntity.Data)); } }
internal Drivers.CommunicationProtocol.PayLoad GetPayLoad() { PayLoad PL = new PayLoad("UIElementAction"); PL.AddValue(this.ElementLocateBy.ToString()); PL.AddValue(GetOrCreateInputParam(Fields.ElementLocateValue).ValueForDriver); // Need Value for driver PL.AddValue(this.ElementType.ToString()); PL.AddValue(this.ElementAction.ToString()); // Make it generic function in Act.cs to be used by other actions List <PayLoad> PLParams = new List <PayLoad>(); foreach (ActInputValue AIV in this.InputValues) { if (!string.IsNullOrEmpty(AIV.Value)) { PayLoad AIVPL = new PayLoad("AIV", AIV.Param, AIV.ValueForDriver); PLParams.Add(AIVPL); } } PL.AddListPayLoad(PLParams); PL.ClosePackage(); return(PL); }
public static SuperEventDetails CreateObject(PayLoad payLoad) { SuperEventDetails superEventDetail = new SuperEventDetails(); foreach (Event _event in payLoad.Data) { if (_event.AdditionalDetails == null) { _event.AdditionalDetails = new AdditionalDetails(); } List <EventDetailHeader> gett = new List <EventDetailHeader>(); var eventDetailHeader = new EventDetailHeader() { EventID = _event.EventID, NextStreamPosition = payLoad.NextStreamPosition, EventTimeStamp = _event.EventTimestamp }; superEventDetail.EventDetailHeaders.Add(eventDetailHeader); switch (_event.ObjectType) { case "SHEET": var sheetDetail = new SheetDetails() { EventID = _event.EventID, ObjectID = _event.ObjectID, Action = _event.Action, SourceObjectID = _event.AdditionalDetails.SourceObjectID, SourceGlobaltemplateID = _event.AdditionalDetails.SourceGlobalTemplateID, SourcetemplateID = _event.AdditionalDetails.SourceTemplateID, Source = _event.AdditionalDetails.Source, SourceType = _event.AdditionalDetails.SourceType, SheetName = _event.AdditionalDetails.SheetName, NewName = _event.AdditionalDetails.NewName, OldName = _event.AdditionalDetails.OldName, AccessLevel = _event.AdditionalDetails.AccessLevel, UserIDInitiator = _event.AdditionalDetails.UserID, GroupID = _event.AdditionalDetails.GroupID, WorkSpaceID = _event.AdditionalDetails.WorkSpaceID, OldUserID = _event.AdditionalDetails.OldUserID, OldAccessLevel = _event.AdditionalDetails.OldAccessLevel, NewUserID = _event.AdditionalDetails.NewUserID, NewAccessLevel = _event.AdditionalDetails.NewAccessLevel, RecipientEmail = _event.AdditionalDetails.RecipientEmail, RecipientGroupID = _event.AdditionalDetails.RecipientGroupID, FormatType = _event.AdditionalDetails.FormatType, RowCount = _event.AdditionalDetails.RowCount, IncludeAttachments = _event.AdditionalDetails.IncludeAttachments, IncludeDiscussions = _event.AdditionalDetails.IncludeDiscussions, SourceSheetID = _event.AdditionalDetails.SourceSheetID, DestinationSheetID = _event.AdditionalDetails.DestinationSheetID, RowsMoved = _event.AdditionalDetails.RowsMoved, RowsCopied = _event.AdditionalDetails.RowsCopied, CelllinkSourceSheetID = _event.AdditionalDetails.CelllinkSourceSheetID, NewParentContainerID = _event.AdditionalDetails.NewParentContainerID, ParentContainerID = _event.AdditionalDetails.ParentContainerID, FolderName = _event.AdditionalDetails.FolderName, RequestUserID = _event.AdditionalDetails.RequestUserID, SendCompletionEmail = _event.AdditionalDetails.SendCompletionEmail, UserIDImpacted = _event.AdditionalDetails.UserIDImpacted, EventTimestamp = _event.AdditionalDetails.EventTimeStamp }; superEventDetail.SheetDetails.Add(sheetDetail); break; case "REPORT": var reportDetail = new ReportDetails() { EventID = _event.EventID, ObjectID = _event.ObjectID, Action = _event.Action, ReportName = _event.AdditionalDetails.ReportName, SourceObjectID = _event.AdditionalDetails.SourceObjectID, SourceGlobaltemplateID = _event.AdditionalDetails.SourceGlobalTemplateID, SourceType = _event.AdditionalDetails.SourceType, NewName = _event.AdditionalDetails.NewName, OldName = _event.AdditionalDetails.OldName, AccessLevel = _event.AdditionalDetails.AccessLevel, UserID = _event.AdditionalDetails.UserID, GroupID = _event.AdditionalDetails.GroupID, WorkSpaceID = _event.AdditionalDetails.WorkSpaceID, OldUserID = _event.AdditionalDetails.OldUserID, OldAccessLevel = _event.AdditionalDetails.OldAccessLevel, NewUserID = _event.AdditionalDetails.NewUserID, NewAccessLevel = _event.AdditionalDetails.NewAccessLevel, NewParentContainerID = _event.AdditionalDetails.NewParentContainerID, ParentContainerID = _event.AdditionalDetails.ParentContainerID, FolderName = _event.AdditionalDetails.FolderName, RecipientEmail = _event.AdditionalDetails.RecipientEmail, RecipientGroupID = _event.AdditionalDetails.RecipientGroupID, FormatType = _event.AdditionalDetails.FormatType, UserIDImpacted = _event.AdditionalDetails.UserIDImpacted, UserIDInitiator = _event.UserID, EventTimestamp = _event.EventTimestamp, RequestUserID = _event.RequestUserID, Source = _event.Source }; superEventDetail.ReportDetails.Add(reportDetail); break; case "ATTACHMENT": var attachmentDetail = new AttachmentDetails() { EventID = _event.EventID, ObjectID = _event.ObjectID, Action = _event.Action, SheetID = _event.AdditionalDetails.SheetID, WorkSpaceID = _event.AdditionalDetails.WorkSpaceID, AttachmentName = _event.AdditionalDetails.AttachmentName, MultifileDownloadname = _event.AdditionalDetails.MultifileDownloadName, RecipientEmail = _event.AdditionalDetails.RecipientEmail, RecipientGroupID = _event.AdditionalDetails.RecipientGroupID, UserIDInitiator = _event.UserID, EventTimestamp = _event.EventTimestamp, RequestUserID = _event.RequestUserID, Source = _event.Source, }; superEventDetail.AttachmentDetails.Add(attachmentDetail); break; case "USER": var userDetail = new UserDetails() { EventID = _event.EventID, ObjectID = _event.ObjectID, Action = _event.Action, UserTypes = _event.AdditionalDetails.UserTypes, EmailAddress = _event.AdditionalDetails.EmailAddress, DeclineReason = _event.AdditionalDetails.DeclineReason, OldownerUserID = _event.AdditionalDetails.OldOwnerUserID, NewownerUserID = _event.AdditionalDetails.NewOwnerUserID, UserIDInitiator = _event.UserID, EventTimestamp = _event.EventTimestamp, RequestUserID = _event.RequestUserID, Source = _event.Source, }; superEventDetail.UserDetails.Add(userDetail); break; case "DISCUSSION": var discussionDetail = new DiscussionDetails() { EventID = _event.EventID, ObjectID = _event.ObjectID, Action = _event.Action, SheetRowID = _event.AdditionalDetails.SheetRowID, SheetID = _event.AdditionalDetails.SheetID, WorkSpaceID = _event.AdditionalDetails.WorkSpaceID, RecipientEmail = _event.AdditionalDetails.RecipientEmail, RecipientGroupID = _event.AdditionalDetails.RecipientGroupID, IncludeAttachments = _event.AdditionalDetails.IncludeAttachments, UserIDInitiator = _event.UserID, EventTimestamp = _event.EventTimestamp, RequestUserID = _event.RequestUserID, Source = _event.Source, }; superEventDetail.DiscussionDetails.Add(discussionDetail); break; case "DASHBOARD": var dashboardDetail = new DashboardDetails() { EventID = _event.EventID, ObjectID = _event.ObjectID, Action = _event.Action, DashboardName = _event.AdditionalDetails.DashboardName, SourceGlobalTemplateID = _event.AdditionalDetails.SourceGlobalTemplateID, SourceObjectID = _event.AdditionalDetails.SourceObjectID, SourceType = _event.AdditionalDetails.SourceType, AccessibleBy = _event.AdditionalDetails.AccessibleBy, PublishType = _event.AdditionalDetails.PublishType, PublishFormat = _event.AdditionalDetails.PublishFormat, AccessLevel = _event.AdditionalDetails.AccessLevel, UserID = _event.AdditionalDetails.UserID, GroupID = _event.AdditionalDetails.GroupID, WorkspaceID = _event.AdditionalDetails.WorkSpaceID, OldUserID = _event.AdditionalDetails.OldUserID, OldAccessLevel = _event.AdditionalDetails.OldAccessLevel, NewUserID = _event.AdditionalDetails.NewUserID, NewAccessLevel = _event.AdditionalDetails.NewAccessLevel, NewparentContainerID = _event.AdditionalDetails.NewParentContainerID, ParentContainerID = _event.AdditionalDetails.ParentContainerID, FolderName = _event.AdditionalDetails.FolderName, OldName = _event.AdditionalDetails.OldName, NewName = _event.AdditionalDetails.NewName, UserIDInitiator = _event.UserID, EventTimestamp = _event.EventTimestamp, RequestUserID = _event.RequestUserID, Source = _event.Source, }; superEventDetail.DashboardDetails.Add(dashboardDetail); break; case "FOLDER": var folderDetail = new FolderDetails() { EventID = _event.EventID, ObjectID = _event.ObjectID, Action = _event.Action, FolderName = _event.AdditionalDetails.FolderName, SourceFolderID = _event.AdditionalDetails.SourceFolderID, OldName = _event.AdditionalDetails.OldName, NewName = _event.AdditionalDetails.NewName, SendCompletionEmail = _event.AdditionalDetails.SendCompletionEmail, IncludeAttachments = _event.AdditionalDetails.IncludeAttachments, FormatType = _event.AdditionalDetails.FormatType, UserIDInitiator = _event.UserID, EventTimestamp = _event.EventTimestamp, RequestUserID = _event.RequestUserID, Source = _event.Source, }; superEventDetail.FolderDetails.Add(folderDetail); break; case "FORM": var formDetail = new FormDetails() { EventID = _event.EventID, ObjectID = _event.ObjectID, Action = _event.Action, FormName = _event.AdditionalDetails.FolderName, SheetID = _event.AdditionalDetails.SheetID, UserIDInitiator = _event.UserID, EventTimestamp = _event.EventTimestamp, RequestUserID = _event.RequestUserID, Source = _event.Source, }; superEventDetail.FormDetails.Add(formDetail); break; case "UPDATE REQUEST": var updateRequestDetail = new UpdateRequestDetails() { EventID = _event.EventID, ObjectID = _event.ObjectID, Action = _event.Action, SheetID = _event.AdditionalDetails.SheetID, RowCounts = _event.AdditionalDetails.RowCount.ToString(), IncludeAttachments = _event.AdditionalDetails.IncludeAttachments, IncludeDiscussions = _event.AdditionalDetails.IncludeDiscussions, UserIDInitiator = _event.UserID, EventTimestamp = _event.EventTimestamp, RequestUserID = _event.RequestUserID, Source = _event.Source, }; superEventDetail.UpdateRequestDetails.Add(updateRequestDetail); break; case "WORKSPACE": var workspaceDetail = new WorkSpaceDetails() { EventID = _event.EventID, ObjectID = _event.ObjectID, Action = _event.Action, OldName = _event.AdditionalDetails.OldName, NewName = _event.AdditionalDetails.NewName, AccessLevel = _event.AdditionalDetails.AccessLevel, UserID = _event.AdditionalDetails.UserID, GroupID = _event.AdditionalDetails.GroupID, IncludeAttachments = _event.AdditionalDetails.IncludeAttachments, SendCompletionEmail = _event.AdditionalDetails.SendCompletionEmail, FormatType = _event.AdditionalDetails.FormatType, UserIDInitiator = _event.UserID, EventTimestamp = _event.EventTimestamp, RequestUserID = _event.RequestUserID, Source = _event.Source, }; superEventDetail.WorkSpaceDetails.Add(workspaceDetail); break; case "ACCESSTOKEN": var accessTokenDetails = new AccessTokenDetails() { EventID = _event.EventID, ObjectID = _event.ObjectID, Action = _event.Action, TokenName = _event.AdditionalDetails.TokenName, TokenDisplayValue = _event.AdditionalDetails.TokenDisplayValue, TokenExpirationTimestamp = _event.AdditionalDetails.TokenExpirationTimestamp, AccessScopes = _event.AdditionalDetails.AccessScopes, AppClientID = _event.AdditionalDetails.AppClientID, AppName = _event.AdditionalDetails.AppName, TokenUserID = _event.AdditionalDetails.TokenUserID, UserIDInitiator = _event.UserID, EventTimestamp = _event.EventTimestamp, RequestUserID = _event.RequestUserID, Source = _event.Source, }; superEventDetail.AccessTokenDetails.Add(accessTokenDetails); break; case "ACCOUNT": var accountDetails = new AccountDetails() { EventID = _event.EventID, ObjectID = _event.ObjectID, Action = _event.Action, NewContactUserID = _event.AdditionalDetails.NewContactUserID, OldContactUserID = _event.AdditionalDetails.OldContactUserID, NewName = _event.AdditionalDetails.NewName, OldName = _event.AdditionalDetails.OldName, UserIDInitiator = _event.UserID, EventTimestamp = _event.EventTimestamp, RequestUserID = _event.RequestUserID, Source = _event.Source, }; superEventDetail.AccountDetails.Add(accountDetails); break; case "GROUP": var groupDetails = new GroupDetails() { EventID = _event.EventID, ObjectID = _event.ObjectID, Action = _event.Action, GroupName = _event.AdditionalDetails.GroupName, OldName = _event.AdditionalDetails.OldName, NewName = _event.AdditionalDetails.NewName, OldownerUserID = _event.AdditionalDetails.OldOwnerUserID, NewownerUserID = _event.AdditionalDetails.NewOwnerUserID, MemberUserID = _event.AdditionalDetails.MemberUserID, UserIDInitiator = _event.UserID, EventTimestamp = _event.EventTimestamp, RequestUserID = _event.RequestUserID, Source = _event.Source, }; superEventDetail.GroupDetails.Add(groupDetails); break; } } return(superEventDetail); }
public async Task <Json> GetAllNew() { PayLoad pl = base.GetCurrentUser <PayLoad>(); return(await _ContactBiz.SelectAllNew(pl.UserId)); }
public void Invalid_PayLoad() { Assert.Throws <DataAuthorityDomainException>(() => { PayLoad payLoad = new PayLoad(1, "sjdhfjsdf"); }); }
public void Create_Payload_Succes() { PayLoad payLoad = new PayLoad(1, "dGVzdGU="); Assert.NotNull(payLoad); }
public async void GetByCorrelationId_WhenCorrelationIdIsNotFound_ShouldReturnEmpty(PayLoad item, string anotherCorrelationId) { var payLoads = new List <PayLoad> { item }; _database.Entities.Returns(payLoads); var result = await _sut.GetByCorrelationId(anotherCorrelationId); result.Should().BeEmpty(); }
static void Main(string[] args) { string path = @$ "D:\Moudel 2\ExceptDemo\Baitap1DeMo\input.json"; PayLoad payload = new PayLoad() { courses = new List <Course>() }; using (StreamReader sr = File.OpenText(path)) { var data = sr.ReadToEnd(); payload = JsonConvert.DeserializeObject <PayLoad>(data); foreach (Course pb in payload.courses) { Console.WriteLine($"{pb.van} {pb.su} {pb.dia}"); } } Repay repay = new Repay() { Sumtotal = new List <total>() }; foreach (Course pb in payload.courses) { repay.Sumtotal.Add(new total { sum = pb.van + pb.su + pb.dia }); } using (StreamWriter sw = File.CreateText($@"{path}output.json")) { var pay = JsonConvert.SerializeObject(repay); sw.WriteLine(pay); } using (StreamWriter swr = File.CreateText($@"{path}output2.json")) { Tichxx repay2 = new Tichxx() { number = new List <Tichx>() }; foreach (Course pb in payload.courses) { repay2.number.Add(new Tichx() { xvan = pb.van * 2, xsu = pb.su * 2, xdia = pb.dia * 2 }); } var hala = JsonConvert.SerializeObject(repay2); swr.WriteLine(hala); } ResData resdata = new ResData() { tich = new List <Data>() }; using (StreamWriter swr = File.CreateText($@"{path}output3.json")) { foreach (Course pb in payload.courses) { resdata.tich.Add(new Data() { a = pb.van * 3, b = pb.su * 3, c = pb.dia * 3 }); } var hala = JsonConvert.SerializeObject(resdata); swr.WriteLine(hala); } }
public static void Add(PayLoad payload) { _payloadQueue.Enqueue(payload); }
//[OutputCache(1)] public async Task <Json> GetAll() { PayLoad pl = base.GetCurrentUser <PayLoad>(); return(await _RoleBiz.GetAll()); }
public override void ExecuteCRMWorkFlowActivity(CodeActivityContext executionContext, LocalWorkflowContext crmWorkflowContext) { String PayloadDetails = PayLoad.Get(executionContext); int? optionSetValue; int ErrorCode = 400; //400 -- bad request String _ErrorMessage = string.Empty; String _ErrorMessageDetail = string.Empty; Guid ContactId = Guid.Empty; Guid CrmGuid = Guid.Empty; StringBuilder ErrorMessage = new StringBuilder(); String UniqueReference = string.Empty; try { objCommon = new IdmNs.Helper(executionContext); objCommon.tracingService.Trace("Load CRM Service from context --- OK"); Entity AccountObject = new Entity(Defra.CustMaster.D365.Common.schema.AccountContants.ENTITY_NAME); objCommon.tracingService.Trace("attempt to seriallised new"); IdmNs.Organisation AccountPayload = JsonConvert.DeserializeObject <IdmNs.Organisation>(PayloadDetails); objCommon.tracingService.Trace("seriallised object working"); var ValidationContext = new ValidationContext(AccountPayload, serviceProvider: null, items: null); ICollection <System.ComponentModel.DataAnnotations.ValidationResult> ValidationResults = null; ICollection <System.ComponentModel.DataAnnotations.ValidationResult> ValidationResultsAddress = null; var isValid = objCommon.Validate(AccountPayload, out ValidationResults); Boolean isValidAddress = AccountPayload.address == null ? true : objCommon.Validate(AccountPayload.address, out ValidationResultsAddress); if (isValid & isValidAddress) { objCommon.tracingService.Trace("length{0}", AccountPayload.name.Length); if (AccountPayload.hierarchylevel != 0) { objCommon.tracingService.Trace("hierarchylevel level: {0}", AccountPayload.hierarchylevel); if (!String.IsNullOrEmpty(Enum.GetName(typeof(defra_OrganisationHierarchyLevel), AccountPayload.hierarchylevel))) { objCommon.tracingService.Trace("before assinging value"); AccountObject[Defra.CustMaster.D365.Common.schema.AccountContants.HIERARCHYLEVEL] = new OptionSetValue(AccountPayload.hierarchylevel); objCommon.tracingService.Trace("after assinging value"); if (!String.IsNullOrEmpty(Enum.GetName(typeof(defra_OrganisationType), AccountPayload.type))) { //check if crn exists OrganizationServiceContext orgSvcContext = new OrganizationServiceContext(objCommon.service); var checkCRNExistis = from c in orgSvcContext.CreateQuery("account") where (string)c[Defra.CustMaster.D365.Common.schema.AccountContants.COMPANY_HOUSE_ID] == AccountPayload.crn select new { organisationid = c.Id }; if (checkCRNExistis.FirstOrDefault() == null) { objCommon.tracingService.Trace("After completing validation 12" + AccountPayload.type); optionSetValue = AccountPayload.type; objCommon.tracingService.Trace("before assigning type " + AccountPayload.type); objCommon.tracingService.Trace(optionSetValue.ToString()); objCommon.tracingService.Trace("after setting up option set value"); OptionSetValueCollection BusinessTypes = new OptionSetValueCollection(); BusinessTypes.Add(new OptionSetValue(optionSetValue.Value)); AccountObject[Defra.CustMaster.D365.Common.schema.AccountContants.TYPE] = BusinessTypes; AccountObject[Defra.CustMaster.D365.Common.schema.AccountContants.NAME] = AccountPayload.name == null ? string.Empty : AccountPayload.name; AccountObject[Defra.CustMaster.D365.Common.schema.AccountContants.COMPANY_HOUSE_ID] = AccountPayload.crn == string.Empty ? null : AccountPayload.crn; AccountObject[Defra.CustMaster.D365.Common.schema.AccountContants.TELEPHONE1] = AccountPayload.telephone == null ? string.Empty : AccountPayload.telephone; objCommon.tracingService.Trace("after setting other fields"); bool IsValidGuid; Guid ParentAccountId; if (AccountPayload.parentorganisation != null && String.IsNullOrEmpty(AccountPayload.parentorganisation.parentorganisationcrmid)) { IsValidGuid = Guid.TryParse(AccountPayload.parentorganisation.parentorganisationcrmid, out ParentAccountId); if (IsValidGuid) { AccountObject[Defra.CustMaster.D365.Common.schema.AccountContants.PARENTACCOUNTID] = ParentAccountId; } } AccountObject[Defra.CustMaster.D365.Common.schema.AccountContants.EMAILADDRESS1] = AccountPayload.email; objCommon.tracingService.Trace("before createing guid:"); CrmGuid = objCommon.service.Create(AccountObject); objCommon.tracingService.Trace("after createing guid:{0}", CrmGuid.ToString()); Entity AccountRecord = objCommon.service.Retrieve("account", CrmGuid, new Microsoft.Xrm.Sdk.Query.ColumnSet(Defra.CustMaster.D365.Common.schema.AccountContants.UNIQUEREFERENCE)); UniqueReference = (string)AccountRecord[Defra.CustMaster.D365.Common.schema.AccountContants.UNIQUEREFERENCE]; objCommon.CreateAddress(AccountPayload.address, new EntityReference(Defra.CustMaster.D365.Common.schema.AccountContants.ENTITY_NAME, CrmGuid)); ErrorCode = 200; } else { ErrorCode = 412; ErrorMessage = ErrorMessage.Append(String.Format("Company house id already exists.")); } } } else { ErrorCode = 400; ErrorMessage = ErrorMessage.Append(String.Format("Option set value {0} for orgnisation hirarchy level not found.", Defra.CustMaster.D365.Common.schema.AccountContants.HIERARCHYLEVEL.ToString())); } } else { ErrorCode = 400; ErrorMessage = ErrorMessage.Append(String.Format("Option set value {0} for orgnisation type does not exists.", AccountPayload.type)); } } else { objCommon.tracingService.Trace("inside validation result"); ErrorMessage = new StringBuilder(); //this will throw an error foreach (System.ComponentModel.DataAnnotations.ValidationResult vr in ValidationResults) { ErrorMessage.Append(vr.ErrorMessage + " "); } foreach (System.ComponentModel.DataAnnotations.ValidationResult vr in ValidationResultsAddress) { ErrorMessage.Append(vr.ErrorMessage + " "); } ErrorCode = 400; } } catch (Exception ex) { objCommon.tracingService.Trace("inside exception"); ErrorCode = 500; _ErrorMessage = "Error occured while processing request"; _ErrorMessageDetail = ex.Message; ErrorCode = 400; this.ReturnMessageDetails.Set(executionContext, _ErrorMessageDetail); objCommon.tracingService.Trace(ex.Message); } finally { objCommon.tracingService.Trace("finally block start"); AccountResponse responsePayload = new AccountResponse() { code = ErrorCode, message = ErrorMessage.ToString(), datetime = DateTime.UtcNow, version = "1.0.0.2", status = ErrorCode == 200 ? "success" : "failure", data = new AccountData() { accountid = CrmGuid, uniquerefere = UniqueReference, error = new ResponseErrorBase() { details = _ErrorMessageDetail } } }; objCommon.tracingService.Trace("attempting to serialise"); string json = JsonConvert.SerializeObject(responsePayload); ReturnMessageDetails.Set(executionContext, json); // OutputCode.Set(executionContext, _errorCode); objCommon.tracingService.Trace("json {0}", json); objCommon.tracingService.Trace("finally block end"); } }
public static rootACSResponseNotificacao EnviarNotificacao(string canal, object Dados, string clientes = "everyone", string Mensagem = "", string Servico = "") { try { rootACSResponseNotificacao resposta = new rootACSResponseNotificacao(); rootACSResponse aux = resposta; //Verifico se o admin está logado. checkLogin(ref aux); resposta = (rootACSResponseNotificacao)aux; //Se não estiver retorno o código de erro -1. if (resposta.meta.code != 0) { return(resposta); } HttpWebRequest request = default(HttpWebRequest); //Url de notificação no ACS. request = (HttpWebRequest)WebRequest.Create("https://api.cloud.appcelerator.com/v1/push_notification/notify.json?key=" + ChaveACS); //Seto o cookie container para manter o valor da sessão. request.CookieContainer = CC; //O método de notificação é POST de acordo a documentação da appcelerator. request.Method = "POST"; //Serializo os dados da notificacao em um json. ParametrosNotificacao info = new ParametrosNotificacao(); //Seto o canal da notificação. info.channel = canal; info.options = new OptionsNotificacao(); //A notificação expira após 1 dia. info.options.expire_after_seconds = 86400; //Envio os dados para os usuários selecionados, por padrão envia para todo mundo. info.to_ids = clientes; //Monto os dados de configuração da notificação. dynamic payload = new PayLoad(); payload.alert = Mensagem; payload.dados = Dados; payload.mensagem = Mensagem; if (!string.IsNullOrEmpty(Servico)) { payload.servico = Servico; } payload.title = "Britec"; info.payload = payload; string postData = JsonConvert.SerializeObject(info); byte[] byteArray = Encoding.UTF8.GetBytes(postData); // Seto o ContentType para json, já que os dados no POST estão no formato JSON. request.ContentType = "application/json"; //Preparo os dados request.ContentLength = byteArray.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); //Obtenho a resposta da requisição HttpWebResponse response = (HttpWebResponse)request.GetResponse(); dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); //Leio a resposta. string responseFromServer = reader.ReadToEnd(); //Deserializo a resposta. resposta = JsonConvert.DeserializeObject <rootACSResponseNotificacao>(responseFromServer); //Fecho os streans. reader.Close(); dataStream.Close(); response.Close(); //Retorno a resposta do serviço return(resposta); } catch (WebException ex) { rootACSResponseNotificacao resposta = new rootACSResponseNotificacao(); rootACSResponse aux = resposta; if (ex.Status == WebExceptionStatus.ProtocolError) { MontaException400(ref aux); } else { MontaExceptionDesconhecido(ref aux); } resposta = (rootACSResponseNotificacao)aux; return(resposta); } catch (Exception) { throw; } }
protected override void Execute(CodeActivityContext executionContext) { #region "Read Parameters" //Account AccountPayload = JsonConvert.DeserializeObject<Account>(PayLoad.Get(executionContext)); String Payload = PayLoad.Get(executionContext); DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(Account)); int? optionSetValue; Int64 ErrorCode = 400; //400 -- bad request String _ErrorMessage = string.Empty; String _ErrorMessageDetail = string.Empty; Guid ContactId = Guid.Empty; Guid CrmGuid; #endregion #region "Load CRM Service from context" try { Common objCommon = new Common(executionContext); objCommon.tracingService.Trace("Load CRM Service from context --- OK"); using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(Payload))) { Account AccountPayload = (Account)deserializer.ReadObject(ms); if (AccountPayload.type == 0) { objCommon.tracingService.Trace("checking business type"); _ErrorMessage = "Business type cannot be empty."; } else if (!String.IsNullOrEmpty(AccountPayload.name) && AccountPayload.name.Length > 160) { objCommon.tracingService.Trace("checking org name"); _ErrorMessage = "Organiation name is more than 160 characters."; } else if (!String.IsNullOrEmpty(AccountPayload.crn) && AccountPayload.crn.Length > 8) { objCommon.tracingService.Trace("checking house id"); _ErrorMessage = "Company House Id cannot be more than 8 characters."; } /* * else if (!(String.IsNullOrWhiteSpace(AccountPayload.)) && (_ValidatedWithCompanyHouse == "y" || _ValidatedWithCompanyHouse == "n")) * { * objCommon.tracingService.Trace("checking validated with company house id"); * * _ErrorMessage = "Validated with company house should have y or n"; * * }*/ /* * else if (!String.IsNullOrEmpty(_Email) && _Email.Length > 100) * { * _ErrorMessage = "Email address cannot be more than 100 characters long."; * * }*/ else { objCommon.tracingService.Trace("After completing validation"); optionSetValue = AccountPayload.type; Entity Account = new Entity("account"); objCommon.tracingService.Trace("before assigning"); objCommon.tracingService.Trace(optionSetValue.ToString()); OptionSetValueCollection BusinessTypes = new OptionSetValueCollection(); BusinessTypes.Add(new OptionSetValue(optionSetValue.Value)); // Account["defra_type"] = BusinessTypes; //Account["defra_businesstype"] = BusinessTypes; Account["name"] = AccountPayload.name; Account["defra_companyhouseid"] = AccountPayload.crn == null ? null : AccountPayload.crn; Account["telephone"] = AccountPayload.telephone == null ? null : AccountPayload.telephone; Account["defra_hierarchylevel"] = AccountPayload.hierarchylevel == null ? null : AccountPayload.hierarchylevel; if (AccountPayload.parentorganisation != null && AccountPayload.parentorganisation.parentorganisationcrmid != Guid.Empty) { Entity ParentAccount = objCommon.service.Retrieve("account", AccountPayload.parentorganisation.parentorganisationcrmid, new Microsoft.Xrm.Sdk.Query.ColumnSet("accountid")); Account["parentaccountid"] = AccountPayload.parentorganisation.parentorganisationcrmid; } objCommon.tracingService.Trace("after assigning"); if (AccountPayload.validatedwithcompanieshouse == "y") { Account["defra_validatedwithcompanyhouse"] = 0; } else if (AccountPayload.validatedwithcompanieshouse == "n") { Account["defra_validatedwithcompanyhouse"] = 1; } if (AccountPayload.email != null) { Account["emailaddress1"] = AccountPayload.email; } objCommon.tracingService.Trace("before createing guid:"); try { CrmGuid = objCommon.service.Create(Account); objCommon.tracingService.Trace("after createing guid:{0}", CrmGuid.ToString()); this.CrmGuid.Set(executionContext, CrmGuid.ToString()); Entity AccountRecord = objCommon.service.Retrieve("account", CrmGuid, new Microsoft.Xrm.Sdk.Query.ColumnSet("defra_uniquereference")); this.Code.Set(executionContext, ErrorCode.ToString()); this.UniqueReference.Set(executionContext, AccountRecord["defra_uniquereference"]); objCommon.CreateAddress(AccountPayload.address, new EntityReference("account", CrmGuid)); } catch (Exception ex) { objCommon.tracingService.Trace("error message:" + ex.Message); } ErrorCode = 200; //success } objCommon.tracingService.Trace("outside 1"); this.Code.Set(executionContext, ErrorCode.ToString()); this.Message.Set(executionContext, _ErrorMessage); this.MessageDetail.Set(executionContext, _ErrorMessageDetail); if (_ErrorMessage != string.Empty) { this.Message.Set(executionContext, _ErrorMessage); } } } catch (Exception ex) { ErrorCode = 500; _ErrorMessage = "Error occured while processing request"; _ErrorMessageDetail = ex.Message; //throw ex; this.Code.Set(executionContext, ErrorCode.ToString()); this.Message.Set(executionContext, _ErrorMessage); this.MessageDetail.Set(executionContext, _ErrorMessageDetail); } #endregion }
//[OutputCache(1)] public async Task <Json> GetAllRuleAssignmentView() { PayLoad pl = base.GetCurrentUser <PayLoad>(); return(await _RuleAssignBiz.GetAllRuleAssignmentView()); }
public void Validate_WhenPayLoadAlreadyExists_IsValidShouldBeFalse(byte[] content, PayLoad payLoad) { var command = new PayLoadCreateCommand("123456", content, SideEnum.Left); _payLoadRepository.GetByCorrelationIdAndSide(command.CorrelationId, command.Side).Returns(payLoad); var validationResult = _sut.Validate(command); validationResult.IsValid.Should().BeFalse(); validationResult.Errors.Should().OnlyContain(x => x.ErrorCode.Equals("PayloadAlreadyExists")); }
public PayLoad Post([FromBody] PayLoad payLoad) { return(payLoad); }
public bool Parse() { ResetContext(); byte[] bytes = new byte[2048]; string data = ""; string[] splitByEndline = null; string[] splitBuffer = null; bool RecievingHTTPMessage = false; int i; //parses Socket Message into a string while ((i = Stream.Read(bytes, 0, bytes.Length)) != 0) { data += System.Text.Encoding.ASCII.GetString(bytes, 0, i); if (!Stream.DataAvailable) { break; } } //splits the string by \n splitByEndline = data.Split('\n'); //trim of /r for (i = 0; i < splitByEndline.Length; i++) { splitByEndline[i] = splitByEndline[i].Trim('\r'); } if (splitByEndline.Length == 0) { return(false); } //split first line by spacebar splitBuffer = splitByEndline[0].Split(' '); //verify that 3 elements exist in first line if (splitBuffer.Length != 3) { return(false); } //assign values. HTTPVerb = splitBuffer[0]; MessageEndPoint = splitBuffer[1]; HttpProtokoll = splitBuffer[2]; //write an imposible string into splitbyendline so we can skip it in foreach loop. splitByEndline[0] = "\n\n\n\0"; foreach (string subString in splitByEndline) { if (subString == "\n\n\n\0") { continue; } //check if recieving payload or recieving headers if (!RecievingHTTPMessage) { //if length = 0 sign for recieving payload if (subString.Length == 0) { RecievingHTTPMessage = true; continue; } //https://stackoverflow.com/questions/21519548/split-string-based-on-the-first-occurrence-of-the-character //split by : splitBuffer = subString.Split(new[] { ':' }, 2); if (splitBuffer.Length == 1) { RecievingHTTPMessage = true; continue; } // example -> host: 127.0.1.2 //trim off spacebar Headers.Add(splitBuffer[0], splitBuffer[1].Trim(' ')); } else { //write payload PayLoad += subString + "\r\n"; continue; } } //trim of trailing \r\n PayLoad = PayLoad.Trim('\n'); PayLoad = PayLoad.Trim('\r'); return(true); }
public async void GetByCorrelationId_WhenCorrelationIdIsFound_ShouldReturnPayLoadAsExpected(PayLoad item) { var payLoads = new List <PayLoad> { item, new PayLoad(item.CorrelationId, item.Content, SideEnum.Right) }; _database.Entities.Returns(payLoads); var result = await _sut.GetByCorrelationId(item.CorrelationId); result.Should().BeEquivalentTo(payLoads); }