Inheritance: UnityEngine.ScriptableObject
Ejemplo n.º 1
0
        public void queryObjects()
        {
            ClientInfoHeader clientHeaderInfo = new ClientInfoHeader();
            clientHeaderInfo.AppID = "Chandu test query objects";
             string queryString = "SELECT O.Opportunities FROM Organization O WHERE O.ID = 1;";
               // string queryString = "Select * from contact";

            Opportunity opportunity = new Opportunity();

            RNObject[] objectTemplates = new RNObject[] { opportunity };

            try
            {
                QueryResultData[] queryObjects = _client.QueryObjects(clientHeaderInfo, queryString, objectTemplates, 10000);
                RNObject[] rnObjects = queryObjects[0].RNObjectsResult;

                foreach (RNObject obj in rnObjects)
                {
                    Opportunity Opportunity = (Opportunity)obj;
                    Console.WriteLine("Opportunity of the organization is - " + Opportunity.Name);
                }

            }
            catch (System.ServiceModel.FaultException ex)
            {
                Console.WriteLine(ex.Code);
                Console.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 2
0
        protected static bool IsAvailable(Opportunity ths, Sim s, ref string msg)
        {
            msg += Common.NewLine + ths.Guid;

            if (s == null)
            {
                msg += Common.NewLine + " Failure: C";
                return false;
            }
            if (!s.OpportunityManager.CheckRepeatOpportunity(ths.RepeatLevel, ths.Guid))
            {
                msg += Common.NewLine + " Failure: D";
                return false;
            }
            if (ths.IsChildOfOrEqualTo(s.OpportunityManager.GetLastOpportunity(ths.OpportunityCategory)) && !s.SimDescription.OpportunityHistory.HasCurrentOpportunity(ths.OpportunityCategory, ths.Guid))
            {
                msg += Common.NewLine + " Failure: E";
                return false;
            }
            if (!CheckAllRequirements(s, ths, OpportunityNames.Undefined, ref msg))
            {
                return false;
            }
            if (ths.mSharedData.mRequirementDelegate != null)
            {
                if (!ths.mSharedData.mRequirementDelegate(s, ths))
                {
                    msg += Common.NewLine + " Failure: F";
                }
            }
            return true;
        }
Ejemplo n.º 3
0
        public JsonResult ApplyDiscount(Opportunity opportunity, Guid voucherId)
        {
            var httpClient = GetHttpClient();
            var success    = OpportunityService.UpdateOpportunity(httpClient, opportunity);

            VoucherService.SetVoucherState(GetService(), voucherId);
            return(Json(success, JsonRequestBehavior.AllowGet));
        }
Ejemplo n.º 4
0
 public ActionResult Delete(Opportunity opportunity)
 {
     if (!_opportunityService.DeleteOpportunity(opportunity))
     {
         return(View(opportunity));
     }
     return(RedirectToAction("Index"));
 }
Ejemplo n.º 5
0
        public Opportunity Update(Opportunity opportunityToUpdate)
        {
            var originalOpportunity = Get(opportunityToUpdate.Id);

            _entities.ApplyCurrentValues(originalOpportunity.EntityKey.EntitySetName, opportunityToUpdate);
            _entities.SaveChanges();
            return(opportunityToUpdate);
        }
Ejemplo n.º 6
0
        public ActionResult DeleteOpportunityConfirm(string Name)
        {
            Opportunity opportunity = db.Opportunities.Find(Name);

            db.Opportunities.Remove(opportunity);
            db.SaveChanges();
            return(RedirectToAction("ManageOp", "Home"));
        }
Ejemplo n.º 7
0
        public OpportunityViewModel(Opportunity opportunity)
        {
            //creating the elements for opportunity status drop down list
            var statuses = Enum.GetNames(typeof(OpportunityStatus));

            Opportunity = opportunity;
            Statuses    = new SelectList(statuses, Opportunity.Status);
        }
Ejemplo n.º 8
0
 public async Task <bool> ValidateSaleStage(Opportunity Opportunity)
 {
     if (Opportunity.SaleStageId == Enums.SaleStageEnum.CLOSED.Id && !Opportunity.PotentialResultId.HasValue)
     {
         Opportunity.AddError(nameof(OpportunityValidator), nameof(Opportunity.PotentialResult), ErrorCode.PotentialResultEmpty);
     }
     return(Opportunity.IsValidated);
 }
 public void MapProperties(OpportunityDto dto, Opportunity target)
 {
     //Mapper.Map<OpportunityDto, Opportunity>(dto, target);
     //Or manually :
     target.Title     = dto.Title;
     target.Location  = dto.Location;
     target.StartDate = dto.StartDate;
 }
Ejemplo n.º 10
0
        public ProxyOpportunity GetOneOpportunity(Guid id)
        {
            //var xrm = new XrmServiceContext("Xrm");
            //return
            Opportunity orig = this.xrm.OpportunitySet.Where(c => c.Id == id).FirstOrDefault();

            return(ObjectConverter.ConvertToReadableOpportunity(orig, this.xrm));
        }
Ejemplo n.º 11
0
 public async Task <bool> ValidateProbability(Opportunity Opportunity)
 {
     if (Opportunity.Probability == null)
     {
         Opportunity.AddError(nameof(OpportunityValidator), nameof(Opportunity.Probability), ErrorCode.ProbabilityEmpty);
     }
     return(Opportunity.IsValidated);
 }
Ejemplo n.º 12
0
        public Opportunity Update(Opportunity Opportunity)
        {
            var OpportunityIndex = _Opportunitys.FindIndex(l => l.id == Opportunity.id);

            _Opportunitys.RemoveAt(OpportunityIndex);
            _Opportunitys.Insert(OpportunityIndex, Opportunity);
            return(Opportunity);
        }
Ejemplo n.º 13
0
        public async Task <StatusCodes> CallAddInWebhookAsync(Opportunity opportunity, string requestId = "")
        {
            var client = await proposalManagerClientFactory.GetProposalManagerClientAsync();

            var result = await client.PostAsync("/api/dynamics/LinkSharePointLocations", new StringContent(JsonConvert.SerializeObject(await opportunityHelpers.OpportunityToViewModelAsync(opportunity, requestId)), Encoding.UTF8, "application/json"));

            return(result.IsSuccessStatusCode ? StatusCodes.Status200OK : StatusCodes.Status400BadRequest);
        }
Ejemplo n.º 14
0
        public ActionResult DeleteConfirmed(int id)
        {
            Opportunity opportunity = db.OpportunitySet.Find(id);

            db.OpportunitySet.Remove(opportunity);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Ejemplo n.º 15
0
        public async Task <Opportunity> Create(Opportunity opportunity, IUser user)
        {
            var newOpportunity = await base.CreateAsync <Opportunity>(opportunity, user);

            await base.CommitAsync();

            return(newOpportunity);
        }
Ejemplo n.º 16
0
        public ActionResult EditOpportunity(int oppID)
        {
            Opportunity toBeChanged = _opportunityRepository.GetOpportunity(oppID);

            ViewData.Model = toBeChanged;

            return(View());
        }
        public async Task <Opportunity> CreateWorkflowAsync(Opportunity opportunity, string requestId = "")
        {
            _logger.LogInformation($"RequestId: {requestId} - CreateDashBoardEntryAsync called.");
            try
            {
                var targetDate = opportunity.Metadata.Fields.ToList().Find(x => x.DisplayName.Equals("Target Date", StringComparison.OrdinalIgnoreCase))?.Values;
                var openedDate = opportunity.Metadata.Fields.ToList().Find(x => x.DisplayName.Equals("Opened Date", StringComparison.OrdinalIgnoreCase))?.Values;

                if (targetDate != null && openedDate != null)
                {
                    var entity = new Dashboard();
                    entity.CustomerName    = opportunity.Metadata.Customer.DisplayName;
                    entity.Status          = opportunity.Metadata.OpportunityState.Name;
                    entity.StartDate       = openedDate ?? String.Empty;
                    entity.OpportunityName = opportunity.DisplayName;
                    entity.OpportunityId   = opportunity.Id;
                    entity.Id                      = String.Empty;
                    entity.TotalNoOfDays           = 0;
                    entity.ProcessList             = new List <DashboardProcessList>();
                    entity.ProcessEndDateList      = new List <DashboradProcessEndDateList>();
                    entity.ProcessLoanOfficerNames = new List <DashboardLoanOfficers>();

                    var processList = (await _processRepository.GetAllAsync(requestId)).ToList().Where(x => x.ProcessType.Equals("checklisttab", StringComparison.OrdinalIgnoreCase));

                    foreach (var process in processList)
                    {
                        entity.ProcessList.Add(new DashboardProcessList
                        {
                            ProcessName      = process.Channel.ToLower(),
                            ProcessEndDate   = string.Empty,
                            ProcessStartDate = string.Empty,
                            NoOfDays         = 0
                        });

                        entity.ProcessEndDateList.Add(new DashboradProcessEndDateList
                        {
                            Process = process.Channel.ToLower() + "enddate",
                            EndDate = string.Empty
                        });
                    }

                    var loanOfficerAdgroup = opportunity.Content.TeamMembers.FirstOrDefault(mem => mem.Fields.Permissions.Any(per => per.Name.Equals("opportunity_readwrite_dealtype", StringComparison.OrdinalIgnoreCase)));
                    entity.ProcessLoanOfficerNames.Add(new DashboardLoanOfficers
                    {
                        AdGroupName = loanOfficerAdgroup != null ? loanOfficerAdgroup.RoleName : string.Empty,
                        OfficerName = loanOfficerAdgroup != null ? loanOfficerAdgroup.DisplayName : string.Empty
                    });

                    await _dashboardRepository.CreateOpportunityAsync(entity, requestId);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"RequestId: {requestId} - CreateDashBoardEntryAsync Service Exception: {ex}");
            }

            return(opportunity);
        }
        public async Task <OpportunityViewModel> MapToModelAsync(Opportunity entity, OpportunityViewModel viewModel, string requestId = "")
        {
            //Granular bug fix : Start
            //Temp fix for checklist process update
            //Overriding granular access while getting exsiting opportunity model from sharepoint
            var overrideAccess = _authorizationService.GetGranularAccessOverride();
            //Granular bug fix : End

            //Granular Access : Start
            var           permissionsNeeded = new List <ApplicationCore.Entities.Permission>();
            List <string> list   = new List <string>();
            var           access = true;

            //going for super access
            list.AddRange(new List <string> {
                Access.Opportunities_Read_All.ToString(), Access.Opportunities_ReadWrite_All.ToString()
            });
            permissionsNeeded = (await _permissionRepository.GetAllAsync(requestId)).ToList().Where(x => list.Any(x.Name.Contains)).ToList();
            if (!(StatusCodes.Status200OK == await _authorizationService.CheckAccessAsync(permissionsNeeded, requestId)))
            {
                //going for opportunity access
                access = await _authorizationService.CheckAccessInOpportunityAsync(entity, PermissionNeededTo.Read, requestId);

                if (!access)
                {
                    access = await _authorizationService.CheckAccessInOpportunityAsync(entity, PermissionNeededTo.ReadPartial, requestId);

                    if (access)
                    {
                        //going for partial accesss
                        list.Clear();
                        list.AddRange(new List <string> {
                            "customerdecision_read", "customerdecision_readwrite"
                        });
                        permissionsNeeded = (await _permissionRepository.GetAllAsync(requestId)).ToList().Where(x => list.Any(x.Name.Contains)).ToList();
                        access            = StatusCodes.Status200OK == await _authorizationService.CheckAccessAsync(permissionsNeeded, requestId) ? true : false;
                    }
                    else
                    {
                        access = false;
                    }
                }
            }

            if (access || overrideAccess)
            {
                viewModel.CustomerDecision = new CustomerDecisionModel
                {
                    Id            = entity.Content.CustomerDecision.Id,
                    Approved      = entity.Content.CustomerDecision.Approved,
                    ApprovedDate  = entity.Content.CustomerDecision.ApprovedDate,
                    LoanDisbursed = entity.Content.CustomerDecision.LoanDisbursed
                };
            }
            //Granular Access : End

            return(viewModel);
        }
Ejemplo n.º 19
0
        public void Dispose()
        {
            if ((mOpportunities != null) && (mSim.OpportunityHistory != null))
            {
                mSim.OpportunityHistory.mCurrentOpportunities = mOpportunities;
                mSim.NeedsOpportunityImport = true;

                if (mSim.CreatedSim != null)
                {
                    if (mSim.CreatedSim.mOpportunityManager == null)
                    {
                        mSim.CreatedSim.mOpportunityManager = new OpportunityManager(mSim.CreatedSim);
                        mSim.CreatedSim.mOpportunityManager.SetupLocationBasedOpportunities();
                    }

                    try
                    {
                        // Due to an odd bit of coding at the bottom of AcceptOpportunityFromTravel(),
                        //   the expiration time for non-expirying opportunities is checked
                        foreach (OpportunityHistory.OpportunityExportInfo info in mSim.OpportunityHistory.GetCurrentOpportunities())
                        {
                            if (info.ExpirationTime < SimClock.CurrentTime())
                            {
                                Opportunity opp = OpportunityManager.GetStaticOpportunity(info.Guid);
                                if (opp != null)
                                {
                                    bool requiresTimeout = false;

                                    switch (opp.Timeout)
                                    {
                                    case Opportunity.OpportunitySharedData.TimeoutCondition.SimDays:
                                    case Opportunity.OpportunitySharedData.TimeoutCondition.SimHours:
                                    case Opportunity.OpportunitySharedData.TimeoutCondition.SimTime:
                                    case Opportunity.OpportunitySharedData.TimeoutCondition.Gig:
                                    case Opportunity.OpportunitySharedData.TimeoutCondition.AfterschoolRecitalOrAudition:
                                        requiresTimeout = true;
                                        break;
                                    }

                                    if (!requiresTimeout)
                                    {
                                        info.ExpirationTime = SimClock.Add(SimClock.CurrentTime(), TimeUnit.Hours, 1);
                                    }
                                }
                            }
                        }

                        mSim.CreatedSim.OpportunityManager.TravelFixup();
                    }
                    catch (Exception e)
                    {
                        Common.Exception(mSim, e);
                    }

                    mSim.NeedsOpportunityImport = false;
                }
            }
        }
Ejemplo n.º 20
0
        public async Task <Opportunity> UpdateWorkflowAsync(Opportunity opportunity, string requestId = "")
        {
            bool    check           = true;
            dynamic jsonDyn         = null;
            var     opportunityName = WebUtility.UrlEncode(opportunity.DisplayName);
            var     options         = new List <QueryParam>();

            options.Add(new QueryParam("filter", $"startswith(displayName,'{opportunityName}')"));
            while (check)
            {
                var groupIdJson = await _graphUserAppService.GetGroupAsync(options, "", requestId);

                jsonDyn = groupIdJson;
                JArray jsonArray = JArray.Parse(jsonDyn["value"].ToString());
                if (jsonArray.Count() > 0)
                {
                    if (!String.IsNullOrEmpty(jsonDyn.value[0].id.ToString()))
                    {
                        check = false;
                    }
                }
            }

            var groupID = String.Empty;

            groupID = jsonDyn.value[0].id.ToString();

            foreach (var teamMember in opportunity.Content.TeamMembers)
            {
                var userId = teamMember.Id;
                if (teamMember.TeamsMembership == TeamsMembership.Owner)
                {
                    try
                    {
                        Guard.Against.NullOrEmpty(teamMember.RoleId, $"UpdateWorkflowAsync_{teamMember.DisplayName} Id NullOrEmpty", requestId);
                        var responseJson = await _graphUserAppService.AddGroupOwnerAsync(userId, groupID, requestId);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError($"RequestId: {requestId} - userId: {userId} - AddGroupOwnerAsync error in CreateWorkflowAsync: {ex}");
                    }
                }
                else
                {
                    try
                    {
                        Guard.Against.NullOrEmpty(userId, "CreateWorkflowAsync_LoanOffier_Ups Null or empty", requestId);
                        var responseJson = await _graphUserAppService.AddGroupMemberAsync(userId, groupID);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError($"RequestId: {requestId} - userId: {userId} - AddGroupMemberAsync error in CreateWorkflowAsync: {ex}");
                    }
                }
            }

            return(opportunity);
        }
Ejemplo n.º 21
0
        private void OpportunityCreate(LocalPluginContext context)
        {
            var svc         = context.OrganizationService;
            var opportunity = new Opportunity(svc, context.PluginExecutionContext.InputParameters["Target"] as Entity);

            //var preOpportunity = new Opportunity(svc, context.PreImage);

            opportunity.AssignOpportunity(svc, opportunity, opportunity);
        }
Ejemplo n.º 22
0
        public async Task <ActionResult> DeleteConfirmed(int id)
        {
            Opportunity opportunity = await db.Opportunities.FindAsync(id);

            db.Opportunities.Remove(opportunity);
            await db.SaveChangesAsync();

            return(RedirectToAction("Index"));
        }
Ejemplo n.º 23
0
        public void OpprtunityOwner_OwnerRequired_GetBrokenRulesSuccess()
        {
            opportunity.OwnerId = 0;
            Opportunity opportunitywithOwner = opportunity;
            var         brokenRuleCount      = opportunitywithOwner.GetBrokenRules().Count();

            Assert.AreEqual(0, opportunitywithOwner.OwnerId);
            Assert.AreEqual(1, brokenRuleCount);
        }
Ejemplo n.º 24
0
        public void OpportunityDetail_OpportunityNoName_GetBrokenRuleSuccess()
        {
            opportunity.OpportunityName = null;
            Opportunity opportunitywithNoDescription = opportunity;
            var         brokenRuleCount = opportunitywithNoDescription.GetBrokenRules().Count();

            Assert.AreEqual(null, opportunitywithNoDescription.OpportunityName);
            Assert.AreEqual(1, brokenRuleCount);
        }
Ejemplo n.º 25
0
        public void OpportunityPotential_PotentialwithRequired_GetBrokenRulesSuccess()
        {
            opportunity.Potential = 0;
            Opportunity opportunitywithPotential = opportunity;
            var         brokenRuleCount          = opportunitywithPotential.GetBrokenRules().Count();

            Assert.AreEqual(0, opportunitywithPotential.Potential);
            Assert.AreEqual(1, brokenRuleCount);
        }
Ejemplo n.º 26
0
        public IActionResult Create([FromBody] Opportunity opportunityIn)
        {
            Opportunity opportunityToCreate = _opportunitiesService.Create(opportunityIn);

            return(CreatedAtRoute(
                       routeName: "GetOpportunityById",
                       routeValues: new { id = opportunityToCreate.Id.ToString() },
                       value: opportunityToCreate));
        }
Ejemplo n.º 27
0
        public void OpportunityStage_StagewithRequired_GetBrokenRulesSuccess()
        {
            opportunity.StageID = 0;
            Opportunity opportunitywithStageID = opportunity;
            var         brokenRuleCount        = opportunitywithStageID.GetBrokenRules().Count();

            Assert.AreEqual(0, opportunitywithStageID.StageID);
            Assert.AreEqual(1, brokenRuleCount);
        }
Ejemplo n.º 28
0
        private static Opportunity MapOpportunity(IDataReader reader, out int r)
        {
            //int r = 0;
            r = 0;

            Opportunity p             = new Opportunity();
            int         startingIndex = 0; // this number is dependant on the columns one decides to include.

            p.Id                     = reader.GetSafeInt32(startingIndex++);
            p.Name                   = reader.GetSafeString(startingIndex++);
            p.Description            = reader.GetSafeString(startingIndex++);
            p.ContactPersonFirstName = reader.GetSafeString(startingIndex++);
            p.ContactPersonLastName  = reader.GetSafeString(startingIndex++);
            p.Email                  = reader.GetSafeString(startingIndex++);
            p.Phone                  = reader.GetSafeString(startingIndex++);
            p.Address1               = reader.GetSafeString(startingIndex++);
            p.Address2               = reader.GetSafeString(startingIndex++);
            p.City                   = reader.GetSafeString(startingIndex++);
            int stateProvinceId = reader.GetSafeInt32(startingIndex++);

            if (stateProvinceId > 0)
            {
                p.StateProvince      = new StateProvinceBase();
                p.StateProvince.Id   = stateProvinceId;
                p.StateProvince.Code = reader.GetSafeString(startingIndex++);
                p.StateProvince.Name = reader.GetSafeString(startingIndex++);
            }
            else
            {
                //p.StateProvince = new StateProvinceBase();
                startingIndex += 2;
            }
            p.PostalCode = reader.GetSafeString(startingIndex++);
            int countryId = reader.GetSafeInt32(startingIndex++);

            if (countryId > 0)
            {
                p.Country          = new Country();
                p.Country.Id       = countryId;
                p.Country.Name     = reader.GetSafeString(startingIndex++);
                p.Country.Code     = reader.GetSafeString(startingIndex++);
                p.Country.LongCode = reader.GetSafeString(startingIndex++);
            }
            else
            {
                p.Country      = new Country();
                startingIndex += 3;
            }
            p.DateTimeStart = reader.GetSafeDateTime(startingIndex++);
            p.DateTimeEnd   = reader.GetSafeDateTime(startingIndex++);

            r = reader.GetSafeInt32(startingIndex++);


            return(p);
        }
Ejemplo n.º 29
0
    protected void SubmitPost(object sender, EventArgs e)
    {
        //Insert into Opportunity table
        Opportunity opp = new Opportunity(JobNameText.Value.ToString(), JobTypeText.Value.ToString(), ApprenText.Value.ToString());

        sc.Open();
        System.Data.SqlClient.SqlCommand insertOpp = new System.Data.SqlClient.SqlCommand();
        insertOpp.Connection  = sc;
        insertOpp.CommandText = "insert into Opportunity(OpportunityName, OpportunityType, isApprenticeship) values(@OpportunityName,@OpportunityType,@isApprenticeship)";
        insertOpp.Parameters.Add(new SqlParameter("@OpportunityName", opp.getOpportunityName()));
        insertOpp.Parameters.Add(new SqlParameter("@OpportunityType", opp.getOpportunityType()));
        insertOpp.Parameters.Add(new SqlParameter("@isApprenticeship", opp.getApprenticeship()));

        insertOpp.ExecuteNonQuery();
        sc.Close();

        //Insert into Post table
        Post post = new Post(JobTypeText.Value.ToString() + " Post", DateTime.Now, DateTime.Parse(DeadlineText.Value), DateTime.Now);

        sc.Open();
        System.Data.SqlClient.SqlCommand matchPersonID = new System.Data.SqlClient.SqlCommand();
        matchPersonID.Connection  = sc;
        matchPersonID.CommandText = "SELECT MAX(PersonID) FROM PERSON";
        matchPersonID.ExecuteNonQuery();
        int holdPostPersonID = (Int32)matchPersonID.ExecuteScalar();

        matchPersonID.ExecuteNonQuery();
        sc.Close();

        sc.Open();
        SqlCommand matchOppID = new SqlCommand();

        matchOppID.Connection  = sc;
        matchOppID.CommandText = "SELECT MAX(OpportunityID) from OPPORTUNITY";
        int holdPostOppID = (Int32)matchOppID.ExecuteScalar();

        SqlCommand insertPost = new SqlCommand();

        insertPost.Connection  = sc;
        insertPost.CommandText = "insert into Post(PostDescription,DateCreated,Deadline,ModifiedDate,PersonID,OpportunityID) " +
                                 "values(@PostDescription,@DateCreated,@Deadline,@ModifiedDate,@PersonID,@OpportunityID)";
        insertPost.Parameters.Add(new SqlParameter("@PostDescription", post.getPostDesc()));
        insertPost.Parameters.Add(new SqlParameter("@DateCreated", post.getDateCreated()));
        insertPost.Parameters.Add(new SqlParameter("@Deadline", post.getDeadline()));
        insertPost.Parameters.Add(new SqlParameter("@ModifiedDate", post.getModDate()));
        insertPost.Parameters.Add(new SqlParameter("@PersonID", holdPostPersonID));
        insertPost.Parameters.Add(new SqlParameter("@OpportunityID", holdPostOppID));

        insertPost.ExecuteNonQuery();

        ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowPost", "ShowPostAlert();", true);



        sc.Close();
    }
Ejemplo n.º 30
0
        public OpportunityRoverTests()
        {
            _requestBuilderMock = new Mock <IRequestBuilder>();

            _requestBuilderMock
            .Setup(m => m.AddPath("Opportunity"))
            .Returns(_requestBuilderMock.Object);

            _rover = new Opportunity(_requestBuilderMock.Object);
        }
        public async static Task <Opportunity> CreateAsync(Opportunity opportunity)
        {
            var wrapperObject = OpportunityWrapper.Load(opportunity);

            var response = await CapsuleClient.makeRequest <OpportunityWrapper>(BASE_ENDPOINT,
                                                                                "POST",
                                                                                wrapperObject);

            return(response.Opportunity);
        }
        /// <summary>
        /// Adding new opportunity details
        /// </summary>
        /// <param name="client">Force client instance</param>
        /// <param name="opportunity">Opportunity Details</param>
        /// <returns></returns>
        public async Task <SalesForceResponse> CreateOpportunity(ForceClient client, Opportunity opportunity)
        {
            var result = await client.CreateAsync(Constants.Opportunity, opportunity);

            return(new SalesForceResponse
            {
                IsSuccess = result.Success,
                Details = result.Success ? Constants.MsgOpportunityAddSuccess : Constants.MsgOpportunityAddFailed
            });
        }
Ejemplo n.º 33
0
        public void Execute(IServiceProvider serviceProvider)
        {
            var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            var serviceFactory =
                (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            var service = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                if (context.MessageName.ToLower() != "create" ||
                        context.PrimaryEntityName != Invoice.EntityLogicalName)
                    return;

                var invoice = (Entity)context.InputParameters["Target"];

                var correntInvoice = invoice.ToEntity<Invoice>();

                if (correntInvoice.SalesOrderId != null)
                {
                    return;
                }

                var account = (Account)service.Retrieve("account", correntInvoice.CustomerId.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet(new String[] { "primarycontactid" }));

                Opportunity orederForCreate = new Opportunity
                {
                    ParentAccountId = correntInvoice.CustomerId,
                    Name = correntInvoice.Name,
                    EstimatedCloseDate = correntInvoice.new_Expecteddatepayment,
                    EstimatedValue = correntInvoice.TotalAmount ?? new Money(0),
                    new_margin = correntInvoice.new_marginUSD,
                    TransactionCurrencyId = correntInvoice.TransactionCurrencyId,
                    PriceLevelId = correntInvoice.PriceLevelId,
                    ParentContactId = account.PrimaryContactId,
                    new_currentphase = new OptionSetValue(100000003)
                };
                var oppID = service.Create(orederForCreate);

                Invoice updateInvoice = new Invoice
                {
                    Id = correntInvoice.Id,
                    OpportunityId = new EntityReference { Id = oppID,LogicalName = Opportunity.EntityLogicalName}
                };
                service.Update(updateInvoice);
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }
Ejemplo n.º 34
0
	/**
	 * Sets the displayed page info, based on the information contained in
	 * the cached Opportunity.
	 */
	private void changeData ()
	{
		opp = GlobalInfo.cached_opportunity;
		if (opp == null) {
			return;
		}
		string text = "";
		
		// Set text based on Opportunity fields
		text += "Description: " + opp.get_description() + '\n' + '\n';
		text += "Location: " + opp.get_location() + '\n' + '\n';
		text += "Minimum GPA Required:" + opp.get_minimum_gpa() + '\n' + '\n';
		text += "Begin Date: " + opp.get_begin_date() + '\n' + '\n';
		text += "End Date: " + opp.get_end_date() + '\n' + '\n';
		text += "Contacts Name: " + opp.get_contact_name() + '\n' + '\n';
		text += "Contacts Email: " + opp.get_contact_email() + '\n' + '\n';
		text += "Contacts Phone: " + opp.get_contact_phone() + '\n' + '\n';
		
		// Assign text to on-screen text box
		activityDescription.text = text;
		Score new_score = opp.get_base_score();
		int score_multiplier = (int)opp.engagement * (int)opp.length;
		new_score *= score_multiplier;
		// Get and display player scores in each of the five dimensions
		IAScore.text = new_score.IA.ToString() + '\n' + "IA";
		TestHarness.check_test ("check the whether the screen can show IA Score: ", !(new_score.IA==null));

		GAScore.text = new_score.GA.ToString()+ '\n' + "GA";
		TestHarness.check_test ("check the whether the screen can show GA Score: ", !(new_score.GA==null));

		PPEScore.text = new_score.PPE.ToString() + '\n' + "PPE";
		TestHarness.check_test ("check the whether the screen can show PPE Score: ", !(new_score.PPE==null));

		SCICScore.text = new_score.SCIC.ToString() + '\n' + "SCIC";
		TestHarness.check_test ("check the whether the screen can show SCIC Score: ", !(new_score.SCIC==null));

		WBScore.text = new_score.WB.ToString() + '\n' + "WB";
		TestHarness.check_test ("check the whether the screen can show WB Score: ", !(new_score.WB==null));

		
		
		if (((Student)Database.studentHash [GlobalInfo.storedUserName]).get_opportunity_history ().Contains (GlobalInfo.cached_opportunity.opportunityID)) {
			ButtonText.text = "Cancel Register";
		} else {
			ButtonText.text = "Need Register";
		}
		

	}
Ejemplo n.º 35
0
        static void Main(string[] args)
        {
            Console.WriteLine("### Observer Pattern ###");

            // Create Opportunity and attach competitors
            Opportunity opp = new Opportunity("Active", 120.00);
            opp.Attach(new Competitor("JLL"));
            opp.Attach(new Competitor("Nordstrom"));

            // Fluctuating prices will notify investors
            opp.Price = 120.10;
            opp.Price = 121.00;
            opp.Price = 120.50;
            opp.Price = 120.75;

            // Wait for user
            Console.ReadKey();
        }
Ejemplo n.º 36
0
        private static bool CheckAllRequirements(Sim s, Opportunity op, OpportunityNames lastOpName, ref string msg)
        {
            Opportunity.OpportunitySharedData sharedData = op.SharedData;
            WorldName mTargetWorldRequired = sharedData.mTargetWorldRequired;
            WorldName currentWorld = GameUtils.GetCurrentWorld();

            if (mTargetWorldRequired == WorldName.SunsetValley)
            {
                mTargetWorldRequired = s.SimDescription.HomeWorld;
            }
            if ((mTargetWorldRequired == currentWorld) || (mTargetWorldRequired == WorldName.Undefined))
            {
                foreach (Opportunity.OpportunitySharedData.RequirementInfo info in sharedData.mRequirementList)
                {
                    if (info.mType == RequirementType.OpportunityComplete)
                    {
                        OpportunityNames mGuid = (OpportunityNames)info.mGuid;
                        if (lastOpName == mGuid)
                        {
                            continue;
                        }
                    }
                    if (!op.CheckRequirement(info, s, sharedData))
                    {
                        msg += Common.NewLine + " Failure: " + info.mType;

                        return false;
                    }
                }
            }
            OpportunityNames mCompletionTriggerOpportunity = sharedData.mCompletionTriggerOpportunity;
            if (mCompletionTriggerOpportunity != OpportunityNames.Undefined)
            {
                Opportunity staticOpportunity = OpportunityManager.GetStaticOpportunity(mCompletionTriggerOpportunity);
                if ((staticOpportunity != null) && !op.CheckAllRequirements(s, staticOpportunity, sharedData.mGuid))
                {
                    msg += Common.NewLine + " Failure: B";
                    return false;
                }
            }
            return true;
        }
    void Start()
    {
        AppController.appController.Load();
        int loadIndex = AppController.appController.getUsersSelectedOpportunityIndex();
        opportunity = AppController.appController.getUsersSelectedOpportunities()[loadIndex];
        ApplicationView.applicationView.currentScreenText = truncateTitle (opportunity, numberOfVisibleCharacters, opportunity.Title.Length);
        ApplicationView.applicationView.currentScreenTextSize = 200 - opportunity.Title.Length;

        displayOpportunityMetadata(opportunity);

        generateDimensionSprites(opportunity);

        generateTextOverlay(.17f, "Complete");
        completeTextButton = generateMetaDataNavigationButton(.17f, 3);

        generateTextOverlay(.5f, "Details");
        detailsTextButton = generateMetaDataNavigationButton(.5f, 3);

        generateTextOverlay(.83f, "Remove");
        removeTextButton = generateMetaDataNavigationButton(.83f, 3);
    }
    // Use this for initialization
    void Start()
    {
        AppController.appController.Load();
        int loadIndex = AppController.appController.getOpportunityFeedIndex();
        opportunity = AppController.appController.getAllOpportunities()[loadIndex];
        ApplicationView.applicationView.currentScreenText = truncateTitle(opportunity, numberOfVisibleCharacters, opportunity.Title.Length);
        ApplicationView.applicationView.currentScreenTextSize = 200 - opportunity.Title.Length;

        displayOpportunityMetadata(opportunity);

        generateDimensionSprites(opportunity);

        GameObject acceptText = generateTextOverlay(.25f, "Accept");
        acceptTextButton = generateMetaDataNavigationButton(.25f, 2);

        generateTextOverlay(.75f, "Details");
        detailsTextButton = generateMetaDataNavigationButton(.75f, 2);

        if (containsOpportunityId(AppController.appController.getUsersSelectedOpportunities(), opportunity.Id))
        {
            acceptText.GetComponent<TextMesh>().text = "Accepted";
        }
    }
		public static void FixComboRabbitHoleOpportunity (Opportunity opp)
		{
			ComboRabbitHole target = opp.TargetObject as ComboRabbitHole;
			if (target != null && opp.mSharedData.mTargetInteractionName == null)
			{
				RabbitHoleType type;
				if (ParserFunctions.TryParseEnum<RabbitHoleType> (opp.TargetData, out type, RabbitHoleType.None))
				{
					foreach (RabbitHole r in target.ContainedRabbitholes.Keys)
					{
						if (r.Guid == type)
						{
							opp.TargetObject = r;
							if (opp.CompletionListener != null)
							{
								opp.mCompletionListener.SetTargetObject (r);
							}
							return;
						}
					}
				}
			}
		}
		/// <summary>
		/// Creates any entity records that this sample requires.
		/// </summary>
		public void CreateRequiredRecords()
		{
			// Create a unit group.
			UoMSchedule unitGroup = new UoMSchedule
			{
				Name = "Example Unit Group",
				BaseUoMName = "Example Primary Unit"
			};
			_unitGroupId = _service.Create(unitGroup);

			// Retrieve the unit.
			QueryExpression unitQuery = new QueryExpression()
			{
				EntityName = UoM.EntityLogicalName,
				ColumnSet = new ColumnSet("uomid", "name"),
				Criteria =
				{
					Conditions = 
					{
						new ConditionExpression ("uomscheduleid", ConditionOperator.Equal, _unitGroupId)
					}
				},
				PageInfo = new PagingInfo
				{
					PageNumber = 1,
					Count = 1
				}
			};
			UoM unit = (UoM)_service.RetrieveMultiple(unitQuery).Entities[0];

			// Create an account.
			Account account = new Account
			{
				Name = "Litware, Inc.",
				Address1_StateOrProvince = "Colorado"
			};
			_accountId = (_service.Create(account));

			// Create the 2 contacts.
			Contact contact = new Contact()
			{
				FirstName = "Ben",
				LastName = "Andrews",
				EMailAddress1 = "*****@*****.**",
				Address1_City = "Redmond",
				Address1_StateOrProvince = "WA",
				Address1_Telephone1 = "(206)555-5555",
				ParentCustomerId = new EntityReference
				{
					Id = _accountId,
					LogicalName = account.LogicalName
				}
			};
			_contactIdList.Add(_service.Create(contact));

			contact = new Contact()
			{
				FirstName = "Colin",
				LastName = "Wilcox",
				EMailAddress1 = "*****@*****.**",
				Address1_City = "Bellevue",
				Address1_StateOrProvince = "WA",
				Address1_Telephone1 = "(425)555-5555",
				ParentCustomerId = new EntityReference
				{
					Id = _accountId,
					LogicalName = account.LogicalName
				}
			};
			_contactIdList.Add(_service.Create(contact));

			// Create pricing and product objects.
			PriceLevel priceLevel = new PriceLevel()
			{
				Name = "Faux Price List"
			};
			_priceLevelId = _service.Create(priceLevel);

			Product product = new Product()
			{
				ProductNumber = "1",
				QuantityDecimal = 4,
				Name = "Faux Product",
				Price = new Money(20.0M),
				DefaultUoMId = new EntityReference
				{
					Id = unit.Id,
					LogicalName = UoM.EntityLogicalName
				},
				DefaultUoMScheduleId = new EntityReference
				{
					Id = _unitGroupId,
					LogicalName = UoMSchedule.EntityLogicalName
				}
			};
			_productId = _service.Create(product);

			ProductPriceLevel productPrice = new ProductPriceLevel()
			{
				PriceLevelId = new EntityReference()
				{
					Id = _priceLevelId,
					LogicalName = PriceLevel.EntityLogicalName
				},
				ProductId = new EntityReference()
				{
					Id = _productId,
					LogicalName = Product.EntityLogicalName
				},
				UoMId = new EntityReference
				{
					Id = unit.Id,
					LogicalName = UoM.EntityLogicalName
				},
				Amount = new Money(20.0M),
			};
			_productPriceId = _service.Create(productPrice);

			// Create 3 orders.
			SalesOrder order = new SalesOrder()
			{
				Name = "Faux Order",
				DateFulfilled = new DateTime(2010, 8, 1),
				PriceLevelId = new EntityReference
				{
					Id = _priceLevelId,
					LogicalName = PriceLevel.EntityLogicalName
				},
				CustomerId = new EntityReference
				{
					Id = _accountId,
					LogicalName = account.LogicalName
				},
				FreightAmount = new Money(20.0M)
			};
			_orderIdList.Add(_service.Create(order));

			order = new SalesOrder()
			{
				Name = "Old Faux Order",
				DateFulfilled = new DateTime(2010, 4, 1),
				PriceLevelId = new EntityReference
				{
					Id = _priceLevelId,
					LogicalName = PriceLevel.EntityLogicalName
				},
				CustomerId = new EntityReference
				{
					Id = _accountId,
					LogicalName = account.LogicalName
				},
				FreightAmount = new Money(20.0M)
			};
			_orderIdList.Add(_service.Create(order));

			order = new SalesOrder()
			{
				Name = "Oldest Faux Order",
				DateFulfilled = new DateTime(2008, 8, 1),
				PriceLevelId = new EntityReference
				{
					Id = _priceLevelId,
					LogicalName = PriceLevel.EntityLogicalName
				},
				CustomerId = new EntityReference
				{
					Id = _accountId,
					LogicalName = account.LogicalName
				},
				FreightAmount = new Money(20.0M)
			};
			_orderIdList.Add(_service.Create(order));

			// Create 2 opportunities.
			Opportunity opportunity = new Opportunity()
			{
				Name = "Litware, Inc. Opportunity 1",
				EstimatedCloseDate = new DateTime(2011, 1, 1),
				CustomerId = new EntityReference
				{
					Id = _accountId,
					LogicalName = account.LogicalName
				}
			};
			_opportunityIdList.Add(_service.Create(opportunity));

			opportunity = new Opportunity()
			{
				Name = "Litware, Inc. Opportunity 2",
				EstimatedCloseDate = new DateTime(2020, 1, 1),
				CustomerId = new EntityReference
				{
					Id = _accountId,
					LogicalName = account.LogicalName
				}
			};
			_opportunityIdList.Add(_service.Create(opportunity));
		}
Ejemplo n.º 41
0
	public static void addOpportunity (Opportunity o)
	{
		opportunityHash.Add (o.opportunityID, o);
	}
 private void SetPrimaryContactFromOppContacts(Opportunity opportunity)
 {
     IContact contact = GetPrimaryOppContact(opportunity.Contacts);
     if (contact == null)
     {
         contact = GetPrimaryContact(opportunity.Account.Contacts);
     }
     Contact.LookupResultValue = contact;
     LeadId.LookupResultValue = null;
 }
Ejemplo n.º 43
0
 void Start()
 {
     harvest = GameObject.Find ("Harvest").GetComponent<Harvest>();
     ops = GameObject.Find ("Opportunity").GetComponent<Opportunity>();
 }
Ejemplo n.º 44
0
 public OpportunityEx(Opportunity.OpportunitySharedData sharedData)
     : base(sharedData)
 { }
        public static ProxyOpportunity ConvertToReadableOpportunity(Opportunity orig, XrmServiceContext context)
        {
            ProxyOpportunity co = new ProxyOpportunity();
            //using (Xrm.XrmServiceContext context = new XrmServiceContext("Xrm"))
            //{

                co.Id = orig.Id;
                co.OpportunityId = orig.OpportunityId;
                co.Name = orig.Name;
                co.Description = orig.Description;
                co.ProjectDescription = orig.new_ProjectDescription;
                co.ProjectRationale = orig.new_ProjectRationale;
                co.Country = EnsureValueFromOptionSet(orig, "new_country");
                co.Region = EnsureValueFromOptionSet(orig, "new_region");
                co.Sector = EnsureValueFromOptionSet(orig, "new_sector");
                co.SubSector = EnsureValueFromOptionSet(orig, "new_subsector");
                var selectedCurrency = context.TransactionCurrencySet.Where(x => x.TransactionCurrencyId == orig.TransactionCurrencyId.Id).FirstOrDefault();
                co.Currency = selectedCurrency.CurrencyName;
                //new_ApprovalLevel
                co.ApprovalLevel = EnsureValueFromOptionSet(orig, "new_approvallevel");
                //BudgetAmount
                co.BudgetAmount = orig.BudgetAmount; // ? orig.BudgetAmount.Value : 0;
                //new_Guarantee
                co.Guarantee =  orig.new_Guarantee.HasValue ? (orig.new_Guarantee.Value ? "Yes" : "No") : string.Empty;
                //new_Borrower
                co.Borrower = orig.new_Borrower;
                //new_CategoryType
                co.CategoryType = EnsureValueFromOptionSet(orig, "new_categorytype");
                //new_ModeofFinancialAssistance
                co.ModeOfFinancialAssistance = EnsureValueFromOptionSet(orig, "new_modeoffinancialassistance");
                //new_ProcessingCategory
                co.ProcessingCategory = EnsureValueFromOptionSet(orig, "new_processingcategory");
                //new_ProcessingScenario
                co.processingScenario = EnsureValueFromOptionSet(orig, "new_processingscenario");
                //new_ProjectStage
                co.ProjectStage = EnsureValueFromOptionSet(orig, "new_projectstage");
                //new_expectedapprovalyear
                co.ExpectedApprovalYear = EnsureValueFromOptionSet(orig, "new_expectedapprovalyear");
                //new_additionalfinancing
                co.AdditionalFinancing = orig.new_AdditionalFinancing.HasValue ? (orig.new_AdditionalFinancing.Value ? "Yes" : "No") : string.Empty;
                //statuscode
                co.ProjectStatus = EnsureValueFromOptionSet(orig, "statuscode");
                co.TaskStatus = EnsureValueFromOptionSet(orig, "new_taskstatus");
                co.Department = orig.new_Department;
                co.ClosingDate = orig.EstimatedCloseDate;
                co.Division = EnsureValueFromOptionSet(orig, "new_division"); // orig.new_Division;
                co.DivisionRole = EnsureValueFromOptionSet(orig, "new_divisionrole");

                co.NSProjectType = EnsureValueFromOptionSet(orig, "new_nsprojecttype");
                co.NSCoreSector = EnsureValueFromOptionSet(orig, "new_nscoresector");

                co.NSOProcessingCategory = EnsureValueFromOptionSet(orig, "new_nsoprocessingcategory");//co.NSOProcessingCategory; //EnsureValueFromOptionSet(orig, "new_nsoprocessingcategory");
                co.ProjectNo = orig.new_ProjectNumber;
                //co.Agencies = ConvertToProxyAccount(orig.new_opportunity_account.ToList()).ToArray();

                //co.RealOpportunity = orig;
                //co.teams = orig.opportunity_Teams;

                //co.c1 = orig.opportunity_connections1;
                //co.c2 = orig.opportunity_connections2;

                co.PRFApproval = orig.new_PRFApproval.HasValue ? orig.new_PRFApproval.Value.ToString() : string.Empty;
                co.CRPICM = orig.new_CRPICM.HasValue ? orig.new_CRPICM.ToString() : string.Empty;
                co.LetterOfNoObjection = orig.new_LetterofNoObjection.HasValue ? orig.new_LetterofNoObjection.Value.ToString() : string.Empty;
                co.FinalReviewICM = orig.new_FinalReviewICM.HasValue ? orig.new_FinalReviewICM.Value.ToString() : string.Empty;
                co.RRPApproval = orig.new_RRPApproval.HasValue ? orig.new_RRPApproval.Value.ToString() : string.Empty;
                co.SigningDate = orig.new_SigningDate.HasValue ? orig.new_SigningDate.Value.ToString() : string.Empty;
                co.EffectivenessDate = orig.new_EffectivenessDate.HasValue ? orig.new_EffectivenessDate.Value.ToString() : string.Empty;
                co.XARRDate = orig.new_XARR.HasValue ? orig.new_XARR.Value.ToString() : string.Empty;
                co.ProjectEndDate = orig.new_ProjectEndDate.HasValue ? orig.new_ProjectEndDate.Value.ToString() : string.Empty;
            return co;
        }
Ejemplo n.º 46
0
        public void UpdateMerhantsOffertoSalesForce()
        {
            if (!Authenticate())
                return;

            DataSet ds = new DataLayer().UpdateMerhantsOffertoSalesForce();
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                Opportunity ops = new Opportunity();
                //Score
                ops.Score__c = ds.Tables[0].Rows[i]["score"].ToString();

                //Average CC sales
                ops.Calculadora_MBP__c = Convert.ToDouble(ds.Tables[0].Rows[i]["avgcc"].ToString());
                ops.Calculadora_MBP__cSpecified = true;
                //Date of offer
                ops.Fecha_Pre_Oferta__c = Convert.ToDateTime(ds.Tables[0].Rows[i]["offerdate"].ToString());
                ops.Fecha_Pre_Oferta__cSpecified = true;
                //Yealry sales
                ops.Ventas_Brutas_Anuales__c = Convert.ToDouble(ds.Tables[0].Rows[i]["yearlysales"].ToString());
                ops.Ventas_Brutas_Anuales__cSpecified = true;
                //MCA Amount
                ops.Amount = Convert.ToDouble(ds.Tables[0].Rows[i]["mcaamount"].ToString());
               // ops.Amount__cSpecified = true;
                //Owned amount
                ops.DAR_1__c = Convert.ToDouble(ds.Tables[0].Rows[i]["loanamount"].ToString());
                ops.DAR_1__cSpecified = true;
                //retention percentage
                ops.IDP_1__c = Convert.ToDouble(ds.Tables[0].Rows[i]["retention"].ToString());
                ops.IDP_1__cSpecified = true;
                //turn
                ops.Retorno_Estimado_1__c = Convert.ToDouble(ds.Tables[0].Rows[i]["turn"].ToString());
                ops.Retorno_Estimado_1__cSpecified = true;
                //total owned amount
                ops.Precio_Oferta_Maxima__c = Convert.ToDouble(ds.Tables[0].Rows[i]["loanamount"].ToString());
                ops.Precio_Oferta_Maxima__cSpecified = true;
                ops.Contract_ID__c =ds.Tables[0].Rows[i]["contractid"].ToString();
                //ops.Contract_ID__cSpecified = true;
                //status
                ops.Contract_Status__c = ds.Tables[0].Rows[i]["status"].ToString();
                //decline reason
                ops.Motivo_Rechazo__c = ds.Tables[0].Rows[i]["reason"].ToString();
                //decline date
                ops.Fecha_Rechazo__c = DateTime.Now;
                ops.AccountId = ds.Tables[0].Rows[i]["accountid"].ToString();
                //Name
                ops.Name = ds.Tables[0].Rows[i]["name"].ToString();
                //Stage
                ops.StageName = "Active";
                //Close date
                ops.CloseDate = Convert.ToDateTime(ds.Tables[0].Rows[i]["closedate"].ToString());
                ops.CloseDateSpecified = true;

                if (!string.IsNullOrEmpty((ds.Tables[0].Rows[i]["accountid"].ToString())))
                {
                    if (string.IsNullOrEmpty((ds.Tables[0].Rows[i]["offeraccountid"].ToString())))
                    {
                        SaveResult[] result = binding.create(new sObject[1] { ops });
                        new DataLayer().MapOfferSalesForceAccountId(result[0].id, Convert.ToInt64(ds.Tables[0].Rows[i]["offerId"].ToString()));
                    }
                    else
                    {
                        ops.Id = ds.Tables[0].Rows[i]["offeraccountid"].ToString();
                        SaveResult[] result = binding.update(new sObject[1] { ops });
                    }
                }
            }
        }
Ejemplo n.º 47
0
	public static void testDatabase02(){
		
		//Test addTag() Method;
		Tag t1 = new Tag ("Asian");
		t1.events = new ArrayList{"NUGOAL_1"} ;
		Tag t2 = new Tag ("Peer");
		t2.events = new ArrayList{"PEERMENTORING", "RA"};
		Tag t3 = new Tag ("Student");
		t3.events = new ArrayList{"PEERMENTORING", "RA","Hall"};
		addTag (t1);
		TestHarness.check_test ("Check adding the Tag with one opportunity: ", tagHash.Contains ("Asian")==true);
		addTag (t2);
		TestHarness.check_test ("Check adding the Tag with two opportunity: ", (tagHash.Contains ("Asian")&&tagHash.Contains ("Peer"))==true);
		addTag (t3);
		TestHarness.check_test ("Check adding the Tag with three opportunity ", (tagHash.Contains ("Student")&&tagHash.Contains ("Asian")&&tagHash.Contains ("Peer"))==true);
		
		
		//Test addStudent() Method;
		Student s1 = new Student ("ritter.g", "Graham Ritter", "admin", "*****@*****.**");
		Student s2 = new Student ("zheng.q", "Qiaozhi Zheng", "admin", "*****@*****.**");
		Student s3 = new Student ("chaoID", "Chao Fang", "admin", "*****@*****.**");
		addStudent (s1);
		TestHarness.check_test ("Check adding the new student: ", studentHash.Contains("ritter.g")==true);
		addStudent (s2);
		TestHarness.check_test ("Check adding two new students: ", (studentHash.Contains("zheng.q")&&studentHash.Contains("ritter.g"))==true);
		addStudent (s3);
		TestHarness.check_test ("Check adding three new students: ", (studentHash.Contains("zheng.q")&&studentHash.Contains("ritter.g")&&studentHash.Contains("chaoID"))==true);
		
		
		
		
		//Test addOpportunity() Method;
		Opportunity e1 = new Opportunity ("NUGOAL_1", "Northeastern University Growth Opportunities for Asian American Leaders (NU GOAL)",
		                                  Opportunity.OPPORTUNITY_FORMATS.TRAINING, new ArrayList{"Multicultural", "Leadership", "Community Engagement", "Exploring Identity"} , "Northeastern University Growth and Opportunity for Asian American Leaders is a program specifically designed for first and second year Asian American students who are looking to increase and gain experiences to empower themselves as leaders at Northeastern University and beyond. A cohort of students will be chosen based on their potential as future leaders and need for leadership development. This seven week program will focus on the intersection of leadership and Asian American racial identity through discussions and projects. It will be facilitated by current Asian American student leaders and AAC staff. Apply by December 1, 2015. View web site for more information: Website", 
		new Date (2015, 12, 1), new Date (2015, 3, 0), Opportunity.OPPORTUNITY_LENGTH._3_499_HOURS, Opportunity.LEVEL_OF_ENGAGEMENT.ACTIVE, Opportunity.OPPORTUNITY_RECURRENCE.DAILY, "Boston Campus", 
		true, 0f, "either", "Self-identify as Asian-American", "Asian American Center", "Kristine Din", 
		"x5554", "*****@*****.**", new ArrayList{"Students will be able to define leadership in relationship to their own racial identity.", 
			"Students will be able to describe their leadership strengths.", "Students will be able to employ their leadership style and strengths in their daily lives.", "Students will be able to analyze leadership in the Asian American community.", "Students will be able to propose a meaningful intervention for building Asian American leadership capacity.", "Students will be able to assess the need for leadership development within the Asian American community at Northeastern."} ,
		new ArrayList{Communication, Collaboration_Teamwork, Social_Awareness, Networking, Organization, Planning});
		
		Opportunity e2 = new Opportunity ("PEERMENTORING", "Peer Mentoring Program", Opportunity.OPPORTUNITY_FORMATS.COURSE, new ArrayList{"Multicultural"} , "Asia Peer Mentoring program is a program for first year and transfer Asian-American students to connect with a community. Mentees will be paired with upper class students for support around themes of Asian-American identity and transition to Northeastern.", 
		new Date (2015, 9, 15), new Date (2016, 5, 0), Opportunity.OPPORTUNITY_LENGTH._180_23999_HOURS, Opportunity.LEVEL_OF_ENGAGEMENT.GENERATIVE, Opportunity.OPPORTUNITY_RECURRENCE.EACH_FALL, "Boston Campus", 
		true, 0f, "either", "", "", "", "", "", new ArrayList (), new ArrayList {Communication, Collaboration_Teamwork, Intercultural_Understanding, Socially_Integrated});
		;
		
		Opportunity e3 = new Opportunity ("RA", "Resident Assistant", Opportunity.OPPORTUNITY_FORMATS.PROGRAM, new ArrayList{"Leadership role", "Peer mentor", "Program facilitator", "Officer", "Student clubs/organizations"} , "The Resident Assistant position at Northeastern provides students to take on a leadership position within our campus residence halls.  Resident Assistants are responsible for engaging with residents individually, programming to the needs of their community, assisting with crisis and duty response, and performing administrative tasks.",
		new Date (2015, 8, 0), new Date (2015, 12, 0), Opportunity.OPPORTUNITY_LENGTH._30_5999_HOURS, Opportunity.LEVEL_OF_ENGAGEMENT.ACTIVE, Opportunity.OPPORTUNITY_RECURRENCE.EACH_SPRING, "Boston Campus", 
		false, 0f, "On-campus", "", "Residential Life", "David Grimes", "617-373-7590", "*****@*****.**",
		new ArrayList{"RAs will learn to be a mentor by providing support, resources, and guidance to the students residing in their community.", "RAs will gain empathy and understanding by engaging with residents individually and learn about them on a personal level.",
			"RAs will reflect on their own values and decision-making by responding to crises and incidents within their communities.", "RAs will navigate their leadership styles by working on a staff team for programming, duty response, training, and other administrative tasks."} , new ArrayList{Empathy, Open_Mindedness, Organization, Collaboration_Teamwork});
		
		
		
		addOpportunity (e1);
		TestHarness.check_test("Check adding one new opportunity", opportunityHash.Contains(e1.opportunityID)==true);
		
		addOpportunity (e2);
		TestHarness.check_test ("Check adding two new opportunities", (opportunityHash.Contains (e1.opportunityID) && opportunityHash.Contains (e2.opportunityID))==true);
		
		addOpportunity (e3);
		TestHarness.check_test ("Check adding two new opportunities", (opportunityHash.Contains (e1.opportunityID) && opportunityHash.Contains (e2.opportunityID) && opportunityHash.Contains (e3.opportunityID)) == true);
		
		
		
		//TestCheckInfo
		TestHarness.check_test ("check if the username and password are both correct: ",checkInfo ("ritter.g","admin") == true);
		
		TestHarness.check_test ("check if the username and password are both correct: ",checkInfo ("chaoID","admin") == true);
		
		TestHarness.check_test ("check if the username is correct but the password is wrong: ",checkInfo ("ritter.g","123") == false);
		
		TestHarness.check_test ("check if the username is correct but the password is wrong: ",checkInfo ("chaoID","234") == false);
		
		TestHarness.check_test ("check if we can't find the username: "******"qin.yue","admin") == false);
		
		
		
		//TestGetStudent
		
		TestHarness.check_test ("Check wheher we can get the student only given that student id: ", 
		                        (get_student("ritter.g") != null)&& (get_student("ritter.g") is Student)&&(get_student("ritter.g").huskyID.Equals("ritter.g"))==true);
		
		TestHarness.check_test ("Check wheher we can get the student only given that student id: ", 
		                        (get_student("zheng.q") != null)&& (get_student("zheng.q") is Student)&&(get_student("zheng.q").huskyID.Equals("zheng.q"))==true);
		
		TestHarness.check_test ("Check wheher we can get the student only given that student id: ", 
		                        (get_student("chaoID") != null)&& (get_student("chaoID") is Student)&&(get_student("chaoID").huskyID.Equals("chaoID"))==true);
		
		//Test AddFriend
		add_friend ("ritter.g","zheng.q");
		TestHarness.check_test ("Check whether one persoen can successfully add another friend as his friend :",
		                        ((get_student("ritter.g"))).friend_IDs.Contains("zheng.q")&&get_student("zheng.q").friend_IDs.Contains("ritter.g"));

		//Test remove_friend
		add_friend ("ritter.g","zhang.ze");
		remove_friend ("ritter.g","zheng.q");
		TestHarness.check_test ("Check whether one persoen can successfully remove another friend:",
		                        (((get_student("ritter.g"))).friend_IDs.Contains("zheng.q")||get_student("zheng.q").friend_IDs.Contains("ritter.g"))==false);
		


		//Test get_opportunity
		TestHarness.check_test ("Check whether we can get the opportunity only from id: ", get_opportunity(e1.opportunityID).opportunityID.Equals(e1.opportunityID));
		TestHarness.check_test ("Check whether we can get the opportunity only from id: ", get_opportunity(e2.opportunityID).opportunityID.Equals(e2.opportunityID));

		
		


	}
Ejemplo n.º 48
0
        /// <summary>
        /// Returns list od opportunity models.
        /// </summary>
        /// <param name="opportunities"></param>
        /// <returns></returns>
        private List<OpportunityModel> getOpportunityModels(Opportunity[] opportunities)
        {
            List<OpportunityModel> opportunityModels = new List<OpportunityModel>();

            if (opportunities == null)
            {
                return opportunityModels;
            }

            foreach (var opportunity in opportunities)
            {
                var opp = new OpportunityModel
                {
                    KeyContactId = opportunity.KeyContactId,
                    PrimaryContactPartyName = opportunity.PrimaryContactPartyName,
                    SalesAccountId = opportunity.SalesAccountId,
                    TargetPartyName = opportunity.TargetPartyName,
                    OptyId = opportunity.OptyId,
                    OptyNumber = opportunity.OptyNumber,
                    PartyName1 = opportunity.PartyName1,
                    EmailAddress = opportunity.EmailAddress,
                    Name = opportunity.Name,
                    Description = opportunity.Description,
                    StatusCode = opportunity.StatusCode,
                    SalesMethod = opportunity.SalesMethod,
                    SalesStage = opportunity.SalesStage,
                    SalesChannelCd = opportunity.SalesChannelCd,
                    CurrencyCode = opportunity.CurrencyCode,
                    Revenue = opportunity.Revenue,
                    WinProb = opportunity.WinProb,
                    CreatedBy = opportunity.CreatedBy,
                    CreationDate = opportunity.CreationDate,
                    ForecastedCloseDate = opportunity.EffectiveDate
                };

                opportunityModels.Add(opp);

            }

            return opportunityModels;

        }
Ejemplo n.º 49
0
        protected override void PerformFile(BooterHelper.BootFile file)
        {
            BooterHelper.DataBootFile dataFile = file as BooterHelper.DataBootFile;
            if (dataFile == null) return;

            XmlDbTable table = dataFile.GetTable("OpportunitiesSetup");
            if (table == null)
            {
                if (file.mPrimary)
                {
                    BooterLogger.AddTrace(file + ": No OpportunitiesSetup");
                }
                else
                {
                    BooterLogger.AddError(file + ": No OpportunitiesSetup");
                }
                return;
            }

            BooterLogger.AddTrace(file + ": Found List = " + table.Rows.Count);

            foreach (XmlDbRow row in table.Rows)
            {
                Opportunity.OpportunitySharedData data = new Opportunity.OpportunitySharedData();
                ParserFunctions.TryParseEnum<ProductVersion>(row.GetString("ProductVersion"), out data.mProductVersion, ProductVersion.BaseGame);

                data.mGuid = GenericManager<OpportunityNames, Opportunity, Opportunity>.ParseGuid(row["GUID"]);

                // New Code
                if (data.mGuid == OpportunityNames.Undefined)
                {
                    data.mGuid = unchecked((OpportunityNames)ResourceUtils.HashString64(row["GUID"]));
                }

                if (GameUtils.IsInstalled(data.mProductVersion))
                {
                    string str2 = row.GetString("Icon");
                    if (!string.IsNullOrEmpty(str2))
                    {
                        data.mIconKey = ResourceKey.CreatePNGKey(str2, 0x0);
                    }
                    ParserFunctions.TryParseEnum<Repeatability>(row["RepeatLevel"], out data.mRepeatLevel, Repeatability.Undefined);
                    data.SetFlags(Opportunity.OpportunitySharedData.FlagField.Ordered, row.GetBool("IsOrdered"));
                    data.SetFlags(Opportunity.OpportunitySharedData.FlagField.Counted, row.GetBool("IsCounted"));
                    data.SetFlags(Opportunity.OpportunitySharedData.FlagField.Totaled, row.GetBool("IsTotaled"));
                    data.mCountOrTotal = row.GetFloat("CountOrTotal", 0f);
                    string str3 = row["Timeout"];
                    if (str3 != string.Empty)
                    {
                        ParserFunctions.TryParseEnum<Opportunity.OpportunitySharedData.TimeoutCondition>(row["Timeout"], out data.mTimeout, Opportunity.OpportunitySharedData.TimeoutCondition.None);
                    }
                    if (data.mTimeout == Opportunity.OpportunitySharedData.TimeoutCondition.SimTime)
                    {
                        if (row.GetString("TimeoutData") != null)
                        {
                            data.mTimeoutData = ParserFunctions.ParseTime(row.GetString("TimeoutData"));
                        }
                        else
                        {
                            BooterLogger.AddError(file + ": TimeoutData missing " + row["GUID"]);
                        }
                    }
                    else
                    {
                        data.mTimeoutData = row.GetFloat("TimeoutData");

                        if (row.GetString("TimeoutEnd") != null)
                        {
                            data.mTimeoutEnd = ParserFunctions.ParseTime(row.GetString("TimeoutEnd"));
                        }
                        else
                        {
                            BooterLogger.AddError(file + ": TimeoutEnd missing " + row["GUID"]);
                        }
                    }
                    string name = row["Loss"];
                    if (name != string.Empty)
                    {
                        ParserFunctions.TryParseEnum<Opportunity.OpportunitySharedData.TimeoutCondition>(name, out data.mLoss, Opportunity.OpportunitySharedData.TimeoutCondition.None);
                    }
                    if (data.mLoss == Opportunity.OpportunitySharedData.TimeoutCondition.SimTime)
                    {
                        if (row.GetString("LossData") != null)
                        {
                            data.mLossData = ParserFunctions.ParseTime(row.GetString("LossData"));
                        }
                        else
                        {
                            BooterLogger.AddError(file + ": LossData missing " + row["GUID"]);
                        }
                    }
                    else
                    {
                        data.mLossData = row.GetFloat("LossData");
                    }

                    data.mChanceToGetOnPhone = row.GetFloat("ChanceToGetOnPhone");
                    row.TryGetEnum<OpportunityAvailability>("Availability", out data.mOpportunityAvailability, OpportunityAvailability.Undefined);
                    data.mOpportunityType = OpportunityType.Undefined;
                    row.TryGetEnum<OpportunityType>("OpportunityType", out data.mOpportunityType, OpportunityType.Undefined);
                    data.mEventList = OpportunityManager.ParseEvents(row, data.mGuid);
                    List<string> entry = row.GetStringList("CompletionEvent", ',', false);
                    if (entry.Count == 0x0)
                    {
                        data.mCompletionEvent = null;
                    }
                    else
                    {
                        data.mCompletionEvent = OpportunityManager.ParseOneEvent(entry, row, data.mGuid);
                        if (data.mOpportunityType == OpportunityType.Career)
                        {
                            data.mCompletionEvent.mEventDelegate = new ProcessEventDelegate(Opportunity.ProcessCompletionEventDelegateCareer);
                        }
                        else if (data.mOpportunityType == OpportunityType.Skill)
                        {
                            data.mCompletionEvent.mEventDelegate = new ProcessEventDelegate(Opportunity.ProcessCompletionEventDelegateSkill);
                        }
                        else if (data.mOpportunityType == OpportunityType.Location)
                        {
                            data.mCompletionEvent.mEventDelegate = new ProcessEventDelegate(Opportunity.ProcessCompletionEventDelegateSpecial);
                        }
                        else if (data.mOpportunityType == OpportunityType.AdventureChina)
                        {
                            data.mCompletionEvent.mEventDelegate = new ProcessEventDelegate(Opportunity.ProcessCompletionEventDelegateAdventureChina);
                        }
                        else if (data.mOpportunityType == OpportunityType.AdventureEgypt)
                        {
                            data.mCompletionEvent.mEventDelegate = new ProcessEventDelegate(Opportunity.ProcessCompletionEventDelegateAdventureEgypt);
                        }
                        else if (data.mOpportunityType == OpportunityType.AdventureFrance)
                        {
                            data.mCompletionEvent.mEventDelegate = new ProcessEventDelegate(Opportunity.ProcessCompletionEventDelegateAdventureFrance);
                        }
                    }
                    data.SetFlags(Opportunity.OpportunitySharedData.FlagField.AllowPhoneCompletion, row.GetBool("AllowPhoneCompletion"));
                    string str5 = row.GetString("CompletionProceduralTestFunction");
                    if (!string.IsNullOrEmpty(str5) && (OpportunityManager.sOpportunitiesTestClassType != null))
                    {
                        MethodInfo method = OpportunityManager.sOpportunitiesTestClassType.GetMethod(str5, BindingFlags.Public | BindingFlags.Static);
                        if (method != null)
                        {
                            data.mTargetProceduralTestDelegate = Delegate.CreateDelegate(typeof(OpportunityTargetProceduralTestDelegate), method) as OpportunityTargetProceduralTestDelegate;
                        }
                    }
                    Opportunity opportunity = null;
                    string typeName = row.GetString("CustomOpportunityClass");
                    if (typeName.Length > 0x0)
                    {
                        Type type = Type.GetType(typeName);
                        if (type != null)
                        {
                            Type[] types = new Type[] { typeof(Opportunity.OpportunitySharedData) };

                            try
                            {
                                opportunity = (Opportunity)type.GetConstructor(types).Invoke(new object[] { data });
                            }
                            catch
                            {
                                BooterLogger.AddError(file + ": Constructor Fail " + typeName);
                            }
                        }
                    }
                    else if (data.HasFlags(Opportunity.OpportunitySharedData.FlagField.Counted))
                    {
                        opportunity = new CountedOpportunity(data);
                    }
                    else if (data.HasFlags(Opportunity.OpportunitySharedData.FlagField.Totaled))
                    {
                        opportunity = new TotaledOpportunity(data);
                    }
                    else if (data.HasFlags(Opportunity.OpportunitySharedData.FlagField.Ordered))
                    {
                        opportunity = new OrderedOpportunity(data);
                    }
                    else
                    {
                        opportunity = new Opportunity(data);
                    }

                    if (opportunity != null)
                    {
                        // New code
                        GenericManager<OpportunityNames, Opportunity, Opportunity>.sDictionary[(ulong)opportunity.Guid] = opportunity;

                        if (opportunity.IsLocationBased && (opportunity.Guid != OpportunityNames.Special_RestoreGhost))
                        {
                            // New code
                            OpportunityManager.sLocationBasedOpportunityList[opportunity.Guid] = opportunity;
                            continue;
                        }
                        if (opportunity.IsSkill || (opportunity.Guid == OpportunityNames.Special_RestoreGhost))
                        {
                            // New code
                            OpportunityManager.sSkillOpportunityList[opportunity.Guid] = opportunity;
                            continue;
                        }
                        if (opportunity.IsAdventureChina)
                        {
                            // New code
                            OpportunityManager.sAdventureChinaOpportunityList[opportunity.Guid] = opportunity;
                        }
                        else
                        {
                            if (opportunity.IsAdventureEgypt)
                            {
                                // New code
                                OpportunityManager.sAdventureEgyptOpportunityList[opportunity.Guid] = opportunity;
                                continue;
                            }
                            if (opportunity.IsAdventureFrance)
                            {
                                // New code
                                OpportunityManager.sAdventureFranceOpportunityList[opportunity.Guid] = opportunity;
                            }
                        }
                    }
                }
            }

            ParseOpportunityNames(dataFile, table.Rows.Count);
            ParseOpportunityRequirements(dataFile, table.Rows.Count);
            ParseOpportunitySetup(dataFile, table.Rows.Count);
            ParseOpportunityCompletion(dataFile, table.Rows.Count);
        }
        /// <summary>
        /// Creates any entity records that this sample requires.
        /// </summary>
        public void CreateRequiredRecords()
        {

            // Create an account.
            var account = new Account
            {
                Name = "Litware, Inc.",
                Address1_StateOrProvince = "Colorado"
            };
            _accountId = (_serviceProxy.Create(account));

            // Create the two contacts.
            var contact = new Contact()
            {
                FirstName = "Ben",
                LastName = "Andrews",
                EMailAddress1 = "*****@*****.**",
                Address1_City = "Redmond",
                Address1_StateOrProvince = "WA",
                Address1_Telephone1 = "(206)555-5555",
                ParentCustomerId = new EntityReference
                {
                    Id = _accountId,
                    LogicalName = account.LogicalName
                }
            };
            _contactIdList.Add(_serviceProxy.Create(contact));

            contact = new Contact()
            {
                FirstName = "Colin",
                LastName = "Wilcox",
                EMailAddress1 = "*****@*****.**",
                Address1_City = "Bellevue",
                Address1_StateOrProvince = "WA",
                Address1_Telephone1 = "(425)555-5555",
                ParentCustomerId = new EntityReference
                {
                    Id = _accountId,
                    LogicalName = account.LogicalName
                }
            };
            _contactIdList.Add(_serviceProxy.Create(contact));

            // Create two opportunities.
            var opportunity = new Opportunity()
            {
                Name = "Litware, Inc. Opportunity 1",
                EstimatedCloseDate = DateTime.Now.AddMonths(6),
                CustomerId = new EntityReference
                {
                    Id = _accountId,
                    LogicalName = account.LogicalName
                }
            };
            _opportunityIdList.Add(_serviceProxy.Create(opportunity));

            opportunity = new Opportunity()
            {
                Name = "Litware, Inc. Opportunity 2",
                EstimatedCloseDate = DateTime.Now.AddYears(4),
                CustomerId = new EntityReference
                {
                    Id = _accountId,
                    LogicalName = account.LogicalName
                }
            };
            _opportunityIdList.Add(_serviceProxy.Create(opportunity));
        }
Ejemplo n.º 51
0
        /// <summary>
        /// Create an Opportunity in OSC
        /// </summary>
        /// <param name="opportunityModel">OpportunityModel</param>
        /// <returns></returns>
        public OpportunityModel CreateOpportunity(OpportunityModel opportunityModel)
        {
            OpportunityModel resultModel = null;
            try
            {
                if (opportunityModel != null)
                {
                    Opportunity opportunity = new Opportunity();
                    opportunity.Name = opportunityModel.Name;
                    opportunity.TargetPartyId = opportunityModel.TargetPartyId;
                    opportunity.TargetPartyIdSpecified = opportunityModel.TargetPartyIdSpecified;
                    opportunity.OwnerResourcePartyId = opportunityModel.OwnerResourcePartyId;
                    opportunity.OwnerResourcePartyIdSpecified = opportunityModel.OwnerResourcePartyIdSpecified;
                    opportunity.KeyContactId = opportunityModel.KeyContactId;
                    opportunity.KeyContactIdSpecified = opportunityModel.KeyContactIdSpecified;

                    OpportunityResource resource = new OpportunityResource();
                    resource.ResourceId = opportunityModel.OpportunityResourceModel.ResourceId;
                    resource.ResourceIdSpecified = opportunityModel.OpportunityResourceModel.ResourceIdSpecified;
                    resource.OwnerFlag = opportunityModel.OpportunityResourceModel.OwnerFlag;
                    resource.OwnerFlagSpecified = opportunityModel.OpportunityResourceModel.OwnerFlagSpecified;

                    OpportunityResource[] resources = new OpportunityResource[] { resource };
                    opportunity.OpportunityResource = resources;
                    if (!OSCCommonUtil.ValidateCurrentSiteName())
                    {
                        resultModel = new OpportunityModel();
                        resultModel.OpportunityId = OSCOpportunitiesCommon.DefaultOpportunitySalesLeadID;
                        return resultModel;
                    }
                    Opportunity result = _opportunityService._opportunityClient.createOpportunity(opportunity);

                    resultModel = new OpportunityModel();
                    resultModel.OpportunityId = result.OptyId;
                }
            }
            catch (Exception exception)
            {
                _logger.Debug("Error occured while creating opportunity. Opportunity Not Created in Sales Cloud.", exception.StackTrace);
                MessageBox.Show(OSCExceptionMessages.LeadOpportunityCannotBeCreated, OSCExceptionMessages.LeadNotCreatedTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            
            return resultModel;
        }
Ejemplo n.º 52
0
        public void CreateRequiredRecords()
        {
            // Create an account
            Account account = new Account
            {
                Name = "Fourth Coffee"
            };
            _accountId = _serviceProxy.Create(account);

            // Create an opportunity
            Opportunity newOpportunity = new Opportunity
            {
                Name = "Opportunity 1",
                CustomerId = new EntityReference
                {
                    Id = _accountId,
                    LogicalName = account.LogicalName
                }                
            };
            _opportunityId = _serviceProxy.Create(newOpportunity);
        }
Ejemplo n.º 53
0
	/*
	 * Build a string description of the given Opportunity for general searching purpose
	 * */
	public static string general_search_string (Opportunity op)
	{
		string result = "";
		string op_id = op.opportunityID + " ";
		string op_name = op.get_name () + " ";
		ArrayList op_tags = op.get_tags ();
		Debug.Log ("Tag list length: " + op_tags.Count);
		result = result + op_id + op_name;
		foreach (string t in op_tags) {
			result = result + t + "/";
		}
		result = result.ToLower ();
		return result;
	}
Ejemplo n.º 54
0
 public KillOpportunity(Opportunity.OpportunitySharedData sharedData)
     : base(sharedData)
 { }
Ejemplo n.º 55
0
	/*
	 * Build a string description of the given Opportunity for Advanced searching purpose
	 * */
	public static string advanced_search_string (Opportunity op)
	{
		string result = "";
		string op_id = op.opportunityID + " ";
		string op_name = op.get_name () + " ";
		ArrayList op_tags = op.get_tags ();
		Debug.Log ("Tag list length: " + op_tags.Count);
		result = result + op_id + op_name;
		foreach (string t in op_tags) {
			result = result + t + "/";
		}
		string op_loc = op.location + " ";
		string op_bd = op.begin_date.ToString () + " ";
		string op_ed = op.end_date.ToString () + " ";
		string type = "";

		if (op.opportunity_format == Opportunity.OPPORTUNITY_FORMATS.COURSE) {
			type = "COURSE" + " ";
		}
		if (op.opportunity_format == Opportunity.OPPORTUNITY_FORMATS.PROGRAM) {
			type = "PROGRAM" + " ";
		} else {
			type = "TRAINING" + " ";
		}

		result = result + op_loc + op_bd + op_ed + type;
		result = result.ToLower ();
		return result;
	}
Ejemplo n.º 56
0
 public RecruitOpportunity(Opportunity.OpportunitySharedData sharedData)
     : base(sharedData)
 { }
Ejemplo n.º 57
0
	/**
	 * An initializer function that fills the database with test data. Should be
	 * run as soon as the application starts. Really ugly, but kind of necessary.
	 */
	public static void initDatabase ()
	{
		studentHash.Clear ();
		tagHash.Clear ();
		opportunityHash.Clear ();

		// Set students and scores.
		Student s1 = new Student ("ritter.g", "Graham Ritter", "admin", "*****@*****.**");
		Student s2 = new Student ("zheng.q", "Qiaozhi Zheng", "admin", "*****@*****.**");
		Student s3 = new Student ("chaoID", "Chao Fang", "admin", "*****@*****.**");
		Student s4 = new Student ("parker.sar", "Sarah Parker", "admin", "*****@*****.**");
		Student s5 = new Student ("zhang.ze", "Zeqing Zhang", "admin", "*****@*****.**");
		Student s6 = new Student ("dylanID", "Dylan Mayerchak", "admin", "*****@*****.**");
		s1.score = new Score (1, 2, 3, 4, 5);
		s2.score = new Score (3, 4, 5, 6, 7);
		s3.score = new Score (1, 3, 2, 10, 2);
		s4.score = new Score (5, 24, 35, 2, 6);
		s5.score = new Score (5, 2, 2, 1, 7);
		s6.score = new Score (7, 4, 2, 8, 10);

		// Set opportunities.
		Opportunity e0 = new Opportunity ();

		Opportunity e1 = new Opportunity ("NUGOAL_1", "Northeastern University Growth Opportunities for Asian American Leaders (NU GOAL)",
		                                  Opportunity.OPPORTUNITY_FORMATS.TRAINING, new ArrayList{"Multicultural", "Leadership", "Community Engagement", "Exploring Identity"}, "Northeastern University Growth and Opportunity for Asian American Leaders is a program specifically designed for first and second year Asian American students who are looking to increase and gain experiences to empower themselves as leaders at Northeastern University and beyond. A cohort of students will be chosen based on their potential as future leaders and need for leadership development. This seven week program will focus on the intersection of leadership and Asian American racial identity through discussions and projects. It will be facilitated by current Asian American student leaders and AAC staff. Apply by December 1, 2015. View web site for more information: Website", 
		                                  new Date (2015, 12, 1), new Date (2015, 3, 0), Opportunity.OPPORTUNITY_LENGTH._3_499_HOURS, Opportunity.LEVEL_OF_ENGAGEMENT.ACTIVE, Opportunity.OPPORTUNITY_RECURRENCE.DAILY, "Boston Campus", 
		                                  true, 0f, "either", "Self-identify as Asian-American", "Asian American Center", "Kristine Din", 
		                                  "x5554", "*****@*****.**", new ArrayList{"Students will be able to define leadership in relationship to their own racial identity.", 
			"Students will be able to describe their leadership strengths.", "Students will be able to employ their leadership style and strengths in their daily lives.", "Students will be able to analyze leadership in the Asian American community.", "Students will be able to propose a meaningful intervention for building Asian American leadership capacity.", "Students will be able to assess the need for leadership development within the Asian American community at Northeastern."},
											new ArrayList{Communication, Collaboration_Teamwork, Social_Awareness, Networking, Organization, Planning});

		Opportunity e2 = new Opportunity ("PEERMENTORING", "Peer Mentoring Program", Opportunity.OPPORTUNITY_FORMATS.COURSE, new ArrayList{"Multicultural"}, "Asia Peer Mentoring program is a program for first year and transfer Asian-American students to connect with a community. Mentees will be paired with upper class students for support around themes of Asian-American identity and transition to Northeastern.", 
		                                  new Date (2015, 9, 15), new Date (2016, 5, 0), Opportunity.OPPORTUNITY_LENGTH._180_23999_HOURS, Opportunity.LEVEL_OF_ENGAGEMENT.GENERATIVE, Opportunity.OPPORTUNITY_RECURRENCE.EACH_FALL, "Boston Campus", 
		true, 0f, "either", "", "", "", "", "", new ArrayList (), new ArrayList {Communication, Collaboration_Teamwork, Intercultural_Understanding, Socially_Integrated});
		;

		Opportunity e3 = new Opportunity ("RA", "Resident Assistant", Opportunity.OPPORTUNITY_FORMATS.PROGRAM, new ArrayList{"Leadership role", "Peer mentor", "Program facilitator", "Officer", "Student clubs/organizations"}, "The Resident Assistant position at Northeastern provides students to take on a leadership position within our campus residence halls.  Resident Assistants are responsible for engaging with residents individually, programming to the needs of their community, assisting with crisis and duty response, and performing administrative tasks.",
		                                  new Date (2015, 8, 0), new Date (2015, 12, 0), Opportunity.OPPORTUNITY_LENGTH._30_5999_HOURS, Opportunity.LEVEL_OF_ENGAGEMENT.ACTIVE, Opportunity.OPPORTUNITY_RECURRENCE.EACH_SPRING, "Boston Campus", 
		                                  false, 0f, "On-campus", "", "Residential Life", "David Grimes", "617-373-7590", "*****@*****.**",
		                                  new ArrayList{"RAs will learn to be a mentor by providing support, resources, and guidance to the students residing in their community.", "RAs will gain empathy and understanding by engaging with residents individually and learn about them on a personal level.",
			"RAs will reflect on their own values and decision-making by responding to crises and incidents within their communities.", "RAs will navigate their leadership styles by working on a staff team for programming, duty response, training, and other administrative tasks."}, new ArrayList{Empathy, Open_Mindedness, Organization, Collaboration_Teamwork});

		Opportunity e4 = new Opportunity ("HALL", "Hall Council", Opportunity.OPPORTUNITY_FORMATS.PROGRAM, new ArrayList{"Campus administrative offices", "Northeastern community", "Leadership", "Community engagement", "Advocacy", "Governance"}, "Hall Councils at Northeastern provide an opportunity for residents to obtainleadership positions within their communities.  These leaders are responsible for advocating for the needs of their residents to the Resident Student Association and assisting in developing a strong and inclusive living community.",
		                                  new Date (2015, 8, 0), new Date (2016, 5, 0), Opportunity.OPPORTUNITY_LENGTH._5_899_HOURS, Opportunity.LEVEL_OF_ENGAGEMENT.ACTIVE, Opportunity.OPPORTUNITY_RECURRENCE.EACH_YEAR, "Boston Campus", 
		                                  true, 0f, "On-campus", "Must live in International Village to be on International Village Hall Council (building specific)", 
		                                  "Residential Life", "David Grimes", "617-373-7590", "*****@*****.**", 
		                                  new ArrayList{"Hall Council members will learn to be a mentor by providing support, resources, and guidance to the students residing in their community.", "Hall Council members will navigate their leadership styles by working on a staff team for programming, duty response, training, and other administrative tasks."}, 
										new ArrayList{Initiative_Resourcefulness, Independence_Autonomy, Socially_Integrated, Adaptable_Flexible, Communication, Integrity, Collaboration_Teamwork, Empathy, Social_Awareness, Open_Mindedness, Planning, Organization});

		// Fill databases.
		addStudent (s1);
		addStudent (s2);
		addStudent (s3);
		addStudent (s4);
		addStudent (s5);
		addStudent (s6);
		
		addOpportunity (e0);
		addOpportunity (e1);
		addOpportunity (e2);
		addOpportunity (e3);
		addOpportunity (e4);
	}
Ejemplo n.º 58
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Create a unit group.
        /// Retrieve the default unit.
        /// Create few products.
        /// Create new discount list and discount.
        /// Create new price list and few price list items.
        /// Create an account record.
        /// Create a new opportunity and few opportunity products.
        /// </summary>
        public void CreateRequiredRecords()
        {
            // Create a unit group
            UoMSchedule newUnitGroup = new UoMSchedule
            {
                Name = "Example Unit Group",
                BaseUoMName = "Example Primary Unit"
            };

            _unitGroupId = _serviceProxy.Create(newUnitGroup);
            Console.WriteLine("Created {0}", newUnitGroup.Name);

            // Retrieve the default unit id that was automatically created
            // when we created the Unit Group
            QueryExpression unitQuery = new QueryExpression
            {
                EntityName = UoM.EntityLogicalName,
                ColumnSet = new ColumnSet("uomid", "name"),
                Criteria = new FilterExpression
                {
                    Conditions = 
                        {
                            new ConditionExpression 
                            {
                                AttributeName = "uomscheduleid",
                                Operator = ConditionOperator.Equal,
                                Values = { _unitGroupId }
                            }
                        }
                },
                PageInfo = new PagingInfo
                {
                    PageNumber = 1,
                    Count = 1
                }
            };          
            
            // Retrieve the unit.
            UoM unit = (UoM)_serviceProxy.RetrieveMultiple(unitQuery).Entities[0];

            _defaultUnitId = unit.UoMId.Value;

            Console.WriteLine("Retrieved {0}", unit.Name);
          
            // Create a few products
            Product newProduct1 = new Product
            {
                ProductNumber = "1",
                Name = "Example Product 1",
                ProductStructure = new OptionSetValue(1),
                QuantityDecimal = 2,
                DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, 
                    _unitGroupId),
                DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId)
            };

            _product1Id = _serviceProxy.Create(newProduct1);
            Console.WriteLine("Created {0}", newProduct1.Name);

            Product newProduct2 = new Product
            {
               ProductNumber = "2",
               Name = "Example Product 2",
               ProductStructure = new OptionSetValue(1),
               QuantityDecimal = 3,
               DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, 
                   _unitGroupId),
               DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId)
            };

            _product2Id = _serviceProxy.Create(newProduct2);
            Console.WriteLine("Created {0}", newProduct2.Name);

            // Create a new discount list
            DiscountType newDiscountType = new DiscountType
            {
                Name = "Example Discount List",
                IsAmountType = false
            };

            _discountTypeId = _serviceProxy.Create(newDiscountType);
            Console.WriteLine("Created {0}", newDiscountType.Name);

            // Create a new discount
            Discount newDiscount = new Discount
            {
                DiscountTypeId = new EntityReference(DiscountType.EntityLogicalName, 
                    _discountTypeId),
                LowQuantity = 5,
                HighQuantity = 10,
                Percentage = 3
            };

            _discountId = _serviceProxy.Create(newDiscount);

            Console.WriteLine("Created new discount for the {0}.", newDiscountType.Name);

            // Create a price list
            PriceLevel newPriceList = new PriceLevel
            {
                Name = "Example Price List"
            };

            _priceListId = _serviceProxy.Create(newPriceList);
            Console.WriteLine("Created {0}", newPriceList.Name);

            // Create a price list item for the first product and apply volume discount
            ProductPriceLevel newPriceListItem1 = new ProductPriceLevel 
            {
                PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId),
                ProductId = new EntityReference(Product.EntityLogicalName, _product1Id),
                UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
                Amount = new Money(20),
                DiscountTypeId = new EntityReference(DiscountType.EntityLogicalName, 
                    _discountTypeId)
            };

            _priceListItem1Id = _serviceProxy.Create(newPriceListItem1);
            Console.WriteLine(@"Created price list item for the {0} and applied 
                volume discount.", newProduct1.Name);

            // Create a price list item for the second product
            ProductPriceLevel newPriceListItem2 = new ProductPriceLevel
            {
                PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId),
                ProductId = new EntityReference(Product.EntityLogicalName, _product2Id),
                UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
                Amount = new Money(20)
            };

            _priceListItem2Id = _serviceProxy.Create(newPriceListItem2);
            Console.WriteLine("Created price list item for the {0}.", newProduct1.Name);

            //Publish Product1
            SetStateRequest publishRequest1 = new SetStateRequest
            {
                EntityMoniker = new EntityReference(Product.EntityLogicalName, _product1Id),
                State = new OptionSetValue((int)ProductState.Active),
                Status = new OptionSetValue(1)
            };
            _serviceProxy.Execute(publishRequest1);

            //Publish Product2
            SetStateRequest publishRequest2 = new SetStateRequest
            {
                EntityMoniker = new EntityReference(Product.EntityLogicalName, _product2Id),
                State = new OptionSetValue((int)ProductState.Active),
                Status = new OptionSetValue(1)
            };
            _serviceProxy.Execute(publishRequest2);
            Console.WriteLine("Published both the products");

            // Create an account record for the opporutnity's potential customerid 
            Account newAccount = new Account
            {
                Name = "Example Account"
            };
            _accountId = _serviceProxy.Create(newAccount);

            Console.WriteLine("Created {0}", newAccount.Name);

            // Create a new opportunity
            Opportunity newOpportunity = new Opportunity
            {
                Name = "Example Opportunity",
                CustomerId = new EntityReference(Account.EntityLogicalName,
                    _accountId),
                PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName,
                    _priceListId)
            };

            _opportunityId = _serviceProxy.Create(newOpportunity);
            Console.WriteLine("Created {0}.", newOpportunity.Name);

            // Create some opportunity products
            OpportunityProduct newOpportunityProduct1 = new OpportunityProduct
            {
                OpportunityId = new EntityReference(Opportunity.EntityLogicalName,
                    _opportunityId),
                ProductId = new EntityReference(Product.EntityLogicalName,
                    _product1Id),
                UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
                Quantity = 8
            };

            _opportunityProduct1Id = _serviceProxy.Create(newOpportunityProduct1);

            OpportunityProduct newOpportunityProduct2 = new OpportunityProduct
            {
                OpportunityId = new EntityReference(Opportunity.EntityLogicalName,
                    _opportunityId),
                ProductId = new EntityReference(Product.EntityLogicalName,
                    _product2Id),
                UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
                Quantity = 1
            };

            _opportunityProduct2Id = _serviceProxy.Create(
                newOpportunityProduct2);

            Console.WriteLine("Created few opportunity products.");

            return;
        }
Ejemplo n.º 59
0
        /// <summary>
        /// This method first connects to the Organization service. Afterwards, an 
        /// opportunity is created to demonstrate a negative estimated value. This is
        /// followed by the creation of a quote with a negative product quantity. 
        /// Finally, a sales order with a negative product price is shown.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetWorkingWithNegativePrices1>
                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    #region Opportunity with negative estimated value

                    // Create a new opportunity with user-specified negative 
                    // estimated value.
                    Opportunity opportunity = new Opportunity
                    {
                        Name = "Example Opportunity",
                        CustomerId = new EntityReference(Account.EntityLogicalName,
                            _accountId),
                        PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName,
                            _priceListId),
                        IsRevenueSystemCalculated = false,
                        EstimatedValue = new Money(-400.00m),
                        FreightAmount = new Money(10.00m),
                        ActualValue = new Money(-390.00m),
                        OwnerId = new EntityReference
                        {
                            Id = _salesRepresentativeIds[0],
                            LogicalName = SystemUser.EntityLogicalName
                        }
                    };
                    _opportunityId = _serviceProxy.Create(opportunity);
                    opportunity.Id = _opportunityId;

                    // Create a catalog product for the opportunity.
                    OpportunityProduct catalogProduct = new OpportunityProduct
                    {
                        OpportunityId = opportunity.ToEntityReference(),
                        ProductId = new EntityReference(Product.EntityLogicalName,
                            _product1Id),
                        UoMId = new EntityReference(UoM.EntityLogicalName,
                            _defaultUnitId),
                        Quantity = 8,
                        Tax = new Money(12.42m),
                    };
                    _catalogProductId = _serviceProxy.Create(catalogProduct);

                    Console.WriteLine("Created opportunity with negative estimated value.");

                    #endregion

                    #region Quote with negative quantity

                    // Create the quote.
                    Quote quote = new Quote()
                    {
                        CustomerId = new EntityReference(Account.EntityLogicalName, 
                            _accountId),
                        Name = "Sample Quote",
                        PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName,
                            _priceListId)
                    };
                    _quoteId = _serviceProxy.Create(quote);
                    quote.Id = _quoteId;

                    // Set the quote's product quantity to a negative value.
                    QuoteDetail quoteDetail = new QuoteDetail()
                    {
                        ProductId = new EntityReference(Product.EntityLogicalName,
                            _product1Id),
                        Quantity = -4,
                        QuoteId = quote.ToEntityReference(),
                        UoMId = new EntityReference(UoM.EntityLogicalName, 
                            _defaultUnitId)
                    };
                    _quoteDetailId = _serviceProxy.Create(quoteDetail);

                    Console.WriteLine("Created quote with negative quantity.");

                    #endregion

                    #region Sales Order with negative price

                    // Create the sales order.
                    SalesOrder order = new SalesOrder()
                    {
                        Name = "Faux Order",
                        DateFulfilled = new DateTime(2010, 8, 1),
                        PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName,
                            _priceListId),
                        CustomerId = new EntityReference(Account.EntityLogicalName,
                            _accountId),
                        FreightAmount = new Money(20.0M)
                    };
                    _orderId = _serviceProxy.Create(order);
                    order.Id = _orderId;

                    // Add the product to the order with the price overriden with a
                    // negative value.
                    SalesOrderDetail orderDetail = new SalesOrderDetail()
                    {
                        ProductId = new EntityReference(Product.EntityLogicalName, 
                            _product1Id),
                        Quantity = 4,
                        SalesOrderId = order.ToEntityReference(),
                        IsPriceOverridden = true,
                        PricePerUnit = new Money(-40.0M),
                        UoMId = new EntityReference(UoM.EntityLogicalName, 
                            _defaultUnitId)
                    };
                    _orderDetailId = _serviceProxy.Create(orderDetail);

                    Console.WriteLine("Created order with negative price per unit.");

                    #endregion

                    DeleteRequiredRecords(promptforDelete);
                }
                //</snippetWorkingWithNegativePrices1>
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Ejemplo n.º 60
0
        public Application CreateApplication(Opportunity opportunity)
        {
            //check if already applied for this opportunity
            var app = Applications.FirstOrDefault(a => a.Opportunity.Id == opportunity.Id);

            if (app == null)
                app = Application.NewApplication(opportunity);

            Applications.Add(app);

            return app;
            // Raise event
        }