Microsoft.Xrm.Sdk.Entity.GetAttributeValue(string)

Here are the examples of the csharp api Microsoft.Xrm.Sdk.Entity.GetAttributeValue(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

748 Examples 7

19 View Source File : OrderStatus.aspx.cs
License : MIT License
Project Creator : Adoxio

protected void AddNote_Click(object sender, EventArgs e)
		{
			if (OrderToEdit == null || (OrderToEdit.GetAttributeValue<EnreplacedyReference>("customerid") != null && !OrderToEdit.GetAttributeValue<EnreplacedyReference>("customerid").Equals(Contact.ToEnreplacedyReference())))
			{
				throw new InvalidOperationException("Unable to retrieve the order.");
			}

			if (!string.IsNullOrEmpty(NewNoteText.Text) ||
				(NewNoteAttachment.PostedFile != null && NewNoteAttachment.PostedFile.ContentLength > 0))
			{
				var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(
					requestContext: Request.RequestContext, portalName: PortalName);

				var dataAdapter = new AnnotationDataAdapter(dataAdapterDependencies);
				
				var annotation = new Annotation
				{
					NoteText = string.Format("{0}{1}", AnnotationHelper.WebAnnotationPrefix, NewNoteText.Text),
					Subject = AnnotationHelper.BuildNoteSubject(dataAdapterDependencies),
					Regarding = OrderToEdit.ToEnreplacedyReference()
				};
				if (NewNoteAttachment.PostedFile != null && NewNoteAttachment.PostedFile.ContentLength > 0)
				{
					annotation.FileAttachment = AnnotationDataAdapter.CreateFileAttachment(new HttpPostedFileWrapper(NewNoteAttachment.PostedFile));
				}
				dataAdapter.CreateAnnotation(annotation);
			}

			Response.Redirect(Request.Url.PathAndQuery);
		}

19 View Source File : EditCustomerAccount.aspx.cs
License : MIT License
Project Creator : Adoxio

protected void SetPrimaryContactButton_Click(object sender, EventArgs e)
		{
			var selectedGuid = new Guid(PrimaryContactList.SelectedItem.Value);

			var contact = XrmContext.CreateQuery("contact").FirstOrDefault(c => c.GetAttributeValue<Guid>("contactid") == selectedGuid);

			if (contact == null)
			{
				throw new ApplicationException(string.Format("Couldn't find contact with contactid equal to {0}.", selectedGuid));
			}

			var account = XrmContext.CreateQuery("account").FirstOrDefault(a => a.GetAttributeValue<Guid>("accountid") == AccountToEdit.GetAttributeValue<Guid>("accountid"));

			if (account == null)
			{
				throw new ApplicationException(string.Format("An account with the account ID equal to {0} couldn’t be found.", AccountToEdit.GetAttributeValue<Guid>("accountid")));
			}

			account.SetAttributeValue("primarycontactid", contact.ToEnreplacedyReference());

			XrmContext.UpdateObject(contact);
			XrmContext.UpdateObject(account);
			XrmContext.SaveChanges();

			SuccessMessage.Visible = true;
		}

19 View Source File : EditCustomerAccount.aspx.cs
License : MIT License
Project Creator : Adoxio

private void BindPrimaryContact()
		{
			var empli = new Lisreplacedem
			{
				Text = " ",
			};

			PrimaryContactList.Items.Add(empli);

			var contacts = ServiceContext.CreateQuery("contact").Where(c => c.GetAttributeValue<EnreplacedyReference>("parentcustomerid") != null && c.GetAttributeValue<EnreplacedyReference>("parentcustomerid").Equals(AccountToEdit.ToEnreplacedyReference())).ToList();

			foreach (var contact in contacts)
			{
				var li = new Lisreplacedem
				{
					Text = contact.GetAttributeValue<string>("fullname"),
					Value = contact.GetAttributeValue<Guid>("contactid").ToString()
				};

				if ((AccountToEdit.GetAttributeValue<EnreplacedyReference>("primarycontactid") != null) && (li.Value == AccountToEdit.GetAttributeValue<EnreplacedyReference>("primarycontactid").Id.ToString()))
				{
					li.Selected = true;
				}

				PrimaryContactList.Items.Add(li);
			}

			if (contacts.Count < 1)
			{
				PrimaryContactList.Enabled = false;

				NoContactsExistWarningMessage.Visible = true;
			}
		}

19 View Source File : EventFeedback.aspx.cs
License : MIT License
Project Creator : Adoxio

protected string GetEventNameFromSchedule(OrganizationServiceContext context, Enreplacedy schedule)
		{
			if (schedule == null)
			{
				return string.Empty;
			}

			var session = schedule.GetRelatedEnreplacedy(context, new Relationship("adx_event_eventschedule"));

			return session == null ? string.Empty : session.GetAttributeValue<string>("adx_name");
		}

19 View Source File : Product.aspx.cs
License : MIT License
Project Creator : Adoxio

protected void Page_Load(object sender, EventArgs e)
		{
			if (IsPostBack)
			{
				return;
			}

			var context = ServiceContext;

			var webPage = Enreplacedy;

			if (webPage == null || webPage.GetAttributeValue<EnreplacedyReference>("adx_subjectid") == null)
			{
				return;
			}

			var products =
				from product in context.GetProductsBySubject(webPage.GetAttributeValue<EnreplacedyReference>("adx_subjectid").Id)
				select new
				{
					Name = product.GetAttributeValue<string>("name"),
					ProductId = product.GetAttributeValue<Guid>("productid"),
					ProductNumber = product.GetAttributeValue<string>("productnumber"),
					Price = (context.GetProductPriceByPriceListName(product, Website, PriceListName) ?? new Money(0)).Value.ToString("C2")
				};

			Products.DataSource = products;
			Products.DataBind();
		}

19 View Source File : QuoteStatus.aspx.cs
License : MIT License
Project Creator : Adoxio

protected void ConvertToOrder_Click(object sender, EventArgs args)
		{
			var quoteToEditEnreplacedy = QuoteToEdit != null ? QuoteToEdit.Enreplacedy : null;

			if (quoteToEditEnreplacedy == null || (quoteToEditEnreplacedy.GetAttributeValue<EnreplacedyReference>("customerid") != null && !quoteToEditEnreplacedy.GetAttributeValue<EnreplacedyReference>("customerid").Equals(Contact.ToEnreplacedyReference())))
			{
				throw new InvalidOperationException("Unable to retrieve the quote.");
			}

			Enreplacedy order;
			
			try
			{
				order = QuoteToEdit.CreateOrder();

				if (order == null)
				{
					ConvertToOrderError.Visible = true;

					return;
				}
			}
			catch (Exception e)
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, e.ToString());

                ConvertToOrderError.Visible = true;

				return;
			}

			var orderid = order.GetAttributeValue<Guid>("salesorderid");

			if (!ServiceContext.IsAttached(Website))
			{
				ServiceContext.Attach(Website);
			}

			var page = ServiceContext.GetPageBySiteMarkerName(Website, "View Order") ?? ServiceContext.GetPageBySiteMarkerName(Website, "Order Status");

			if (page == null)
			{
				return;
			}

			var url = new UrlBuilder(ServiceContext.GetUrl(page));

			url.QueryString.Set("OrderID", orderid.ToString());

			Response.Redirect(url.PathWithQueryString);
		}

19 View Source File : NewsFeedHandler.cs
License : MIT License
Project Creator : Adoxio

private static IEnumerable<SyndicationItem> GetSyndicationItems(OrganizationServiceContext serviceContext, EnreplacedyReference newsRootPage)
		{
			var securityProvider = PortalCrmConfigurationManager.CreateCrmEnreplacedySecurityProvider();

			return serviceContext.CreateQuery("adx_webpage")
				.Where(e => e.GetAttributeValue<EnreplacedyReference>("adx_parentpageid") == newsRootPage)
				.OrderByDescending(e => e.GetAttributeValue<DateTime?>("adx_displaydate"))
				.Take(20)
				.ToArray()
				.Where(e => securityProvider.Tryreplacedert(serviceContext, e, CrmEnreplacedyRight.Read))
				.Select(e => GetSyndicationItem(serviceContext, e));
		}

19 View Source File : NewsFeedHandler.cs
License : MIT License
Project Creator : Adoxio

private static SyndicationItem GetSyndicationItem(OrganizationServiceContext serviceContext, Enreplacedy newsItemPage)
		{
			var displayDate = newsItemPage.GetAttributeValue<DateTime?>("adx_displaydate");

			var item = new SyndicationItem(
				newsItemPage.GetAttributeValue<string>("adx_replacedle") ?? newsItemPage.GetAttributeValue<string>("adx_name"),
				SyndicationContent.CreateHtmlContent(newsItemPage.GetAttributeValue<string>("adx_copy") ?? string.Empty),
				new Uri(new UrlBuilder(serviceContext.GetUrl(newsItemPage))),
				"uuid:{0}".FormatWith(newsItemPage.Id),
				displayDate.GetValueOrDefault(newsItemPage.GetAttributeValue<DateTime?>("modifiedon").GetValueOrDefault(DateTime.UtcNow)));

			if (displayDate != null)
			{
				item.PublishDate = displayDate.Value;
			}

			return item;
		}

19 View Source File : Sponsors.aspx.cs
License : MIT License
Project Creator : Adoxio

protected IEnumerable<Enreplacedy> GetSponsorsByCategory(int? category)
		{
			return category == null ?
				new Enreplacedy[] { }
				: _sponsors.Where(es => es.GetAttributeValue<OptionSetValue>("adx_sponsorshipcategory") != null
					&& es.GetAttributeValue<OptionSetValue>("adx_sponsorshipcategory").Value == category);
		}

19 View Source File : CreateCustomerContact.aspx.cs
License : MIT License
Project Creator : Adoxio

private void PopulateDropDownList(EnreplacedyReference managingPartner)
		{
			if (managingPartner == null)
			{
				return;
			}

			CompanyNameList.Items.Add(new Lisreplacedem("None"));

			var accounts =
				ServiceContext.CreateQuery("account")
					.Where(
						a =>
							a.GetAttributeValue<EnreplacedyReference>("msa_managingpartnerid") != null &&
							a.GetAttributeValue<EnreplacedyReference>("msa_managingpartnerid").Equals(managingPartner))
					.OrderBy(a => a.GetAttributeValue<string>("name"));

			foreach (var account in accounts)
			{
				var li = new Lisreplacedem
				{
					Text = account.GetAttributeValue<string>("name"),
					Value = account.GetAttributeValue<Guid>("accountid").ToString()
				};

				if ((ParentCustomerAccount != null) && (account.GetAttributeValue<Guid>("accountid") == ParentCustomerAccount.GetAttributeValue<Guid>("accountid")))
				{
					li.Selected = true;
				}

				CompanyNameList.Items.Add(li);
			}
		}

19 View Source File : EditCustomerAccount.aspx.cs
License : MIT License
Project Creator : Adoxio

protected void Page_Load(object sender, EventArgs e)
		{
			RedirectToLoginIfAnonymous();

			if (AccountToEdit == null)
			{
				RecordNotFoundError.Visible = true;

				EditAccountForm.Visible = false;

				return;
			}

			var formViewDataSource = new CrmDataSource { ID = "WebFormDataSource", CrmDataContextName = FormView.ContextName };
			var managingPartnerAccount = ServiceContext.CreateQuery("account").FirstOrDefault(a => a.GetAttributeValue<Guid>("accountid") == (AccountToEdit.GetAttributeValue<EnreplacedyReference>("msa_managingpartnerid") == null ? Guid.Empty : AccountToEdit.GetAttributeValue<EnreplacedyReference>("msa_managingpartnerid").Id));
			var channelPermission = ServiceContext.GetChannelAccessByContact(Contact);
			var channelCreateAccess = (channelPermission != null && channelPermission.GetAttributeValue<bool?>("adx_create").GetValueOrDefault(false));
			var channelWriteAccess = (channelPermission != null && channelPermission.GetAttributeValue<bool?>("adx_write").GetValueOrDefault(false));
			var channelPermissionForParentAccountExists = managingPartnerAccount != null && channelPermission != null && channelPermission.GetAttributeValue<EnreplacedyReference>("adx_accountid") != null && channelPermission.GetAttributeValue<EnreplacedyReference>("adx_accountid").Equals(managingPartnerAccount.ToEnreplacedyReference());
			var validAcccountClreplacedificationCode = managingPartnerAccount != null && managingPartnerAccount.GetAttributeValue<OptionSetValue>("accountclreplacedificationcode") != null && managingPartnerAccount.GetAttributeValue<OptionSetValue>("accountclreplacedificationcode").Value == (int)Enums.AccountClreplacedificationCode.Partner;
			
			if (channelPermission == null)
			{
				NoChannelPermissionsRecordError.Visible = true;

				EditAccountForm.Visible = false;

				ContactsList.Visible = false;

				return;
			}

			if (!channelWriteAccess)
			{
				ChannelPermissionsError.Visible = true;
			}
			else
			{
				if (managingPartnerAccount == null)
				{
					NoParentAccountError.Visible = true;
				}
				else if (!validAcccountClreplacedificationCode)
				{
					ParentAccountClreplacedificationCodeError.Visible = true;
				}
				else if (!channelPermissionForParentAccountExists)
				{
					NoChannelPermissionsForParentAccountError.Visible = true;
				}
			}

			if (!channelWriteAccess || managingPartnerAccount == null || !channelPermissionForParentAccountExists || !validAcccountClreplacedificationCode)
			{
				EditAccountForm.Visible = false;

				ContactsList.Visible = false;

				return;
			}

			CreateContactButton.Visible = channelCreateAccess;

			CreateContactButton.QueryStringCollection = CreateCustomerContactQueryStringCollection();

			var fetchXml = string.Format("<fetch mapping='logical'><enreplacedy name='{0}'><all-attributes /><filter type='and'><condition attribute = '{1}' operator='eq' value='{{{2}}}'/></filter></enreplacedy></fetch>", "account", "accountid", AccountToEdit.GetAttributeValue<Guid>("accountid"));

			formViewDataSource.FetchXml = fetchXml;

			AccountForm.Controls.Add(formViewDataSource);

			FormView.DataSourceID = "WebFormDataSource";

			if (!IsPostBack)
			{
				BindPrimaryContact();

				var contacts = ServiceContext.CreateQuery("contact").Where(c => c.GetAttributeValue<EnreplacedyReference>("parentcustomerid") != null && c.GetAttributeValue<EnreplacedyReference>("parentcustomerid").Equals(AccountToEdit.ToEnreplacedyReference()));

				_contacts = EnumerableExtensions.CopyToDataTable(contacts.Select(c => new
				{
					contactid = c.GetAttributeValue<Guid>("contactid"),
					ID = c.GetAttributeValue<string>("fullname"),
					CompanyName = c.GetRelatedEnreplacedy(ServiceContext, new Relationship("contact_customer_accounts")) == null ? string.Empty : c.GetRelatedEnreplacedy(ServiceContext, new Relationship("contact_customer_accounts")).GetAttributeValue<string>("name"),
					City = c.GetAttributeValue<string>("address1_city"),
					State = c.GetAttributeValue<string>("address1_stateorprovince"),
					Phone = c.GetAttributeValue<string>("address1_telephone1"),
					Email = c.GetAttributeValue<string>("emailaddress1"),
				}).ToList().OrderBy(c => c.CompanyName));

				_contacts.Columns["City"].ColumnName = "City";
				_contacts.Columns["State"].ColumnName = "State";
				_contacts.Columns["Phone"].ColumnName = "Phone";
				_contacts.Columns["Email"].ColumnName = "E-mail Address";

				AccountContactsList.DataKeyNames = new[] { "contactid" };
				AccountContactsList.DataSource = _contacts;
				AccountContactsList.DataBind();
			}
		}

19 View Source File : UrlMapping.cs
License : MIT License
Project Creator : Adoxio

private static Enreplacedy LookupPageByUrlPath(OrganizationServiceContext context, Enreplacedy website, string urlPath, Func<Enreplacedy, bool> predicate)
		{
			website.replacedertEnreplacedyName("adx_website");

			if (website.Id == Guid.Empty) throw new NullReferenceException("Unable to retrieve the Id of the website.  Lookup failed.");

			var urlWithoutWebsitePath = WebsitePathUtility.ToRelative(website, urlPath);

			var webPages = website.GetRelatedEnreplacedies(context, "adx_website_webpage").Where(predicate);

			// Check if we can find a page with the exact URL.
			var page = webPages.Where(wp => string.Compare(wp.GetAttributeValue<string>("adx_partialurl"), urlWithoutWebsitePath, StringComparison.InvariantCultureIgnoreCase) == 0).FirstOrDefault();

			if (page != null)
			{
				// We found the page (probably root).
				return page;
			}

			string parentPath;
			string thisPath;

			if (ParseParentPath(urlWithoutWebsitePath, out parentPath, out thisPath))
			{
				var parentPage = LookupPageByUrlPath(context, website, parentPath, predicate);

				if (parentPage != null)
				{
					page = context.GetChildPages(parentPage).Where(p => predicate(p) && string.Equals(p.GetAttributeValue<string>("adx_partialurl"), thisPath, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();

					if (page != null)
					{
						return page;
					}
				}
			}

			return null;
		}

19 View Source File : EditPortalContact.aspx.cs
License : MIT License
Project Creator : Adoxio

protected void Page_Load(object sender, EventArgs e)
		{
			RedirectToLoginIfAnonymous();

			if (ContactToEdit == null)
			{
				RecordNotFoundError.Visible = true;

				ContactInformation.Visible = false;

				return;
			}

			var parentAccount = Contact.GetAttributeValue<EnreplacedyReference>("parentcustomerid") == null ? null : XrmContext.CreateQuery("account").FirstOrDefault(a => a.GetAttributeValue<Guid>("accountid") == Contact.GetAttributeValue<EnreplacedyReference>("parentcustomerid").Id);
			var accountAccessPermissionsForParentAccount = parentAccount == null ? new List<Enreplacedy>() : XrmContext.GetAccountAccessByContact(Contact).Where(a => a.GetAttributeValue<EnreplacedyReference>("adx_accountid") != null && a.GetAttributeValue<EnreplacedyReference>("adx_accountid").Equals(parentAccount.ToEnreplacedyReference())).ToList();
			var contactAccessPermissions = parentAccount == null ? new List<Enreplacedy>() : XrmContext.GetContactAccessByContact(Contact).ToList();
			var contactAccessPermissionsForParentAccount = parentAccount == null ? new List<Enreplacedy>() : contactAccessPermissions.Where(c => c.GetAttributeValue<EnreplacedyReference>("adx_accountid") != null && c.GetAttributeValue<EnreplacedyReference>("adx_accountid").Equals(parentAccount.ToEnreplacedyReference()) && c.GetAttributeValue<OptionSetValue>("adx_scope").Value == (int)Enums.ContactAccessScope.Account).ToList();
			var canEditContacts = false;
			var canReadContacts = false;
			var canManagePermissions = false;

			if (parentAccount == null)
			{
				ContactInformation.Visible = false;
				
				NoParentAccountError.Visible = true;

				return;
			}

			if (!contactAccessPermissions.Any())
			{
				ContactInformation.Visible = false;

				NoContactAccessPermissionsRecordError.Visible = true;

				return;
			}

			if (!contactAccessPermissionsForParentAccount.Any())
			{
				ContactInformation.Visible = false;

				NoContactAccessPermissionsForParentAccountError.Visible = true;

				return;
			}

			foreach (var access in contactAccessPermissionsForParentAccount)
			{
				if (access.GetAttributeValue<bool?>("adx_write").GetValueOrDefault(false))
				{
					canEditContacts = true;
					canReadContacts = true;
				}
				if (access.GetAttributeValue<bool?>("adx_read").GetValueOrDefault(false))
				{
					canReadContacts = true;
				}
			}

			foreach (var access in accountAccessPermissionsForParentAccount)
			{
				if (access.GetAttributeValue<bool?>("adx_managepermissions").GetValueOrDefault(false))
				{
					canManagePermissions = true;
				}
			}
			
			if (!canReadContacts)
			{
				ContactInformation.Visible = false;

				return;
			}

			if (!canEditContacts)
			{
				ContactEditFormView.Visible = false;

				ContactReadOnlyFormView.Visible = true;

				ContactAccessWritePermissionDeniedMessage.Visible = true;
			}

			ManagePermissionsButton.Visible = canManagePermissions;
			
			var formViewDataSource = new CrmDataSource { ID = "WebFormDataSource", CrmDataContextName = ContactEditFormView.ContextName };

			var fetchXml = string.Format("<fetch mapping='logical'><enreplacedy name='{0}'><all-attributes /><filter type='and'><condition attribute = '{1}' operator='eq' value='{{{2}}}'/></filter></enreplacedy></fetch>", "contact", "contactid", ContactToEdit.GetAttributeValue<Guid>("contactid"));

			formViewDataSource.FetchXml = fetchXml;

			ContactInformation.Controls.Add(formViewDataSource);

			ContactEditFormView.DataSourceID = "WebFormDataSource";

			ContactReadOnlyFormView.DataSourceID = "WebFormDataSource";
		}

19 View Source File : AcceptedOpportunities.aspx.cs
License : MIT License
Project Creator : Adoxio

protected void Page_Load(object sender, EventArgs e)
		{
			RedirectToLoginIfAnonymous();

			replacedertContactHasParentAccount();

			var opportunities = Enumerable.Empty<Enreplacedy>();

			if (string.Equals(CustomerDropDown.Text, "My", StringComparison.InvariantCulture))
			{
				opportunities = ServiceContext.GetOpportunitiesSpecificToContact(Contact)
					.Where(o => o.GetAttributeValue<OptionSetValue>("statuscode") != null && o.GetAttributeValue<OptionSetValue>("statuscode").Value != (int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.Delivered
								&& o.GetAttributeValue<OptionSetValue>("statuscode").Value != (int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.Declined);
			}
			else //if (string.Equals(CustomerFilter.Text, "All", StringComparison.InvariantCulture))
			{
				opportunities = ServiceContext.GetOpportunitiesForContact(Contact)
					.Where(o => o.GetAttributeValue<OptionSetValue>("statuscode") != null && o.GetAttributeValue<OptionSetValue>("statuscode").Value != (int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.Delivered
								&& o.GetAttributeValue<OptionSetValue>("statuscode").Value != (int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.Declined && o.GetAttributeValue<EnreplacedyReference>("msa_partnerid") != null &&
					o.GetAttributeValue<EnreplacedyReference>("msa_partnerid").Equals(Contact.GetAttributeValue<EnreplacedyReference>("parentcustomerid")));
			}
			//var searchQuery = Request["query"];

			if (!IsPostBack)
			{
				PopulateCustomerFilter(ServiceContext, Contact);
			}

			HideControlsBasedOnAccess(ServiceContext, Contact);

			if (string.Equals(StatusDropDown.Text, "Open", StringComparison.InvariantCulture))
			{
				opportunities = opportunities.Where(o => o.GetAttributeValue<OptionSetValue>("statecode") != null && o.GetAttributeValue<OptionSetValue>("statecode").Value == (int)Adxstudio.Xrm.Partner.Enums.OpportunityState.Open);
			}
			else if (string.Equals(StatusDropDown.Text, "Won", StringComparison.InvariantCulture))
			{
				opportunities = opportunities.Where(o => o.GetAttributeValue<OptionSetValue>("statecode") != null && o.GetAttributeValue<OptionSetValue>("statecode").Value == (int)Adxstudio.Xrm.Partner.Enums.OpportunityState.Won);
			}
			else if (string.Equals(StatusDropDown.Text, "Lost", StringComparison.InvariantCulture))
			{
				opportunities = opportunities.Where(o => o.GetAttributeValue<OptionSetValue>("statecode") != null && o.GetAttributeValue<OptionSetValue>("statecode").Value == (int)Adxstudio.Xrm.Partner.Enums.OpportunityState.Lost);
			}

			if (!string.IsNullOrEmpty(SearchText.Text))
			{
				opportunities =
					from o in opportunities
					join a in ServiceContext.CreateQuery("account") on o.GetAttributeValue<EnreplacedyReference>("customerid").Id equals
						a.GetAttributeValue<Guid>("accountid")
					where o.GetAttributeValue<EnreplacedyReference>("customerid") != null
					where
						a.GetAttributeValue<string>("name").ToLower().Contains(SearchText.Text.ToLower()) ||
							(!string.IsNullOrEmpty(o.GetAttributeValue<string>("adx_referencecode")) &&
								o.GetAttributeValue<string>("adx_referencecode").IndexOf(SearchText.Text.ToLower(), StringComparison.OrdinalIgnoreCase) >= 0)
					select o;
			}

			_opportunities = EnumerableExtensions.CopyToDataTable(opportunities.Select(opp => new
			{
				opportunityid = opp.GetAttributeValue<Guid>("opportunityid"),
				ID = opp.GetAttributeValue<string>("adx_referencecode"),
				Accepted = opp.GetAttributeValue<DateTime?>("adx_accepteddate").HasValue ? opp.GetAttributeValue<DateTime?>("adx_accepteddate").GetValueOrDefault().ToString("yyyy/MM/dd") : null,
				CompanyName = opp.GetRelatedEnreplacedy(ServiceContext, new Relationship("opportunity_customer_accounts")) != null ? opp.GetRelatedEnreplacedy(ServiceContext, new Relationship("opportunity_customer_accounts")).GetAttributeValue<string>("name") : " ",
				City = opp.GetRelatedEnreplacedy(ServiceContext, new Relationship("opportunity_customer_accounts")) != null ? opp.GetRelatedEnreplacedy(ServiceContext, new Relationship("opportunity_customer_accounts")).GetAttributeValue<string>("address1_city") : " ",
				Territory = opp.GetRelatedEnreplacedy(ServiceContext, new Relationship("adx_territory_opportunity")) != null ? opp.GetRelatedEnreplacedy(ServiceContext, new Relationship("adx_territory_opportunity")).GetAttributeValue<string>("name") : " ",
				Products = string.Join(", ", opp.GetRelatedEnreplacedies(ServiceContext, new Relationship("adx_opportunity_product")).Select(product => product.GetAttributeValue<string>("name"))),
				EstRevenue = opp.GetAttributeValue<Money>("estimatedvalue") != null ? opp.GetAttributeValue<Money>("estimatedvalue").Value.ToString("C") : null,
				EstClose = opp.GetAttributeValue<DateTime?>("estimatedclosedate").HasValue ? opp.GetAttributeValue<DateTime?>("estimatedclosedate").GetValueOrDefault().ToString("yyyy/MM/dd") : null,
				replacedignedTo = (opp.GetRelatedEnreplacedy(ServiceContext, new Relationship("msa_contact_opportunity")) != null) ? opp.GetRelatedEnreplacedy(ServiceContext, new Relationship("msa_contact_opportunity")).GetAttributeValue<string>("fullname") : " ",
				Status = Enum.GetName(typeof(Adxstudio.Xrm.Partner.Enums.OpportunityState), opp.GetAttributeValue<OptionSetValue>("statecode").Value),
			}).OrderBy(opp => opp.CompanyName));

			_opportunities.Columns["ID"].ColumnName = "Topic";
			_opportunities.Columns["CompanyName"].ColumnName = "Company Name";
			_opportunities.Columns["EstRevenue"].ColumnName = "Est. Revenue";
			_opportunities.Columns["EstClose"].ColumnName = "Est. Purchase";
			_opportunities.Columns["replacedignedTo"].ColumnName = "replacedigned To";

			AcceptedOpportunitiesList.DataKeyNames = new[] { "opportunityid" };
			AcceptedOpportunitiesList.DataSource = _opportunities;
			AcceptedOpportunitiesList.DataBind();
		}

19 View Source File : CitizenProfile.aspx.cs
License : MIT License
Project Creator : Adoxio

public void ManageLists(OrganizationServiceContext context, Enreplacedy contact)
		{
			foreach (var item in MarketingListsListView.Items)
			{
				if (item == null)
				{
					continue;
				}

				var listViewItem = item;

				var hiddenListId = (HiddenField)listViewItem.FindControl("ListID");

				if (hiddenListId == null)
				{
					continue;
				}

				var listId = new Guid(hiddenListId.Value);

				var ml = context.CreateQuery("list").First(m => m.GetAttributeValue<Guid>("listid") == listId);

				var listCheckBox = (CheckBox)item.FindControl("ListCheckbox");

				if (listCheckBox == null)
				{
					continue;
				}

				var contactLists = contact.GetRelatedEnreplacedies(XrmContext, new Relationship("listcontact_replacedociation")).ToList();

				var inList = contactLists.Any(list => list.GetAttributeValue<Guid>("listid") == ml.Id);

				if (listCheckBox.Checked && !inList)
				{
					context.AddMemberList(ml.GetAttributeValue<Guid>("listid"), contact.GetAttributeValue<Guid>("contactid"));
				}
				else if (!listCheckBox.Checked && inList)
				{
					context.RemoveMemberList(ml.GetAttributeValue<Guid>("listid"), contact.GetAttributeValue<Guid>("contactid"));
				}
			}
		}

19 View Source File : WebFormSupportRequestSelectOrder.ascx.cs
License : MIT License
Project Creator : Adoxio

private void PopulatePlanPackageList()
		{
			PlanPackageList.Items.Clear();

			var supportRequest = XrmContext.CreateQuery("adx_supportrequest")
				.FirstOrDefault(sr => sr.GetAttributeValue<Guid>("adx_supportrequestid") == CurrentStepEnreplacedyID);
			if (supportRequest == null)
			{
				throw new ApplicationException(string.Format("Couldn't find support request record with id equal to {0}.", CurrentStepEnreplacedyID));
			}
			var supportRequestProductReference = supportRequest.GetAttributeValue<EnreplacedyReference>("adx_product");
			var parentProduct = supportRequestProductReference == null ? null : XrmContext.CreateQuery("product").FirstOrDefault(pp => pp.GetAttributeValue<Guid>("productid") == supportRequestProductReference.Id);
			IQueryable<Enreplacedy> supportProducts;
			if (parentProduct != null)
			{
				supportProducts = from product in XrmContext.CreateQuery("product")
								join supportedset in XrmContext.CreateQuery("adx_supportedproduct_productplan") on product.GetAttributeValue<Guid>("productid") equals supportedset.GetAttributeValue<Guid>("productidone")
								join supportedProduct in XrmContext.CreateQuery("product") on supportedset.GetAttributeValue<Guid>("productidtwo") equals supportedProduct.GetAttributeValue<Guid>("productid")
								where product.GetAttributeValue<OptionSetValue>("statecode") != null && product.GetAttributeValue<OptionSetValue>("statecode").Value == 0
								where product.GetAttributeValue<Guid>("productid") == parentProduct.GetAttributeValue<Guid>("productid")
								where supportedProduct.GetAttributeValue<OptionSetValue>("producttypecode") != null && supportedProduct.GetAttributeValue<OptionSetValue>("producttypecode").Value == (int)ProductTypeCode.SupportPlan
								select supportedProduct;
			}
			else
			{
				supportProducts = XrmContext.CreateQuery("product").Where(p => p.GetAttributeValue<OptionSetValue>("statecode") != null && p.GetAttributeValue<OptionSetValue>("statecode").Value == 0 && p.GetAttributeValue<OptionSetValue>("producttypecode") != null && p.GetAttributeValue<OptionSetValue>("producttypecode").Value == (int)ProductTypeCode.SupportPlan);
			}
			
			foreach (var supportProduct in supportProducts)
			{
				var supportUnit =
					XrmContext.CreateQuery("uomschedule").FirstOrDefault(unit => unit.GetAttributeValue<Guid>("uomscheduleid") == (supportProduct.GetAttributeValue<EnreplacedyReference>("defaultuomscheduleid") == null ? Guid.Empty : supportProduct.GetAttributeValue<EnreplacedyReference>("defaultuomscheduleid").Id));

				var baseUom = XrmContext.CreateQuery("uom").FirstOrDefault(baseuom => baseuom.GetAttributeValue<string>("name") == supportUnit.GetAttributeValue<string>("baseuomname"));

				var uoms = XrmContext.CreateQuery("uom").Where(uom => uom.GetAttributeValue<Guid>("baseuom") == baseUom.Id);

				foreach (var u in uoms)
				{
					var amount = new Money(0);
					var priceLisreplacedem = XrmContext.GetPriceLisreplacedemByPriceListNameAndUom(supportProduct.GetAttributeValue<Guid>("productid"), u.Id, PriceListName);
					
					if (priceLisreplacedem != null)
					{
						amount = priceLisreplacedem.GetAttributeValue<Money>("amount");
					}

					PlanPackageList.Items.Add(new Lisreplacedem(
												string.Format("{0} - {1} - {2}", supportProduct.GetAttributeValue<string>("name"), u.GetAttributeValue<string>("name"), amount.Value.ToString("c0")),
												string.Format("{0}&{1}", supportProduct.GetAttributeValue<Guid>("productid"), u.GetAttributeValue<Guid>("uomid"))));
				}
			}
		}

19 View Source File : IssuesController.cs
License : MIT License
Project Creator : Adoxio

private static Enreplacedy GetIssue(string issuePartialUrl, Enreplacedy issueForum, OrganizationServiceContext context)
		{
			var issue = context.CreateQuery("adx_issue")
				.FirstOrDefault(adxIssue => adxIssue.GetAttributeValue<EnreplacedyReference>("adx_issueforumid") == issueForum.ToEnreplacedyReference()
					&& adxIssue.GetAttributeValue<string>("adx_partialurl") == issuePartialUrl
					&& adxIssue.GetAttributeValue<bool?>("adx_approved").GetValueOrDefault(false)
					&& adxIssue.GetAttributeValue<OptionSetValue>("statecode") != null && adxIssue.GetAttributeValue<OptionSetValue>("statecode").Value == 0);
			
			return issue;
		}

19 View Source File : IssuesController.cs
License : MIT License
Project Creator : Adoxio

private static Enreplacedy GetIssueForum(string issueForumPartialUrl, OrganizationServiceContext context)
		{
			var website = PortalCrmConfigurationManager.CreatePortalContext().Website;

			var issueForum = context.CreateQuery("adx_issueforum")
				.FirstOrDefault(forum => forum.GetAttributeValue<EnreplacedyReference>("adx_websiteid") == website.ToEnreplacedyReference()
					&& forum.GetAttributeValue<string>("adx_partialurl") == issueForumPartialUrl
					&& forum.GetAttributeValue<OptionSetValue>("statecode") != null && forum.GetAttributeValue<OptionSetValue>("statecode").Value == 0);
			
			return issueForum;
		}

19 View Source File : OpportunityDetails.aspx.cs
License : MIT License
Project Creator : Adoxio

protected void Page_Load(object sender, EventArgs e)
		{
			RedirectToLoginIfAnonymous();

			var primaryContact = GetPrimaryContactAndSetCompanyName();

			if (primaryContact == null || OpenOpportunity.GetAttributeValue<OptionSetValue>("statuscode") != null && (OpenOpportunity.GetAttributeValue<OptionSetValue>("statuscode").Value == (int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.Delivered || OpenOpportunity.GetAttributeValue<OptionSetValue>("statuscode").Value == (int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.Declined))
			{
				//Push a content-snippet error message saying that the opportunity is corrupt.
				ErrorMessage.Visible = true;
				CrmEnreplacedyFormViewsPanel.Visible = false;
				OpportunityStatusPanel.Visible = false;
				return;
			}

            AddFetchXmlToDataSource(ContactWebFormDataSource, "contact", "contactid", primaryContact.Id);

            ContactWebFormDataSource.CrmDataContextName = ContactFormView.ContextName;

			ContactFormView.DataSourceID = ContactWebFormDataSource.ID;

            AddFetchXmlToDataSource(OpportunityDataSource, "opportunity", "opportunityid", OpenOpportunity.Id);

            OpportunityDataSource.CrmDataContextName = OpportunityFormView.ContextName;

			OpportunityFormView.DataSourceID = OpportunityDataSource.ID;

			//GetContactList();

			//GetLeadHistory();

			PipelinePhaseText.Text = OpenOpportunity.GetAttributeValue<string>("stepname");

			if (!IsPostBack)
			{
				GetContactList();

				GetLeadHistory();

				BindPipelinePhaseDetails();
			}

			BindProductsLeadNotesContactsAndreplacedignedTo();

			if (!OpenOpportunity.GetAttributeValue<bool?>("adx_partnercreated").GetValueOrDefault(false))
			{
				CancelOpportunity.Visible = false;
				CancelDetails.Visible = false;
				//CancelButton.Visible = false;
				//AddContactCheckBox.Visible = false;
				//AddContactList.Visible = false;
			}
			else
			{
				ReturnToNetwork.Visible = false;
				ReasonForReturn.Visible = false;
				//ReasonForReturnSource.Visible = false;
			}

			AddContactButton.QueryStringCollection = CreateCustomerContactQueryString();

		}

19 View Source File : OpportunityDetails.aspx.cs
License : MIT License
Project Creator : Adoxio

private void BindProductsLeadNotesContactsAndreplacedignedTo()
		{
			var opportunityContact = OpenOpportunity.GetRelatedEnreplacedy(XrmContext, new Relationship("msa_contact_opportunity"));
			CurrentlyreplacedignedToLabel.Text = (opportunityContact != null) ? opportunityContact.GetAttributeValue<string>("fullname") : string.Empty;

			if (IsPostBack)
			{
				return;
			}

			Products.Text = string.Join(", ", OpenOpportunity.GetRelatedEnreplacedies(XrmContext, new Relationship("adx_opportunity_product")).Select(product => product.GetAttributeValue<string>("name")));

			OpportunityNotes.Text = GetFormattedDescription(OpenOpportunity.GetAttributeValue<string>("description"));

			//LeadreplacedignedTo.Text = OpenOpportunity.adx_PartnerreplacedignedTo;

			var empli = new Lisreplacedem();

			replacedignToList.Items.Add(empli);

			//var contacts = XrmContext.GetContactsForContact(Contact).Cast<Contact>();

			replacedertContactHasParentAccount();

			var contacts = XrmContext.CreateQuery("contact").Where(c => c.GetAttributeValue<EnreplacedyReference>("parentcustomerid") == Contact.GetAttributeValue<EnreplacedyReference>("parentcustomerid"));

			foreach (var contact in contacts)
			{
				if (contact.GetAttributeValue<OptionSetValue>("statecode") != null && contact.GetAttributeValue<OptionSetValue>("statecode").Value == 0)
				{
					var li = new Lisreplacedem()
					{
						Text = contact.GetAttributeValue<string>("fullname"),
						Value = contact.GetAttributeValue<Guid>("contactid").ToString()
					};

					if (OpenOpportunity.GetAttributeValue<EnreplacedyReference>("msa_partneroppid") != null && li.Value == OpenOpportunity.GetAttributeValue<EnreplacedyReference>("msa_partneroppid").Id.ToString())
					{
						li.Selected = true;
					}

					replacedignToList.Items.Add(li);
				}
			}

			var partnerAccount = ServiceContext.CreateQuery("account").FirstOrDefault(a => a.GetAttributeValue<Guid>("accountid") == (Contact.GetAttributeValue<EnreplacedyReference>("parentcustomerid") == null ? Guid.Empty : Contact.GetAttributeValue<EnreplacedyReference>("parentcustomerid").Id));

			if (partnerAccount != null)
			{
				
				var fetchXmlString = string.Format(@"
					<fetch mapping=""logical"" distinct=""true"">
						<enreplacedy name=""contact"">
							<attribute name=""fullname"" />
							<attribute name=""telephone1"" />
							<attribute name=""contactid"" />
							<order attribute=""fullname"" descending=""false"" />
							<link-enreplacedy name=""account"" from=""accountid"" to=""parentcustomerid"" alias=""accountmanagingpartnerlink"" link-type=""outer"">
							</link-enreplacedy>
							<link-enreplacedy name=""adx_opportunity_contact"" from=""contactid"" to=""contactid"" link-type=""outer"">
								<link-enreplacedy name=""opportunity"" from=""opportunityid"" to=""opportunityid"" alias=""opportunitylink"" link-type=""outer""></link-enreplacedy>
							</link-enreplacedy>
							<filter type=""and"">
								<filter type=""or"">
									<condition attribute=""msa_managingpartnerid"" operator=""eq"" value=""{0}"" />
									<condition enreplacedyname=""accountmanagingpartnerlink"" attribute=""msa_managingpartnerid"" operator=""eq"" value=""{0}"" />
								</filter>
								<condition enreplacedyname=""opportunitylink"" attribute=""opportunityid"" operator=""ne"" value=""{1}"" />
							</filter>
						</enreplacedy>
					</fetch>", partnerAccount.Id, OpenOpportunity.Id);

				var fetchXml = XDoreplacedent.Parse(fetchXmlString);

				var response = (RetrieveMultipleResponse)ServiceContext.Execute(new RetrieveMultipleRequest
				{
					Query = new FetchExpression(fetchXml.ToString())
				});

				var customerContacts = response.EnreplacedyCollection.Enreplacedies.ToList();

				foreach (var li in customerContacts.Select(customerContact => new Lisreplacedem()
					{
						Text = customerContact.GetAttributeValue<string>("fullname"),
						Value = customerContact.GetAttributeValue<Guid>("contactid").ToString()
					}))
				{ AddContactList.Items.Add(li); }

			}

			if (AddContactList.Items.Count >= 1) return;

			AddContactList.Visible = false;
			AddContactCheckBox.Visible = false;
		}

19 View Source File : OpportunityDetails.aspx.cs
License : MIT License
Project Creator : Adoxio

private void BindPipelinePhaseDetails()
		{

			PipelinePhase.Items.Clear();

			var response = (RetrieveAttributeResponse)ServiceContext.Execute(new RetrieveAttributeRequest
			{
				EnreplacedyLogicalName = "opportunity",
				LogicalName = "salesstagecode"
			});

			var picklist = response.AttributeMetadata as PicklistAttributeMetadata;
			if (picklist == null)
			{
				return;
			}

			var phase = 0;

			foreach (var option in picklist.OptionSet.Options)
			{
				var text = option.Label.GetLocalizedLabelString();
				var value = option.Value.Value.ToString();

				if (text == OpenOpportunity.GetAttributeValue<string>("stepname"))
				{
					phase = option.Value.Value;
				}
			}

			foreach (var option in picklist.OptionSet.Options)
			{
				var li = new Lisreplacedem()
				{
					Text = option.Label.GetLocalizedLabelString(),
					Value = option.Value.Value.ToString()
				};

				if (option.Value.Value >= phase)
				{
					bool GoodToGo = true;

					foreach (Lisreplacedem item in PipelinePhase.Items)
					{
						if (item.Text == li.Text)
						{
							GoodToGo = false;
						}
					}

					if (GoodToGo)
					{
						PipelinePhase.Items.Add(li);
					}
				}

				if (li.Text == OpenOpportunity.GetAttributeValue<string>("stepname"))
				{
					li.Selected = true;
				}

			}
			DisableControlsBasedOnPipelinePhaseAndAccessPermissions();
		}

19 View Source File : OpportunityDetails.aspx.cs
License : MIT License
Project Creator : Adoxio

private void DisableControlsBasedOnPipelinePhaseAndAccessPermissions()
		{

			var accessPermissions = XrmContext.GetOpportunityAccessByContact(Contact);

			//CreateCaseLink.Visible = false;
			replacedignToList.Visible = false;
			//replacedignToContact.Visible = false;
			OpportunityStatusPanel.Visible = false;
			SubmitButton.Visible = false;
			CancelOpportunity.Visible = false;

			foreach (var access in accessPermissions)
			{
				if (access.GetAttributeValue<bool?>("adx_write").GetValueOrDefault(false))
				{
					//CreateCaseLink.Visible = true;
					SubmitButton.Visible = true;
					OpportunityStatusPanel.Visible = true;
				}

				if (access.GetAttributeValue<bool?>("adx_replacedign").GetValueOrDefault(false))
				{
					replacedignToList.Visible = true;
					//replacedignToContact.Visible = true;
				}

				if (access.GetAttributeValue<bool?>("adx_delete").GetValueOrDefault(false))
				{
					CancelOpportunity.Visible = true;
				}

			}

			CurrentlyreplacedignedToLabel.Visible = !replacedignToList.Visible;

			if (OpenOpportunity.GetAttributeValue<OptionSetValue>("statecode") != null && (OpenOpportunity.GetAttributeValue<OptionSetValue>("statecode").Value == (int)Adxstudio.Xrm.Partner.Enums.OpportunityState.Lost || OpenOpportunity.GetAttributeValue<OptionSetValue>("statecode").Value == (int)Adxstudio.Xrm.Partner.Enums.OpportunityState.Won))
			{
				CrmEnreplacedyFormViewsPanel.Enabled = false;
				OpportunityStatusPanel.Enabled = false;
			}

		}

19 View Source File : OpportunityDetails.aspx.cs
License : MIT License
Project Creator : Adoxio

private Enreplacedy GetPrimaryContactAndSetCompanyName()
		{
			if (OpenOpportunity == null)
			{
				return null;
			}

			Enreplacedy primaryContact = null;

			var customer = OpenOpportunity.GetAttributeValue<EnreplacedyReference>("customerid");

			if (customer.LogicalName == "account")
			{
				var account = XrmContext.CreateQuery("account").First(a => a.GetAttributeValue<Guid>("accountid") == customer.Id);

				CompanyName.Text = account.GetAttributeValue<string>("name");

				primaryContact = account.GetRelatedEnreplacedy(XrmContext, new Relationship("account_primary_contact"));

				var channelPermission = XrmContext.GetChannelAccessByContact(Contact);

				var channelWriteAccess = (channelPermission != null && channelPermission.GetAttributeValue<bool?>("adx_write").GetValueOrDefault(false));

				var channelReadAccess = (channelPermission != null && channelPermission.GetAttributeValue<bool?>("adx_read").GetValueOrDefault(false));

				var parentAccount = (account.GetAttributeValue<EnreplacedyReference>("msa_managingpartnerid") != null) ? XrmContext.CreateQuery("account").FirstOrDefault(a => a.GetAttributeValue<Guid>("accountid") == account.GetAttributeValue<EnreplacedyReference>("msa_managingpartnerid").Id) : null;

				if (parentAccount != null && ((channelPermission != null && channelPermission.GetAttributeValue<EnreplacedyReference>("adx_accountid") != null) && channelPermission.GetAttributeValue<EnreplacedyReference>("adx_accountid").Equals(parentAccount.ToEnreplacedyReference())) && (parentAccount.GetAttributeValue<OptionSetValue>("accountclreplacedificationcode") != null && parentAccount.GetAttributeValue<OptionSetValue>("accountclreplacedificationcode").Value == 100000000))
				{
					if (channelWriteAccess)
					{
						CompanyName.Text = string.Format(@"<a href=""{0}"" clreplaced=""Edit"">{1}</a>",
						HttpUtility.HtmlEncode(EditAccountUrl(account.GetAttributeValue<Guid>("accountid"))),
						HttpUtility.HtmlEncode(CompanyName.Text));
					}
					else if (channelReadAccess)
					{
						CompanyName.Text = string.Format(@"<a href=""{0}"" clreplaced=""Edit"">{1}</a>",
						HttpUtility.HtmlEncode(ReadOnlyAccountUrl(account.GetAttributeValue<Guid>("accountid"))),
						HttpUtility.HtmlEncode(CompanyName.Text));
					}
				}


				//CompanyName.Attributes.Add("style", "white-space: nowrap;");

			}
			else if (customer.LogicalName == "contact")
			{
				primaryContact = XrmContext.CreateQuery("contact").First(c => c.GetAttributeValue<Guid>("contactid") == customer.Id);

				var account = primaryContact.GetRelatedEnreplacedy(XrmContext, new Relationship("account_primary_contact"));

				CompanyName.Text = account != null ? account.GetAttributeValue<string>("name") : primaryContact.GetAttributeValue<string>("adx_organizationname");
			}

			return primaryContact;
		}

19 View Source File : OrganizationServiceContextExtensions.cs
License : MIT License
Project Creator : Adoxio

public static Enum GetAlertType(this OrganizationServiceContext context, Guid? id, Enreplacedy website)
		{
			if (id == null)
			{
				return Enums.AlertType.None;
			}

			var opportunity = context.CreateQuery("opportunity").First(opp => opp.GetAttributeValue<Guid>("opportunityid") == id);

			if (opportunity.GetAttributeValue<OptionSetValue>("statecode") != null && opportunity.GetAttributeValue<OptionSetValue>("statecode").Value != (int)Adxstudio.Xrm.Partner.Enums.OpportunityState.Open)
			{
				return Enums.AlertType.None;
			}

			if (opportunity.GetAttributeValue<OptionSetValue>("statuscode") != null && opportunity.GetAttributeValue<OptionSetValue>("statuscode").Value == (int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.Delivered)
			{
				return Enums.AlertType.New;
			}

			var opportunityLatestStatusModifiedOn = context.GetOpportunityLatestStatusModifiedOn(opportunity);

			return opportunityLatestStatusModifiedOn == null
					   ? Enums.AlertType.None
					   : opportunityLatestStatusModifiedOn <= DateTime.Now.AddDays(-context.GetInactiveDaysUntilPotentiallyStalled(website))
							 ? Enums.AlertType.PotentiallyStalled
							 : (opportunityLatestStatusModifiedOn <= DateTime.Now.AddDays(-context.GetInactiveDaysUntilOverdue(website))
									? Enums.AlertType.Overdue
									: Enums.AlertType.None);
		}

19 View Source File : Home.aspx.cs
License : MIT License
Project Creator : Adoxio

protected void Page_Load(object sender, EventArgs e)
		{
			//RedirectToLoginIfNecessary();

			var contact = Contact;

			if (contact != null)
			{
				var homeAlertsSavedQuery = XrmContext.CreateQuery("savedquery").FirstOrDefault(query => query.GetAttributeValue<OptionSetValue>("statecode") != null && query.GetAttributeValue<OptionSetValue>("statecode").Value == 0 && query.GetAttributeValue<string>("name") == HomeAlertsSavedQueryName);

				var alerts = Opportunities.Where(opp => (opp.GetAttributeValue<OptionSetValue>("statuscode") != null && opp.GetAttributeValue<OptionSetValue>("statuscode").Value == (int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.Delivered)
					|| XrmContext.GetOpportunityLatestStatusModifiedOn(opp) <= DateTime.Now.AddDays(-ServiceContext.GetInactiveDaysUntilOverdue(Website)))
					.OrderByDescending(opp => GetAlertType(opp.Id)).ThenBy(opp => opp.GetRelatedEnreplacedy(XrmContext, new Relationship("opportunity_customer_accounts")).GetAttributeValue<string>("name"));
				
				var columnsGenerator = new SavedQueryColumnsGenerator(XrmContext, homeAlertsSavedQuery);

				Alerts.DataKeyNames = new[] { "opportunityid" };
				Alerts.DataSource = columnsGenerator.ToDataTable(alerts);
				Alerts.ColumnsGenerator = columnsGenerator;
				Alerts.DataBind();

				var newOpportunities = Opportunities.Where(opp => opp.GetAttributeValue<OptionSetValue>("statuscode") != null && opp.GetAttributeValue<OptionSetValue>("statuscode").Value == 
					(int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.Delivered);

				NewOpportunityCount.Text = newOpportunities.Count().ToString();
				NewOpportunityValue.Text = newOpportunities.Where(o => o.GetAttributeValue<Money>("estimatedvalue") != null).Sum(opp => opp.GetAttributeValue<Money>("estimatedvalue").Value).ToString("C");

				var acceptedOpportunities = Opportunities.Where(opp => opp.GetAttributeValue<OptionSetValue>("statuscode") != null && opp.GetAttributeValue<OptionSetValue>("statuscode").Value !=
					(int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.Delivered);

				AcceptedOpportunityCount.Text = acceptedOpportunities.Count().ToString();
				AcceptedOpportunityValue.Text = acceptedOpportunities.Where(o => o.GetAttributeValue<Money>("estimatedvalue") != null).Sum(opp => opp.GetAttributeValue<Money>("estimatedvalue").Value).ToString("C");
			}
			else
			{
				PartnerHomePanel.Visible = false;
			}
		}

19 View Source File : PermitApplicationDetails.aspx.cs
License : MIT License
Project Creator : Adoxio

protected void Page_Load(object sender, EventArgs e)
		{
			var reference = Enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_enreplacedyform");

			var enreplacedyFormRecord = XrmContext.CreateQuery("adx_enreplacedyform").FirstOrDefault(ef => ef.GetAttributeValue<Guid>("adx_enreplacedyformid") == reference.Id);

			if (enreplacedyFormRecord != null)
			{
				var recordEnreplacedyLogicalName = enreplacedyFormRecord.GetAttributeValue<string>("adx_enreplacedyname");

				Guid recordId;

				if (Guid.TryParse(Request["id"], out recordId))
				{

					var metadataRequest = new RetrieveEnreplacedyRequest
					{
						LogicalName = recordEnreplacedyLogicalName,
						EnreplacedyFilters = EnreplacedyFilters.Attributes
					};

					var metadataResponse = (RetrieveEnreplacedyResponse)XrmContext.Execute(metadataRequest);

					var primaryFieldLogicalName = metadataResponse.EnreplacedyMetadata.PrimaryIdAttribute;

					var permitRecord = XrmContext.CreateQuery(recordEnreplacedyLogicalName).FirstOrDefault(r => r.GetAttributeValue<Guid>(primaryFieldLogicalName) == recordId);

					var permitTypeReference = permitRecord.GetAttributeValue<EnreplacedyReference>("adx_permittype");

					var permitType =
						XrmContext.CreateQuery("adx_permittype").FirstOrDefault(
							srt => srt.GetAttributeValue<Guid>("adx_permittypeid") == permitTypeReference.Id);

					var enreplacedyName = permitType.GetAttributeValue<string>("adx_enreplacedyname");

					RegardingContactFieldName = permitType.GetAttributeValue<string>("adx_regardingcontactfieldname");

					var trueMetadataRequest = new RetrieveEnreplacedyRequest
					{
						LogicalName = enreplacedyName,
						EnreplacedyFilters = EnreplacedyFilters.Attributes
					};

					var trueMetadataResponse = (RetrieveEnreplacedyResponse)XrmContext.Execute(trueMetadataRequest);

					var primaryFieldName = trueMetadataResponse.EnreplacedyMetadata.PrimaryIdAttribute;

					var enreplacedyId = permitRecord.GetAttributeValue<string>("adx_enreplacedyid");

					var trueRecordId = Guid.Parse(enreplacedyId);

					var trueRecord = XrmContext.CreateQuery(enreplacedyName).FirstOrDefault(r => r.GetAttributeValue<Guid>(primaryFieldName) == trueRecordId);

					Permit = trueRecord;

					var permitDataSource = CreateDataSource("PermitDataSource", enreplacedyName, primaryFieldName, trueRecordId);

					var permitFormView = new CrmEnreplacedyFormView() { FormName = "Details Form", Mode = FormViewMode.Edit, EnreplacedyName = enreplacedyName, CssClreplaced = "crmEnreplacedyFormView", AutoGenerateSteps = false };

					var languageCodeSetting = OrganizationServiceContextExtensions.GetSiteSettingValueByName(ServiceContext, Portal.Website, "Language Code");
					if (!string.IsNullOrWhiteSpace(languageCodeSetting))
					{
						int languageCode;
						if (int.TryParse(languageCodeSetting, out languageCode))
						{
							permitFormView.LanguageCode = languageCode;
							permitFormView.ContextName = languageCode.ToString(CultureInfo.InvariantCulture);
							permitDataSource.CrmDataContextName = languageCode.ToString(CultureInfo.InvariantCulture);
						}
					}

					CrmEnreplacedyFormViewPanel.Controls.Add(permitFormView);

					permitFormView.DataSourceID = permitDataSource.ID;

					var regardingContact = Permit.GetAttributeValue<EnreplacedyReference>(RegardingContactFieldName);

					if (regardingContact == null || Contact == null || regardingContact.Id != Contact.Id)
					{
						PermitControls.Enabled = false;
						PermitControls.Visible = false;
						AddNoteInline.Visible = false;
						AddNoteInline.Enabled = false;
					}
					else
					{
						var dataAdapterDependencies =
							new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: PortalName);
						var dataAdapter = new AnnotationDataAdapter(dataAdapterDependencies);
						var annotations = dataAdapter.GetAnnotations(Permit.ToEnreplacedyReference(),
							new List<Order> { new Order("createdon") }, respectPermissions: false);

						NotesList.DataSource = annotations;
						NotesList.DataBind();
					}
				}
			}
		}

19 View Source File : PermitApplicationDetails.aspx.cs
License : MIT License
Project Creator : Adoxio

protected void AddNote_Click(object sender, EventArgs e)
		{
			var regardingContact = Permit.GetAttributeValue<EnreplacedyReference>(RegardingContactFieldName);

			if (regardingContact == null || Contact == null || regardingContact.Id != Contact.Id)
			{
				throw new InvalidOperationException("Unable to retrieve the order.");
			}

			if (!string.IsNullOrEmpty(NewNoteText.Text) || (NewNoteAttachment.PostedFile != null && NewNoteAttachment.PostedFile.ContentLength > 0))
			{
				var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(
					requestContext: Request.RequestContext, portalName: PortalName);

				var dataAdapter = new AnnotationDataAdapter(dataAdapterDependencies);
				
				var annotation = new Annotation
				{
					NoteText = string.Format("{0}{1}", AnnotationHelper.WebAnnotationPrefix, NewNoteText.Text),
					Subject = AnnotationHelper.BuildNoteSubject(dataAdapterDependencies),
					Regarding = Permit.ToEnreplacedyReference()
				};
				if (NewNoteAttachment.PostedFile != null && NewNoteAttachment.PostedFile.ContentLength > 0)
				{
					annotation.FileAttachment = AnnotationDataAdapter.CreateFileAttachment(new HttpPostedFileWrapper(NewNoteAttachment.PostedFile));
				}
				dataAdapter.CreateAnnotation(annotation);
			}

			Response.Redirect(Request.Url.PathAndQuery);
		}

19 View Source File : EditCustomerContact.aspx.cs
License : MIT License
Project Creator : Adoxio

protected void Page_Load(object sender, EventArgs e)
		{
			RedirectToLoginIfAnonymous();

			if (ContactToEdit == null)
			{
				RecordNotFoundError.Visible = true;

				EditContactForm.Visible = false;

				return;
			}

			var formViewDataSource = new CrmDataSource { ID = "WebFormDataSource", CrmDataContextName = ContactFormView.ContextName };
			var managingPartnerAccount = Contact.GetAttributeValue<EnreplacedyReference>("parentcustomerid") == null ? null : ServiceContext.CreateQuery("account").FirstOrDefault(a => a.GetAttributeValue<Guid>("accountid") == Contact.GetAttributeValue<EnreplacedyReference>("parentcustomerid").Id);
			var channelPermission = ServiceContext.GetChannelAccessByContact(Contact);
			var channelWriteAccess = (channelPermission != null && channelPermission.GetAttributeValue<bool?>("adx_write").GetValueOrDefault(false));
			var channelPermissionForParentAccountExists = managingPartnerAccount != null && channelPermission != null && channelPermission.GetAttributeValue<EnreplacedyReference>("adx_accountid") != null && channelPermission.GetAttributeValue<EnreplacedyReference>("adx_accountid").Equals(managingPartnerAccount.ToEnreplacedyReference());
			var validAcccountClreplacedificationCode = managingPartnerAccount != null && managingPartnerAccount.GetAttributeValue<OptionSetValue>("accountclreplacedificationcode") != null && managingPartnerAccount.GetAttributeValue<OptionSetValue>("accountclreplacedificationcode").Value == (int)Enums.AccountClreplacedificationCode.Partner;
			
			if (channelPermission == null)
			{
				NoChannelPermissionsRecordError.Visible = true;

				EditContactForm.Visible = false;

				return;
			}

			if (!channelWriteAccess)
			{
				ChannelPermissionsError.Visible = true;
			}
			else
			{
				if (managingPartnerAccount == null)
				{
					NoParentAccountError.Visible = true;
				}
				else if (!validAcccountClreplacedificationCode)
				{
					ParentAccountClreplacedificationCodeError.Visible = true;
				}
				else if (!channelPermissionForParentAccountExists)
				{
					NoChannelPermissionsForParentAccountError.Visible = true;
				}
			}

			if (!channelWriteAccess || managingPartnerAccount == null || !channelPermissionForParentAccountExists || !validAcccountClreplacedificationCode)
			{
				EditContactForm.Visible = false;

				return;
			}

			var fetchXml = string.Format("<fetch mapping='logical'><enreplacedy name='{0}'><all-attributes /><filter type='and'><condition attribute = '{1}' operator='eq' value='{{{2}}}'/></filter></enreplacedy></fetch>", "contact", "contactid", ContactToEdit.GetAttributeValue<Guid>("contactid"));

			formViewDataSource.FetchXml = fetchXml;

			EditContactForm.Controls.Add(formViewDataSource);

			ContactFormView.DataSourceID = "WebFormDataSource";
		}

19 View Source File : ReadOnlyContactView.aspx.cs
License : MIT License
Project Creator : Adoxio

protected void Page_Load(object sender, EventArgs e)
		{
			RedirectToLoginIfAnonymous();

			if (ContactToEdit == null)
			{
				RecordNotFoundError.Visible = true;

				ContactForm.Visible = false;

				return;
			}

			var formViewDataSource = new CrmDataSource { ID = "WebFormDataSource", CrmDataContextName = FormView.ContextName };
			
			var managingPartnerAccount = Contact.GetAttributeValue<EnreplacedyReference>("parentcustomerid") == null ? null : ServiceContext.CreateQuery("account").FirstOrDefault(a => a.GetAttributeValue<Guid>("accountid") == Contact.GetAttributeValue<EnreplacedyReference>("parentcustomerid").Id);
			var channelPermission = ServiceContext.GetChannelAccessByContact(Contact);
			var channelReadAccess = (channelPermission != null && channelPermission.GetAttributeValue<bool?>("adx_read").GetValueOrDefault(false));
			var channelWriteAccess = (channelPermission != null && channelPermission.GetAttributeValue<bool?>("adx_write").GetValueOrDefault(false));
			var channelPermissionForParentAccountExists = managingPartnerAccount != null && channelPermission != null && channelPermission.GetAttributeValue<EnreplacedyReference>("adx_accountid") != null && channelPermission.GetAttributeValue<EnreplacedyReference>("adx_accountid").Equals(managingPartnerAccount.ToEnreplacedyReference());
			var validAcccountClreplacedificationCode = managingPartnerAccount != null && managingPartnerAccount.GetAttributeValue<OptionSetValue>("accountclreplacedificationcode") != null && managingPartnerAccount.GetAttributeValue<OptionSetValue>("accountclreplacedificationcode").Value == (int)Enums.AccountClreplacedificationCode.Partner;

			if (channelPermission == null)
			{
				NoChannelPermissionsRecordError.Visible = true;

				ContactForm.Visible = false;

				return;
			}

			if (!channelReadAccess || !channelWriteAccess)
			{
				ChannelPermissionsError.Visible = true;
			}
			else
			{
				if (managingPartnerAccount == null)
				{
					NoParentAccountError.Visible = true;
				}
				else if (!validAcccountClreplacedificationCode)
				{
					ParentAccountClreplacedificationCodeError.Visible = true;
				}
				else if (!channelPermissionForParentAccountExists)
				{
					NoChannelPermissionsForParentAccountError.Visible = true;
				}
			}

			if (!channelWriteAccess || managingPartnerAccount == null || !channelPermissionForParentAccountExists || !validAcccountClreplacedificationCode)
			{
				ContactForm.Visible = false;

				return;
			}

			var fetchXml = string.Format("<fetch mapping='logical'><enreplacedy name='{0}'><all-attributes /><filter type='and'><condition attribute = '{1}' operator='eq' value='{{{2}}}'/></filter></enreplacedy></fetch>", "account", "accountid", ContactToEdit.GetAttributeValue<Guid>("accountid"));

			formViewDataSource.FetchXml = fetchXml;

			ContactForm.Controls.Add(formViewDataSource);

			FormView.DataSourceID = "WebFormDataSource";
		}

19 View Source File : ArticleController.cs
License : MIT License
Project Creator : Adoxio

[HttpGet]
		public ActionResult Article(string number, string lang, int? page)
		{
			var serviceContext = PortalCrmConfigurationManager.CreateServiceContext();

			// If the article is specifically being requested (via URL) in a language, multi-language is enabled, and the requested language
			// is different than the context language, then update the context language to respect the language of the article being viewed.
			// remove the old lang parameter and update url if necessary
			var contextLanguageInfo = this.HttpContext.GetContextLanguageInfo();
			if (contextLanguageInfo.IsCrmMultiLanguageEnabled)
			{
				var needsRedirect = ContextLanguageInfo.DisplayLanguageCodeInUrl != contextLanguageInfo.RequestUrlHasLanguageCode
									|| contextLanguageInfo.ContextLanguage.UsedAsFallback || !string.IsNullOrWhiteSpace(lang);

				var llcc = !string.IsNullOrWhiteSpace(lang) ? lang : contextLanguageInfo.ContextLanguage.Code;
				var activeLangauges = contextLanguageInfo.ActiveWebsiteLanguages;
				if (!string.IsNullOrWhiteSpace(lang) && !activeLangauges.Any(l => l.Code.Equals(lang, StringComparison.InvariantCultureIgnoreCase)))
				{
					IWebsiteLanguage language;
					if (ContextLanguageInfo.TryGetLanguageFromMapping(contextLanguageInfo.ActiveWebsiteLanguages, lang, out language))
					{
						llcc = language.UsedAsFallback && contextLanguageInfo.ContextLanguage.CrmLcid == language.CrmLcid
									? contextLanguageInfo.ContextLanguage.Code
									: language.Code;
					}
				}

				var articleUrl = ContextLanguageInfo.DisplayLanguageCodeInUrl
									? contextLanguageInfo.FormatUrlWithLanguage(overrideLanguageCode: llcc)
									: contextLanguageInfo.AbsolutePathWithoutLanguageCode;


				var queryParameters = new NameValueCollection(this.Request.QueryString);
				articleUrl = articleUrl.Replace(queryParameters.Count == 1 ?
					string.Format("?lang={0}", lang) : string.Format("lang={0}", lang),
					string.Empty);

				if (needsRedirect && articleUrl != Request.Url.PathAndQuery)
				{
					return Redirect(articleUrl);
				}
			}

			string langCode;
			var article = GetArticle(serviceContext, number, this.HttpContext.GetWebsite(), lang, out langCode);

			if (article == null)
			{
				return View("ArticleUnavailable");
			}

			if (!Authorized(serviceContext, article))
			{
				return RedirectToAccessDeniedPage();
			}
			
			//Log Customer Journey Tracking
			if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.CustomerJourneyTracking))
			{
				PortalTrackingTrace.TraceInstance.Log(Constants.Article, article.Id.ToString(), article.GetAttributeValue<string>("replacedle"));
			}
			return GetArticleView(article, page, langCode);
		}

19 View Source File : CreateNewOpportunity.aspx.cs
License : MIT License
Project Creator : Adoxio

protected void Page_Load(object sender, EventArgs e)
		{
			RedirectToLoginIfAnonymous();

			if (Page.IsPostBack)
			{
				return;
			}
			
			var opportunityPermissions = XrmContext.GetOpportunityAccessByContact(Contact).ToList();

			if (!opportunityPermissions.Any())
			{
				NoOpportunityPermissionsRecordError.Visible = true;

				OpportunityDetailsPanel.Visible = false;

				return;
			}

			bool createAccess = false;

			foreach (var access in opportunityPermissions)
			{
				var opportunityCreateAccess = (access != null && access.GetAttributeValue<bool?>("adx_create").GetValueOrDefault(false));

				if (opportunityCreateAccess)
				{
					createAccess = true;
				}
			}

			if (!createAccess)
			{
				OpportunityPermissionsError.Visible = true;

				OpportunityDetailsPanel.Visible = false;

				return;
			}

			var channelPermission = ServiceContext.GetChannelAccessByContact(Contact);
			var channelCreateAccess = (channelPermission != null && channelPermission.GetAttributeValue<bool?>("adx_create").GetValueOrDefault(false));
			var parentCustomerAccount = Contact.GetAttributeValue<EnreplacedyReference>("parentcustomerid") == null ? null : ServiceContext.CreateQuery("account").FirstOrDefault(a => a.GetAttributeValue<Guid>("accountid") == Contact.GetAttributeValue<EnreplacedyReference>("parentcustomerid").Id);
			var validAcccountClreplacedificationCode = parentCustomerAccount != null && parentCustomerAccount.GetAttributeValue<OptionSetValue>("accountclreplacedificationcode") != null && parentCustomerAccount.GetAttributeValue<OptionSetValue>("accountclreplacedificationcode").Value == (int)CustomerManagement.Enums.AccountClreplacedificationCode.Partner;

			if (channelPermission == null)
			{
				NoChannelPermissionsRecordError.Visible = true;

				CreateCustomerButton.Visible = false;
			}
			else
			{
				if (!channelCreateAccess)
				{
					ChannelPermissionsError.Visible = true;
				}
				else
				{
					if (parentCustomerAccount == null)
					{
						NoParentAccountError.Visible = true;
					}
					else
					{
						ParentAccountClreplacedificationCodeError.Visible = !validAcccountClreplacedificationCode;
					}
				}

				if ((!channelCreateAccess) || parentCustomerAccount == null || !validAcccountClreplacedificationCode)
				{
					CreateCustomerButton.Visible = false;
				}
			}

			var partnerAccounts = ServiceContext.CreateQuery("account").Where(a => a.GetAttributeValue<EnreplacedyReference>("msa_managingpartnerid") != null && a.GetAttributeValue<EnreplacedyReference>("msa_managingpartnerid").Equals(parentCustomerAccount.ToEnreplacedyReference())).ToList();

			var accounts = partnerAccounts
				.Where(a => a.GetAttributeValue<EnreplacedyReference>("primarycontactid") != null)
				.OrderBy(a => a.GetAttributeValue<string>("name"))
				.Select(a => new Lisreplacedem(a.GetAttributeValue<string>("name"), a.GetAttributeValue<Guid>("accountid").ToString())).ToList();

			if (!accounts.Any())
			{
				Account_dropdown.Enabled = false;
				
				if (!partnerAccounts.Any())
				{
					NoManagingPartnerCustomerAccountsMessage.Visible = true;
				}
				else
				{
					NoPrimaryContactOnManagingPartnerCustomerAccountsMessage.Visible = true;

					ManageCustomersButton.Visible = true;
				}
			}
			else
			{
				NoManagingPartnerCustomerAccountsMessage.Visible = false;

				NoPrimaryContactOnManagingPartnerCustomerAccountsMessage.Visible = false;

				Account_dropdown.DataSource = accounts;

				Account_dropdown.DataTextField = "Text";

				Account_dropdown.DataValueField = "Value";

				Account_dropdown.DataBind();

				if (ParentCustomerAccount != null)
				{
					Account_dropdown.ClearSelection();

					foreach (Lisreplacedem li in Account_dropdown.Items)
					{
						Guid id;

						if (Guid.TryParse(li.Value, out id) && id == ParentCustomerAccount.GetAttributeValue<Guid>("accountid"))
						{
							li.Selected = true;
						}
					}
				}
			}
		}

19 View Source File : OpportunityDetails.aspx.cs
License : MIT License
Project Creator : Adoxio

private void AddContactDiv(Enreplacedy contact)
		{
			var account = (contact.GetAttributeValue<EnreplacedyReference>("parentcustomerid") != null) ?
				ServiceContext.CreateQuery("account").FirstOrDefault(a => a.GetAttributeValue<Guid>("accountid") == (contact.GetAttributeValue<EnreplacedyReference>("parentcustomerid") == null ? Guid.Empty : contact.GetAttributeValue<EnreplacedyReference>("parentcustomerid").Id)) : null;

			var companyName = account != null ? account.GetAttributeValue<string>("name") : contact.GetAttributeValue<string>("adx_organizationname");

			HtmlGenericControl div;

			var channelPermission = ServiceContext.GetChannelAccessByContact(Contact);

			var channelWriteAccess = (channelPermission != null && channelPermission.GetAttributeValue<bool?>("adx_write").GetValueOrDefault(false));

			var channelReadAccess = (channelPermission != null && channelPermission.GetAttributeValue<bool?>("adx_read").GetValueOrDefault(false));

			var parentAccount = (account != null && account.GetAttributeValue<EnreplacedyReference>("msa_managingpartnerid") != null) ?
				ServiceContext.CreateQuery("account").FirstOrDefault(a => a.GetAttributeValue<Guid>("accountid") == account.GetAttributeValue<EnreplacedyReference>("msa_managingpartnerid").Id) : null;

			string contactFormattedString = string.Empty;

			if ((parentAccount != null && channelPermission != null && channelPermission.GetAttributeValue<EnreplacedyReference>("adx_accountid") != null && (channelPermission.GetAttributeValue<EnreplacedyReference>("adx_accountid").Equals(parentAccount.ToEnreplacedyReference()))) ||
					(contact.GetAttributeValue<EnreplacedyReference>("msa_managingpartnerid") != null && channelPermission != null && contact.GetAttributeValue<EnreplacedyReference>("msa_managingpartnerid").Equals(channelPermission.GetAttributeValue<EnreplacedyReference>("adx_accountid"))))
			{
				if (channelWriteAccess)
				{
					contactFormattedString = string.Format(@"<i clreplaced=""fa fa-edit""></i><a href=""{0}"" clreplaced=""Edit"">{1}</a>",
						EditContactUrl(contact.GetAttributeValue<Guid>("contactid")),
						contact.GetAttributeValue<string>("fullname"));
				}
				else if (channelReadAccess)
				{
					contactFormattedString = string.Format(@"<a href=""{0}"">{1}</a>",
						ReadOnlyContactUrl(contact.GetAttributeValue<Guid>("contactid")),
						contact.GetAttributeValue<string>("fullname"));
				}
			}
			else
			{
				contactFormattedString = contact.GetAttributeValue<string>("fullname");
			}

			div = new HtmlGenericControl("div")
			{

				InnerHtml = string.Format(@"<span clreplaced=""contact-name"">{0}</span>{1}",
					contactFormattedString,
					!string.IsNullOrEmpty(companyName)
					? string.Format(@"<span clreplaced=""contact-company-name"">{0}</span>", Server.HtmlEncode(companyName)) : string.Empty)
			};

			// add div at the beginning for reverse chronological order
			OpportunityContactsPlaceHolder.Controls.AddAt(0, div);
		}

19 View Source File : OpportunityDetails.aspx.cs
License : MIT License
Project Creator : Adoxio

protected QueryStringCollection CreateCustomerContactQueryString()
		{
			var queryStringCollection = new QueryStringCollection(string.Empty);

			var oppId = OpenOpportunity.GetAttributeValue<Guid>("opportunityid");

			var account = OpenOpportunity.GetAttributeValue<EnreplacedyReference>("customerid");

			queryStringCollection.Set("OpportunityId", oppId.ToString());

			if (account != null)
			{
				queryStringCollection.Set("AccountId", account.Id.ToString());
			}

			return queryStringCollection;
		}

19 View Source File : EntityActivityController.cs
License : MIT License
Project Creator : Adoxio

private static IEnumerable<KeyValuePair<string, object>> FlattenAllPartiesAttribute(KeyValuePair<string, object> attribute)
		{
			var attributeCollection = new List<KeyValuePair<string, object>> { };
			var toRecipients = new List<EnreplacedyReference>();
			var ccRecipients = new List<EnreplacedyReference>();
			var requiredAttendees = new List<EnreplacedyReference>();

			if (attribute.Key.Equals("allparties"))
			{
				// Iterate through each enreplacedy in allparties and replacedign to Sender, To, or CC
				foreach (var enreplacedy in ((EnreplacedyCollection)attribute.Value).Enreplacedies.Where(enreplacedy => enreplacedy.Attributes.ContainsKey("participationtypemask") && enreplacedy.Attributes.ContainsKey("partyid")))
				{
					switch (enreplacedy.GetAttributeValue<OptionSetValue>("participationtypemask").Value)
					{
						// Sender or Organizer should be represented as "from"
						case (int)Activity.ParticipationTypeMaskOptionSetValue.Sender:
						case (int)Activity.ParticipationTypeMaskOptionSetValue.Organizer:
							attributeCollection.Add(new KeyValuePair<string, object>("from", enreplacedy.GetAttributeValue<EnreplacedyReference>("partyid")));
							break;
						case (int)Activity.ParticipationTypeMaskOptionSetValue.ToRecipient:
							toRecipients.Add(enreplacedy.GetAttributeValue<EnreplacedyReference>("partyid"));
							break;
						case (int)Activity.ParticipationTypeMaskOptionSetValue.CcRecipient:
							ccRecipients.Add(enreplacedy.GetAttributeValue<EnreplacedyReference>("partyid"));
							break;
						case (int)Activity.ParticipationTypeMaskOptionSetValue.RequiredAttendee:
							requiredAttendees.Add(enreplacedy.GetAttributeValue<EnreplacedyReference>("partyid"));
							break;
					}
				}

				// flatten lists for to and cc recipient
				if (toRecipients.Any())
				{
					attributeCollection.Add(new KeyValuePair<string, object>("to", toRecipients));
				}
				if (ccRecipients.Any())
				{
					attributeCollection.Add(new KeyValuePair<string, object>("cc", ccRecipients));
				}
				if (requiredAttendees.Any())
				{
					attributeCollection.Add(new KeyValuePair<string, object>("requiredattendees", requiredAttendees));
				}
			}
			else
			{
				attributeCollection.Add(attribute);
			}
			return attributeCollection;
		}

19 View Source File : EntityGridController.cs
License : MIT License
Project Creator : Adoxio

private static CreateActionMetadata GetOpportunityProductCreateActionMetadata(EnreplacedyReference opportunity, IDataAdapterDependencies dataAdapterDependencies)
		{
			var serviceContext = dataAdapterDependencies.GetServiceContext();

			var response = (RetrieveResponse)serviceContext.Execute(new RetrieveRequest
			{
				Target = opportunity,
				ColumnSet = new ColumnSet("pricelevelid")
			});

			return new CreateActionMetadata(
				response.Enreplacedy.GetAttributeValue<EnreplacedyReference>("pricelevelid") == null,
				ResourceManager.GetString("Opportunity_Product_Price_List_Required"));
		}

19 View Source File : Permits.aspx.cs
License : MIT License
Project Creator : Adoxio

protected string GetThumbnailUrl(object webpageObject)
		{
			var webpageEnreplacedy = webpageObject as Enreplacedy;

			if (webpageEnreplacedy == null)
			{
				return null;
			}

			var imageReference = webpageEnreplacedy.GetAttributeValue<EnreplacedyReference>("adx_image");

			if (imageReference == null)
			{
				return null;
			}
		
			var webfile = ServiceContext.CreateQuery("adx_webfile").FirstOrDefault(file => file.GetAttributeValue<Guid>("adx_webfileid") == imageReference.Id);

			if (webfile == null)
			{
				return null;
			}

			var url = new UrlBuilder(ServiceContext.GetUrl(webfile));

			return url.Path;
		}

19 View Source File : ProductCollections.aspx.cs
License : MIT License
Project Creator : Adoxio

protected string BuildImageTag(Enreplacedy enreplacedy)
		{
			const string defaultUrl = "/image-not-available-150x150.png/";
			var url = string.Empty;

			if (enreplacedy == null || string.IsNullOrWhiteSpace(enreplacedy.LogicalName))
			{
				return string.Empty;
			}

			if (enreplacedy.LogicalName == "adx_webpage")
			{
				var webFileReference = enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_image");
				if (webFileReference == null)
				{
					var thumbnailURL = enreplacedy.GetAttributeValue<string>("adx_imageurl");
					url =  string.IsNullOrWhiteSpace(thumbnailURL) ? string.Empty : thumbnailURL;
				}
				else
				{
					var webFile = ServiceContext.CreateQuery("adx_webfile").FirstOrDefault(e => e.GetAttributeValue<Guid>("adx_webfileid") == webFileReference.Id);
					if (webFile != null)
					{
						url = ServiceContext.GetUrl(webFile);
					}
				}

				if (string.IsNullOrWhiteSpace(url))
				{
					url = defaultUrl;
				}
			}

			return string.IsNullOrWhiteSpace(url) ? string.Empty : string.Format("<img alt='' src='{0}' runat='server' />", url);
		}

19 View Source File : ScheduleService.aspx.cs
License : MIT License
Project Creator : Adoxio

protected void FindTimes_Click(object sender, EventArgs args)
		{
			var startTimeInMinutesFromMidnight = int.Parse(StartTime.SelectedValue);

			var startDate = StartDate.SelectedDate.AddMinutes(startTimeInMinutesFromMidnight);

			var endTimeInMinutesFromMidnight = int.Parse(EndTime.SelectedValue);

			var endDate = EndDate.SelectedDate.AddMinutes(endTimeInMinutesFromMidnight);

			if (!SelectedDatesAndTimesAreValid(startDate, endDate, startTimeInMinutesFromMidnight, endTimeInMinutesFromMidnight))
			{
				return;
			}

			// Add the timezone selected to the CRM Contact for next time.
			var contact = XrmContext.CreateQuery("contact").FirstOrDefault(c => c.GetAttributeValue<Guid>("contactid") == Contact.Id);

			if (contact == null)
			{
				throw new ApplicationException(string.Format("Couldn't find the user contact where contactid equals {0}.", Contact.Id));
			}

			contact.SetAttributeValue("adx_timezone", int.Parse(TimeZoneSelection.SelectedValue));

			XrmContext.UpdateObject(contact);

			XrmContext.SaveChanges();

			var usersMinutesFromGmt = GetUsersMinutesFromGmt(contact.GetAttributeValue<int?>("adx_timezone"), XrmContext);

			var appointmentRequest = new AppointmentRequest
			{
				AnchorOffset = Service.GetAttributeValue<int?>("anchoroffset").GetValueOrDefault(),
				Direction = SearchDirection.Forward,
				Duration = Service.GetAttributeValue<int?>("duration").GetValueOrDefault(60),
				NumberOfResults = 10,
				RecurrenceDuration = endTimeInMinutesFromMidnight - startTimeInMinutesFromMidnight,
				RecurrenceTimeZoneCode = contact.GetAttributeValue<int?>("adx_timezone").GetValueOrDefault(),
				SearchRecurrenceRule = "FREQ=DAILY;INTERVAL=1",
				SearchRecurrenceStart = new DateTime(startDate.AddMinutes(usersMinutesFromGmt * -1).Ticks, DateTimeKind.Utc),
				SearchWindowEnd = new DateTime(endDate.AddMinutes(usersMinutesFromGmt * -1).Ticks, DateTimeKind.Utc),
				ServiceId = Service.GetAttributeValue<Guid>("serviceid")
			};

			var service = XrmContext;

			var searchRequest = new OrganizationRequest("Search");
			searchRequest.Parameters["AppointmentRequest"] = appointmentRequest;

			var searchResults = (SearchResults)service.Execute(searchRequest).Results["SearchResults"];

			var schedules = searchResults.Proposals.Select(proposal => new
			{
				ScheduledStart = proposal.Start.GetValueOrDefault().ToUniversalTime().AddMinutes(usersMinutesFromGmt),
				ScheduledStartUniversalTime = proposal.Start.GetValueOrDefault().ToUniversalTime(),
				ScheduledEnd = proposal.End.GetValueOrDefault().ToUniversalTime().AddMinutes(usersMinutesFromGmt),
				ScheduledEndUniversalTime = proposal.End.GetValueOrDefault().ToUniversalTime(),
				AvailableResource = proposal.ProposalParties.First().ResourceId
			}).Where(proposal => proposal.ScheduledStartUniversalTime >= DateTime.UtcNow);

			if (!schedules.Any())
			{
				SearchPanel.Visible = true;
				NoTimesMessage.Visible = true;
				ResultsDisplay.Visible = false;

				return;
			}

			AvailableTimes.DataSource = schedules;
			AvailableTimes.DataBind();

			SearchPanel.Visible = false;
			ResultsDisplay.Visible = true;
			ScheduleServiceButton.Enabled = false;
		}

19 View Source File : ScheduleService.aspx.cs
License : MIT License
Project Creator : Adoxio

private void BindServicesDropDown(IEnumerable<Enreplacedy> services)
		{
			ServiceType.DataSource = services.Select(s => new Lisreplacedem(s.GetAttributeValue<string>("name"), s.GetAttributeValue<Guid>("serviceid").ToString()));
			ServiceType.DataTextField = "Text";
			ServiceType.DataValueField = "Value";
			ServiceType.DataBind();
		}

19 View Source File : ReviewController.cs
License : MIT License
Project Creator : Adoxio

private static Enreplacedy GetReview(Guid reviewId, OrganizationServiceContext context)
		{
			var product = context.CreateQuery("adx_review").FirstOrDefault(p => p.GetAttributeValue<Guid>("adx_reviewid") == reviewId);

			return product;
		}

19 View Source File : ScheduleService.aspx.cs
License : MIT License
Project Creator : Adoxio

private static int GetUsersMinutesFromGmt(int? timeZoneCode, OrganizationServiceContext crmContext)
		{
			var definition = crmContext.CreateQuery("timezonedefinition").First(timeZone => timeZone.GetAttributeValue<int>("timezonecode") == timeZoneCode);

			if (definition == null)
			{
				return 0;
			}

			var rule = definition.GetRelatedEnreplacedies(crmContext, new Relationship("lk_timezonerule_timezonedefinitionid")).ToList();

			return !rule.Any() ? 0 : rule.First().GetAttributeValue<int?>("bias").GetValueOrDefault(0) * -1;
		}

19 View Source File : MapController.cs
License : MIT License
Project Creator : Adoxio

[AcceptVerbs(HttpVerbs.Post)]
		[AjaxValidateAntiForgeryToken, SuppressMessage("ASP.NET.MVC.Security", "CA5332:MarkVerbHandlersWithValidateAntiforgeryToken", Justification = "Handled with the custom attribute AjaxValidateAntiForgeryToken")]
		public ActionResult Search(int dateFilterCode, string dateFrom, string dateTo, int statusFilterCode, int priorityFilterCode, string[] types, bool includeAlerts)
		{
			dateFilterCode = (dateFilterCode >= 0) ? dateFilterCode : 0;
			var status = (statusFilterCode > 0) ? statusFilterCode : 999;
			var priority = (priorityFilterCode >= 0) ? priorityFilterCode : 0;
			DateTime fromDate;
			DateTime.TryParse(dateFrom, out fromDate);
			DateTime toDate;
			DateTime.TryParse(dateTo, out toDate);
			var typesGuids = types == null || types.Length < 1 ? null : Array.ConvertAll(types, Guid.Parse);
			var context = PortalCrmConfigurationManager.CreateServiceContext();

			var serviceRequests = context.CreateQuery("adx_servicerequest").Where(s => s.GetAttributeValue<decimal?>("adx_lareplacedude") != null && s.GetAttributeValue<decimal?>("adx_longitude") != null)
				.FilterServiceRequestsByPriority(priority)
				.FilterServiceRequestsByStatus(status)
				.FilterServiceRequestsByDate(dateFilterCode, fromDate, toDate.AddDays(1))
				.FilterServiceRequestsByType(typesGuids)
				.ToList();

			var serviceRequestMapNodes = new List<MapNode>();

			if (serviceRequests.Any())
			{
				serviceRequestMapNodes =
					serviceRequests.Select(
						s =>
							new MapNode(
								MapNode.NodeType.ServiceRequest,
								s.GetAttributeValue<string>("adx_servicerequestnumber"),
								s.GetAttributeValue<string>("adx_name"),
								s.GetAttributeValue<string>("adx_location"),
								string.Empty,
								s.GetAttributeValue<OptionSetValue>("adx_servicestatus") == null ? 0 : s.GetAttributeValue<OptionSetValue>("adx_servicestatus").Value,
								s.GetAttributeValue<OptionSetValue>("adx_priority") == null ? 0 : s.GetAttributeValue<OptionSetValue>("adx_priority").Value,
								s.GetAttributeValue<DateTime>("adx_incidentdate"),
								s.GetAttributeValue<DateTime>("adx_scheduleddate"),
								s.GetAttributeValue<DateTime>("adx_closeddate"),
								s.GetAttributeValue<decimal?>("adx_lareplacedude").GetValueOrDefault(0),
								s.GetAttributeValue<decimal?>("adx_longitude").GetValueOrDefault(0),
								ServiceRequestHelpers.GetPushpinImageUrl(context, s),
								ServiceRequestHelpers.GetCheckStatusUrl(s))).ToList();
			}

			var alertMapNodes = new List<MapNode>();

			if (includeAlerts)
			{
				var alerts = context.CreateQuery("adx_311alert").Where(a =>
					a.GetAttributeValue<decimal?>("adx_lareplacedude") != null && a.GetAttributeValue<decimal?>("adx_longitude") != null && a.GetAttributeValue<bool?>("adx_publishtoweb").GetValueOrDefault(false) == true)
					.FilterAlertsByDate(dateFilterCode, fromDate, toDate.AddDays(1)).ToList();

				if (alerts.Any())
				{
					var alertIconImageUrl = ServiceRequestHelpers.GetAlertPushpinImageUrl();
					alertMapNodes = alerts.Select(a => new MapNode(MapNode.NodeType.Alert, a.GetAttributeValue<string>("adx_name"), a.GetAttributeValue<string>("adx_address1_line1"), a.GetAttributeValue<string>("adx_description"), a.GetAttributeValue<DateTime?>("adx_scheduledstartdate"), a.GetAttributeValue<DateTime?>("adx_scheduledenddate"), a.GetAttributeValue<decimal?>("adx_lareplacedude") ?? 0, a.GetAttributeValue<decimal?>("adx_longitude") ?? 0, alertIconImageUrl)).ToList();
				}
			}

			var mapNodes = serviceRequestMapNodes.Union(alertMapNodes).ToList();

			var json = Json(mapNodes);

			return json;
		}

19 View Source File : OpportunityDetails.aspx.cs
License : MIT License
Project Creator : Adoxio

protected void OpportunityUpdated(object sender, CrmEnreplacedyFormViewUpdatedEventArgs e)
		{
			var context = PortalCrmConfigurationManager.CreateServiceContext();

			var opportunity = context.CreateQuery("opportunity").First(o => o.GetAttributeValue<Guid>("opportunityid") == e.Enreplacedy.Id);

			var partnerReference = opportunity.GetAttributeValue<EnreplacedyReference>("msa_partnerid");

			if (partnerReference == null)
			{
				return;
			}

			var partner = context.CreateQuery("account").First(p => p.GetAttributeValue<Guid>("accountid") == partnerReference.Id);

			if (partner.GetAttributeValue<int?>("adx_numberofopportunitiesaccepted").GetValueOrDefault(0) == 0)
			{
				partner.SetAttributeValue("adx_numberofopportunitiesaccepted", 1);
			}

			var oppnote = new Enreplacedy("adx_opportunitynote");
			var oppnote2 = new Enreplacedy("adx_opportunitynote");
			var feedbackrate = (double)(partner.GetAttributeValue<int?>("adx_numberofopportunitieswithfeedback").GetValueOrDefault(0)) / (partner.GetAttributeValue<int?>("adx_numberofopportunitiesaccepted").GetValueOrDefault(1));

			if (UpdatePipelinePhase.Checked)
			{
				context.SetOpportunityStatusAndSave(opportunity, "Open", 0);
				opportunity.SetAttributeValue("statuscode", new OptionSetValue((int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.InProgress));
				if (!opportunity.GetAttributeValue<bool?>("adx_feedbackyet").GetValueOrDefault(false))
				{
					if (!(opportunity.GetAttributeValue<bool?>("adx_partnercreated").GetValueOrDefault(false)))
					{
						partner.SetAttributeValue("adx_numberofopportunitieswithfeedback", partner.GetAttributeValue<int?>("adx_numberofopportunitieswithfeedback").GetValueOrDefault(0) + 1);
						partner.SetAttributeValue("adx_feedbackrate", feedbackrate);
						opportunity.SetAttributeValue("adx_feedbackyet", true);
					}
				}

				oppnote.SetAttributeValue("adx_name", PipelinePhase.SelectedItem.Text);
				oppnote.SetAttributeValue("adx_date", DateTime.UtcNow);
				oppnote.SetAttributeValue("adx_description", PipelineUpdateDetails.Text);
			}
			else if (WinOpportunity.Checked)
			{
				context.SetOpportunityStatusAndSave(opportunity, "Won", 0);
				opportunity.SetAttributeValue("statuscode", new OptionSetValue((int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.Purchased));
				if (!opportunity.GetAttributeValue<bool?>("adx_feedbackyet").GetValueOrDefault(false))
				{
					if (!(opportunity.GetAttributeValue<bool?>("adx_partnercreated").GetValueOrDefault(false)))
					{
						partner.SetAttributeValue("adx_numberofopportunitieswithfeedback", partner.GetAttributeValue<int?>("adx_numberofopportunitieswithfeedback").GetValueOrDefault(0) + 1);
						partner.SetAttributeValue("adx_feedbackrate", feedbackrate);
						opportunity.SetAttributeValue("adx_feedbackyet", true);
					}
				}

				opportunity.SetAttributeValue("adx_wondate", DateTime.UtcNow);
				var wonSetting = XrmContext.CreateQuery("adx_sitesetting").FirstOrDefault(ss => ss.GetAttributeValue<string>("adx_name") == "Won Opportunity Note");
				var wonNote = "Won";
				wonNote = (wonSetting != null) ? wonSetting.GetAttributeValue<string>("adx_value") : wonNote;

				oppnote.SetAttributeValue("adx_name", wonNote);
				oppnote.SetAttributeValue("adx_date", DateTime.UtcNow);
				oppnote.SetAttributeValue("adx_description", WonDetails.Text);
			}
			else if (CancelOpportunity.Checked)
			{
				context.SetOpportunityStatusAndSave(opportunity, "Lost", 0);
				opportunity.SetAttributeValue("statuscode", new OptionSetValue((int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.Canceled));
				if (!opportunity.GetAttributeValue<bool?>("adx_feedbackyet").GetValueOrDefault(false))
				{
					if (!(opportunity.GetAttributeValue<bool?>("adx_partnercreated").GetValueOrDefault(false)))
					{
						partner.SetAttributeValue("adx_numberofopportunitieswithfeedback", partner.GetAttributeValue<int?>("adx_numberofopportunitieswithfeedback").GetValueOrDefault(0) + 1);
						partner.SetAttributeValue("adx_feedbackrate", feedbackrate);
						opportunity.SetAttributeValue("adx_feedbackyet", true);
					}
				}

				var cancelSetting = XrmContext.CreateQuery("adx_sitesetting").FirstOrDefault(ss => ss.GetAttributeValue<string>("adx_name") == "Cancel Opportunity Note");
				var cancelNote = "Canceled";
				cancelNote = (cancelSetting != null) ? cancelSetting.GetAttributeValue<string>("adx_value") : cancelNote;

				oppnote.SetAttributeValue("adx_name", cancelNote);
				oppnote.SetAttributeValue("adx_date", DateTime.UtcNow);
				oppnote.SetAttributeValue("adx_description", CancelDetails.Text);
			}
			else if (AddContactCheckBox.Checked)
			{
				var selectedGuid = new Guid(AddContactList.SelectedItem.Value);

				var contact = context.CreateQuery("contact").FirstOrDefault(c => c.GetAttributeValue<Guid>("contactid") == selectedGuid);

				var contactCrossover = opportunity.GetRelatedEnreplacedies(context, new Relationship("adx_opportunity_contact")).FirstOrDefault(c => c.GetAttributeValue<Guid>("contactid") == contact.GetAttributeValue<Guid>("contactid"));

				if (contactCrossover == null)
				{
					context.AddLink(opportunity, new Relationship("adx_opportunity_contact"), contact);

					oppnote2.SetAttributeValue("adx_name", "Contact Added: " + contact.GetAttributeValue<string>("fullname"));
					oppnote2.SetAttributeValue("adx_date", DateTime.UtcNow);
					oppnote2.SetAttributeValue("adx_description", "Contact Added: " + contact.GetAttributeValue<string>("fullname"));

					context.UpdateObject(contact);
				}

				//var opportunity = OpenOpportunity;
			}
			else if (ReturnToNetwork.Checked)
			{
				context.SetOpportunityStatusAndSave(opportunity, "Lost", 0);
				opportunity.SetAttributeValue("statuscode", new OptionSetValue((int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.Returned));
				
				if (!(opportunity.GetAttributeValue<bool?>("adx_partnercreated").GetValueOrDefault(false)))
				{
					partner.SetAttributeValue("adx_numberofreturnedopportunities", partner.GetAttributeValue<int?>("adx_numberofreturnedopportunities").GetValueOrDefault(0) + 1);
					partner.SetAttributeValue("adx_returnrate", (double)partner.GetAttributeValue<int?>("adx_numberofreturnedopportunities").GetValueOrDefault(0) / (partner.GetAttributeValue<int?>("adx_numberofopportunitiesaccepted").GetValueOrDefault(1)));
				}

				var returnSetting = XrmContext.CreateQuery("adx_sitesetting").FirstOrDefault(ss => ss.GetAttributeValue<string>("adx_name") == "Return Opportunity Note");
				var returnNote = "Returned to Network";
				returnNote = (returnSetting != null) ? returnSetting.GetAttributeValue<string>("adx_value") : returnNote;

				oppnote.SetAttributeValue("adx_name", returnNote);
				oppnote.SetAttributeValue("adx_date", DateTime.UtcNow);
				oppnote.SetAttributeValue("adx_description", ReasonForReturn.SelectedItem.Text);

				//add the OpportunityNote enreplacedy
			}

			var calculatePartnerDetailsAction = new Enreplacedy("adx_calculatepartnercapacityworkflowaction");
			calculatePartnerDetailsAction.SetAttributeValue("adx_accountid", partner.ToEnreplacedyReference());
			var replacedignedto = opportunity.GetRelatedEnreplacedy(context, new Relationship("msa_contact_opportunity"));

			if (!string.IsNullOrEmpty(oppnote.GetAttributeValue<string>("adx_name")))
			{
				oppnote.SetAttributeValue("adx_opportunityid", opportunity.ToEnreplacedyReference());
				oppnote.SetAttributeValue("adx_replacedignedto", replacedignedto != null ? replacedignedto.GetAttributeValue<string>("fullname") : string.Empty);
				context.AddObject(oppnote);
			}
			if (!string.IsNullOrEmpty(oppnote2.GetAttributeValue<string>("adx_name")))
			{
				oppnote2.SetAttributeValue("adx_opportunityid", opportunity.ToEnreplacedyReference());
				oppnote2.SetAttributeValue("adx_replacedignedto", replacedignedto != null ? replacedignedto.GetAttributeValue<string>("fullname") : string.Empty);
				context.AddObject(oppnote2);
			}
			var oppID = opportunity.Id;

			context.UpdateObject(partner);
			context.UpdateObject(opportunity);
			context.SaveChanges();

			if (!(opportunity.GetAttributeValue<bool?>("adx_partnercreated").GetValueOrDefault(false)))
			{
				context.AddObject(calculatePartnerDetailsAction);
			}

			context.SaveChanges();

			var opp = context.CreateQuery("opportunity").FirstOrDefault(o => o.GetAttributeValue<Guid>("opportunityid") == oppID);

			if (opp != null)
			{
				CurrentlyreplacedignedToLabel.Text = replacedignedto != null ? replacedignedto.GetAttributeValue<string>("fullname") : string.Empty;
				PipelinePhaseText.Text = HttpUtility.HtmlEncode(opp.GetAttributeValue<string>("stepname"));
			}

			DisableControlsBasedOnPipelinePhaseAndAccessPermissions();

			BindPipelinePhaseDetails();

			GetLeadHistory();

			GetContactList();

			ConfirmationMessage.Visible = true;
		}

19 View Source File : ServiceDetails.aspx.cs
License : MIT License
Project Creator : Adoxio

private static int GetUsersMinutesFromGmt(int? timeZoneCode, OrganizationServiceContext crmContext)
		{
			var definition = crmContext.CreateQuery("timezonedefinition").FirstOrDefault(timeZone => timeZone.GetAttributeValue<int>("timezonecode") == timeZoneCode);

			if (definition == null)
			{
				return 0;
			}

			var rule = definition.GetRelatedEnreplacedies(crmContext, new Relationship("lk_timezonerule_timezonedefinitionid"));

			return rule == null ? 0 : rule.First().GetAttributeValue<int?>("bias").GetValueOrDefault() * -1;
		}

19 View Source File : ViewScheduledServices.aspx.cs
License : MIT License
Project Creator : Adoxio

protected void Page_Load(object sender, EventArgs e)
		{
			RedirectToLoginIfAnonymous();

			if (Page.IsPostBack) return;

			if (Contact == null) return;

			if (Contact.GetAttributeValue<int?>("adx_timezone") == null) return;

			var appointmentFetchXml = string.Format(AppointmentFetchXmlFormat, AppointmentStatusScheduled, DateTime.UtcNow, Contact.GetAttributeValue<Guid>("contactid"));

			var response = (RetrieveMultipleResponse)ServiceContext.Execute(new RetrieveMultipleRequest
			{
				Query = new FetchExpression(appointmentFetchXml)
			});

			if (response == null || response.EnreplacedyCollection == null || response.EnreplacedyCollection.Enreplacedies == null)
			{
				return;
			}

			var usersMinutesFromGmt = GetUsersMinutesFromGmt(Contact.GetAttributeValue<int?>("adx_timezone").GetValueOrDefault(), ServiceContext);

			var appointments = response.EnreplacedyCollection.Enreplacedies.Select(a => new
				{
					scheduledStart = a.GetAttributeValue<DateTime?>("scheduledstart").GetValueOrDefault().ToUniversalTime().AddMinutes(usersMinutesFromGmt),
					scheduledEnd = a.GetAttributeValue<DateTime?>("scheduledend").GetValueOrDefault().ToUniversalTime().AddMinutes(usersMinutesFromGmt),
					serviceType = a.GetAttributeValue<EnreplacedyReference>("serviceid") == null ? string.Empty : a.GetAttributeValue<EnreplacedyReference>("serviceid").Name,
					dateBooked = a.GetAttributeValue<DateTime>("createdon").ToUniversalTime().AddMinutes(usersMinutesFromGmt),
					serviceId = a.GetAttributeValue<Guid>("activityid")
				});

			BookedAppointments.DataSource = appointments;
			BookedAppointments.DataBind();
		}

19 View Source File : ViewScheduledServices.aspx.cs
License : MIT License
Project Creator : Adoxio

private static int GetUsersMinutesFromGmt(int? timeZoneCode, OrganizationServiceContext crmContext)
		{
			var definition = crmContext.CreateQuery("timezonedefinition").FirstOrDefault(timeZone => timeZone.GetAttributeValue<int>("timezonecode") == timeZoneCode);

			if (definition == null)
			{
				return 0;
			}

			var rule = definition.GetRelatedEnreplacedies(crmContext, new Relationship("lk_timezonerule_timezonedefinitionid")).ToList();

			return !rule.Any() ? 0 : rule.First().GetAttributeValue<int?>("bias").GetValueOrDefault(0) * -1;
		}

19 View Source File : MapController.cs
License : MIT License
Project Creator : Adoxio

public static IQueryable<Enreplacedy> FilterAlertsByDate(this IQueryable<Enreplacedy> query, int dateFilterCode, DateTime dateFrom, DateTime dateTo)
		{
			switch (dateFilterCode)
			{
				case 0: // filter last 7 days
					return query.Where(a => a.GetAttributeValue<DateTime?>("adx_scheduledstartdate").GetValueOrDefault() > DateTime.Now.AddDays(-7));
				case 1: // filter last 30 days
					return query.Where(a => a.GetAttributeValue<DateTime?>("adx_scheduledstartdate").GetValueOrDefault() > DateTime.Now.AddDays(-30));
				case 2: // filter last 12 months
					return query.Where(a => a.GetAttributeValue<DateTime?>("adx_scheduledstartdate").GetValueOrDefault() > DateTime.Now.AddMonths(-12));
				case 3: // filter by date range
					return query.Where(a => a.GetAttributeValue<DateTime?>("adx_scheduledstartdate").GetValueOrDefault() >= dateFrom && a.GetAttributeValue<DateTime?>("adx_scheduledstartdate").GetValueOrDefault() <= dateTo);
				default:
					return query;
			}
		}

19 View Source File : MapController.cs
License : MIT License
Project Creator : Adoxio

public static IQueryable<Enreplacedy> FilterServiceRequestsByDate(this IQueryable<Enreplacedy> query, int dateFilterCode, DateTime dateFrom, DateTime dateTo)
		{
			switch (dateFilterCode)
			{
				case 0: // filter last 7 days
					return query.Where(s => s.GetAttributeValue<DateTime?>("adx_incidentdate").GetValueOrDefault() > DateTime.Now.AddDays(-7));
				case 1: // filter last 30 days
					return query.Where(s => s.GetAttributeValue<DateTime?>("adx_incidentdate").GetValueOrDefault() > DateTime.Now.AddDays(-30));
				case 2: // filter last 12 months
					return query.Where(s => s.GetAttributeValue<DateTime?>("adx_incidentdate").GetValueOrDefault() > DateTime.Now.AddMonths(-12));
				case 3: // filter by date range
					return query.Where(s => s.GetAttributeValue<DateTime?>("adx_incidentdate").GetValueOrDefault() >= dateFrom && s.GetAttributeValue<DateTime?>("adx_incidentdate").GetValueOrDefault() <= dateTo);
				default:
					return query;
			}
		}

19 View Source File : WebFormServiceRequestResolveDuplicates.ascx.cs
License : MIT License
Project Creator : Adoxio

protected void Page_Load(object sender, EventArgs e)
		{
			if (Page.IsPostBack) return;

			if (PreviousStepEnreplacedyID == Guid.Empty)
			{
				throw new NullReferenceException("The ID of the previous web form step's created enreplacedy is null.");
			}

			var context = PortalCrmConfigurationManager.CreateServiceContext();
			var type = GetServiceRequestType(context);
			var duplicateDetectionView = type.GetAttributeValue<string>("adx_duplicateview");
			Guid viewId;

			if (!string.IsNullOrWhiteSpace(duplicateDetectionView) && Guid.TryParse(duplicateDetectionView, out viewId))
			{
				RegisterClientSideDependencies(this);

				var lareplacedudeFieldName = type.GetAttributeValue<string>("adx_lareplacedudefieldname");
				var longitudeFieldName = type.GetAttributeValue<string>("adx_longitudefieldname");

				var duplicateDistance = Convert.ToDouble(type.GetAttributeValue("adx_duplicatedistance"));
				var distanceUnit = type.GetAttributeValue<OptionSetValue>("adx_duplicatedistanceunit");
				var unit = distanceUnit != null ? (DuplicateDistanceUnit)distanceUnit.Value : DuplicateDistanceUnit.Miles;
				var distance = unit == DuplicateDistanceUnit.Miles ? (1.60934 * duplicateDistance) : duplicateDistance;

				var enreplacedy = GetPreviousStepEnreplacedy(context);
				var lareplacedude = enreplacedy.GetAttributeValue(lareplacedudeFieldName);
				var longitude = enreplacedy.GetAttributeValue(longitudeFieldName);

				if (lareplacedude != null && longitude != null)
				{
					CurrentServiceRequestId.Value = PreviousStepEnreplacedyID.ToString();
					RenderDuplicatesList(context, viewId, lareplacedudeFieldName, longitudeFieldName, Convert.ToDouble(lareplacedude), Convert.ToDouble(longitude), distance);
					RenderCurrentList(context, viewId);

					return;
				}
			}

			_isUnique = true;
			MoveToNextStep(PreviousStepEnreplacedyID);
		}

19 View Source File : WebFormServiceRequestResolveDuplicates.ascx.cs
License : MIT License
Project Creator : Adoxio

protected void Page_Load(object sender, EventArgs e)
		{
			if (Page.IsPostBack) return;

			if (PreviousStepEnreplacedyID == Guid.Empty)
			{
				throw new NullReferenceException("The ID of the previous web form step's created enreplacedy is null.");
			}

			var context = PortalCrmConfigurationManager.CreateServiceContext();
			var type = GetServiceRequestType(context);
			var duplicateDetectionView = type.GetAttributeValue<string>("adx_duplicateview");
			Guid viewId;

			if (!string.IsNullOrWhiteSpace(duplicateDetectionView) && Guid.TryParse(duplicateDetectionView, out viewId))
			{
				RegisterClientSideDependencies(this);

				var lareplacedudeFieldName = type.GetAttributeValue<string>("adx_lareplacedudefieldname");
				var longitudeFieldName = type.GetAttributeValue<string>("adx_longitudefieldname");

				var duplicateDistance = Convert.ToDouble(type.GetAttributeValue("adx_duplicatedistance"));
				var distanceUnit = type.GetAttributeValue<OptionSetValue>("adx_duplicatedistanceunit");
				var unit = distanceUnit != null ? (DuplicateDistanceUnit)distanceUnit.Value : DuplicateDistanceUnit.Miles;
				var distance = unit == DuplicateDistanceUnit.Miles ? (1.60934 * duplicateDistance) : duplicateDistance;

				var enreplacedy = GetPreviousStepEnreplacedy(context);
				var lareplacedude = enreplacedy.GetAttributeValue(lareplacedudeFieldName);
				var longitude = enreplacedy.GetAttributeValue(longitudeFieldName);

				if (lareplacedude != null && longitude != null)
				{
					CurrentServiceRequestId.Value = PreviousStepEnreplacedyID.ToString();
					RenderDuplicatesList(context, viewId, lareplacedudeFieldName, longitudeFieldName, Convert.ToDouble(lareplacedude), Convert.ToDouble(longitude), distance);
					RenderCurrentList(context, viewId);

					return;
				}
			}

			_isUnique = true;
			MoveToNextStep(PreviousStepEnreplacedyID);
		}

See More Examples