private static Guid FindPluginAssembly(OrganizationService service, string assemblyName) { var query = new QueryExpression { EntityName = "pluginassembly", ColumnSet = null, Criteria = new FilterExpression() }; query.Criteria.AddCondition("name", ConditionOperator.Equal, assemblyName); var request = new RetrieveMultipleRequest { Query = query }; var response = (RetrieveMultipleResponse)service.Execute(request); if (response.EntityCollection.Entities.Count == 1) { var id = response.EntityCollection[0].GetAttributeValue<Guid>("pluginassemblyid"); _logger.Log(LogLevel.Debug, () => string.Format("Found id {0} for assembly", id)); return id; } return Guid.Empty; }
public override DTSExecResult Validate(IDTSInfoEvents infoEvents) { // プロパティが一つでも空だったらエラーとする if (!PropertiesValidate(infoEvents, URL, Domain, UserName, Password)) { return DTSExecResult.Failure; } // 接続テスト try { var con = CrmConnection.Parse(ConnectionString); con.Timeout = TimeSpan.FromSeconds(30); using (var service = new OrganizationService(con)) { service.Execute<WhoAmIResponse>(new WhoAmIRequest()); } } catch (Exception e) { infoEvents.FireError(0, "Dynamics CRM 2011 接続マネージャー", e.Message, string.Empty, 0); return DTSExecResult.Failure; } return DTSExecResult.Success; }
private static void Export() { var service = new OrganizationService(CrmConnection.Parse("Url=http://dev-crm/SCAMPROD;")); //var doc = new WordDocumentDocX(); //doc.Settings = new GenerationSettings //{ // FilePath = @"c:\temp\doc.docx", // AddAuditInformation = true, // AddEntitiesSummary = true, // AddFieldSecureInformation = true, // AddFormLocation = true, // AddRequiredLevelInformation = true, // AddValidForAdvancedFind = true, // AttributesSelection = AttributeSelectionOption.AllAttributes, // DisplayNamesLangugageCode = 1033, // EntitiesToProceed = new List<EntityItem>{new EntityItem // { // Name = "scam_repartition" // }}, // IncludeOnlyAttributesOnForms = false, // OutputDocumentType = Output.Word, //}; //doc.Generate(service); }
/// <summary> /// 接続テスト /// </summary> /// <param name="sender"></param> /// <param name="ev"></param> private void btnTest_Click(object sender, EventArgs ev) { var connectionString = CreateConnectionString ( Url => txbURL.Text, Domain => txbDomain.Text, Username => txbUserName.Text, Password => txbPassword.Text ); // connection test try { var con = CrmConnection.Parse(connectionString); con.Timeout = TimeSpan.FromSeconds(30); using (var service = new OrganizationService(con)) { service.Execute<WhoAmIResponse>(new WhoAmIRequest()); } } catch (Exception e) { MessageBox.Show(e.Message, "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } MessageBox.Show("OK", "確認", MessageBoxButtons.OK, MessageBoxIcon.Information); }
public virtual void Connect() { string CrmConnectionString = string.Format("Url={0}; Username={1}; Password={2};", Url, Username, Password); crmConnection = CrmConnection.Parse(CrmConnectionString); service = new OrganizationService(crmConnection); }
private EntityCollection GetYelpAccounts() { CrmConnection connection = CrmConnection.Parse(_connection); using (_orgService = new OrganizationService(connection)) { var query = new QueryExpression { EntityName = "account", ColumnSet = new ColumnSet("test9_yelpid"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "test9_yelpid", Operator = ConditionOperator.NotNull } } } }; return _orgService.RetrieveMultiple(query); } }
/// <summary> /// retrieves a list of CRM roles assigned to a specific user /// </summary> /// <param name="userid"></param> /// <param name="service"></param> /// <returns></returns> private List<string> GetUserRoles(Guid userid, OrganizationService service) { List<string> roles = new List<string>(); string fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'> <entity name='role'> <attribute name='name' /> <attribute name='businessunitid' /> <attribute name='roleid' /> <order attribute='name' descending='false' /> <link-entity name='systemuserroles' from='roleid' to='roleid' visible='false' intersect='true'> <link-entity name='systemuser' from='systemuserid' to='systemuserid' alias='af'> <filter type='and'> <condition attribute='systemuserid' operator='eq' uitype='systemuser' value='{$USERID}' /> </filter> </link-entity> </link-entity> </entity> </fetch>"; fetchXml = fetchXml.Replace("$USERID", userid.ToString()); EntityCollection results = service.RetrieveMultiple(new FetchExpression(fetchXml)); foreach (Entity entity in results.Entities) { roles.Add((string)entity["name"]); } return roles; }
public async Task<bool> IsAuthenticated(PortalUser user) { string Url = ConfigurationManager.AppSettings["URL"].ToString(); string CrmConnectionString = string.Format("Url={0}; Username={1}; Password={2}", Url, user.Username, user.Password); ClientCredentials credential = new ClientCredentials(); credential.UserName.UserName = user.Username; credential.UserName.Password = user.Password; CrmConnection crmConnection = CrmConnection.Parse(CrmConnectionString); crmConnection.ClientCredentials = credential; OrganizationService service = new OrganizationService(crmConnection); QueryExpression qe = new QueryExpression("systemuser"); qe.ColumnSet = new ColumnSet(); qe.ColumnSet.AddColumn("systemuserid"); qe.ColumnSet.AddColumn("fullname"); qe.Criteria = new FilterExpression(); qe.Criteria.AddCondition("domainname", ConditionOperator.Equal, user.Username); EntityCollection collection = service.RetrieveMultiple(qe); if (collection.Entities.Count == 0) { return false; } return true; }
public void PublishInCRM(ServiceRequest serviceRequest) { //Connects to the database and Logs the User In var connection = ConnectToDatabase(); var service = new OrganizationService(connection); var context = new CrmOrganizationServiceContext(connection); //const int hour = 60; EventLog.saveMessage("PublishIssue SRID:" + serviceRequest.SRID); //Creating the new Case Entity incident = new Entity("incident"); try { //Filling the Data for the new case incident["createdon"] = serviceRequest.RegistrationDate; incident["description"] = serviceRequest.LongDescription; incident["statuscode"] = ReturnStatusCode(serviceRequest.ServiceRequestStatus); incident["subjectid"] = ReturnRequestType(serviceRequest.ServiceRequestType); incident["new_moduleoptionset"] = ReturnModuleCode("TS"); //incident["ownerid"] = new EntityReference("systemuser", findConsultantID(serviceRequest.AssignedPerson, service)); incident["new_caseasignedto"] = serviceRequest.AssignedPerson; incident["new_statushistory"] = serviceRequest.CommentsMatricia; incident["casetypecode"] = returnRequestKind(serviceRequest.ServiceRequestKind); incident["followupby"] = serviceRequest.DueDate; incident["new_supportrequestid"] = serviceRequest.SRID; incident["title"] = serviceRequest.AssignedToClient + " " + serviceRequest.SRID + " " + serviceRequest.companyName; //incident["customerid"] = new EntityReference("account", findCustomer((string)serviceRequest.companyName, service)); incident["customerid"] = new EntityReference("account", findCustomerID(serviceRequest.companyName)); incident["new_statushistory"] = serviceRequest.ShortDescription; incident["new_assignedfrom"] = serviceRequest.CreatedBy; Guid consultantID = findConsultantID(serviceRequest.AssignedPerson, service); //Adding the created case to CRM; var incidentGuid = service.Create(incident); //Assign a case! EventLog.saveMessage("Start of Assignment! to :" + consultantID); AssignRequest assignRequest = new AssignRequest(); assignRequest.Assignee = new EntityReference("systemuser", consultantID); assignRequest.Target = new EntityReference(incident.LogicalName, incidentGuid); service.Execute(assignRequest); } catch (Exception) { EventLog.saveMessage("This case was not created in CRM " + serviceRequest.CreatedBy + "'" + serviceRequest.SRID); ; } }
static void Main(string[] args) { CrmConnection connection = CrmConnection.Parse( ConfigurationManager.ConnectionStrings["CRMConnectionString"].ConnectionString); using (_orgService = new OrganizationService(connection)) { //Do stuff } }
public void TestSiteMapCacheRequest() { IOrganizationService service = new OrganizationService(new CrmConnection("CRM")); StringWriter mapJson = new StringWriter(); SiteMapLoader loader = new SiteMapLoader(1033); ITracingService tace = new debugTrace(); loader.ParseSiteMapToJson(service,tace, mapJson); Console.WriteLine(mapJson.ToString()); }
public void TestMethod1() { IOrganizationService service = new OrganizationService(new CrmConnection("CRM")); RetrieveFormXmlRequest request = new RetrieveFormXmlRequest(); request.EntityName = "contact"; var response = service.Execute<RetrieveFormXmlResponse>(request); Console.WriteLine(response.FormXml); }
/// <summary> /// コンストラクタ。dynamicsとの接続を確立する。 /// </summary> /// <param name="user"></param> /// <param name="pass"></param> /// <param name="url"></param> public DynamicsCls(string user, string pass, string url) { string connetString = String.Format("Url={0}; Username={1}; Password={2};", url, user, pass); CrmConnection connection = CrmConnection.Parse(connetString); _service = new OrganizationService(connection); WhoAmIResponse res = (WhoAmIResponse)_service.Execute(new WhoAmIRequest()); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { var myConnection = new CrmConnection("Xrm"); using (var myService = new OrganizationService(myConnection)) using (var myContext = new Xrm.XRMServiceContext(myService)) { var accounts = myContext.bro_managetemplateSet.ToList(); } } }
public override int DeleteInactiveProfiles(ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate) { //MAS using (OrganizationService service = new OrganizationService(OurConnect())) { ConditionExpression appCondition = new ConditionExpression(); ConditionExpression authenticationCondition = new ConditionExpression(); appCondition.AttributeName = consts.appname; appCondition.Operator = ConditionOperator.Equal; appCondition.Values.Add(_ApplicationName); switch (authenticationOption) { case ProfileAuthenticationOption.Anonymous: authenticationCondition.AttributeName = consts.isanonymous; authenticationCondition.Operator = ConditionOperator.Equal; authenticationCondition.Values.Add(true); break; case ProfileAuthenticationOption.Authenticated: authenticationCondition.AttributeName = consts.isanonymous; authenticationCondition.Operator = ConditionOperator.Equal; authenticationCondition.Values.Add(false); break; default: break; } FilterExpression filter = new FilterExpression(); filter.Conditions.Add(appCondition); filter.Conditions.Add(authenticationCondition); QueryExpression query = new QueryExpression(consts.userprofile); query.ColumnSet.AddColumn(consts.username); query.Criteria.AddFilter(filter); EntityCollection collection = service.RetrieveMultiple(query); string[] usersToDelete = null; int j = 0; for(int i=0;i<collection.TotalRecordCount;i++) { if (DateTime.Compare(lastActivity((string)collection.Entities[i][consts.username], String.Empty), userInactiveSinceDate) < 0) { usersToDelete[j] = (string)collection.Entities[i][consts.username]; j++; } } return DeleteProfiles(usersToDelete); } }
/// <summary> /// Validate method to attempt to connect to CRM with supplied username/password and then execute a whoami request /// </summary> /// <param name="username">crm username</param> /// <param name="password">crm password</param> public override void Validate(string username, string password) { //get the httpcontext so we can store the user guid for impersonation later HttpContext context = HttpContext.Current; //if username or password are null, obvs we can't continue if (null == username || null == password) { throw new ArgumentNullException(); } //get the crm connection Microsoft.Xrm.Client.CrmConnection connection = CrmUtils.GetCrmConnection(username, password); //try the whoami request //if it fails (user can't be authenticated, is disabled, etc.), the client will get a soap fault message using (OrganizationService service = new OrganizationService(connection)) { try { WhoAmIRequest req = new WhoAmIRequest(); WhoAmIResponse resp = (WhoAmIResponse)service.Execute(req); Entity systemuser = CrmUtils.GetSystemUser(resp.UserId, service); CrmIdentity crmIdentity = new CrmIdentity(); crmIdentity.Name = (string)systemuser["fullname"]; crmIdentity.FirstName = (string)systemuser["firstname"]; crmIdentity.LastName = (string)systemuser["lastname"]; crmIdentity.Email = (string)systemuser["internalemailaddress"]; crmIdentity.UserId = resp.UserId; crmIdentity.SetAuthenticated(true); List<string> roles = CrmUtils.GetUserRoles(resp.UserId, service); foreach (string role in roles) { crmIdentity.AddRole(role); } context.User = new GenericPrincipal(crmIdentity, roles.ToArray()); } catch (System.ServiceModel.Security.MessageSecurityException ex) { throw new FaultException(ex.Message); } catch (Exception ex) { throw new FaultException(ex.Message); } } }
public void Get() { _connection = ConfigurationManager.ConnectionStrings["CRMOnlineO365"].ConnectionString; CrmConnection connection = CrmConnection.Parse(_connection); EntityCollection results = GetYelpAccounts(); if (!results.Entities.Any()) return; using (_orgService = new OrganizationService(connection)) { foreach (Entity entity in results.Entities) { GetYelpData(entity.Id, entity.GetAttributeValue<string>("test9_yelpid")); } } }
public void AddRemarksForEntry(Guid entryID, Annotation data, string Username, string Password) { Entity note = new Entity("annotation"); note["objectid"] = new EntityReference("gsc_timeentry", entryID); note["subject"] = data.Subject; note["notetext"] = data.NoteText; string Url = ConfigurationManager.AppSettings["Url"].ToString(); string CrmConnectionString = string.Format("Url={0}; Username={1}; Password={2}", Url, Username, Password); CrmConnection crmConnection = null; crmConnection = CrmConnection.Parse(CrmConnectionString); OrganizationService service = new OrganizationService(crmConnection); service.Create(note); }
public void Create(string entityName, [FromBody] JObject objStructure) { var connectionString = ConfigurationManager.ConnectionStrings["CRMConnectionString"].ConnectionString; CrmConnection crmConnection = CrmConnection.Parse(connectionString); using (OrganizationService service = new OrganizationService(crmConnection)) { if (objStructure != null) { Entity entity = new Entity(entityName); Guid guidValue; foreach (var attribute in objStructure) { if (Guid.TryParse(attribute.Value.ToString(), out guidValue)) { RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = attribute.Key.ToString(), RetrieveAsIfPublished = true }; // Execute the request RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)service.Execute(attributeRequest); if (attributeResponse.AttributeMetadata.AttributeType == AttributeTypeCode.Lookup) { string relatedEntityName = ((LookupAttributeMetadata)(attributeResponse.AttributeMetadata)).Targets[0]; EntityReference eref = new EntityReference(relatedEntityName, guidValue); entity[attribute.Key.ToString()] = eref; continue; } } entity[attribute.Key.ToString()] = attribute.Value.ToString(); } service.Create(entity); } } }
static void Main(string[] args) { try { CrmConnection connection = CrmConnection.Parse( ConfigurationManager.ConnectionStrings["CRMConnectionString"].ConnectionString); using (_orgService = new OrganizationService(connection)) { //Do stuff } } catch (FaultException<OrganizationServiceFault> ex) { string message = ex.Message; throw; } }
public void TestTokenising() { IOrganizationService service = new OrganizationService(new CrmConnection("CRM")); string text = @"// This content is static var someStaticValue = 123; /*metadata // This content will be dynamically evaluated on first request - and then again when the webresource cache key is changed after a publish // It is enclosed in the comment tags so that if the metadata server plugin is not installed it does not cause syntax errors // Account //<@format=ResourceStrings.{1}_{2}_{3}={0}@> <@account.DisplayName@>; <@account.DisplayCollectionName@>; <@account.name.DisplayName@>; // Contact <@contact.DisplayName@>; <@contact.DisplayCollectionName@>; <@contact.fullname.DisplayName@>; //<@format=@> MultiLanguageView.AddOptionsetMetadata('account','accountcategorycode',<@account.accountcategorycode.OptionSet@>); var more = <@contact.fullname.DisplayName@>; var accountDisplayName = <@account.DisplayName@>; var someFetchXml = <@fetch=<fetch version=""1.0"" output-format=""xml-platform"" mapping=""logical"" distinct=""false""> <entity name=""account""> <attribute name=""name"" /> <attribute name=""primarycontactid"" /> <attribute name=""telephone1"" /> <attribute name=""accountid"" /> <order attribute=""name"" descending=""false"" /> </entity> </fetch>@>; metadata*/"; var plugin = new MetadataServerPlugin("Debug", ""); string result = plugin.ParseTemplate(text, 1031, service); //1031- German //1036 - French //1025 - Arabic Console.WriteLine(result); }
private void GetConnection(Action<MyDynamicsServiceContext> action) { _logger.Info("Connecting to CRM...", this); var connection = new CrmConnection("CRMServiceConnection"); using (var org = new OrganizationService(connection)) { try { var context = new MyDynamicsServiceContext(org); action(context); } catch (Exception ex) { //Log the exception, then let the business layer handle the error scenario _logger.Error("There was a problem connecting to CRM", ex, this); throw ex; } } }
static void Main(string[] args) { CrmConnection connection = CrmConnection.Parse( ConfigurationManager.ConnectionStrings["CRMConnectionString"].ConnectionString); using (_orgService = new OrganizationService(connection)) { Entity account1 = new Entity("account"); account1["Name"] = "test1"; //C# 6.0 Entity account2 = new Entity("account") {["Name"] = "test2"}; Entity account3 = new Entity("account"); account3.Attributes.Add("Name", "test3"); } }
/// <summary> /// Returns a valid List of all audit records for a case /// </summary> /// <remarks> /// Microsoft article on how to retrieve audit history data: /// https://msdn.microsoft.com/en-us/library/gg309735.aspx /// </remarks> /// <param name="guid"></param> /// <param name="entityLogicalName"></param> /// <param name="fallbackCreatedOn"></param> /// <param name="fallbackTicketNumber"></param> /// <param name="fallbackDueDate"></param> /// <param name="fallbackOwner"></param> /// <param name="svc"></param> /// <returns>List of AuditDataChange</returns> public List<AuditDataChange> GetAuditDetails(Guid guid, string entityLogicalName) { try { var auditDataChangeList = new List<AuditDataChange>(); RetrieveRecordChangeHistoryResponse changeResponse; RetrieveRecordChangeHistoryRequest changeRequest = new RetrieveRecordChangeHistoryRequest(); changeRequest.Target = new EntityReference(entityLogicalName, guid); AuditDetailCollection details; using (OrganizationService svc = new OrganizationService(new CrmConnection("Crm"))) { changeResponse = (RetrieveRecordChangeHistoryResponse)svc.Execute(changeRequest); } if (changeResponse != null) { details = changeResponse.AuditDetailCollection; } else { throw new Exception("change response was null?"); } if (details != null) { // filter thru AuditDetailCollection and build List<AuditDataChange> auditDataChangeList = _ProcessAuditDetails(details); } return auditDataChangeList; } catch (Exception ex) { Util.WriteErrorToLog("GetAuditDetails", new Dictionary<string, string>() { { "guid", guid.ToString() }, { "entityLogicalName", entityLogicalName } }, ex); throw ex; } }
public void TestConnection(string connectionString) { try { var crmConnection = CrmConnection.Parse(connectionString); //to escape "another assembly" exception crmConnection.ProxyTypesAssembly = Assembly.GetExecutingAssembly(); OrganizationService orgService; using (orgService = new OrganizationService(crmConnection)) { orgService.Execute(new WhoAmIRequest()); ConnectionString = connectionString; Close(); } } catch (Exception ex) { ConnectionStatusLabel.Dispatcher.BeginInvoke(new Action(() => ConnectionStatusLabel.Content = "Connection Failed.")); } }
public string Post([FromBody] FormDataCollection formValues) { string domain = HttpContext.Current.Request.Headers["Origin"].ToLower(); string host = HttpContext.Current.Request.Url.Host.ToLower(); //if (!domain.Contains("jlleadform.azurewebsites.net") && !domain.Contains(host)) // return "fail!"; CrmConnection connection = CrmConnection.Parse( ConfigurationManager.ConnectionStrings["CRMOnlineO365"].ConnectionString); using (_orgService = new OrganizationService(connection)) { Entity lead = new Entity("lead"); lead["firstname"] = formValues.Get("FirstName"); lead["lastname"] = formValues.Get("LastName"); _orgService.Create(lead); } return "success"; }
/// <summary> /// Validate method to attempt to connect to CRM with supplied username/password and then execute a whoami request /// </summary> /// <param name="username">crm username</param> /// <param name="password">crm password</param> public override void Validate(string username, string password) { //get the httpcontext so we can store the user guid for impersonation later HttpContext context = HttpContext.Current; //if username or password are null, obvs we can't continue if (null == username || null == password) { throw new ArgumentNullException(); } //get the crm connection using the simplified connection string method // the following assumes the server url is stored in the web.config appsettings collection like so: // <add key="crmconnectionstring" value="Url=https://crm.example.com; "/> string connectionString = ConfigurationManager.AppSettings["crmconnectionstring"]; connectionString += " Username="******"; Password=" + password; Microsoft.Xrm.Client.CrmConnection connection = CrmConnection.Parse(connectionString); //try the whoami request //if it fails (user can't be authenticated, is disabled, etc.), the client will get a soap fault message using (OrganizationService service = new OrganizationService(connection)) { try { WhoAmIRequest req = new WhoAmIRequest(); WhoAmIResponse resp = (WhoAmIResponse)service.Execute(req); List<string> roles = GetUserRoles(resp.UserId, service); context.User = new GenericPrincipal(new GenericIdentity(resp.UserId.ToString()), roles.ToArray()); } catch (System.ServiceModel.Security.MessageSecurityException ex) { throw new FaultException(ex.Message); } catch (Exception ex) { throw new FaultException(ex.Message); } } }
private static bool? ChangeStateCode(Guid id) { var service = new OrganizationService(connection); SetStateRequest state = new SetStateRequest(); state.State = new OptionSetValue((int)TaskState.Completed); state.Status = new OptionSetValue(5); state.EntityMoniker = new EntityReference() { Id = id, LogicalName = SoftLine.Models.Task.EntityLogicalName }; SetStateResponse stateSet = (SetStateResponse)service.Execute(state); SoftLine.Models.Task task = service.Retrieve(SoftLine.Models.Task.EntityLogicalName, id, new ColumnSet("statecode")).ToEntity<SoftLine.Models.Task>(); if (task.StateCode == TaskState.Completed) { return true; } return null; }
public JsonResult<NewOppCount> Get(string userId) { OrganizationService orgService; CrmConnection connection = CrmConnection.Parse( ConfigurationManager.ConnectionStrings["CRMConnectionString"].ConnectionString); using (orgService = new OrganizationService(connection)) { //Query the CRM data based on the user id being passed in FetchExpression query = new FetchExpression(@" <fetch distinct='true' aggregate='true' > <entity name='opportunity' > <attribute name='opportunityid' alias='NewOppCount' aggregate='count' /> <attribute name='ownerid' alias='ownerid' groupby='true' /> <filter type='and' > <condition attribute='ownerid' operator='eq' value='" + userId + @"' /> <condition attribute='createdon' operator='today' /> </filter> </entity> </fetch>"); //Get the result values for output EntityCollection results = orgService.RetrieveMultiple(query); string username = (string)results.Entities[0].GetAttributeValue<AliasedValue>("ownerid_owneridname").Value; int count = (int)results.Entities[0].GetAttributeValue<AliasedValue>("NewOppCount").Value; NewOppCount result = new NewOppCount { Username = username, Message = "New Opps Today:", Count = count }; //Return JSON or XML return Json(result); } }
private void ExecuteButton_Click(object sender, RoutedEventArgs e) { var fetchXml = FetchXmlTextBox.Text; var crmConnection = CrmConnection.Parse(_connectionString); //to escape "another assembly" exception crmConnection.ProxyTypesAssembly = Assembly.GetExecutingAssembly(); try { using (var organizationService = new OrganizationService(crmConnection)) { FetchXmlToQueryExpressionRequest req = new FetchXmlToQueryExpressionRequest {FetchXml = fetchXml}; var response = (FetchXmlToQueryExpressionResponse) organizationService.Execute(req); new ShowDataWindow(response).ShowDialog(); } } catch (Exception ex) { MessageBox.Show("Not Connected!" + ex); } }
public ActionResult Upload(Document model, HttpPostedFileBase uploadFile) { // Verify that the user selected a file if (model != null && uploadFile != null && uploadFile.ContentLength > 0) { try { int UserID = int.Parse(Request.Cookies["UserID"].Value); bool authorized = Framework.Security.SecurityBase.IsUserRoleAuthorized(UserID, model.DepartmentID, model.SubDepartmentID, "Doc Upload"); if (!authorized) { throw new Exception("Access denied! You donot have permission to upload any document for the department/subdepartment."); } using (TransactionScope trans = new TransactionScope()) { // extract only the fielname var fileName = Path.GetFileName(uploadFile.FileName); // Save file model.FileType = new FileInfo(fileName).Extension; model.CreatedBy = Request.Cookies["UserEmail"].Value; Document newDocinfo = new DocumentFacade().Save(model); string rootpath = Server.MapPath("~/WorkSpaces/" + newDocinfo.PhysicalPath); var path = Path.Combine(rootpath, model.DocumentName + model.FileType); if (DocumentHelper.CreatePath(path)) { // Save meta data var metadata_path = Path.Combine(Server.MapPath("~/WorkSpaces/" + newDocinfo.MetaDataPath), model.DocumentName + ".xml"); string metadata = XmlHelper.Serialize(newDocinfo, newDocinfo.GetType()); System.IO.File.WriteAllText(metadata_path, metadata); // Save document uploadFile.SaveAs(path); trans.Complete(); } } // build response message var dept = new DepartmentService().GetDepartmentDetails(model.DepartmentID); string deptName = dept.DepartmentName; // build response message string subDeptName = ""; if (model.SubDepartmentID > 0) { var subdept = new SubDepartmentService().GetSubDepartmentDetails(model.SubDepartmentID); subDeptName = "/" + subdept.SubDepartmentName; } this.ShowMessage(Helpers.MessageType.Success, "New document for " + deptName + subDeptName + " created/revised successfully"); return(RedirectToAction("Index", "DocumentLibrary")); } catch (Exception ex) { ModelState.AddModelError("", ex.Message); } } // Rebuild data int OrgID = int.Parse(Request.Cookies["OrgID"].Value); List <DepartmentModel> depts = new OrganizationService().GetOrganizationByID(OrgID).Departments; ViewBag.Departments = depts; ViewBag.SubDepartments = new List <SubDepartmentModel>(); return(View(model)); }
public OrganizationsController() : base() { entityService = new OrganizationService(base.db); }
/// <summary> /// source: https://community.dynamics.com/crm/b/tsgrdcrmblog/archive/2014/03/06/microsoft-dynamics-crm-2013-application-lifetime-management-part-2 /// </summary> public void Import(string solutionFilename, bool importAsync = true) { var solutionFileBytes = File.ReadAllBytes(solutionFilename); var importSolutionRequest = new ImportSolutionRequest { CustomizationFile = solutionFileBytes, PublishWorkflows = true, ImportJobId = new Guid(), OverwriteUnmanagedCustomizations = true }; if (importAsync) { var asyncRequest = new ExecuteAsyncRequest { Request = importSolutionRequest }; var asyncResponse = OrganizationService.Execute(asyncRequest) as ExecuteAsyncResponse; Guid?asyncJobId = asyncResponse.AsyncJobId; var end = DateTime.Now.AddMinutes(CrmParameter.ConnectionTimeOutMinutes); bool finished = false; while (!finished) { // Wait for 15 Seconds to prevent us overloading the server with too many requests Thread.Sleep(15 * 1000); if (end < DateTime.Now) { throw new Exception(($"Solution import has timed out: {CrmParameter.ConnectionTimeOutMinutes} minutes")); } Entity asyncOperation; try { asyncOperation = OrganizationService.Retrieve("asyncoperation", asyncJobId.Value, new ColumnSet("asyncoperationid", Constant.Entity.StatusCode, "message")); } catch (Exception e) { /* Unfortunately CRM Online seems to lock up the application when importing * Large Solutions, and thus it generates random errors. Mainly they are * SQL Client errors, but we can't guarantee this so we just catch them and report to user * then continue on. */ MessageLogger?.Invoke(this, $"{e.Message}"); continue; } var statusCode = asyncOperation.GetAttributeValue <OptionSetValue>(Constant.Entity.StatusCode).Value; var message = asyncOperation.GetAttributeValue <string>("message"); // Succeeded if (statusCode == 30) { finished = true; break; } // Pausing // Canceling // Failed // Canceled if (statusCode == 21 || statusCode == 22 || statusCode == 31 || statusCode == 32) { throw new Exception($"Solution Import Failed: {statusCode} {message}"); } } } else { var response = (ImportSolutionResponse)OrganizationService.Execute(importSolutionRequest); } }
public static void Main() { //get the config data GetConfig(); //connect to rabbitmq Console.WriteLine("Connecting . . ."); var factory = new ConnectionFactory(); factory.HostName = _brokerEndpoint; factory.UserName = _brokerUser; factory.Password = _brokerPassword; factory.VirtualHost = "/"; //assumes we use the default vhost factory.Protocol = Protocols.DefaultProtocol; //assumes we use the default protocol factory.Port = AmqpTcpEndpoint.UseDefaultPort; //assumes we use the default port using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { //wait for some messages var consumer = new QueueingBasicConsumer(channel); channel.BasicConsume(_queue, false, consumer); Console.WriteLine(" [*] Waiting for messages. To exit press CTRL+C"); //instantiate crm org service using (OrganizationService service = new OrganizationService(_targetConn)) { while (true) { //get the message from the queue var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue(); var body = ea.Body; var message = Encoding.UTF8.GetString(body); try { //deserialize message json to object LeadType lead = JsonConvert.DeserializeObject <LeadType>(message); try { //create record in crm Entity entity = new Entity("lead"); entity["firstname"] = lead.FirstName; entity["lastname"] = lead.LastName; entity["subject"] = lead.Topic; entity["companyname"] = lead.Company; service.Create(entity); //write success message to cli Console.WriteLine("Created lead: {0} {1}", lead.FirstName, lead.LastName); //IMPORTANT - tell the queue the message was processed successfully so it doesn't get requeued channel.BasicAck(ea.DeliveryTag, false); } catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex) { //return error - note no confirmation is sent to the queue, so the message will be requeued Console.WriteLine("Could not create lead: {0} {1}", lead.FirstName, lead.LastName); Console.WriteLine("Error: {0}", ex.Message); } } catch (Exception ex) { //return error - note no confirmation is sent to the queue, so the message will be requeued Console.WriteLine("Could not process message from queue"); Console.WriteLine("Error: {0}", ex.Message); } } } } } }
public ActionResult Details(int id) { var Organization = new OrganizationService().GetOrganizationDetailsById(id); return(View(Organization)); }
public ActionResult Websites(Uri url, string username, string password) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("url={0}", url)); try { var serviceUri = GetOrganizationServiceUrl(url); var authenticationType = GetAuthenticationType(serviceUri); var connection = GetConnection(serviceUri, authenticationType, username, password); using (var service = new OrganizationService(connection)) { var query = new QueryExpression("adx_website") { ColumnSet = new ColumnSet("adx_name") }; query.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0); query.Criteria.AddCondition("adx_parentwebsiteid", ConditionOperator.Null); var linkEntity = new LinkEntity("adx_website", "adx_websitebinding", "adx_websiteid", "adx_websiteid", JoinOperator.LeftOuter); linkEntity.Columns.AddColumn("adx_websitebindingid"); linkEntity.EntityAlias = "binding"; linkEntity.LinkCriteria.AddCondition("statecode", ConditionOperator.Equal, 0); linkEntity.LinkCriteria.AddCondition("adx_sitename", ConditionOperator.Equal, SetupManager.GetSiteName()); var filter = linkEntity.LinkCriteria.AddFilter(LogicalOperator.Or); var path = HostingEnvironment.ApplicationVirtualPath ?? "/"; if (!path.StartsWith("/")) { path = "/" + path; } filter.AddCondition("adx_virtualpath", ConditionOperator.Equal, path); filter.AddCondition("adx_virtualpath", ConditionOperator.Equal, path.Substring(1)); if (path.Substring(1) == string.Empty) { filter.AddCondition("adx_virtualpath", ConditionOperator.Null); } query.LinkEntities.Add(linkEntity); var entities = service.RetrieveMultiple(query).Entities; var websites = entities .Select(w => new { Name = w.GetAttributeValue <string>("adx_name"), Id = w.GetAttributeValue <Guid>("adx_websiteid"), Binding = w.GetAttributeValue <AliasedValue>("binding.adx_websitebindingid") != null }) .OrderBy(w => w.Name) .ToList(); if (!websites.Any()) { throw new ModelErrorException("Website", ResourceManager.GetString("No_Active_Website_Found_Exception"), null); } return(Json(websites)); } } catch (ModelErrorException mee) { return(ToJsonModelError(mee.Key, mee)); } catch (Exception e) { return(ToJsonModelError("Website", e)); } }
protected override void ProcessRecord() { base.ProcessRecord(); base.WriteVerbose(string.Format("Importing Solution: {0}", SolutionFilePath)); // TODO: I think this is not necessary because you will get back an Id if you overload Guid.Empty if (ImportJobId == Guid.Empty) { ImportJobId = Guid.NewGuid(); } if (AsyncWaitTimeout == 0) { AsyncWaitTimeout = 15 * 60; base.WriteVerbose(string.Format("Setting Default AsyncWaitTimeout: {0}", AsyncWaitTimeout)); } if (SleepInterval == 0) { SleepInterval = 15; base.WriteVerbose(string.Format("Setting Default SleepInterval: {0}", SleepInterval)); } base.WriteVerbose(string.Format("ImportJobId {0}", ImportJobId)); byte[] solutionBytes = File.ReadAllBytes(SolutionFilePath); var importSolutionRequest = new ImportSolutionRequest { CustomizationFile = solutionBytes, PublishWorkflows = PublishWorkflows, ConvertToManaged = ConvertToManaged, OverwriteUnmanagedCustomizations = OverwriteUnmanagedCustomizations, SkipProductUpdateDependencies = SkipProductUpdateDependencies, ImportJobId = ImportJobId, RequestId = ImportJobId, HoldingSolution = HoldingSolution }; if (ImportAsync) { var asyncRequest = new ExecuteAsyncRequest { Request = importSolutionRequest, RequestId = ImportJobId }; var asyncResponse = OrganizationService.Execute(asyncRequest) as ExecuteAsyncResponse; Guid asyncJobId = asyncResponse.AsyncJobId; WriteObject(asyncJobId); if (WaitForCompletion) { AwaitCompletion(asyncJobId); } } else { OrganizationService.Execute(importSolutionRequest); } base.WriteVerbose(string.Format("{0} Imported Completed {1}", SolutionFilePath, ImportJobId)); }
protected void btnImport_Click(object sender, EventArgs e) { lterror.Text = ""; if (flReport.HasFile) { string strext = Path.GetExtension(flReport.PostedFile.FileName).Substring(1); if (strext == "xls" || strext == "xlsx") { string fullfilename = "~/UserFile/" + flReport.FileName; if (File.Exists(Server.MapPath(fullfilename))) { lterror.Text = "File đã tồn tại, vui lòng đổi tên khác"; return; } flReport.PostedFile.SaveAs(Server.MapPath(fullfilename)); if (File.Exists(Server.MapPath(fullfilename))) { log.Info("File: " + flReport.FileName); DataTable dt = new DataTable(); string connectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", Server.MapPath(fullfilename)); string query = String.Format("select * from [{0}$]", "Sheet1"); SecurityBSO securityBSO = new SecurityBSO(); OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString); DataSet dataSet = new DataSet(); dataAdapter.Fill(dataSet); DataTable myTable = dataSet.Tables[0]; EnterpriseService comBSO = new EnterpriseService(); int rowi = 0; foreach (DataRow drow in myTable.Rows) { rowi++; log.Info("Dong thu: " + rowi); try { ReportTemp2014 temp = new ReportTemp2014(); Enterprise enter = new Enterprise(); int eId = 0; enter.Title = drow["Ten_DN"].ToString(); temp.Title = enter.Title; log.Info("Doanh nghiep: " + enter.Title); enter.OrganizationId = Convert.ToInt32(drow["SCT_ID"]); temp.OrgId = enter.OrganizationId; if (drow["DiaChi"] != DBNull.Value) { enter.Address = drow["DiaChi"].ToString(); temp.Address = enter.Address; } if (drow["LinhVuc_Id"] != DBNull.Value && drow["LinhVuc_Id"].ToString() != "") { temp.AreaId = Convert.ToInt32(drow["LinhVuc_Id"]); enter.AreaId = temp.AreaId; } enter.ProvinceId = Convert.ToInt32(drow["TinhTP_ID"]); enter.ManProvinceId = enter.ProvinceId; enter.OrganizationId = Convert.ToInt32(drow["SCT_ID"]); if (drow["Ma_DN"] != DBNull.Value && drow["Ma_DN"].ToString().Trim() != "") { eId = Convert.ToInt32(drow["Ma_DN"]); //enter = comBSO.FindByKey(eId); } else { enter.ActiveYear = 2015; enter.CustomerCode = ""; enter.TaxCode = ""; if (drow["PhanNganh"] != DBNull.Value && drow["PhanNganh"].ToString() != "") { DataTable dtSub = new AreaService().getAreaByName(drow["PhanNganh"].ToString()); if (dtSub != null && dtSub.Rows.Count > 0) { enter.SubAreaId = Convert.ToInt32(dtSub.Rows[0]["Id"]); temp.SubAreaId = enter.SubAreaId; } else { Area sub = new Area(); sub.AreaName = drow["PhanNganh"].ToString(); sub.ParentId = enter.AreaId; sub.IsStatus = 1; sub.SortOrder = 0; int subId = new AreaService().Insert(sub); temp.SubAreaId = subId; enter.SubAreaId = subId; } enter.Info = drow["PhanNganh"].ToString(); temp.SubAreaName = drow["PhanNganh"].ToString(); } eId = comBSO.Insert(enter);//Them doanh nghiep if (eId > 0) { Organization org = new OrganizationService().FindByKey(enter.OrganizationId); //Tao tai khoan doanh nghiep Utils objUtil = new Utils(); MemberService memberService = new MemberService(); int STT = 0; STT = new EnterpriseService().GetNoAccount(enter.OrganizationId); STT++; ePower.DE.Domain.Member member = new ePower.DE.Domain.Member(); member.EnterpriseId = eId; member.IsDelete = false; member.AccountName = "dn." + Utils.UCS2Convert(org.Title).Replace(" ", "").Replace("-", "").ToLower() + "." + STT.ToString("000"); member.Password = securityBSO.EncPwd("abc123"); int mId = memberService.Insert(member); if (mId < 0) { log.Info("Khong tao duoc tai khoan"); } } else { log.Info("Khong tao duoc DN"); } } if (eId > 0) { ReportFuel report = new ReportFuel(); ReportFuelService reportService = new ReportFuelService(); report.EnterpriseId = eId; report.OrganizationId = enter.OrganizationId; report.ReportDate = DateTime.Now; report.CompanyName = enter.Title; report.Address = enter.Address; report.ApprovedSatus = true; report.AprovedDate = DateTime.Now; report.AreaId = enter.AreaId; report.ConfirmedDate = DateTime.Now; report.Created = DateTime.Now; report.DistrictId = enter.DistrictId; report.Email = enter.Email; report.Fax = enter.Fax; report.IsFiveYear = false; report.IsDelete = false; report.Phone = enter.Phone; report.ReportDate = DateTime.Now; report.SendSatus = 1; report.Year = 2018; report.SubAreaId = enter.SubAreaId; report.Year = Convert.ToInt32(txtPlanYear.Text.Trim()); temp.EnterpriseId = eId; int reportId = reportService.Insert(report); if (reportId > 0) { ReportFuelDetailService serviceDetail = new ReportFuelDetailService(); ReportFuelDetail detail = new ReportFuelDetail(); int detailid = 0; if (drow["Dien_kWh"] != DBNull.Value && drow["Dien_kWh"].ToString().Trim() != "") { temp.Dien_kWh = drow["Dien_kWh"].ToString(); detail.EnterpriseId = report.EnterpriseId; detail.FuelId = 1; detail.MeasurementId = 1; detail.No_RateTOE = 0.0001543m; detail.Price = 0; detail.Year = 2017; if (drow["Dien_kWh"] != DBNull.Value && drow["Dien_kWh"].ToString() != "") { detail.NoFuel = Convert.ToDecimal(drow["Dien_kWh"]); } detail.NoFuel_TOE = detail.No_RateTOE * detail.NoFuel; detail.ReportId = reportId; detailid = serviceDetail.Insert(detail); if (detailid <= 0) { log.Info("Them dien loi"); } } if (drow["ThanDa_Tan"] != DBNull.Value && drow["ThanDa_Tan"].ToString().Trim() != "") { detail = new ReportFuelDetail(); temp.Than_Tan = drow["ThanDa_Tan"].ToString(); detail.EnterpriseId = report.EnterpriseId; detail.FuelId = 2; detail.MeasurementId = 2; detail.No_RateTOE = 0.7m; detail.Price = 0; detail.Year = 2017; if (drow["ThanDa_Tan"] != DBNull.Value && drow["ThanDa_Tan"].ToString() != "") { detail.NoFuel = Convert.ToDecimal(drow["ThanDa_Tan"]); } detail.NoFuel_TOE = detail.No_RateTOE * detail.NoFuel; detail.ReportId = reportId; detailid = serviceDetail.Insert(detail); if (detailid <= 0) { log.Info("Them than da_tan loi"); } } if (drow["Than12_Tan"] != DBNull.Value && drow["Than12_Tan"].ToString().Trim() != "") { detail = new ReportFuelDetail(); temp.Than_Tan = drow["Than12_Tan"].ToString(); detail.EnterpriseId = report.EnterpriseId; detail.FuelId = 3; detail.MeasurementId = 2; detail.No_RateTOE = 0.7m; detail.Price = 0; detail.Year = 2017; if (drow["Than12_Tan"] != DBNull.Value && drow["Than12_Tan"].ToString() != "") { detail.NoFuel = Convert.ToDecimal(drow["Than12_Tan"]); } detail.NoFuel_TOE = detail.No_RateTOE * detail.NoFuel; detail.ReportId = reportId; detailid = serviceDetail.Insert(detail); if (detailid <= 0) { log.Info("Them than 12 loi"); } } if (drow["Than34_Tan"] != DBNull.Value && drow["Than34_Tan"].ToString().Trim() != "") { detail = new ReportFuelDetail(); temp.Than_Tan = drow["Than34_Tan"].ToString(); detail.EnterpriseId = report.EnterpriseId; detail.FuelId = 4; detail.MeasurementId = 2; detail.No_RateTOE = 0.6m; detail.Price = 0; detail.Year = 2017; if (drow["Than34_Tan"] != DBNull.Value && drow["Than34_Tan"].ToString() != "") { detail.NoFuel = Convert.ToDecimal(drow["Than34_Tan"]); } detail.NoFuel_TOE = detail.No_RateTOE * detail.NoFuel; detail.ReportId = reportId; detailid = serviceDetail.Insert(detail); if (detailid <= 0) { log.Info("Them than34 loi"); } } if (drow["Than56_Tan"] != DBNull.Value && drow["Than56_Tan"].ToString().Trim() != "") { detail = new ReportFuelDetail(); temp.Than_Tan = drow["Than56_Tan"].ToString(); detail.EnterpriseId = report.EnterpriseId; detail.FuelId = 5; detail.MeasurementId = 2; detail.No_RateTOE = 0.5m; detail.Price = 0; detail.Year = 2017; if (drow["Than56_Tan"] != DBNull.Value && drow["Than56_Tan"].ToString() != "") { detail.NoFuel = Convert.ToDecimal(drow["Than56_Tan"]); } detail.NoFuel_TOE = detail.No_RateTOE * detail.NoFuel; detail.ReportId = reportId; detailid = serviceDetail.Insert(detail); if (detailid <= 0) { log.Info("Them than56 loi"); } } if (drow["DO_Tan"] != DBNull.Value && drow["DO_Tan"].ToString().Trim() != "") { detail = new ReportFuelDetail(); temp.DO_Tan = drow["DO_Tan"].ToString(); detail.EnterpriseId = report.EnterpriseId; detail.FuelId = 6; detail.MeasurementId = 2; detail.No_RateTOE = 1.02m; detail.Price = 0; detail.Year = 2017; if (drow["DO_Tan"] != DBNull.Value && drow["DO_Tan"].ToString() != "") { detail.NoFuel = Convert.ToDecimal(drow["DO_Tan"]); } detail.NoFuel_TOE = detail.No_RateTOE * detail.NoFuel; detail.ReportId = reportId; detailid = serviceDetail.Insert(detail); if (detailid <= 0) { log.Info("Them dau do_tan loi"); } } if (drow["DO_lit"] != DBNull.Value && drow["DO_lit"].ToString().Trim() != "") { temp.DO_lit = drow["DO_lit"].ToString(); detail = new ReportFuelDetail(); detail.EnterpriseId = report.EnterpriseId; detail.FuelId = 6; detail.MeasurementId = 3; detail.No_RateTOE = 0.00088m; detail.Price = 0; detail.Year = 2017; if (drow["DO_lit"] != DBNull.Value && drow["DO_lit"].ToString() != "") { detail.NoFuel = Convert.ToDecimal(drow["DO_lit"]); } detail.NoFuel_TOE = detail.No_RateTOE * detail.NoFuel; detail.ReportId = reportId; detailid = serviceDetail.Insert(detail); if (detailid <= 0) { log.Info("Them dauDO_lit loi"); } } if (drow["FO_Tan"] != DBNull.Value && drow["FO_Tan"].ToString().Trim() != "") { temp.FO_Tan = drow["FO_Tan"].ToString(); detail = new ReportFuelDetail(); detail.EnterpriseId = report.EnterpriseId; detail.FuelId = 7; detail.MeasurementId = 2; detail.No_RateTOE = 0.99m; detail.Price = 0; detail.Year = 2017; if (drow["FO_Tan"] != DBNull.Value && drow["FO_Tan"].ToString() != "") { detail.NoFuel = Convert.ToDecimal(drow["FO_Tan"]); } detail.NoFuel_TOE = detail.No_RateTOE * detail.NoFuel; detail.ReportId = reportId; detailid = serviceDetail.Insert(detail); if (detailid <= 0) { log.Info("Them dau FO_tan loi"); } } if (drow["FO_lit"] != DBNull.Value && drow["FO_lit"].ToString().Trim() != "") { temp.FO_lit = drow["FO_lit"].ToString(); detail = new ReportFuelDetail(); detail.EnterpriseId = report.EnterpriseId; detail.FuelId = 7; detail.MeasurementId = 3; detail.No_RateTOE = 0.00094m; detail.Price = 0; detail.Year = 2017; if (drow["FO_lit"] != DBNull.Value && drow["FO_lit"].ToString() != "") { detail.NoFuel = Convert.ToDecimal(drow["FO_lit"]); } detail.NoFuel_TOE = detail.No_RateTOE * detail.NoFuel; detail.ReportId = reportId; detailid = serviceDetail.Insert(detail); if (detailid <= 0) { log.Info("Them dau FO_Lit loi"); } } if (drow["Xang_Tan"] != DBNull.Value && drow["Xang_Tan"].ToString().Trim() != "") { temp.Xang_Tan = drow["Xang_Tan"].ToString(); detail = new ReportFuelDetail(); detail.EnterpriseId = report.EnterpriseId; detail.FuelId = 11; detail.MeasurementId = 2; detail.No_RateTOE = 1.05m; detail.Price = 0; detail.Year = 2017; if (drow["Xang_Tan"] != DBNull.Value && drow["Xang_Tan"].ToString() != "") { detail.NoFuel = Convert.ToDecimal(drow["Xang_Tan"]); } detail.NoFuel_TOE = detail.No_RateTOE * detail.NoFuel; detail.ReportId = reportId; detailid = serviceDetail.Insert(detail); if (detailid <= 0) { log.Info("Them xang_tan loi"); } } if (drow["Xang_lit"] != DBNull.Value && drow["Xang_lit"].ToString().Trim() != "") { temp.Xang_lit = drow["Xang_lit"].ToString(); detail = new ReportFuelDetail(); detail.EnterpriseId = report.EnterpriseId; detail.FuelId = 11; detail.MeasurementId = 3; detail.No_RateTOE = 0.00083m; detail.Price = 0; detail.Year = 2017; if (drow["Xang_lit"] != DBNull.Value && drow["Xang_lit"].ToString() != "") { detail.NoFuel = Convert.ToDecimal(drow["Xang_lit"]); } detail.NoFuel_TOE = detail.No_RateTOE * detail.NoFuel; detail.ReportId = reportId; detailid = serviceDetail.Insert(detail); if (detailid <= 0) { log.Info("Them xang_lit loi"); } } if (drow["Gas_Tan"] != DBNull.Value && drow["Gas_Tan"].ToString().Trim() != "") { temp.Gas_Tan = drow["Gas_Tan"].ToString(); detail = new ReportFuelDetail(); detail.EnterpriseId = report.EnterpriseId; detail.FuelId = 10; detail.MeasurementId = 4; detail.No_RateTOE = 0.0009m; detail.Price = 0; detail.Year = 2017; if (drow["Gas_Tan"] != DBNull.Value && drow["Gas_Tan"].ToString() != "") { detail.NoFuel = Convert.ToDecimal(drow["Gas_Tan"]); } detail.NoFuel_TOE = detail.No_RateTOE * detail.NoFuel; detail.ReportId = reportId; detailid = serviceDetail.Insert(detail); if (detailid <= 0) { log.Info("Them Gas_Tan loi"); } } if (drow["Khi_m3"] != DBNull.Value && drow["Khi_m3"].ToString().Trim() != "") { temp.Khi_M3 = drow["Khi_m3"].ToString(); detail = new ReportFuelDetail(); detail.EnterpriseId = report.EnterpriseId; detail.FuelId = 10; detail.MeasurementId = 1; detail.No_RateTOE = 0.0009m; detail.Price = 0; detail.Year = 2017; if (drow["Khi_m3"] != DBNull.Value && drow["Khi_m3"].ToString() != "") { detail.NoFuel = Convert.ToDecimal(drow["Khi_m3"]); } detail.NoFuel_TOE = detail.No_RateTOE * detail.NoFuel; detail.ReportId = reportId; detailid = serviceDetail.Insert(detail); if (detailid <= 0) { log.Info("Them Khi_m3 loi"); } } if (drow["LPG_Tan"] != DBNull.Value && drow["LPG_Tan"].ToString().Trim() != "") { temp.LPG_Tan = drow["LPG_Tan"].ToString(); detail = new ReportFuelDetail(); detail.EnterpriseId = report.EnterpriseId; detail.FuelId = 8; detail.MeasurementId = 2; detail.No_RateTOE = 1.09m; detail.Price = 0; detail.Year = 2017; if (drow["LPG_Tan"] != DBNull.Value && drow["LPG_Tan"].ToString() != "") { detail.NoFuel = Convert.ToDecimal(drow["LPG_Tan"]); } detail.NoFuel_TOE = detail.No_RateTOE * detail.NoFuel; detail.ReportId = reportId; detailid = serviceDetail.Insert(detail); if (detailid <= 0) { log.Info("Them LPG loi"); } } if (drow["NLPL_Tan"] != DBNull.Value && drow["NLPL_Tan"].ToString().Trim() != "") { temp.NLPL_Tan = drow["NLPL_Tan"].ToString(); detail = new ReportFuelDetail(); detail.EnterpriseId = report.EnterpriseId; detail.FuelId = 12; detail.MeasurementId = 2; detail.No_RateTOE = 1.05m; detail.Price = 0; detail.Year = 2017; if (drow["NLPL_Tan"] != DBNull.Value && drow["NLPL_Tan"].ToString() != "") { detail.NoFuel = Convert.ToDecimal(drow["NLPL_Tan"]); } detail.NoFuel_TOE = detail.No_RateTOE * detail.NoFuel; detail.ReportId = reportId; detailid = serviceDetail.Insert(detail); if (detailid <= 0) { log.Info("Them NLPL loi"); } } if (drow["Khac_tan"] != DBNull.Value && drow["Khac_tan"].ToString().Trim() != "") { temp.KhacSoDo = drow["Khac_tan"].ToString(); detail = new ReportFuelDetail(); detail.EnterpriseId = report.EnterpriseId; detail.FuelId = 1; detail.MeasurementId = 1; detail.No_RateTOE = 0.0002770000m; detail.Price = 0; detail.Year = 2017; if (drow["Khac_tan"] != DBNull.Value && drow["Khac_tan"].ToString() != "") { detail.NoFuel = Convert.ToDecimal(drow["Khac_tan"]); } detail.NoFuel_TOE = detail.No_RateTOE * detail.NoFuel; detail.ReportId = reportId; detailid = serviceDetail.Insert(detail); if (detailid <= 0) { log.Info("Them khac loi"); } } if (drow["GhiChu"] != DBNull.Value && drow["GhiChu"].ToString().Trim() != "") { temp.Note = drow["GhiChu"].ToString(); } EnterpriseYearService eYService = new EnterpriseYearService(); EnterpriseYear ey = new EnterpriseYear(); ey.EnterpriseId = eId; ey.ReportId = reportId; ey.Year = 2017; ey.IsKey = true; if (drow["No_TOE"] != DBNull.Value && drow["No_TOE"].ToString().Trim() != "") { ey.No_TOE = Convert.ToDecimal(drow["No_TOE"]); } temp.No_TOE = ey.No_TOE; temp.Year = 2017; int retTemp = new ReportTemp2014Service().Insert(temp);//Them bao cao tam ey.IsDelete = false; ey.Year = temp.Year; int retempId = eYService.Insert(ey);//Them nam bao cao if (retempId <= 0) { log.Info("Them bao cao loi loi"); } } else { log.Info("Khong tao duoc bao cao"); } } } catch (Exception ex) { log.Error("Loi import du lieu dong thu i: " + rowi, ex); } } } else { lterror.Text = "Không upload được file"; } } else { lterror.Text = "Chỉ chọn file Excel đuôi .xls và .xlsx"; } } else { lterror.Text = "File không tồn tại"; } }
public AddAccessRequestController(UserService userService, FormService formService, RequestService requestService, SystemService systemService, OrganizationService orgnizationService, IAuthorizationService authService, TreeViewService treeViewService, ILogger <AddAccessRequestController> logger) : base(userService, formService, requestService, systemService, orgnizationService, authService, treeViewService, logger) { }
public static async Task <object> Handle(string organizationId, RosterRequest request) { const string baseMasterReportFileName_Page1 = "MASTER - Marine Turtle Holding Facility Quarterly Report Page 1.pdf"; const string baseMasterReportFileName_Page2 = "MASTER - Marine Turtle Holding Facility Quarterly Report Page 2.pdf"; const string baseMasterReportFileName_Page3 = "MASTER - Marine Turtle Holding Facility Quarterly Report Page 3.pdf"; const int PAGE_1_LINES_PER_PAGE = 8; const int PAGE_2_LINES_PER_PAGE = 22; const int PAGE_3_LINES_PER_PAGE = 34; var filledReportFileNames = new List <string>(); var fileTimestamp = $"{DateTime.Now:yyyyMMddHHmmss} UTC"; var basePath = AppDomain.CurrentDomain.BaseDirectory; PdfReader pdfReader; var reportOptions = JsonSerializer.Deserialize <MarineTurtleHoldingFacilityQuarterlyReportOptionsDto>(request.body.GetRawText()); reportOptions.dateFrom ??= "0000-00-00"; reportOptions.dateThru ??= "9999-99-99"; var organizationService = new OrganizationService(organizationId); var organization = await organizationService.GetOrganization(); var organizationAndPermitNumber = $"{organization.organizationName} - {organization.permitNumber}"; string monthsAndYearOfReport; var dateFrom = ReportHelper.ToDate(reportOptions.dateFrom); var dateThru = ReportHelper.ToDate(reportOptions.dateThru); if (dateFrom.Year == dateThru.Year) { monthsAndYearOfReport = $"{dateFrom:dd} {dateFrom:MMMM} - {dateThru:dd} {dateThru:MMMM} {dateThru.Year}"; } else { monthsAndYearOfReport = $"{dateFrom:dd} {dateFrom:MMMM} {dateFrom.Year} - {dateThru:dd} {dateThru:MMMM} {dateThru.Year}"; } var seaTurtleService = new SeaTurtleService(organizationId); var seaTurtles = (await seaTurtleService.GetSeaTurtles()) .Where(x => !string.IsNullOrEmpty(x.dateAcquired) && x.dateAcquired.CompareTo(reportOptions.dateThru) <= 0) .Where(x => string.IsNullOrEmpty(x.dateRelinquished) || (!string.IsNullOrEmpty(x.dateRelinquished) && reportOptions.dateFrom.CompareTo(x.dateRelinquished) <= 0)) .OrderBy(x => x.sidNumber) .ThenBy(x => x.dateAcquired) .ThenBy(x => x.seaTurtleName); var seaTurtleMapperConfiguration = new MapperConfiguration(cfg => { cfg.CreateMap <SeaTurtleModel, HoldingFacilitySeaTurtleReportItem>(); }); var seaTurtleMapper = new Mapper(seaTurtleMapperConfiguration); var seaTurtleReportItems = new List <HoldingFacilitySeaTurtleReportItem>(); foreach (var seaTurtle in seaTurtles) { //---------------------------------------------------------------- //-- kludge to account for all the data we want to cram into the //-- status/tag number line...ugh... //---------------------------------------------------------------- var reportTagNumberFieldData = await GetReportTagNumberFieldData(organizationId, seaTurtle, reportOptions); var lines = ReportHelper.WrapLine(reportTagNumberFieldData, 92); //-- add main information line for this sea turtle var item = seaTurtleMapper.Map <HoldingFacilitySeaTurtleReportItem>(seaTurtle); item.reportTagNumberFieldData = lines.Length > 0 ? lines[0] : string.Empty; seaTurtleReportItems.Add(item); //-- add any status/tag info that overflowed to additional lines for (int i = 1; i < lines.Length; i++) { seaTurtleReportItems.Add(new HoldingFacilitySeaTurtleReportItem { reportTagNumberFieldData = lines[i] }); } } var holdingTankService = new HoldingTankService(organizationId); var holdingTanks = await holdingTankService.GetHoldingTanks(); var holdingTankMeasurementReportItems = new List <HoldingFacilityHoldingTankMeasurementReportItem>(); foreach (var holdingTank in holdingTanks) { var holdingTankMeasurementMapperConfiguration = new MapperConfiguration(cfg => { cfg.CreateMap <HoldingTankMeasurementModel, HoldingFacilityHoldingTankMeasurementReportItem>() .ConstructUsing(x => new HoldingFacilityHoldingTankMeasurementReportItem(holdingTank.holdingTankName)); }); var holdingTankMeasurementMapper = new Mapper(holdingTankMeasurementMapperConfiguration); var holdingTankMeasurementService = new HoldingTankMeasurementService(organizationId, holdingTank.holdingTankId); var items = (await holdingTankMeasurementService.GetHoldingTankMeasurements()) .Where(x => reportOptions.dateFrom.CompareTo(x.dateMeasured) <= 0 && x.dateMeasured.CompareTo(reportOptions.dateThru) <= 0) .Select(x => holdingTankMeasurementMapper.Map <HoldingFacilityHoldingTankMeasurementReportItem>(x)) ; holdingTankMeasurementReportItems.AddRange(items); } if (reportOptions.groupTankDataBy == "tank") { holdingTankMeasurementReportItems = holdingTankMeasurementReportItems .OrderBy(x => x.holdingTankName) .ThenBy(x => x.dateMeasured).ToList(); } else { holdingTankMeasurementReportItems = holdingTankMeasurementReportItems .OrderBy(x => x.dateMeasured) .ThenBy(x => x.holdingTankName).ToList(); } //-- [PAGE 1] -- [PAGE 1] -- [PAGE 1] -- [PAGE 1] -- [PAGE 1] -- [PAGE 1] -- [PAGE 1] -- [PAGE 1] -- [PAGE 1] -- [PAGE 1] -- var masterReportFileName_Page1 = Path.Combine(basePath, "pdf", baseMasterReportFileName_Page1); var filledReportFileName_Page1 = Path.Combine("/tmp", baseMasterReportFileName_Page1.Replace("MASTER - ", "FILLED - ").Replace(".pdf", $" - {fileTimestamp}.pdf")); filledReportFileNames.Add(filledReportFileName_Page1); pdfReader = new PdfReader(masterReportFileName_Page1); pdfReader.RemoveUsageRights(); using (var fs = new FileStream(filledReportFileName_Page1, FileMode.Create)) { var pdfStamper = new PdfStamper(pdfReader, fs, '\0', false); var info = pdfReader.Info; info["Title"] = baseMasterReportFileName_Page1.Replace("MASTER - ", "").Replace(".pdf", $" - {fileTimestamp}.pdf"); pdfStamper.MoreInfo = info; var acroFields = pdfStamper.AcroFields; acroFields.SetField("txtOrganizationAndPermitNumber", organizationAndPermitNumber); acroFields.SetField("txtMonthsAndYearOfReport", monthsAndYearOfReport); var pageOneItems = seaTurtleReportItems.Take(PAGE_1_LINES_PER_PAGE).ToList(); for (int i = 0; i < pageOneItems.Count; i++) { var item = pageOneItems[i]; FillSectionOneRow(acroFields, (i + 1).ToString().PadLeft(2, '0'), item, reportOptions); } pdfStamper.FormFlattening = true; // 'true' to make the PDF read-only pdfStamper.Close(); } pdfReader.Close(); //-- [PAGE 2] -- [PAGE 2] -- [PAGE 2] -- [PAGE 2] -- [PAGE 2] -- [PAGE 2] -- [PAGE 2] -- [PAGE 2] -- [PAGE 2] -- [PAGE 2] -- var page2Items = seaTurtleReportItems.Skip(PAGE_1_LINES_PER_PAGE).ToList().ChunkBy(PAGE_2_LINES_PER_PAGE); for (int chunkIndex = 0; chunkIndex < page2Items.Count; chunkIndex++) { var masterReportFileName_Page2 = Path.Combine(basePath, "pdf", baseMasterReportFileName_Page2); var filledReportFileName_Page2 = Path.Combine("/tmp", baseMasterReportFileName_Page2.Replace("MASTER - ", "FILLED - ").Replace(".pdf", $" - {fileTimestamp} - {chunkIndex.ToString().PadLeft(2, '0')}.pdf")); filledReportFileNames.Add(filledReportFileName_Page2); pdfReader = new PdfReader(masterReportFileName_Page2); pdfReader.RemoveUsageRights(); using (var fs = new FileStream(filledReportFileName_Page2, FileMode.Create)) { var pdfStamper = new PdfStamper(pdfReader, fs, '\0', false); var info = pdfReader.Info; info["Title"] = baseMasterReportFileName_Page2.Replace("MASTER - ", "").Replace(".pdf", $" - {fileTimestamp}.pdf"); pdfStamper.MoreInfo = info; var acroFields = pdfStamper.AcroFields; acroFields.SetField("txtOrganizationAndPermitNumber", organizationAndPermitNumber); acroFields.SetField("txtMonthsAndYearOfReport", monthsAndYearOfReport); for (int i = 0; i < page2Items[chunkIndex].Count; i++) { var item = page2Items[chunkIndex][i]; FillSectionOneRow(acroFields, (i + 1 + PAGE_1_LINES_PER_PAGE).ToString().PadLeft(2, '0'), item, reportOptions); } pdfStamper.FormFlattening = true; // 'true' to make the PDF read-only pdfStamper.Close(); } pdfReader.Close(); } //-- [PAGE 3] -- [PAGE 3] -- [PAGE 3] -- [PAGE 3] -- [PAGE 3] -- [PAGE 3] -- [PAGE 3] -- [PAGE 3] -- [PAGE 3] -- [PAGE 3] -- var page3Items = holdingTankMeasurementReportItems.ChunkBy(PAGE_3_LINES_PER_PAGE); for (int chunkIndex = 0; chunkIndex < page3Items.Count; chunkIndex++) { var masterReportFileName_Page3 = Path.Combine(basePath, "pdf", baseMasterReportFileName_Page3); var filledReportFileName_Page3 = Path.Combine("/tmp", baseMasterReportFileName_Page3.Replace("MASTER - ", "FILLED - ").Replace(".pdf", $" - {fileTimestamp} - {chunkIndex.ToString().PadLeft(2, '0')}.pdf")); filledReportFileNames.Add(filledReportFileName_Page3); pdfReader = new PdfReader(masterReportFileName_Page3); pdfReader.RemoveUsageRights(); using (var fs = new FileStream(filledReportFileName_Page3, FileMode.Create)) { var pdfStamper = new PdfStamper(pdfReader, fs, '\0', false); var info = pdfReader.Info; info["Title"] = baseMasterReportFileName_Page3.Replace("MASTER - ", "").Replace(".pdf", $" - {fileTimestamp}.pdf"); pdfStamper.MoreInfo = info; var acroFields = pdfStamper.AcroFields; acroFields.SetField("txtOrganizationAndPermitNumber", organizationAndPermitNumber); acroFields.SetField("txtMonthsAndYearOfReport", monthsAndYearOfReport); for (int i = 0; i < page3Items[chunkIndex].Count; i++) { var item = page3Items[chunkIndex][i]; var fieldNumber = (i + 1).ToString().PadLeft(2, '0'); acroFields.SetField($"txtDate{fieldNumber}", item.dateMeasured); acroFields.SetField($"txtTank{fieldNumber}", item.holdingTankName); acroFields.SetField($"txtTemperature{fieldNumber}", item.temperature); acroFields.SetField($"txtSalinity{fieldNumber}", item.salinity); acroFields.SetField($"txtPH{fieldNumber}", item.ph); } pdfStamper.FormFlattening = true; // 'true' to make the PDF read-only pdfStamper.Close(); } pdfReader.Close(); } // ========================================================================================================================= const string masterReportFileName_Final = "MASTER - Marine Turtle Holding Facility Quarterly Report.pdf"; var filledReportFileName_Final = Path.Combine("/tmp", masterReportFileName_Final.Replace("MASTER - ", "FILLED - ").Replace(".pdf", $" - {fileTimestamp}.pdf")); ReportHelper.ConcatenatePdfFiles(filledReportFileNames, filledReportFileName_Final); var bytes = await File.ReadAllBytesAsync(filledReportFileName_Final); return(bytes); }
public string ExportSolution( string outputFolder, SolutionExportOptions options) { Logger.LogVerbose("Exporting Solution: {0}", options.SolutionName); var solutionFile = new StringBuilder(); Solution solution = GetSolution(options.SolutionName, new ColumnSet("version")); if (solution is null) { throw new Exception($"Unable to find solution with unique name: {options.SolutionName}"); } else { Logger.LogInformation($"Exporting Solution: {options.SolutionName}, version: {solution.Version}"); } solutionFile.Append(options.SolutionName); if (options.IncludeVersionInName) { solutionFile.Append("_"); solutionFile.Append(solution.Version.Replace(".", "_")); } if (options.Managed) { solutionFile.Append("_managed"); } solutionFile.Append(".zip"); var exportSolutionRequest = new ExportSolutionRequest { Managed = options.Managed, SolutionName = options.SolutionName, ExportAutoNumberingSettings = options.ExportAutoNumberingSettings, ExportCalendarSettings = options.ExportCalendarSettings, ExportCustomizationSettings = options.ExportCustomizationSettings, ExportEmailTrackingSettings = options.ExportEmailTrackingSettings, ExportGeneralSettings = options.ExportGeneralSettings, ExportIsvConfig = options.ExportIsvConfig, ExportMarketingSettings = options.ExportMarketingSettings, ExportOutlookSynchronizationSettings = options.ExportOutlookSynchronizationSettings, ExportRelationshipRoles = options.ExportRelationshipRoles, ExportSales = options.ExportSales, TargetVersion = options.TargetVersion, RequestId = Guid.NewGuid() }; Logger.LogVerbose($"RequestId: {exportSolutionRequest.RequestId}"); //keep seperate to allow compatibility with crm2015 if (options.ExportExternalApplications) { exportSolutionRequest.ExportExternalApplications = options.ExportExternalApplications; } byte[] solutionBytes; if (options.ExportAsync) { Logger.LogInformation("Exporting Solution using Async Mode"); exportSolutionRequest.RequestName = "ExportSolutionAsync"; var asyncExportResponse = OrganizationService.Execute(exportSolutionRequest); //Guid asyncJobId = asyncResponse.AsyncJobId; Guid asyncJobId = (Guid)asyncExportResponse.Results["AsyncOperationId"]; Guid exportJobId = (Guid)asyncExportResponse.Results["ExportJobId"]; Logger.LogInformation($"AsyncOperationId: {asyncJobId}"); Logger.LogInformation($"ExportJobId: {exportJobId}"); AsyncOperationManager asyncOperationManager = new AsyncOperationManager(Logger, OrganizationService); AsyncOperation operation = asyncOperationManager.AwaitCompletion(asyncJobId, options.AsyncWaitTimeout, options.SleepInterval, null); Logger.LogInformation("Async Operation completed with status: {0}", ((AsyncOperation_StatusCode)operation.StatusCode.Value).ToString()); Logger.LogInformation("Async Operation completed with message: {0}", operation.Message); if (operation.StatusCode.Value == (int)AsyncOperation_StatusCode.Succeeded) { OrganizationRequest downloadReq = new OrganizationRequest("DownloadSolutionExportData"); downloadReq.Parameters.Add("ExportJobId", exportJobId); OrganizationResponse downloadRes = OrganizationService.Execute(downloadReq); solutionBytes = (byte[])downloadRes.Results["ExportSolutionFile"]; } else { throw new Exception($"Export of solution '{options.SolutionName}' failed: {operation.Message}"); } } else { Logger.LogInformation("Exporting Solution using Sync Mode"); var exportSolutionResponse = OrganizationService.Execute(exportSolutionRequest) as ExportSolutionResponse; solutionBytes = exportSolutionResponse.ExportSolutionFile; } string solutionFilePath = Path.Combine(outputFolder, solutionFile.ToString()); File.WriteAllBytes(solutionFilePath, solutionBytes); Logger.LogInformation($"Solution Exported to: {solutionFilePath}"); Logger.LogInformation("Solution Zip Size: {0}", FileUtilities.GetFileSize(solutionFilePath)); return(solutionFilePath); }
public OrganizationController() { service = new OrganizationService(); }
static void Main(string[] args) { CrmServiceClient connection = new CrmServiceClient( ConfigurationManager.ConnectionStrings["CRMConnectionString"].ConnectionString); //构建查询信息 QueryExpression query = new QueryExpression() { EntityName = "comba_project", ColumnSet = new ColumnSet(new string[] { "comba_name", "comba_projectcode", "comba_sapprojectcode", "ownerid", "comba_projecttypesecond", "comba_account", "comba_businessunit", "comba_province", "comba_projecttype", "comba_purchasetype", "comba_crmmainproject", "comba_projectlevel" }) }; query.Criteria.AddCondition("comba_projectstatus", ConditionOperator.In, new object[] { 151220003, 151220000 }); query.Criteria.AddCondition("comba_projectcode", ConditionOperator.Equal, new object[] { "11190020 - 11" }); var crmProxy = new OrganizationService(connection); var entities = crmProxy.RetrieveMultiple(query); if (entities != null && entities.Entities.Count > 0) { var entity = entities[0]; var projectInfo = new ProjectInfo(); //使用映射 projectInfo.MapFrom(entity); var mainprojectID = entity.GetAttributeValue <EntityReference>("comba_crmmainproject").Id.ToString(); var bidrecord = GetBidrecord(mainprojectID, crmProxy); if (bidrecord != null) { projectInfo.MapFrom(bidrecord); //多个CRMEntity映射到一个DTO } projectInfo.comba_projecttype = CRMHelper.GetPicklistDisplayName(crmProxy, "comba_project", "comba_projecttype", int.Parse(projectInfo.comba_projecttype)); projectInfo.comba_purchasetype = CRMHelper.GetPicklistDisplayName(crmProxy, "comba_project", "comba_purchasetype", int.Parse(projectInfo.comba_purchasetype)); //end //不使用映射的代码 //if (entity.Contains("comba_name")) // projectInfo.comba_name = entity["comba_name"].ToString(); //if (entity.Contains("comba_projectcode")) // projectInfo.comba_projectcode = entity["comba_projectcode"].ToString(); //if (entity.Contains("comba_sapprojectcode")) // projectInfo.comba_sapprojectcode = entity["comba_sapprojectcode"].ToString(); //if (entity.Contains("comba_projecttype")) //{ // var pt = entity.GetAttributeValue<OptionSetValue>("comba_projecttype").Value; // var value = CRMHelper.GetPicklistDisplayName(crmProxy, "comba_project", "comba_projecttype", pt); // projectInfo.comba_projecttype = value; //} //if (entity.Contains("comba_purchasetype")) //{ // var pt = entity.GetAttributeValue<OptionSetValue>("comba_purchasetype").Value; // var value = CRMHelper.GetPicklistDisplayName(crmProxy, "comba_project", "comba_purchasetype", pt); // projectInfo.comba_purchasetype = value; //} //if (entity.Contains("ownerid")) //{ // var owner = entity.GetAttributeValue<EntityReference>("ownerid"); // projectInfo.ownerid = owner == null ? "" : owner.Name; //} //if (entity.Contains("comba_projecttypesecond")) //{ // var ps = entity.GetAttributeValue<EntityReference>("comba_projecttypesecond"); // projectInfo.comba_projecttypesecond = ps == null ? "" : ps.Name; //} //if (entity.Contains("comba_account")) //{ // var account = entity.GetAttributeValue<EntityReference>("comba_account"); // projectInfo.comba_account = account == null ? "" : account.Name; //} //if (entity.Contains("comba_businessunit")) //{ // var bizUnit = entity.GetAttributeValue<EntityReference>("comba_businessunit"); // projectInfo.comba_businessunit = bizUnit == null ? "" : bizUnit.Name; //} //if (entity.Contains("comba_province")) //{ // var province = entity.GetAttributeValue<EntityReference>("comba_province"); // projectInfo.comba_province = province == null ? "" : province.Name; //} //var mainprojectID = entity.GetAttributeValue<EntityReference>("comba_crmmainproject").Id.ToString(); //var bidrecord = GetBidrecord(mainprojectID); //if(bidrecord != null) //{ // if(bidrecord.Contains("comba_acceptedamount")) // projectInfo.comba_acceptedamount = bidrecord.GetAttributeValue<Money>("comba_acceptedamount").Value; // if (bidrecord.Contains("comba_acceptedamountaftertax")) // projectInfo.comba_acceptedamountaftertax = bidrecord.GetAttributeValue<Money>("comba_acceptedamountaftertax").Value; // if (bidrecord.Contains("comba_bidshare")) // projectInfo.comba_bidshare = bidrecord["comba_bidshare"].ToString(); // if (bidrecord.Contains("comba_opendate")) // projectInfo.comba_opendate = bidrecord["comba_opendate"].ToString(); //} //end } }
protected void btn_add_Click(object sender, EventArgs e) { try { EnterpriseService objlogic = new EnterpriseService(); Enterprise obj = new Enterprise(); obj.Title = txtTitle.Text; //if (ddlProvince.SelectedIndex > 0) obj.ProvinceId = Convert.ToInt32(ddlProvince.SelectedValue); if (ddlDistrict.SelectedIndex > 0) { obj.DistrictId = Convert.ToInt32(ddlDistrict.SelectedValue); } if (ddlArea.SelectedIndex > 0) { obj.AreaId = Convert.ToInt32(ddlArea.SelectedValue); } if (ddlSubArea.SelectedIndex > 0) { obj.SubAreaId = Convert.ToInt32(ddlSubArea.SelectedValue); } IFormatProvider culture = new System.Globalization.CultureInfo("en-US", true); if (txtMST.Text != "") { obj.TaxCode = txtMST.Text.Trim(); } if (txtCustomerCode.Text != "") { obj.CustomerCode = txtCustomerCode.Text.Trim(); } obj.Phone = txtPhone.Text; obj.Email = txtEmail.Text; obj.Fax = txtFax.Text; obj.ManPerson = txtResponsible.Text; obj.Address = txtAddress.Text; obj.OwnerId = Convert.ToInt32(ddlOwner.SelectedValue); obj.ParentName = txtParentName.Text; if (ddlProvinceReporter.SelectedIndex > 0) { obj.ManProvinceId = Convert.ToInt32(ddlProvinceReporter.SelectedValue); } if (ddlDistrictReporter.SelectedIndex > 0) { obj.ManDistrictId = Convert.ToInt32(ddlDistrictReporter.SelectedValue); } obj.ManAddress = txtAddressReporter.Text; obj.ManPhone = txtPhoneReporter.Text; obj.ManFax = txtFaxReporter.Text; obj.ManEmail = txtManEmail.Text; if (cbxActive.Checked) { obj.IsActive = true; } else { obj.IsActive = false; } try { if (txtAtiveYear.Text.Trim() != "") { obj.ActiveYear = Convert.ToInt32(txtAtiveYear.Text); } } catch { } obj.OrganizationId = m_UserValidation.OrgId; if (ItemId > 0) { obj.Id = ItemId; if (objlogic.Update(obj) != null) { /*Cap nhat du lieu trong diem nam hien tai*/ //if (ImportantYears != "" && !ImportantYears.Contains(DateTime.Today.ToString("yyyy")) && cbxIsImportant.Checked) //{ // EnterpriseYear ey = new EnterpriseYear(); // ey.EnterpriseId = ItemId; // ey.Year = DateTime.Today.Year; // new EnterpriseYearService().Insert(ey); //} //BindImportantYear(); BindData(); error.Text = "<div class='alert alert-primary'>Cập nhật thành công !</div>"; } else { error.Text = "<div class='alert alert-dangers'>Cập nhật không thành công !</div>"; } } else { ItemId = objlogic.Insert(obj); if (ItemId > 0) { /*Tao tai khoan mac dinh*/ Organization org = new OrganizationService().FindByKey(m_UserValidation.OrgId); if (org != null) { int noAccount = new EnterpriseService().GetNoAccount(m_UserValidation.OrgId); SecurityBSO securityBSO = new SecurityBSO(); AdminRolesBSO adminRolesBSO = new AdminRolesBSO(); Utils objUtil = new Utils(); MemberService memberService = new MemberService(); ePower.DE.Domain.Member member = new ePower.DE.Domain.Member(); member.EnterpriseId = ItemId; member.IsDelete = false; member.IsActive = true; member.AccountName = "dn." + Utils.UCS2Convert(org.Title).Replace(" ", "").Replace("-", "").ToLower() + "." + (noAccount).ToString("000"); string spassdefault = "abc123"; spassdefault = ConfigurationManager.AppSettings["DefaultPassword"].ToString(); member.Password = securityBSO.EncPwd(spassdefault); int iMember = 0; iMember = memberService.Insert(member); //if (memberService.Insert(member) > 0) //{ // BindMember(); //} //else // error.Text = "<div class='alert alert-dangers'>Tạo tài khoản không thành công !</div>"; } /*Cap nhat du lieu trong diem nam hien tai*/ //if (ImportantYears != "" && !ImportantYears.Contains(DateTime.Today.ToString("yyyy")) && cbxIsImportant.Checked) //{ // EnterpriseYear ey = new EnterpriseYear(); // ey.EnterpriseId = ItemId; // ey.Year = DateTime.Today.Year; // new EnterpriseYearService().Insert(ey); //} Response.Redirect(ResolveUrl("~") + "Admin/EditEnterprise/" + ItemId.ToString() + "/Default.aspx"); } else { error.Text = "<div class='alert alert-dangers'>Thêm mới không thành công !</div>"; } } } catch (Exception ex) { error.Text = ex.Message.ToString(); } }
public SolutionImportResult ImportSolution( string solutionFilePath, bool publishWorkflows, bool convertToManaged, bool overwriteUnmanagedCustomizations, bool skipProductUpdateDependencies, bool holdingSolution, bool overrideSameVersion, bool importAsync, int sleepInterval, int asyncWaitTimeout, Guid?importJobId, bool downloadFormattedLog, string logDirectory, string logFileName ) { Logger.LogInformation("Importing Solution: {0}", solutionFilePath); if (!importJobId.HasValue || importJobId.Value == Guid.Empty) { importJobId = Guid.NewGuid(); } Logger.LogVerbose("ImportJobId {0}", importJobId); if (asyncWaitTimeout == 0) { asyncWaitTimeout = 15 * 60; } Logger.LogVerbose("AsyncWaitTimeout: {0}", asyncWaitTimeout); if (sleepInterval == 0) { sleepInterval = 15; } Logger.LogVerbose("SleepInterval: {0}", sleepInterval); if (!File.Exists(solutionFilePath)) { Logger.LogError("Solution File does not exist: {0}", solutionFilePath); throw new FileNotFoundException("Solution File does not exist", solutionFilePath); } Logger.LogInformation("Solution Zip Size: {0}", FileUtilities.GetFileSize(solutionFilePath)); SolutionImportResult result = null; SolutionXml solutionXml = new SolutionXml(Logger); XrmSolutionInfo info = solutionXml.GetSolutionInfoFromZip(solutionFilePath); if (info == null) { result = new SolutionImportResult() { ErrorMessage = "Invalid Solution File" }; return(result); } else { Logger.LogInformation("Solution Unique Name: {0}, Version: {1}", info.UniqueName, info.Version); } bool skipImport = SkipImport(info, holdingSolution, overrideSameVersion); if (skipImport) { Logger.LogInformation("Solution Import Skipped"); result = new SolutionImportResult() { Success = true, ImportSkipped = true }; result.SolutionName = info.UniqueName; result.VersionNumber = info.Version; return(result); } if (downloadFormattedLog) { if (string.IsNullOrEmpty(logFileName)) { logFileName = $"ImportLog_{Path.GetFileNameWithoutExtension(solutionFilePath)}_{DateTime.Now.ToString("yyyy_MM_dd__HH_mm")}.xml"; Logger.LogVerbose("Setting logFileName to {0}", logFileName); } if (string.IsNullOrEmpty(logDirectory)) { logDirectory = Path.GetDirectoryName(solutionFilePath); Logger.LogVerbose("Settings logDirectory to {0}", logDirectory); } if (!Directory.Exists(logDirectory)) { Logger.LogError("logDirectory not exist: {0}", logDirectory); throw new DirectoryNotFoundException("logDirectory does not exist"); } } byte[] solutionBytes = File.ReadAllBytes(solutionFilePath); var importSolutionRequest = new ImportSolutionRequest { CustomizationFile = solutionBytes, PublishWorkflows = publishWorkflows, ConvertToManaged = convertToManaged, OverwriteUnmanagedCustomizations = overwriteUnmanagedCustomizations, SkipProductUpdateDependencies = skipProductUpdateDependencies, ImportJobId = importJobId.Value, RequestId = importJobId, HoldingSolution = holdingSolution }; if (importAsync) { Logger.LogVerbose(string.Format("Importing solution in Async Mode")); var asyncRequest = new ExecuteAsyncRequest { Request = importSolutionRequest }; var asyncResponse = OrganizationService.Execute(asyncRequest) as ExecuteAsyncResponse; Guid asyncJobId = asyncResponse.AsyncJobId; Logger.LogVerbose("Awaiting for Async Operation Completion"); AsyncUpdateHandler updateHandler = new AsyncUpdateHandler( Logger, PollingOrganizationService, importJobId.Value); AsyncOperationManager operationManager = new AsyncOperationManager(Logger, PollingOrganizationService); AsyncOperation asyncOperation = operationManager.AwaitCompletion( asyncJobId, asyncWaitTimeout, sleepInterval, updateHandler); Logger.LogInformation("Async Operation completed with status: {0}", ((AsyncOperation_StatusCode)asyncOperation.StatusCode.Value).ToString()); Logger.LogInformation("Async Operation completed with message: {0}", asyncOperation.Message); result = VerifySolutionImport(importAsync, importJobId.Value, asyncOperation, null); } else { Logger.LogVerbose("Importing solution in Sync Mode"); SyncImportHandler importHandler = new SyncImportHandler( Logger, OrganizationService, importSolutionRequest); ImportJobHandler jobHandler = new ImportJobHandler( Logger, OrganizationService, importHandler); Logger.LogVerbose("Creating Import Task"); Action importAction = () => importHandler.ImportSolution(); Task importTask = new Task(importAction); Logger.LogVerbose("Starting Import Task"); importTask.Start(); Logger.LogVerbose("Thread Started. Starting to Query Import Status"); ImportJobManager jobManager = new ImportJobManager(Logger, PollingOrganizationService); jobManager.AwaitImportJob(importJobId.Value, asyncWaitTimeout, sleepInterval, true, jobHandler); importTask.Wait(); result = VerifySolutionImport(importAsync, importJobId.Value, null, importHandler.Error); } result.SolutionName = info.UniqueName; result.VersionNumber = info.Version; if (result.ImportJobAvailable && downloadFormattedLog) { ImportJobManager jobManager = new ImportJobManager(Logger, OrganizationService); jobManager.SaveFormattedLog(importJobId.Value, logDirectory, logFileName); } if (result.Success) { Logger.LogInformation("Solution Import Completed Successfully"); } else { Logger.LogInformation("Solution Import Failed"); } return(result); }
public async Task OrgImportCreateNewUsersAndMarryExistingUser() { var orgRepo = Substitute.For <IOrganizationRepository>(); var orgUserRepo = Substitute.For <IOrganizationUserRepository>(); var collectionRepo = Substitute.For <ICollectionRepository>(); var userRepo = Substitute.For <IUserRepository>(); var groupRepo = Substitute.For <IGroupRepository>(); var dataProtector = Substitute.For <IDataProtector>(); var mailService = Substitute.For <IMailService>(); var pushNotService = Substitute.For <IPushNotificationService>(); var pushRegService = Substitute.For <IPushRegistrationService>(); var deviceRepo = Substitute.For <IDeviceRepository>(); var licenseService = Substitute.For <ILicensingService>(); var eventService = Substitute.For <IEventService>(); var installationRepo = Substitute.For <IInstallationRepository>(); var appCacheService = Substitute.For <IApplicationCacheService>(); var paymentService = Substitute.For <IPaymentService>(); var policyRepo = Substitute.For <IPolicyRepository>(); var ssoConfigRepo = Substitute.For <ISsoConfigRepository>(); var ssoUserRepo = Substitute.For <ISsoUserRepository>(); var referenceEventService = Substitute.For <IReferenceEventService>(); var globalSettings = Substitute.For <GlobalSettings>(); var taxRateRepo = Substitute.For <ITaxRateRepository>(); var orgService = new OrganizationService(orgRepo, orgUserRepo, collectionRepo, userRepo, groupRepo, dataProtector, mailService, pushNotService, pushRegService, deviceRepo, licenseService, eventService, installationRepo, appCacheService, paymentService, policyRepo, ssoConfigRepo, ssoUserRepo, referenceEventService, globalSettings, taxRateRepo); var id = Guid.NewGuid(); var userId = Guid.NewGuid(); var org = new Organization { Id = id, Name = "Test Org", UseDirectory = true, UseGroups = true, Seats = 3 }; orgRepo.GetByIdAsync(id).Returns(org); var existingUserAId = Guid.NewGuid(); var existingUsers = new List <OrganizationUserUserDetails>(); existingUsers.Add(new OrganizationUserUserDetails { Id = existingUserAId, // No external id here Email = "*****@*****.**" }); orgUserRepo.GetManyDetailsByOrganizationAsync(id).Returns(existingUsers); orgUserRepo.GetCountByOrganizationIdAsync(id).Returns(1); orgUserRepo.GetByIdAsync(existingUserAId).Returns(new OrganizationUser { Id = existingUserAId }); var newUsers = new List <Models.Business.ImportedOrganizationUser>(); newUsers.Add(new Models.Business.ImportedOrganizationUser { Email = "*****@*****.**", ExternalId = "a" }); newUsers.Add(new Models.Business.ImportedOrganizationUser { Email = "*****@*****.**", ExternalId = "b" }); newUsers.Add(new Models.Business.ImportedOrganizationUser { Email = "*****@*****.**", ExternalId = "c" }); await orgService.ImportAsync(id, userId, null, newUsers, null, false); await orgUserRepo.Received(1).UpsertAsync(Arg.Any <OrganizationUser>()); await orgUserRepo.Received(2).CreateAsync(Arg.Any <OrganizationUser>()); }
static void execute(OrganizationService service, OrganizationServiceProxy _serviceProxy) { int queryCount = 50; int pageNumber = 1; QueryExpression pagequery = new QueryExpression(); pagequery.EntityName = "lead"; pagequery.ColumnSet = new ColumnSet(true); //retrieves all columns pagequery.Criteria = new FilterExpression(); pagequery.Criteria.FilterOperator = LogicalOperator.And; pagequery.Criteria.AddCondition("relatedobjectid", ConditionOperator.NotNull); //pagequery.Criteria.AddCondition("firstname",ConditionOperator.Equal,"LogicApp8"); pagequery.PageInfo = new PagingInfo(); pagequery.PageInfo.Count = queryCount; pagequery.PageInfo.PageNumber = pageNumber; pagequery.PageInfo.PagingCookie = null; int i = 0; int step = 0; while (true) { try { step = 1; Console.WriteLine("Retrieving Page {0}", pagequery.PageInfo.PageNumber); EntityCollection results = service.RetrieveMultiple(pagequery); step = 2; if (results.Entities.Count > 0) { foreach (Entity leadEntity in results.Entities) { try { step = 3; Entity campaignResponse = service.Retrieve("campaignresponse", ((EntityReference)leadEntity.Attributes["relatedobjectid"]).Id, new ColumnSet(true)); Entity updateCR = new Entity { LogicalName = "campaignresponse", Id = ((EntityReference)leadEntity.Attributes["relatedobjectid"]).Id }; updateCR["fdx_sourcecampaignresponse"] = true; updateCR["fdx_reconversionlead"] = new EntityReference("lead", leadEntity.Id); step = 4; service.Update(updateCR); } catch (Exception ex) { Console.WriteLine(string.Format("error at step {0} - {1}", step, ex.ToString())); } } } if (results.MoreRecords) { pagequery.PageInfo.PageNumber++; pagequery.PageInfo.PagingCookie = results.PagingCookie; } else { //If no more records are in the result nodes, exit the loop. break; } } catch (Exception ex) { Console.WriteLine(string.Format("error at step {0} - {1}", step, ex.ToString())); } } Console.WriteLine("Total records created: {0}", i); }
static void Main(string[] args) { Console.WriteLine("Enter the source connection string: "); sourceOrg = Console.ReadLine(); try { sourceConn = CrmConnection.Parse(sourceOrg); } catch (Exception ex) { Console.WriteLine("Could not parse source connection string: {0}", ex.Message); return; } Console.WriteLine("Enter the destination connection string: "); targetOrg = Console.ReadLine(); try { targetConn = CrmConnection.Parse(targetOrg); } catch (Exception ex) { Console.WriteLine("Could not parse destination connection string: {0}", ex.Message); return; } //export teamtemplates using (OrganizationService service = new OrganizationService(sourceConn)) { try { //attributes to exclude from the query List <string> IgnoredAttributes = new List <string> { "issystem" }; Console.WriteLine("Retrieving entity metadata . . ."); RetrieveEntityRequest entityreq = new RetrieveEntityRequest { LogicalName = "teamtemplate", EntityFilters = Microsoft.Xrm.Sdk.Metadata.EntityFilters.Attributes }; RetrieveEntityResponse entityres = (RetrieveEntityResponse)service.Execute(entityreq); string fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>"; fetchXml += "<entity name='teamtemplate'>"; foreach (AttributeMetadata amd in entityres.EntityMetadata.Attributes) { if (!IgnoredAttributes.Contains(amd.LogicalName)) { fetchXml += "<attribute name='" + amd.LogicalName + "' />"; //Console.WriteLine(amd.LogicalName); } } fetchXml += "</entity></fetch>"; Console.WriteLine(""); Console.WriteLine("Exporting data . . ."); exported = service.RetrieveMultiple(new FetchExpression(fetchXml)); } catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex) { Console.WriteLine("Could not export data: {0}", ex.Message); return; } } //import teamtemplates Console.WriteLine("Importing data . . ."); using (OrganizationService service = new OrganizationService(targetConn)) { if (exported.Entities.Count > 0) { foreach (Entity entity in exported.Entities) { try { //Console.WriteLine("Id - {0}", entity.Id.ToString()); //try to update first try { service.Update(entity); } catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { //if update fails, then create service.Create(entity); } } catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex) { //if everything fails, return error Console.WriteLine("Error: {0} - {1}", entity.Id, entity["teamtemplatename"]); } } } } Console.WriteLine("Import complete"); Console.WriteLine(""); Console.WriteLine("Press the enter key to exit"); Console.ReadLine(); }
protected void btnImportTemp_Click(object sender, EventArgs e) { DataTable dt = new DataTable(); string connectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", Server.MapPath("~/UserFile/Data_2016.xls")); //string query = String.Format("select * from [{0}$]", "Area"); string query = String.Format("select * from [{0}$]", "Nam_2016"); SecurityBSO securityBSO = new SecurityBSO(); OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString); DataSet dataSet = new DataSet(); dataAdapter.Fill(dataSet); DataTable myTable = dataSet.Tables[0]; EnterpriseService comBSO = new EnterpriseService(); foreach (DataRow drow in myTable.Rows) { ReportTemp2014 temp = new ReportTemp2014(); Enterprise area = new Enterprise(); area.Title = drow["Title"].ToString(); temp.Title = area.Title; if (drow["Address"] != null) { area.Address = drow["Address"].ToString(); temp.Address = area.Address; } area.OrganizationId = Convert.ToInt32(drow["OrgId"]); temp.OrgId = area.OrganizationId; Organization org = new OrganizationService().FindByKey(area.OrganizationId); if (drow["AreaName"] != null && drow["AreaName"].ToString() != "") { temp.AreaName = drow["AreaName"].ToString(); if (drow["AreaName"].ToString() == "Công nghiệp") { area.AreaId = 5; } else if (drow["AreaName"].ToString() == "Nông nghiệp") { area.AreaId = 3; } else if (drow["AreaName"].ToString() == "Công trình xây dựng") { area.AreaId = 6; } else { area.AreaId = 1; } temp.AreaId = area.AreaId; } if (drow["SubAreaName"] != null && drow["SubAreaName"].ToString() != "") { DataTable dtSub = new AreaService().getAreaByName(drow["SubAreaName"].ToString()); if (dtSub != null && dtSub.Rows.Count > 0) { area.SubAreaId = Convert.ToInt32(dtSub.Rows[0]["Id"]); temp.SubAreaId = area.SubAreaId; } else { Area sub = new Area(); sub.AreaName = drow["SubAreaName"].ToString(); sub.ParentId = area.AreaId; sub.IsStatus = 1; sub.SortOrder = 0; int subId = new AreaService().Insert(sub); temp.SubAreaId = subId; area.SubAreaId = subId; } area.Info = drow["SubAreaName"].ToString(); temp.SubAreaName = drow["SubAreaName"].ToString(); } area.ProvinceId = Convert.ToInt32(drow["ProvinceId"]); area.ManProvinceId = Convert.ToInt32(drow["ManProvinceId"]); int eId = comBSO.Insert(area);//Them doanh nghiep if (eId > 0) { temp.EnterpriseId = eId; if (drow["Dien_kWh"] != null && drow["Dien_kWh"].ToString().Trim() != "") { temp.Dien_kWh = drow["Dien_kWh"].ToString(); } if (drow["Than_Tan"] != null && drow["Than_Tan"].ToString().Trim() != "") { temp.Than_Tan = drow["Than_Tan"].ToString(); } if (drow["DO_Tan"] != null && drow["DO_Tan"].ToString().Trim() != "") { temp.DO_Tan = drow["DO_Tan"].ToString(); } if (drow["DO_lit"] != null && drow["DO_lit"].ToString().Trim() != "") { temp.DO_lit = drow["DO_lit"].ToString(); } if (drow["FO_Tan"] != null && drow["FO_Tan"].ToString().Trim() != "") { temp.FO_Tan = drow["FO_Tan"].ToString(); } if (drow["FO_lit"] != null && drow["FO_lit"].ToString().Trim() != "") { temp.FO_lit = drow["FO_Tan"].ToString(); } if (drow["Xang_Tan"] != null && drow["Xang_Tan"].ToString().Trim() != "") { temp.Xang_Tan = drow["Xang_Tan"].ToString(); } if (drow["Xang_lit"] != null && drow["Xang_lit"].ToString().Trim() != "") { temp.Xang_lit = drow["Xang_lit"].ToString(); } if (drow["Gas_Tan"] != null && drow["Gas_Tan"].ToString().Trim() != "") { temp.Gas_Tan = drow["Gas_Tan"].ToString(); } if (drow["Khi_m3"] != null && drow["Khi_m3"].ToString().Trim() != "") { temp.Khi_M3 = drow["Khi_m3"].ToString(); } if (drow["LPG_Tan"] != null && drow["LPG_Tan"].ToString().Trim() != "") { temp.LPG_Tan = drow["LPG_Tan"].ToString(); } if (drow["NLPL_Tan"] != null && drow["NLPL_Tan"].ToString().Trim() != "") { temp.NLPL_Tan = drow["NLPL_Tan"].ToString(); } if (drow["Khac_tan"] != null && drow["Khac_tan"].ToString().Trim() != "") { temp.KhacSoDo = drow["Khac_tan"].ToString(); } if (drow["Note"] != null && drow["Note"].ToString().Trim() != "") { temp.Note = drow["Note"].ToString(); } EnterpriseYearService eYService = new EnterpriseYearService(); EnterpriseYear ey = new EnterpriseYear(); ey.EnterpriseId = eId; if (drow["No_TOE"] != null && drow["No_TOE"].ToString().Trim() != "" && Convert.ToDecimal(drow["No_TOE"]) > 0) { ey.No_TOE = Convert.ToDecimal(drow["No_TOE"]); temp.No_TOE = ey.No_TOE; temp.Year = 2016; int retTemp = new ReportTemp2014Service().Insert(temp);//Them bao cao tam ey.IsDelete = false; ey.Year = temp.Year; eYService.Insert(ey);//Them nam bao cao } //Tao tai khoan doanh nghiep Utils objUtil = new Utils(); MemberService memberService = new MemberService(); int STT = 0; STT = new EnterpriseService().GetNoAccount(area.OrganizationId); STT++; ePower.DE.Domain.Member member = new ePower.DE.Domain.Member(); member.EnterpriseId = eId; member.IsDelete = false; member.AccountName = "dn." + Utils.UCS2Convert(org.Title).Replace(" ", "").Replace("-", "").ToLower() + "." + STT.ToString("000"); member.Password = securityBSO.EncPwd("123456"); memberService.Insert(member); } } }
public void Test_ContactImport() { CrmConnection crmConnection = (CrmConnection)connection.GetConnection(); IOrganizationService service = new OrganizationService(crmConnection); string accountName1 = Guid.NewGuid().ToString(); Entity account = new Entity("account"); account.Attributes.Add("name", accountName1); Guid account1 = service.Create(account); IntegrationTool.Module.WriteToDynamicsCrm.WriteToDynamicsCrmConfiguration writeToCrmConfig = new IntegrationTool.Module.WriteToDynamicsCrm.WriteToDynamicsCrmConfiguration(); writeToCrmConfig.EntityName = "contact"; writeToCrmConfig.PrimaryKeyAttributes.Add("new_id"); writeToCrmConfig.ImportMode = Module.WriteToDynamicsCrm.SDK.Enums.ImportMode.All; writeToCrmConfig.MultipleFoundMode = Module.WriteToDynamicsCrm.SDK.Enums.MultipleFoundMode.All; writeToCrmConfig.Mapping.Add(new IntegrationTool.DataMappingControl.DataMapping() { Source = "ID", Target = "new_id" }); writeToCrmConfig.Mapping.Add(new IntegrationTool.DataMappingControl.DataMapping() { Source = "FirstName", Target = "firstname" }); writeToCrmConfig.Mapping.Add(new IntegrationTool.DataMappingControl.DataMapping() { Source = "LastName", Target = "lastname" }); writeToCrmConfig.Mapping.Add(new IntegrationTool.DataMappingControl.DataMapping() { Source = "Status", Target = "statuscode" }); writeToCrmConfig.Mapping.Add(new IntegrationTool.DataMappingControl.DataMapping() { Source = "Birthdate", Target = "birthdate" }); writeToCrmConfig.RelationMapping.Add(new Module.WriteToDynamicsCrm.SDK.RelationMapping() { EntityName = "account", LogicalName = "parentcustomerid", Mapping = new List <DataMappingControl.DataMapping>() { new DataMappingControl.DataMapping() { Source = "CompanyName", Target = "name" } } }); writeToCrmConfig.ConfigurationId = Guid.NewGuid(); writeToCrmConfig.SelectedConnectionConfigurationId = Test_Helpers.CRMCONNECTIONID; writeToCrmConfig.PicklistMapping.Add(new Module.WriteToDynamicsCrm.SDK.PicklistMapping() { LogicalName = "statuscode", MappingType = Module.WriteToDynamicsCrm.SDK.Enums.PicklistMappingType.Manual, Mapping = new List <DataMappingControl.DataMapping>() { new DataMappingControl.DataMapping() { Source = "Active", Target = "1" }, new DataMappingControl.DataMapping() { Source = "Inactive", Target = "2" } } }); IDatastore dataObject = DataStoreFactory.GetDatastore(); dataObject.AddColumn(new ColumnMetadata("FirstName")); dataObject.AddColumn(new ColumnMetadata("LastName")); dataObject.AddColumn(new ColumnMetadata("City")); dataObject.AddColumn(new ColumnMetadata("ID")); dataObject.AddColumn(new ColumnMetadata("CompanyName")); dataObject.AddColumn(new ColumnMetadata("Status")); dataObject.AddColumn(new ColumnMetadata("Birthdate")); dataObject.AddData(new object[] { "Peter", "Widmer", "Wettingen", 1001, accountName1, "Active", new DateTime(1980, 06, 23) }); dataObject.AddData(new object[] { "Joachim 2", "Suter", "Dättwil", 1002, accountName1, "Inactive", new DateTime(2004, 12, 03) }); dataObject.AddData(new object[] { "James", "Brown", "London", 1003, null, "Active", null }); // Doublekey to test it works too dataObject.AddData(new object[] { "Peter", "Widmer", "Wettingen", 1001, accountName1, "Active", new DateTime(1980, 06, 23) }); IModule module = Activator.CreateInstance(typeof(WriteToDynamicsCrm)) as IModule; module.SetConfiguration(writeToCrmConfig); ((IDataTarget)module).WriteData(connection, new DummyDatabaseInterface(), dataObject, Test_Helpers.ReportProgressMethod); service.Delete("account", account1); }
protected override void ProcessRecord() { base.ProcessRecord(); base.WriteVerbose("Executing CloneAsPatchRequest"); using (var context = new CIContext(OrganizationService)) { base.WriteVerbose("VersionNumber not supplied. Generating default VersionNumber"); if (string.IsNullOrEmpty(VersionNumber)) { var solution = (from sol in context.SolutionSet where sol.UniqueName == ParentSolutionUniqueName || sol.UniqueName.StartsWith(ParentSolutionUniqueName + "_Patch") orderby sol.Version descending select new Solution { Version = sol.Version, FriendlyName = sol.FriendlyName }).FirstOrDefault(); if (solution == null || string.IsNullOrEmpty(solution.Version)) { throw new Exception(string.Format("Parent solution with unique name {0} not found.", ParentSolutionUniqueName)); } string[] versions = solution.Version.Split('.'); char dot = '.'; VersionNumber = string.Concat(versions[0], dot, versions[1], dot, Convert.ToInt32(versions[2]) + 1, dot, 0); base.WriteVerbose(string.Format("New VersionNumber: {0}", VersionNumber)); } if (string.IsNullOrEmpty(DisplayName)) { var solution = (from sol in context.SolutionSet where sol.UniqueName == ParentSolutionUniqueName select new Solution { FriendlyName = sol.FriendlyName }).FirstOrDefault(); base.WriteVerbose((solution == null).ToString()); base.WriteVerbose(solution.FriendlyName); if (solution == null || string.IsNullOrEmpty(solution.FriendlyName)) { throw new Exception(string.Format("Parent solution with unique name {0} not found.", ParentSolutionUniqueName)); } DisplayName = solution.FriendlyName; } var cloneAsPatch = new CloneAsPatchRequest { DisplayName = DisplayName, ParentSolutionUniqueName = ParentSolutionUniqueName, VersionNumber = VersionNumber, }; CloneAsPatchResponse response = OrganizationService.Execute(cloneAsPatch) as CloneAsPatchResponse; base.WriteVerbose(string.Format("Patch solution created with Id {0}", response.SolutionId)); base.WriteVerbose("Retrieving Patch Name"); var patch = (from sol in context.SolutionSet where sol.Id == response.SolutionId select new Solution { UniqueName = sol.UniqueName }).FirstOrDefault(); if (patch == null || string.IsNullOrEmpty(patch.UniqueName)) { throw new Exception(string.Format("Solution with Id {0} not found.", response.SolutionId)); } base.WriteVerbose(string.Format("Patch solution name: {0}", patch.UniqueName)); base.WriteObject(patch.UniqueName); } base.WriteVerbose("Completed CloneAsPatchRequest"); }
public OrganizationController(OrganizationService OrganizationService) { _OrganizationService = OrganizationService; }
protected override void ProcessRecord() { base.ProcessRecord(); base.WriteVerbose(string.Format("Exporting Solution: {0}", UniqueSolutionName)); var solutionFile = new StringBuilder(); Solution solution; using (var context = new CIContext(OrganizationService)) { var query = from s in context.SolutionSet where s.UniqueName == UniqueSolutionName select s; solution = query.FirstOrDefault(); } if (solution == null) { throw new Exception(string.Format("Solution {0} could not be found", UniqueSolutionName)); } solutionFile.Append(UniqueSolutionName); if (IncludeVersionInName) { solutionFile.Append("_"); solutionFile.Append(solution.Version.Replace(".", "_")); } if (Managed) { solutionFile.Append("_managed"); } solutionFile.Append(".zip"); var exportSolutionRequest = new ExportSolutionRequest { Managed = Managed, SolutionName = UniqueSolutionName, ExportAutoNumberingSettings = ExportAutoNumberingSettings, ExportCalendarSettings = ExportCalendarSettings, ExportCustomizationSettings = ExportCustomizationSettings, ExportEmailTrackingSettings = ExportEmailTrackingSettings, ExportGeneralSettings = ExportGeneralSettings, ExportIsvConfig = ExportIsvConfig, ExportMarketingSettings = ExportMarketingSettings, ExportOutlookSynchronizationSettings = ExportOutlookSynchronizationSettings, ExportRelationshipRoles = ExportRelationshipRoles, ExportSales = ExportSales, TargetVersion = TargetVersion, ExportExternalApplications = ExportExternalApplications }; var exportSolutionResponse = OrganizationService.Execute(exportSolutionRequest) as ExportSolutionResponse; string solutionFilePath = Path.Combine(OutputFolder, solutionFile.ToString()); File.WriteAllBytes(solutionFilePath, exportSolutionResponse.ExportSolutionFile); base.WriteObject(solutionFile.ToString()); }
private bool UpdateCrmAssembly(AssemblyItem assemblyItem, CrmServiceClient connection) { _dte.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationDeploy); try { string outputFileName = ConnPane.SelectedProject.Properties.Item("OutputFileName").Value.ToString(); string path = GetOutputPath() + outputFileName; //Build the project SolutionBuild solutionBuild = _dte.Solution.SolutionBuild; solutionBuild.BuildProject(_dte.Solution.SolutionBuild.ActiveConfiguration.Name, ConnPane.SelectedProject.UniqueName, true); if (solutionBuild.LastBuildInfo > 0) { return(false); } //Make sure Major and Minor versions match Version assemblyVersion = Version.Parse(ConnPane.SelectedProject.Properties.Item("AssemblyVersion").Value.ToString()); if (assemblyItem.Version.Major != assemblyVersion.Major || assemblyItem.Version.Minor != assemblyVersion.Minor) { _logger.WriteToOutputWindow("Error Updating Assembly In CRM: Changes To Major & Minor Versions Require Redeployment", Logger.MessageType.Error); return(false); } //Make sure assembly names match string assemblyName = ConnPane.SelectedProject.Properties.Item("AssemblyName").Value.ToString(); if (assemblyName.ToUpper() != assemblyItem.Name.ToUpper()) { _logger.WriteToOutputWindow("Error Updating Assembly In CRM: Changes To Assembly Name Require Redeployment", Logger.MessageType.Error); return(false); } //Update CRM using (OrganizationService orgService = new OrganizationService(connection)) { Entity crmAssembly = new Entity("pluginassembly") { Id = assemblyItem.AssemblyId }; crmAssembly["content"] = Convert.ToBase64String(File.ReadAllBytes(path)); orgService.Update(crmAssembly); } //Update assembly name and version numbers assemblyItem.Version = assemblyVersion; assemblyItem.Name = ConnPane.SelectedProject.Properties.Item("AssemblyName").Value.ToString(); assemblyItem.DisplayName = assemblyItem.Name + " (" + assemblyVersion + ")"; assemblyItem.DisplayName += (assemblyItem.IsWorkflowActivity) ? " [Workflow]" : " [Plug-in]"; return(true); } catch (FaultException <OrganizationServiceFault> crmEx) { _logger.WriteToOutputWindow("Error Updating Assembly In CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error); return(false); } catch (Exception ex) { _logger.WriteToOutputWindow("Error Updating Assembly In CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error); return(false); } finally { _dte.StatusBar.Clear(); _dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy); } }
public OrganizationController(OrganizationService service) { _service = service; }
public SolutionApplyResult ApplySolution( string solutionName, bool importAsync, int sleepInterval, int asyncWaitTimeout ) { Logger.LogVerbose("Upgrading Solution: {0}", solutionName); if (SkipUpgrade(solutionName)) { return(new SolutionApplyResult() { Success = true, ApplySkipped = true }); } Exception syncApplyException = null; AsyncOperation asyncOperation = null; var upgradeSolutionRequest = new DeleteAndPromoteRequest { UniqueName = solutionName }; if (importAsync) { var asyncRequest = new ExecuteAsyncRequest { Request = upgradeSolutionRequest }; Logger.LogVerbose("Applying using Async Mode"); var asyncResponse = OrganizationService.Execute(asyncRequest) as ExecuteAsyncResponse; Guid asyncJobId = asyncResponse.AsyncJobId; Logger.LogInformation(string.Format("Async JobId: {0}", asyncJobId)); Logger.LogVerbose("Awaiting for Async Operation Completion"); AsyncOperationManager asyncOperationManager = new AsyncOperationManager( Logger, PollingOrganizationService); asyncOperation = asyncOperationManager.AwaitCompletion( asyncJobId, asyncWaitTimeout, sleepInterval, null); Logger.LogInformation("Async Operation completed with status: {0}", ((AsyncOperation_StatusCode)asyncOperation.StatusCode.Value).ToString()); Logger.LogInformation("Async Operation completed with message: {0}", asyncOperation.Message); } else { try { OrganizationService.Execute(upgradeSolutionRequest); } catch (Exception ex) { syncApplyException = ex; } } SolutionApplyResult result = VerifyUpgrade( solutionName, asyncOperation, syncApplyException); if (result.Success) { Logger.LogInformation("Solution Apply Completed Successfully"); } else { Logger.LogInformation("Solution Apply Failed"); } return(result); }
public ReportController(ReportService report, OrganizationService organization) { _reportService = report; _orgService = organization; }
public Solution CreatePatch(string uniqueName, string versionNumber, string displayName) { using (var context = new CIContext(OrganizationService)) { if (string.IsNullOrEmpty(versionNumber)) { Logger.LogVerbose("VersionNumber not supplied. Generating default VersionNumber"); var solution = (from sol in context.SolutionSet where sol.UniqueName == uniqueName || sol.UniqueName.StartsWith(uniqueName + "_Patch") orderby sol.Version descending select new Solution { Version = sol.Version, FriendlyName = sol.FriendlyName }).FirstOrDefault(); if (solution == null || string.IsNullOrEmpty(solution.Version)) { throw new Exception(string.Format("Parent solution with unique name {0} not found.", uniqueName)); } string[] versions = solution.Version.Split('.'); char dot = '.'; versionNumber = string.Concat(versions[0], dot, versions[1], dot, Convert.ToInt32(versions[2]) + 1, dot, 0); Logger.LogVerbose("New VersionNumber: {0}", versionNumber); } if (string.IsNullOrEmpty(displayName)) { Logger.LogVerbose("displayName not supplied. Generating default DisplayName"); var solution = (from sol in context.SolutionSet where sol.UniqueName == uniqueName select new Solution { FriendlyName = sol.FriendlyName }).FirstOrDefault(); if (solution == null || string.IsNullOrEmpty(solution.FriendlyName)) { throw new Exception(string.Format("Parent solution with unique name {0} not found.", uniqueName)); } displayName = solution.FriendlyName; } var cloneAsPatch = new CloneAsPatchRequest { DisplayName = displayName, ParentSolutionUniqueName = uniqueName, VersionNumber = versionNumber, }; CloneAsPatchResponse response = OrganizationService.Execute(cloneAsPatch) as CloneAsPatchResponse; Logger.LogInformation("Patch solution created with Id {0}", response.SolutionId); Solution patch = GetSolution(response.SolutionId, new ColumnSet(true)); Logger.LogInformation("Patch solution name: {0}", patch.UniqueName); return(patch); } }
public AuthController(ILoggerFactory loggerFactory, IUserRepository userRepository, IOrganizationRepository orgRepository, ITemplatedMailService mailer, ITokenRepository tokenRepository, OrganizationService organizationService) { _logger = loggerFactory?.CreateLogger <AuthController>() ?? NullLogger.Instance; _userRepository = userRepository; _organizationRepository = orgRepository; _mailer = mailer; _tokenRepository = tokenRepository; _organizationService = organizationService; }
public OrganizationServiceTests() { _repositoryMock = new Mock <IRepository <Organization> >(); _organizationService = new OrganizationService(_repositoryMock.Object); }