23 Ekim 2012 Salı

CRM 2011-Teklife Ürün Ekleme ( Create Quote Detail)


QuoteDetail detail = new QuoteDetail();

 detail.ProductId = urun.ToEntityReference();
 detail.UoMId = priceListItem.UoMId;
 detail.Quantity = miktar;
 detail.QuoteId = teklif.ToEntityReference();
 detail.ManualDiscountAmount = new Microsoft.Xrm.Sdk.Money(100,43);
 detail.IsPriceOverridden = true;
 detail.PricePerUnit = new Microsoft.Xrm.Sdk.Money(fiyat);

  //detail.ExtendedAmount = new Microsoft.Xrm.Sdk.Money(30);

  Guid _teklifurunId = service.Create(detail);

Burada dikkat edilmesi gerekenler;
UoMId=Teklifin fiyat listesindeki ürün kaleminin uomId sidir.
IsPriceOverridden=true =>FiyatListesiKalemindeki ürün degerını kullanmayıp yanı atanan fiyatı kullanır.

Yukarıdaki kodda urun degiskeni Product tipinde,teklif değiskeni de Quote tipindedir.

CRM 2011-IFrame Link Verme


Asagısaı javascript fonksıyonu sayfanın onLoad , onSave ya da fieldların onChange ine yazılabilir.
function IFrameLinkSet() {

    var entityid = Xrm.Page.data.entity.getId();
    var pricelistValue = new Array(); /*Guid deger alınıyor.*/
    pricelistValue = Xrm.Page.getAttribute("pricelevelid").getValue();
    var pricelistid = pricelistValue != null ? pricelistValue[0].id : null;

    var formType = Xrm.Page.ui.getFormType();
    if (formType == 2) {
        if (entityid != null && pricelistid != null) {

     /*IFrame de acılacak sayfanın adresi veriliyor.Ve adresle birlikte sayfaya veri gönderiliyor.*/
            var url = "http://localhost:8989/SalesAddProduct/SalesOrderProductView.aspx?entityid=" + entityid + "&pricelistid=" + pricelistid;

/*Link IFrame e setSrc() kullanılarak verildi.*/
            Xrm.Page.getControl("IFRAME_SalesOrderDetailsView").setSrc(url);
        }
    }
}

Crm 2011-ProductPriceLevel (Fiyat Listesi Kalemi) Bulma


Fiyatlistesi id ve ürün id ye göre fiyatlistesi kalemi bulma


Metot geriye productpricelevel döndürür.
public static ProductPriceLevel FindProductPriceLevel(Guid pricelevelid, Guid productId, IOrganizationService ser)
        {
            try
            {
                QueryExpression sorgu = new QueryExpression()
                {
                    EntityName = "productpricelevel",
                    ColumnSet = new ColumnSet() { AllColumns = true },
                };

                FilterExpression anaFilter = new FilterExpression(LogicalOperator.And);

                ConditionExpression sart1 = new ConditionExpression("pricelevelid", ConditionOperator.Equal, pricelevelid);
                ConditionExpression sart2 = new ConditionExpression("productid", ConditionOperator.Equal, productId);

                anaFilter.AddCondition(sart1);
                anaFilter.AddCondition(sart2);

                sorgu.Criteria.AddFilter(anaFilter);

                EntityCollection ec = null;

                ec = ser.RetrieveMultiple(sorgu);

                if (ec != null)
                {
                    if (ec.Entities.Count == 1)
                    {
                        return (ProductPriceLevel)ec.Entities[0];
                    }
                    else
                    {
                        return new ProductPriceLevel();
                       /*Eger fiyat listesinde ilgili üründen bir tane varsa geriye döndürür.Ürün yoksa ve birden fazlaysa geriye bos productpricelevel döndürür.*/
                    }
                }
                else
                {
                    return new ProductPriceLevel();
                }
            }

            catch (Exception)
            {
                return new ProductPriceLevel();
            }
        }
Sorularınızı gkhnmnts@gmail adresine atabilirsiniz.

Crm de Guid Bir Değere Göre Entity nin Bulunması


Aşagıdaki metoda veriyi çekeceğimiz entity nın adını,hangi field a göre sorgunun cekilecegi ve neye göre çekilecegi degerleriyle birlikte IOrganization nesnesini göndererek verimizi cekebiliriz.

public class Metotlar{
   public static Entity GetLookUp(string entityname, Guid id, string conditionField, IOrganizationService service)
        {
            try
            {
                QueryExpression sorgu = new QueryExpression()
                {
                    EntityName = entityname,
                    ColumnSet = new ColumnSet() { AllColumns = true },/*Tum kolonlar cekilir.*/
                };

                FilterExpression anaFilter = new FilterExpression(LogicalOperator.And);

                ConditionExpression sart1 = new ConditionExpression(conditionField, ConditionOperator.Equal, id);
                anaFilter.AddCondition(sart1);

                sorgu.Criteria.AddFilter(anaFilter);

                EntityCollection ec = null;

                ec = service.RetrieveMultiple(sorgu);

                if (ec != null)
                {
                    if (ec.Entities.Count > 0)
                    {
                        return ec.Entities[0];
                    }
                    else
                    {
                        return new Entity();
                    }
                }
                else
                {
                    return new Entity();
                }
            }

            catch (Exception)
            {
                return new Entity();
            }
        }
}
Örnek:
IOrganizationService crmService=DynamicCrmBaglanma.GetCrmService();
/*Crm e baglanılır.DynamicCrmBaglanma classı blog da bulunmaktadır.*/
if(crmService !=null){
Guid _productId=guid.NewGuid();
/*Ben yeni bir guid deger olusturarak parametre olarak gönderdim.*/
Entity product=Metotlar.GetLookUp(Product.EntityLogicalName,_productId,"productid",crmService);
if(product !=null && product.Id !=Guid.Empty){
Product urun=(Product)product;/*Entity Product a cast edildi.*/
}
}

CRM 2011 - INVOICE CANCELED


Şimdi sizlere formun ribbonundan bir butona tıklanarak invoice un nasıl canceled edilecegini anlatacağım.
İlk olarak formun ribbonuna bir buton ekleyelim ve javascript yazarak bu butona tıklanınca bir aspx sayfasına yönlendirilmesini sağlayalım.(ribbona buton ekleme ve bunun calıstırılacagı javascript dosyasının nasıl verildiğini bir başka yazımda anlatmıştım. )

namespace TestCRM.InvoiceInterface
{
    public partial class InvoiceCanceled : System.Web.UI.Page
    {
        IOrganizationService crmService;
//İlk olarak bir web sayfasından aspx sayfasına veri göndermeyi ve veri alıs verişini saglamak için Render metodunu kullandık.Gonderdıgımız veriyi queryString ile okuyoruz.
Verinin javascriptle nasıl yollandıgı sayfanın en alt kısmında bulabilirsiniz.
        protected override void Render(HtmlTextWriter writer)
        {
            Response.Clear();
            Response.ContentType = "text/xml";
            string entityID = Request.QueryString["entityid"];
            Session["entityid"] = entityID;// entity id yi postback olsa da kullanabiliyoruz.Sayfa kapanana kadar session da saklayıp ,istediğimiz zaman kullanabiliriz.
            if (!string.IsNullOrEmpty(entityID))
            {
                CanceledInvoice();
            }
            else
            {
                Response.Redirect("../ErrorPage.aspx");
//entity id javascript ile gönderilemezse hata sayfasına yonlendırıyoruz.
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
            }
        }
        private void CanceledInvoice()
        {
            string invoiceId = (string)Session["entityid"];
            Guid _invoiceId = Guid.Empty;

            if (!string.IsNullOrEmpty(invoiceId))
                _invoiceId = Guid.Parse(invoiceId);
            if (_invoiceId != Guid.Empty)
            {
//Crm e baglanıyoruz.
                crmService = DynamicCrmConnection.GetCrmService();
                if (crmService != null)
                {
                    Invoice invoice = (Invoice)crmService.Retrieve("invoice", invoice.Id, new ColumnSet() { AllColumns=true});
                    if (invoice != null && invoice.Id != Guid.Empty)
                    {
                        if (invoice.StateCode ==InvoiceState.Active)
                        {//invoice active se cancel edilebilir.
                            try
                            {
//SetStateRequest ile invoice un id si ve logical name ini vererek cancel edebiliyoruz.
//Statecode=3 invoice formunun canceled oldugunu gosterir.
//Status  =100003 de canceled formunun bir durumudur.
                                SetStateRequest setStateRequest = new SetStateRequest()
                                {
                                    EntityMoniker = new EntityReference
                                    {
                                        Id = invoice.Id,
                                        LogicalName = "invoice"
                                    },
                                    State = new OptionSetValue(3),// inactive
                                    Status = new OptionSetValue(100003)// qualified
                                };
                                crmService.Execute(setStateRequest); 
                            }
                            catch (Exception)
                            {
//Hata alınmazsa invoice canceled olmus demektir.  
                            }
                        }
                    }
                }
            }
        }
    }
}

Javascript

function CanceledInvoice() {

    var entityid = Xrm.Page.data.entity.getId();
/*invoice  formunun id si alınır ve XML.Dom kullanılarak aspx sayfasına veri gönderilir ve geriye veri okunur.*/
    var xmldoc_sendApp = new ActiveXObject("Microsoft.XMLDOM");
    xmldoc_sendApp.async = false;
    xmldoc_sendApp.load("http://denemehost:8989/InvoiceInterface/InvoiceCanceled.aspx?entityid=" + entityid);
/*yukarıdakı url sayfanızı host ettiğiniz sayfanın adresidir.Ben IIS teki yolunu verdim.8989 ise sayfanın bulundugu hostdakı port numarasıdır.*/
    var logMessage = xmldoc_sendApp.selectSingleNode("logmessage");
/*logmessage tagları arasında geriye veri gönderilir.*/
    if (logMessage != null) {
        if (logMessage.text != "") {
            alert(logMessage.text);
            window.location.reload();//Sayfa refresh olur.
        }
    }
}
Sorularınızı gkhnmnts@gmail adresine atabilirsiniz.

13 Eylül 2012 Perşembe

CRM 2011 ile Email Atma


Bir önceki yazımda template kullanarak email atmayı görmüstük.Bu yazım da da template kullanmadan basit mail atmayı anlatacagım.
Not:Bir önceki yazımda bu classın nasıl kullanılacagı bulunmaktadır.

public static Boolean EmailAt(IOrganizationService service,Guid fromUserId,Guid toContactId)
        {
            try
            {
                Boolean atildiMi = false;
                // Create the 'From:' activity party for the email
                ActivityParty fromParty = new ActivityParty
                {
                    PartyId = new EntityReference(SystemUser.EntityLogicalName, fromUserId)
                };

                // Create the 'To:' activity party for the email
                ActivityParty toParty = new ActivityParty
                {
                    PartyId = new EntityReference(Contact.EntityLogicalName, toContactId)
                };
                //"Created activity parties."

                // Create an e-mail message.
                Email email = new Email
                {
                    To = new ActivityParty[] { toParty },
                    From = new ActivityParty[] { fromParty },
                    Subject = "Quote Ready",
                    Description = "SDK Sample for SendEmail Message.",
                    DirectionCode = true
                };
                Guid _emailId = service.Create(email);

                // Use the SendEmail message to send an e-mail message.
                SendEmailRequest sendEmailreq = new SendEmailRequest
                {
                    EmailId = _emailId,
                    TrackingToken = "",
                    IssueSend = true
                };

                //"Sent the e-mail message." 
                SendEmailResponse sendEmailresp = (SendEmailResponse)service.Execute(sendEmailreq);
                atildiMi = sendEmailresp !=null ? true :false;

                return atildiMi;
            }
            catch (Exception)
            {
                return false;
            }
        }

Template Kullanarak Crm 2011 ile Email Yollama


İlk önce mail atan classı paylasacagım sızlerle.Daha sonra da bu classın nasıl kullanıldıgını anlatacagım.

EmailAt Classı:
Mail atma işlemi basarılıysa geriye true,degil se false degeri dondurur.
namespace SendEmail
{
    public class EmailClass
    {
        public static Boolean EmailAt(IOrganizationService service,Guid fromUserId,Guid toContactId)
        {
            try
            {
                Boolean atildiMi = false;
                // Kimin email atılacagı tanımlanıyor.
                ActivityParty fromParty = new ActivityParty
                {
                    PartyId = new EntityReference(SystemUser.EntityLogicalName, fromUserId)
                };

                // Kime email atılacagı tanımlanıyor.
                ActivityParty toParty = new ActivityParty
                {
                    PartyId = new EntityReference(Contact.EntityLogicalName, toContactId)
                };

                // Gonderılecek  Email mesajını olusturalım
                Email email = new Email
                {
                    To = new ActivityParty[] { toParty },
                    From = new ActivityParty[] { fromParty },
                    Subject = "Quote Ready",
                    Description = "SDK Sample for SendEmail Message.",
                    DirectionCode = true
                };
                // Email mesajının sablonunu olusturalım.
                SendEmailFromTemplateRequest emailUsingTemplateReq = new SendEmailFromTemplateRequest
                {
                    Target = email,
                    //  Crm im hazır bir template ini kullanıyoruz.
                    TemplateId = new Guid("07B94C1D-C85F-492F-B120-F0A743C540E6"),

                    // Email dekı hitap içerigini tanımlıyoruz.
                    RegardingId = toContactId,
                    RegardingType = Contact.EntityLogicalName
                };
                SendEmailFromTemplateResponse emailUsingTemplateResp = (SendEmailFromTemplateResponse)service.Execute(emailUsingTemplateReq);

                //Template ile birlikte bir email id olusturup.Emaili yaratmıs oluyoruz.
                Guid _emailId = emailUsingTemplateResp.Id;

                atildiMi = !_emailId.Equals(Guid.Empty) ? true :false;
                //atildımı true ise :Basarılı bir sekılde email yollandı.

                return atildiMi;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }

Default.aspx :
Ben burada crm den javascript ile atılacak kişilerin id degerini QueryString ile aldım.Siz isterseniz direkt olarak id degerini verebilirsiniz.
namespace SendEmail
{
    public partial class Default : System.Web.UI.Page
    {
        IOrganizationService crmService;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Guid _firstApprovedId =!string.IsNullOrEmpty(Request.QueryString["firstApproved"] )? 
                                         Guid.Parse(Request.QueryString["firstApproved"]) :Guid.Empty;
                Guid _secondApprovedId =!string.IsNullOrEmpty(Request.QueryString["secondApproved"]) ? 
                                        Guid.Parse(Request.QueryString["secondApproved"]) : Guid.Empty;
                Guid _thirdApprovedId = !string.IsNullOrEmpty(Request.QueryString["thirdApproved"]) ? 
                                        Guid.Parse(Request.QueryString["thirdApproved"]) : Guid.Empty;

                EmailYolla(_firstApprovedId,_secondApprovedId,_thirdApprovedId);
            }
        }

        protected void EmailYolla(Guid firstApprovedId,Guid secondApprovedId,Guid thirdApprovedId)
        {
            crmService = DynamicCrmBaglanma.GetCrmService();
            Boolean onay1 = false;
            Boolean onay2 = false;
            Boolean onay3 = false;
            string DonusMesaji="";

            ColumnSet tumKolon = new ColumnSet() { AllColumns = true };

            WhoAmIRequest systemUserRequest = new WhoAmIRequest();
            WhoAmIResponse systemUserResponse = (WhoAmIResponse)crmService.Execute(systemUserRequest);
            Guid _userId = systemUserResponse.UserId;

            Contact firstApproved = (Contact)crmService.Retrieve("contact", firstApprovedId, tumKolon);
            Contact secondApproved = (Contact)crmService.Retrieve("contact", secondApprovedId, tumKolon);
            Contact thirdApproved = (Contact)crmService.Retrieve("contact", thirdApprovedId, tumKolon);

            if (firstApproved != null && firstApproved.Id != Guid.Empty && firstApproved.EMailAddress1 !=string.Empty)
                onay1 = EmailClass.EmailAt(crmService, _userId, firstApproved.Id);

            if (secondApproved != null && secondApproved.Id != Guid.Empty && secondApproved.EMailAddress1 != string.Empty)
                onay2 = EmailClass.EmailAt(crmService, _userId, secondApproved.Id);

            if (thirdApproved != null && thirdApproved.Id != Guid.Empty && thirdApproved.EMailAddress1 != string.Empty)
                onay3 = EmailClass.EmailAt(crmService, _userId, thirdApproved.Id);

            if (onay1 != true && onay2 !=true && onay3 != true)
            {
                DonusMesaji="Unsucceeded";
            }
            else
            {
                DonusMesaji = "Send Email.";
            }
        }
    }