Example #1
0
        public void ProcessRequest(HttpContext context)
        {
            FileLogHelper.LogEvent("Kale-uploadHelper", @"C:\DO\");

            context.Response.ContentType = "application/json";

            object returnValue = null;

            JavaScriptSerializer serializer = new JavaScriptSerializer();

            try
            {
                _sda = new SqlDataAccess();
                _sda.openConnection(Globals.ConnectionString);

                string operation  = context.Request.QueryString["operation"];
                string userId     = context.Request.QueryString["userid"];
                string graffitiId = context.Request.QueryString["graffitiId"];

                if (operation == "1" && !string.IsNullOrEmpty(userId)) //Profile resmi güncelleme
                {
                    returnValue = new MsCrmResult();

                    _service = MSCRM.GetOrgService(true);
                    HttpPostedFile file = context.Request.Files[0];

                    returnValue = SaveProfileImage(userId, file, context);
                }
                else if (operation == "2" && !string.IsNullOrEmpty(graffitiId)) //Duvar yazısı resim ekleme
                {
                    returnValue = new MsCrmResult();

                    _service = MSCRM.GetOrgService(true);
                    HttpPostedFile file = context.Request.Files[0];

                    returnValue = SaveGraffitiImage(new Guid(graffitiId), file, context);
                }
                else
                {
                    ((MsCrmResultObject)returnValue).Result = "Eksik veya yanlış parametre.";
                }
            }
            catch (Exception ex)
            {
                returnValue = new MsCrmResult();
                ((MsCrmResult)returnValue).HasException = true;
                ((MsCrmResult)returnValue).Result       = ex.Message;
            }
            finally
            {
                if (_sda != null)
                {
                    _sda.closeConnection();
                }
            }

            var dataRes = serializer.Serialize(returnValue);

            context.Response.Write(dataRes);
        }
Example #2
0
        static void Main(string[] args)
        {
            SqlDataAccess sda = null;

            try
            {
                sda = new SqlDataAccess();
                sda.openConnection(Globals.ConnectionString);

                IOrganizationService service = MSCRM.GetOrgService(true);

                ProductProcess.Process(sda, service);

                HomeOptionProductProcess.SetOptionState(sda, service);

                //HomeOptionProductProcess.SetProductStatus(sda, service);
            }
            catch (Exception)
            {
            }
            finally
            {
                if (sda != null)
                {
                    sda.closeConnection();
                }
            }
        }
Example #3
0
        static void Main(string[] args)
        {
            SqlDataAccess sda = null;

            try
            {
                sda = new SqlDataAccess();
                sda.openConnection(Globals.ConnectionString);

                IOrganizationService service = MSCRM.GetOrgService(true);
                //Musterının sahıbı olan Satıs Temsılcısıne 1 haftalık vadesı olan senetlerı Gönderir
                Process.ExecuteFilterUser(sda, service);
                //Filtresiz Mail Grubuna Göndeir
                Process.ExecuteMailGroup(sda, service);
            }
            catch (Exception)
            {
            }
            finally
            {
                if (sda != null)
                {
                    sda.closeConnection();
                }
            }
        }
Example #4
0
        public static MsCrmResult SaveAnnotation(Annotation note, string relationName)
        {
            MsCrmResult returnValue = new MsCrmResult();

            try
            {
                IOrganizationService service = MSCRM.GetOrgService(true);

                int splitLength = note.FileName.Split('.').Length;
                note.FilePath = Guid.NewGuid() + "." + note.FileName.Split('.')[splitLength - 1].ToLower();

                returnValue = AttachmentFileHelper.CreateAttachmentFile(note, service);

                if (returnValue.Success)
                {
                    byte[] data = Convert.FromBase64String(note.File);
                    //File.WriteAllBytes(HostingEnvironment.MapPath("~/attachments") + "/" + note.FilePath, data);
                    File.WriteAllBytes(@Globals.AttachmentFolder + @"\" + note.FilePath, data);

                    note.AttachmentFile = new EntityReference("new_attachment", returnValue.CrmId);
                    returnValue         = AttachmentFileHelper.AssociateAttachmentToEntity(returnValue.CrmId, note.Object, relationName, service);
                }
            }
            catch (Exception ex)
            {
                returnValue.Success = false;
                returnValue.Result  = ex.Message;
            }
            return(returnValue);
        }
Example #5
0
        public static void ExtractFromAudit()
        {
            IOrganizationService service = MSCRM.GetOrgService(true);

            // The GUID of the object you want to retirve in this case i am passing contactid
            var entityId = new Guid("B53045DC-8BF1-E411-80D0-005056A60603");

            Console.WriteLine("Retrieving the change history.\n");

            //
            //RetrieveAttributeChangeHistoryRequest req = new RetrieveAttributeChangeHistoryRequest();
            //req.Target = new Microsoft.Xrm.Sdk.EntityReference("quote", new Guid("592AF7E6-ADC1-E011-8D7C-1CC1DE79838E"));
            //req.AttributeLogicalName = "totallineitemamount";
            //RetrieveAttributeChangeHistoryResponse resp = (RetrieveAttributeChangeHistoryResponse)service.Execute(req);



            // Retrieve the audit history for the account and display it.
            RetrieveRecordChangeHistoryRequest changeRequest = new RetrieveRecordChangeHistoryRequest();

            changeRequest.Target = new Microsoft.Xrm.Sdk.EntityReference("quote", entityId);



            RetrieveRecordChangeHistoryResponse changeResponse =
                (RetrieveRecordChangeHistoryResponse)service.Execute(changeRequest);

            AuditDetailCollection details = changeResponse.AuditDetailCollection;

            foreach (AttributeAuditDetail detail in details.AuditDetails)
            {
                DisplayAuditDetails(detail);
                // Display some of the detail information in each audit record.
            }
        }
Example #6
0
        public SendSms()
        {
            InitializeComponent();

            try
            {
                LOG_PATH       = Globals.FileLogPath;
                ERROR_LOG_PATH = Globals.FileLogPath;

                _tokenSource = new CancellationTokenSource();
                _token       = _tokenSource.Token;

                _timer           = new System.Timers.Timer();
                _timer.Interval  = Convert.ToDouble(ConfigurationManager.AppSettings["serviceInterval"]);
                _timer.AutoReset = true;
                _timer.Enabled   = true;

                _timer.Elapsed += timer_Elapsed;

                _sda = new SqlDataAccess();
                _sda.openConnection(Globals.ConnectionString);

                _service = MSCRM.GetOrgService(true);

                _serviceProcess = new ServiceProcess(_sda, _service);
            }
            catch (Exception ex)
            {
                FileLogHelper.LogFunction(this.GetType().Name, "SendSms_SendSms_EXCEPTION:" + ex.Message, ERROR_LOG_PATH);
            }
        }
Example #7
0
        public static MsCrmResult DeleteProfileImage(string entityId, string entityName, string fieldName, string fileName)
        {
            MsCrmResult returnValue = new MsCrmResult();

            try
            {
                IOrganizationService service = MSCRM.GetOrgService(true);

                //string filePath = HostingEnvironment.MapPath("~/attachments") + "/" + fileName;
                string filePath = @Globals.AttachmentFolder + @"\" + fileName;

                if (System.IO.File.Exists(filePath))
                {
                    System.IO.File.Delete(filePath);

                    Entity ent = new Entity(entityName);
                    ent[entityName + "id"] = new Guid(entityId);
                    ent[fieldName]         = null;

                    service.Update(ent);
                }

                returnValue.Success = true;
                returnValue.Result  = "Dosya silindi!";
            }
            catch (Exception ex)
            {
                returnValue.Success = false;
                returnValue.Result  = ex.Message;
            }
            return(returnValue);
        }
Example #8
0
        public MsCrmResult GetToken(string userName, string password)
        {
            MsCrmResult returnValue = new MsCrmResult();

            try
            {
                if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
                {
                    _sda = new SqlDataAccess();
                    _sda.openConnection(Globals.ConnectionString);

                    returnValue = LoginHelper.LoginControl(new Guid(Globals.DefaultPortalId), userName, password, _sda);

                    //returnValue.Success = true;

                    if (returnValue.Success)
                    {
                        Guid systemUserId = returnValue.CrmId;

                        _service = MSCRM.GetOrgService(true);
                        string ipAddress = HttpContext.Current.Request.UserHostAddress;

                        MsCrmResult logResult = LoginHelper.LogLogIn(returnValue.CrmId, new Guid(Globals.DefaultPortalId), DateTime.Now, ipAddress, _service);

                        returnValue.Result = Guid.NewGuid().ToString().Replace("-", "");

                        MsCrmResult sessionResult = SetUserSession(returnValue.Result, new Guid(Globals.DefaultPortalId), systemUserId);

                        if (!sessionResult.Success)
                        {
                            return(sessionResult);
                        }
                    }
                }
                else
                {
                    returnValue.Result = "Eksik Parametre.";
                }
            }
            catch (Exception ex)
            {
                returnValue.Result = ex.Message;
            }
            finally
            {
                if (_sda != null)
                {
                    _sda.closeConnection();
                }
            }

            return(returnValue);
        }
Example #9
0
        public static MsCrmResult SaveObjectProfileImage(Annotation note, string fieldName, SqlDataAccess sda)
        {
            MsCrmResult returnValue = new MsCrmResult();

            try
            {
                IOrganizationService service = MSCRM.GetOrgService(true);

                int splitLength = note.FileName.Split('.').Length;
                note.FilePath = Guid.NewGuid() + "." + note.FileName.Split('.')[splitLength - 1].ToLower();

                byte[] data = Convert.FromBase64String(note.File);

                //File.WriteAllBytes(HostingEnvironment.MapPath("~/attachments") + "/" + note.FilePath, data);
                File.WriteAllBytes(@Globals.AttachmentFolder + @"\" + note.FilePath, data);

                #region | DELETE PREVIOUS IMAGE FILE |

                string fileName = AttachmentFileHelper.GetEntityProfileImageFileName(note.Object.Id.ToString(), note.Object.LogicalName, fieldName, sda);

                if (!string.IsNullOrEmpty(fileName))
                {
                    //string filePath = HostingEnvironment.MapPath("~/attachments") + "/" + fileName;
                    string filePath = @Globals.AttachmentFolder + @"\" + fileName;

                    if (System.IO.File.Exists(filePath))
                    {
                        System.IO.File.Delete(filePath);
                    }
                }

                #endregion

                #region | UPDATE CRM ENTITY |

                Entity ent = new Entity(note.Object.LogicalName.ToLower());
                ent[note.Object.LogicalName.ToLower() + "id"] = note.Object.Id;
                ent[fieldName] = note.FilePath;

                service.Update(ent);

                #endregion

                returnValue.Success = true;
                returnValue.Result  = note.FilePath;
            }
            catch (Exception ex)
            {
                returnValue.Success = false;
                returnValue.Result  = ex.Message;
            }
            return(returnValue);
        }
Example #10
0
        private void StartOperation()
        {
            _sda = new SqlDataAccess();
            _sda.openConnection(Globals.ConnectionString);

            _service = MSCRM.GetOrgService(true);

            _timer           = new System.Timers.Timer();
            _timer.Interval  = SERVICE_INTERVAL;
            _timer.AutoReset = true;
            _timer.Enabled   = true;

            _timer.Elapsed += _timer_Elapsed;

            _timer.Start();
        }
Example #11
0
        public static MsCrmResult QuoteHasPrePayment(Guid quoteId, SqlDataAccess sda)
        {
            MsCrmResult returnValue = new MsCrmResult();

            try
            {
                #region | SQL QUERY |
                string query = @"SELECT
	                                P.new_paymentId PaymentId
                                FROM
	                                new_payment AS P WITH (NOLOCK)
                                WHERE
	                                P.new_type = {0}
                                    AND 
	                                P.new_quoteid = '{1}'
                                    AND
                                    P.StateCode = 0";
                #endregion
                IOrganizationService service = MSCRM.GetOrgService(true);
                DataTable            dt      = sda.getDataTable(string.Format(query, (int)PaymentTypes.KaporaOdemesi, quoteId));
                Entity product = GetProductByQuoteId(service, quoteId);
                if (product == null)
                {
                    returnValue.Success = false;
                    return(returnValue);
                }
                Guid             projectId = product.Contains("new_projectid") ? ((EntityReference)product.Attributes["new_projectid"]).Id : Guid.Empty;
                EntityCollection list      = GetProjectSalesCollaborateList(service, projectId);
                if (dt != null && (dt.Rows.Count >= list.Entities.Count))//Ortaklık yapısı 2 olduğu için ÖDeme kaydı 2 adet oluşuyor
                {
                    returnValue.CrmId   = (Guid)dt.Rows[0]["PaymentId"];
                    returnValue.Result  = "Satışla ilgili kapora kaydı bulunmaktadır!";
                    returnValue.Success = true;
                }
                //else if (dt != null && dt.Rows.Count == 0)
                else
                {
                    returnValue.Result  = "Satışla ilgili kapora kaydı bulunmamaktadır!";
                    returnValue.Success = false;
                }
            }
            catch (Exception)
            {
                throw;
            }
            return(returnValue);
        }
Example #12
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";

            JavaScriptSerializer serializer = new JavaScriptSerializer();

            string message = string.Empty;

            var op = context.Request.QueryString["operation"];


            if (op != null && op == "1")
            {
                var base64Data = context.Request.Form["data"];
                var quoteId    = context.Request.Form["quoteid"];

                IOrganizationService service = MSCRM.GetOrgService(true);

                Entity attach = new Entity("annotation");

                attach["filename"]       = context.Request.Form["name"];
                attach["mimetype"]       = context.Request.Form["type"];
                attach["filesize"]       = context.Request.Form["size"];
                attach["subject"]        = context.Request.Form["name"];
                attach["documentbody"]   = base64Data;
                attach["objecttypecode"] = 1084;
                attach["isdocument"]     = true;
                attach["objectid"]       = new EntityReference("quote", new Guid(quoteId));

                service.Create(attach);

                var data = serializer.Serialize(true);
                context.Response.Write(data);
            }
            else if (op == "2")
            {
                var data = context.Request.Form["data"];

                JavaScriptSerializer js            = new JavaScriptSerializer();
                List <Activity>      phoneCallList = js.Deserialize <List <Activity> >(data);
                MsCrmResult          result        = ExportPhoneCall(phoneCallList);

                var dataRes = serializer.Serialize(result);
                context.Response.Write(dataRes);
            }
        }
Example #13
0
        static void Main(string[] args)
        {
            IOrganizationService service = MSCRM.GetOrgService(true);
            SqlDataAccess        sda     = new SqlDataAccess();

            sda.openConnection(Globals.ConnectionString);
            string    query = @"SELECT new_channelofawarenessId FROM new_channelofawareness";
            DataTable dt    = sda.getDataTable(query);

            sda.closeConnection();

            foreach (DataRow dr in dt.Rows)
            {
                Entity c = new Entity("new_channelofawareness");
                c.Id          = (Guid)dr["new_channelofawarenessId"];
                c["new_code"] = (dt.Rows.IndexOf(dr) + 1).ToString();
                service.Update(c);
            }
        }
Example #14
0
        public static MsCrmResult Process()
        {
            MsCrmResult returnValue = new MsCrmResult();

            try
            {
                service = MSCRM.GetOrgService(true);

                SqlDataAccess sda = new SqlDataAccess();
                sda.openConnection(Globals.ConnectionString);

                List <ExpenseCenter> expenseCenterList = LogoHelper.GetExpenseCenterList(sda);

                if (expenseCenterList.Count > 0)
                {
                    for (int i = 0; i < expenseCenterList.Count; i++)
                    {
                        List <LogoAccount> logoAccountList = LogoHelper.GetLogoFirmalar(expenseCenterList[i].ProjeID, sda);

                        if (logoAccountList.Count > 0)
                        {
                            for (int j = 0; j < logoAccountList.Count; j++)
                            {
                                LogoHelper.CreateExpenseCenter(expenseCenterList[i], logoAccountList[j]);
                            }
                        }

                        LogoHelper.LogoAktarimFalse(expenseCenterList[i].MasrafMerkezId, "product", service);
                    }
                }

                returnValue.Success = true;
                returnValue.Result  = "Masraf merkezi entegrasyonu tamamlandı.";
            }
            catch (Exception ex)
            {
                returnValue.Result = ex.Message;
            }

            return(returnValue);
        }
Example #15
0
        public GiftServiceResult Post(GiftUpdateInfo val)
        {
            GiftServiceResult returnValue = new GiftServiceResult();

            if (string.IsNullOrWhiteSpace(val.api_key) || string.IsNullOrWhiteSpace(val.id))
            {
                returnValue.message = "Failure";

                return(returnValue);
            }

            if (val.api_key != "6r9ZTok8zp4yZxKq")
            {
                returnValue.message = "Not authorized";

                return(returnValue);
            }

            try
            {
                IOrganizationService service = MSCRM.GetOrgService(true);

                UserGiftRequest request = new UserGiftRequest();
                request.Id = new Guid(val.id);

                request.ShippingCompany = val.shipping_company;
                request.ShippingNo      = val.shipping_no;
                request.Note            = val.note;
                request.ServiceStatus   = val.status;

                GiftHelper.UpdateGiftRequest(request, service);

                returnValue.message = "Success";
            }
            catch (Exception ex)
            {
                returnValue.message = "Failure | Ex:" + ex.Message;
            }

            return(returnValue);
        }
Example #16
0
        Dictionary <Guid, QuoteStatus> GetQuoteId(string quoteNumber)
        {
            Dictionary <Guid, QuoteStatus> returnValue = new Dictionary <Guid, QuoteStatus>();

            IOrganizationService service = MSCRM.GetOrgService(true);
            ConditionExpression  con1    = new ConditionExpression();

            con1.AttributeName = "quotenumber";
            con1.Operator      = ConditionOperator.Equal;
            con1.Values.Add(quoteNumber);

            ConditionExpression con2 = new ConditionExpression();

            con2.AttributeName = "statuscode";
            con2.Operator      = ConditionOperator.NotEqual;
            con2.Values.Add(7);//Düzeltilmiş olmayacak

            FilterExpression filter = new FilterExpression();

            filter.FilterOperator = LogicalOperator.And;
            filter.Conditions.Add(con1);
            filter.Conditions.Add(con2);

            QueryExpression Query = new QueryExpression("quote");

            Query.ColumnSet = new ColumnSet(true);
            Query.Criteria.FilterOperator = LogicalOperator.And;
            Query.Criteria.Filters.Add(filter);

            EntityCollection Result = service.RetrieveMultiple(Query);

            if (Result.Entities.Count > 0)
            {
                Entity q = Result.Entities[0];

                returnValue.Add(q.Id, (QuoteStatus)(int)((OptionSetValue)q["statuscode"]).Value);
            }

            return(returnValue);
        }
Example #17
0
        static void Main(string[] args)
        {
            SqlDataAccess sda = null;

            try
            {
                sda = new SqlDataAccess();
                sda.openConnection(Globals.ConnectionString);
                IOrganizationService service = MSCRM.GetOrgService(true);
                Process.Execute(sda, service);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (sda != null)
                {
                    sda.closeConnection();
                }
            }
        }
Example #18
0
        public MsCrmResult CreateAsseblyRequest(string token, AssemblyRequestInfo requestInfo)
        {
            MsCrmResult returnValue = new MsCrmResult();

            LoginSession ls = new LoginSession();

            try
            {
                #region | CHECK SESSION |
                MsCrmResultObj <LoginSession> sessionResult = GetUserSession(token);

                if (!sessionResult.Success)
                {
                    returnValue.Result = sessionResult.Result;
                    return(returnValue);
                }
                else
                {
                    ls = sessionResult.ReturnObject;
                }

                #endregion

                _service = MSCRM.GetOrgService(true);

                //_sda = new SqlDataAccess();
                //_sda.openConnection(Globals.ConnectionString);

                #region | DATA VALIDATION |

                if (string.IsNullOrWhiteSpace(requestInfo.FirstName))
                {
                    returnValue.Result = "Ad alanı boş olamaz.";

                    return(returnValue);
                }

                if (string.IsNullOrWhiteSpace(requestInfo.LastName))
                {
                    returnValue.Result = "Soyad alanı boş olamaz.";

                    return(returnValue);
                }

                if (string.IsNullOrWhiteSpace(requestInfo.MobilePhoneNumber))
                {
                    returnValue.Result = "Cep Telefonu alanı boş olamaz.";

                    return(returnValue);
                }

                if (!ValidationHelper.CheckTelephoneNumber(requestInfo.MobilePhoneNumber).isFormatOK)
                {
                    returnValue.Result = "Cep Telefonu formatı hatalıdır. Örn:+90-5xx-xxxxxxx şeklinde olmalıdır.";

                    return(returnValue);
                }

                if (string.IsNullOrWhiteSpace(requestInfo.EmailAddress))
                {
                    returnValue.Result = "Email adresi alanı boş olamaz.";

                    return(returnValue);
                }

                if (string.IsNullOrWhiteSpace(requestInfo.AddressDetail))
                {
                    returnValue.Result = "Adres detayı alanı boş olamaz.";

                    return(returnValue);
                }

                if (requestInfo.RequestCityId == null || requestInfo.RequestCityId == Guid.Empty)
                {
                    returnValue.Result = "İl alanı boş olamaz.";

                    return(returnValue);
                }

                if (requestInfo.RequestTownId == null || requestInfo.RequestTownId == Guid.Empty)
                {
                    returnValue.Result = "İlçe alanı boş olamaz.";

                    return(returnValue);
                }

                #endregion

                requestInfo.Name = requestInfo.Name + "|" + requestInfo.LastName + "|" + DateTime.Now.ToString("dd.MM.yyyy HH:mm");

                returnValue = AssemblyRequestHelper.CreateAssemblyRequest(requestInfo, _service);
            }
            catch (Exception ex)
            {
                returnValue.HasException = true;
                returnValue.Result       = ex.Message;
            }
            finally
            {
                if (_sda != null)
                {
                    _sda.closeConnection();
                }
            }

            return(returnValue);
        }
Example #19
0
        public string GetQuote(string productNumber)
        {
            string returnValue       = string.Empty;
            JavaScriptSerializer ser = new JavaScriptSerializer();

            QuoteInfoResult quoteInfoResult = new QuoteInfoResult();
            QuoteInfo       quoteInfo       = new QuoteInfo();


            MsCrmResult result = new MsCrmResult();

            IOrganizationService service;

            if (string.IsNullOrWhiteSpace(productNumber))
            {
                result.Message = "productNumber Değeri Boş Olmaz";
                result.Success = false;

                returnValue = ser.Serialize(quoteInfoResult);
                return(returnValue);
            }

            try
            {
                service = MSCRM.GetOrgService(true);
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Message = "CRM Erişimi Yapılamamaktadır " + ex.Message;

                quoteInfoResult.Result = result;
                returnValue            = ser.Serialize(quoteInfoResult);
                return(returnValue);
            }

            try
            {
                LinkEntity productLink = new LinkEntity();
                productLink.EntityAlias           = "productLink";
                productLink.LinkFromEntityName    = "quote";
                productLink.LinkFromAttributeName = "new_productid";
                productLink.LinkToEntityName      = "product";
                productLink.LinkToAttributeName   = "productid";
                productLink.Columns      = new ColumnSet("productid", "new_licencenumber");
                productLink.LinkCriteria = new FilterExpression(LogicalOperator.And);
                productLink.LinkCriteria.AddCondition("productnumber", ConditionOperator.Equal, productNumber);


                FilterExpression filterExpression = new FilterExpression();
                filterExpression.FilterOperator = LogicalOperator.Or;
                filterExpression.AddCondition("statuscode", ConditionOperator.Equal, (int)QuoteStatus.Kazanıldı);
                filterExpression.AddCondition("statuscode", ConditionOperator.Equal, (int)QuoteStatus.SozlesmeHazirlandi);
                filterExpression.AddCondition("statuscode", ConditionOperator.Equal, (int)QuoteStatus.Sözleşmeİmzalandı);
                filterExpression.AddCondition("statuscode", ConditionOperator.Equal, (int)QuoteStatus.MuhasebeyeAktarıldı);
                filterExpression.AddCondition("statuscode", ConditionOperator.Equal, (int)QuoteStatus.TeslimEdildi);

                QueryExpression quoteQuery = new QueryExpression();
                quoteQuery.EntityName = "quote";
                quoteQuery.Criteria   = new FilterExpression(LogicalOperator.And);
                quoteQuery.ColumnSet  = new ColumnSet("quotenumber", "new_projectid", "new_productid", "customerid");
                quoteQuery.Criteria.AddFilter(filterExpression);
                quoteQuery.LinkEntities.Add(productLink);
                quoteQuery.NoLock   = true;
                quoteQuery.TopCount = 1;
                EntityCollection quoteList = service.RetrieveMultiple(quoteQuery);
                if (quoteList.Entities.Count > 0)
                {
                    string name         = string.Empty;
                    string phone        = string.Empty;
                    string emailaddress = string.Empty;

                    Entity       quote              = quoteList.Entities[0];
                    AliasedValue licenceNumber      = quote.GetAttributeValue <AliasedValue>("productLink.new_licencenumber");
                    string       licenceNumberValue = string.Empty;
                    if (licenceNumber != null)
                    {
                        licenceNumberValue = Convert.ToString(licenceNumber.Value);
                    }

                    EntityReference productRef  = quote.GetAttributeValue <EntityReference>("new_productid");
                    EntityReference projectRef  = quote.GetAttributeValue <EntityReference>("new_projectid");
                    string          quoteNumber = quote.GetAttributeValue <string>("quotenumber");
                    EntityReference customerRef = quote.GetAttributeValue <EntityReference>("customerid");

                    if (customerRef.LogicalName == "account")
                    {
                        Entity account = service.Retrieve(customerRef.LogicalName, customerRef.Id, new ColumnSet("name", "telephone1", "emailaddress1"));
                        name         = account.GetAttributeValue <string>("name");
                        phone        = account.GetAttributeValue <string>("telephone1");
                        emailaddress = account.GetAttributeValue <string>("emailaddress1");
                    }
                    else if (customerRef.LogicalName == "contact")
                    {
                        Entity contact = service.Retrieve(customerRef.LogicalName, customerRef.Id, new ColumnSet("fullname", "mobilephone", "emailaddress1"));
                        name         = contact.GetAttributeValue <string>("fullname");
                        phone        = contact.GetAttributeValue <string>("mobilephone");
                        emailaddress = contact.GetAttributeValue <string>("emailaddress1");
                    }

                    quoteInfo.Name          = name;
                    quoteInfo.Email         = emailaddress;
                    quoteInfo.Phone         = phone;
                    quoteInfo.ProjectName   = projectRef.Name;
                    quoteInfo.QuoteNumber   = quoteNumber;
                    quoteInfo.LicenceNumber = licenceNumberValue;

                    result.Success = true;
                    result.Message = SuccessMessage;

                    quoteInfoResult.QuoteInfo = quoteInfo;
                }
                else
                {
                    result.Success = false;
                    result.Message = productNumber + " Nolu Konut Bulunmamakta yada Uygun Satış Bilgisi Bulunmamaktadır.";
                }
            }
            catch (Exception ex)
            {
                eventLog = new EventLogHelper(service, "CompanyInternal");
                eventLog.Log("GetQuote", ex.Message, EventLogHelper.EventType.Exception);
                result.Message = ex.Message;
                result.Success = false;
            }

            quoteInfoResult.Result = result;
            returnValue            = ser.Serialize(quoteInfoResult);
            return(returnValue);
        }
Example #20
0
        public static MsCrmResult Process()
        {
            MsCrmResult returnValue = new MsCrmResult();

            Console.WriteLine("Update Contact Title Case working....");

            int errorCount   = 0;
            int successCount = 0;

            IOrganizationService service = MSCRM.GetOrgService(true);
            SqlDataAccess        sda     = new SqlDataAccess();

            sda.openConnection(Globals.ConnectionString);

            #region | SQL QUERY |

            string sqlQuery = @"SELECT
	                                c.ContactId
	                                ,c.FirstName
	                                ,c.LastName
                                FROM
                                Contact AS c (NOLOCK)
                                WHERE
                                c.StateCode=0
                                --AND
                                --c.ContactId IN ('09055AF4-95F4-E411-80D0-005056A60603','B40A2ADB-94F4-E411-80D0-005056A60603')
                                ORDER BY 
	                                c.CreatedOn DESC"    ;
            #endregion

            DataTable dt = sda.getDataTable(sqlQuery);

            Console.SetCursorPosition(0, 2);
            Console.WriteLine("Data Count:" + dt.Rows.Count.ToString());

            if (dt.Rows.Count > 0)
            {
                OrganizationRequestCollection reqList = new OrganizationRequestCollection();

                int packetCount = dt.Rows.Count % 1000;

                int packetCounter = 0;

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Console.SetCursorPosition(0, 3);
                    Console.WriteLine("COUNTER:" + (i + 1).ToString());

                    try
                    {
                        string firstName = dt.Rows[i]["FirstName"] != DBNull.Value ? dt.Rows[i]["FirstName"].ToString() : string.Empty;
                        string lastName  = dt.Rows[i]["LastName"] != DBNull.Value ? dt.Rows[i]["LastName"].ToString() : string.Empty;

                        string newFirstName = string.Empty;
                        string newLastName  = string.Empty;

                        if (firstName != string.Empty)
                        {
                            newFirstName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(firstName.ToLower());
                        }

                        if (lastName != string.Empty)
                        {
                            newLastName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(lastName.ToLower());
                        }


                        Entity ent = new Entity("contact");
                        ent.Id           = (Guid)dt.Rows[i]["ContactId"];
                        ent["firstname"] = newFirstName;
                        ent["lastname"]  = newLastName;

                        UpdateRequest updateRequest = new UpdateRequest();
                        updateRequest.Target = ent;

                        reqList.Add(updateRequest);

                        if (reqList.Count == 1000)
                        {
                            MigrationHelper.executeMultipleWithRequests(reqList, "contacttitlecase", service);
                            reqList = new OrganizationRequestCollection();

                            packetCounter++;

                            Console.SetCursorPosition(0, 8);
                            Console.WriteLine("Packet:" + packetCounter.ToString());
                        }

                        if (packetCounter > packetCount && (i + 1) == dt.Rows.Count)
                        {
                            MigrationHelper.executeMultipleWithRequests(reqList, "contacttitlecase", service);
                            reqList = new OrganizationRequestCollection();
                        }
                        //service.Update(ent);

                        successCount++;

                        Console.SetCursorPosition(0, 5);
                        Console.WriteLine("Success:" + successCount.ToString());
                    }
                    catch (Exception ex)
                    {
                        errorCount++;
                        Console.SetCursorPosition(0, 6);
                        Console.WriteLine("Error:" + errorCount.ToString());
                    }
                }
            }

            return(returnValue);
        }
Example #21
0
        public static MsCrmResult Process()
        {
            MsCrmResult returnValue = new MsCrmResult();

            try
            {
                int                  totalCount   = 0;
                int                  errorCount   = 0;
                int                  successCount = 0;
                StringBuilder        sb           = new StringBuilder();
                IOrganizationService service      = MSCRM.GetOrgService(true);

                SqlDataAccess sda = new SqlDataAccess();
                sda.openConnection(Globals.ConnectionString);

                List <HouseImport> lstImports = ProductHelper.GetNotImportedList(sda);

                Console.SetCursorPosition(0, 1);
                Console.WriteLine("Listeler çekildi. Adet:" + lstImports.Count.ToString());

                if (lstImports.Count > 0)
                {
                    for (int i = 0; i < lstImports.Count; i++)
                    {
                        Console.SetCursorPosition(0, 2);
                        Console.WriteLine((i + 1).ToString() + ". Liste İşleniyor.");

                        totalCount   = 0;
                        errorCount   = 0;
                        successCount = 0;

                        MsCrmResult resultProcessing = ProductHelper.UpdateImportListToProcessing(lstImports[i].HouseImportId, service);

                        if (resultProcessing.Success)
                        {
                            DataTable dt = ProductHelper.GetHouseImportListDetail(lstImports[i].HouseImportId, sda);

                            Console.SetCursorPosition(0, 3);
                            Console.WriteLine((i + 1).ToString() + ". Liste Kayıt sayısı: " + dt.Rows.Count.ToString());

                            if (dt.Rows.Count > 0)
                            {
                                totalCount = dt.Rows.Count;

                                for (int j = 0; j < totalCount; j++)
                                {
                                    Console.SetCursorPosition(0, 4);
                                    Console.WriteLine("Sayaç:" + (j + 1).ToString());

                                    #region | PRODUCT IMPORT OPERATIONS |
                                    try
                                    {
                                        Guid existProductId = Guid.Empty;
                                        Guid newProductId   = Guid.Empty;

                                        MsCrmResult resultProductCheck = GeneralHelper.GetEntityIdByAttributeName("Product", "Name", dt.Rows[j]["Daire Kimlik No"].ToString(), sda);

                                        if (resultProductCheck.Success)
                                        {
                                            existProductId = resultProductCheck.CrmId;
                                        }

                                        Entity ent = new Entity("product");

                                        #region | PROJECT |

                                        if (dt.Rows[j]["Proje"] != DBNull.Value && dt.Rows[j]["Proje"] != string.Empty)
                                        {
                                            MsCrmResult resultProject = GeneralHelper.GetEntityIdByAttributeName("new_project", "new_name", dt.Rows[j]["Proje"].ToString(), sda);

                                            if (resultProject.Success)
                                            {
                                                ent["new_projectid"] = new EntityReference("new_project", resultProject.CrmId);
                                            }
                                            else
                                            {
                                                resultProject        = GeneralHelper.CreateEntity("new_project", "new_name", dt.Rows[j]["Proje"].ToString(), service);
                                                ent["new_projectid"] = new EntityReference("new_project", resultProject.CrmId);
                                            }
                                        }

                                        #endregion

                                        #region | BLOCK |

                                        if (dt.Rows[j]["Blok"] != DBNull.Value && dt.Rows[j]["Blok"] != string.Empty)
                                        {
                                            MsCrmResult resultBlock = GeneralHelper.GetEntityIdByAttributeName("new_block", "new_name", dt.Rows[j]["Blok"].ToString(), sda);

                                            if (resultBlock.Success)
                                            {
                                                ent["new_blockid"] = new EntityReference("new_block", resultBlock.CrmId);
                                            }
                                            else
                                            {
                                                resultBlock        = GeneralHelper.CreateEntity("new_block", "new_name", dt.Rows[j]["Blok"].ToString(), service);
                                                ent["new_blockid"] = new EntityReference("new_block", resultBlock.CrmId);
                                            }
                                        }

                                        #endregion

                                        #region | FLOOR NUMBER |

                                        if (dt.Rows[j]["Kat"] != DBNull.Value && dt.Rows[j]["Kat"] != string.Empty)
                                        {
                                            ent["new_floornumber"] = Convert.ToInt32(dt.Rows[j]["Kat"]);
                                        }

                                        #endregion

                                        #region | HOME NUMBER |

                                        if (dt.Rows[j]["Daire No"] != DBNull.Value && dt.Rows[j]["Daire No"] != string.Empty)
                                        {
                                            ent["new_homenumber"] = dt.Rows[j]["Daire No"].ToString();
                                        }

                                        #endregion

                                        #region | NAME && PRODUCT NUMBER |

                                        if (dt.Rows[j]["Daire Kimlik No"] != DBNull.Value && dt.Rows[j]["Daire Kimlik No"] != string.Empty)
                                        {
                                            ent["name"]          = dt.Rows[j]["Daire Kimlik No"].ToString();
                                            ent["productnumber"] = dt.Rows[j]["Daire Kimlik No"].ToString();
                                        }

                                        #endregion

                                        #region | UNIT TYPE |

                                        if (dt.Rows[j]["Ünite Tipi"] != DBNull.Value && dt.Rows[j]["Ünite Tipi"] != string.Empty)
                                        {
                                            MsCrmResult resultUnitType = GeneralHelper.GetEntityIdByAttributeName("new_unittype", "new_name", dt.Rows[j]["Ünite Tipi"].ToString(), sda);

                                            if (resultUnitType.Success)
                                            {
                                                ent["new_unittypeid"] = new EntityReference("new_unittype", resultUnitType.CrmId);
                                            }
                                            else
                                            {
                                                resultUnitType        = GeneralHelper.CreateEntity("new_unittype", "new_name", dt.Rows[j]["Ünite Tipi"].ToString(), service);
                                                ent["new_unittypeid"] = new EntityReference("new_unittype", resultUnitType.CrmId);
                                            }
                                        }

                                        #endregion

                                        #region | GENERAL TYPE OF HOME |

                                        if (dt.Rows[j]["Genel Daire Tipi"] != DBNull.Value && dt.Rows[j]["Genel Daire Tipi"] != string.Empty)
                                        {
                                            MsCrmResult resultGeneralTypeHome = GeneralHelper.GetEntityIdByAttributeName("new_generaltypeofhome", "new_name", dt.Rows[j]["Genel Daire Tipi"].ToString(), sda);

                                            if (resultGeneralTypeHome.Success)
                                            {
                                                ent["new_generaltypeofhomeid"] = new EntityReference("new_generaltypeofhome", resultGeneralTypeHome.CrmId);
                                            }
                                            else
                                            {
                                                resultGeneralTypeHome          = GeneralHelper.CreateEntity("new_generaltypeofhome", "new_name", dt.Rows[j]["Genel Daire Tipi"].ToString(), service);
                                                ent["new_generaltypeofhomeid"] = new EntityReference("new_generaltypeofhome", resultGeneralTypeHome.CrmId);
                                            }
                                        }

                                        #endregion

                                        #region | TYPE OF HOME-???-OK |

                                        if (dt.Rows[j]["Daire Tipi"] != DBNull.Value && dt.Rows[j]["Daire Tipi"] != string.Empty && ent.Contains("new_generaltypeofhomeid") && ent["new_generaltypeofhomeid"] != null)
                                        {
                                            MsCrmResult resultTypeHome = ProductHelper.CheckTypeOfHomeExists(dt.Rows[j]["Daire Tipi"].ToString(), ((EntityReference)ent["new_generaltypeofhomeid"]).Id, sda);

                                            if (resultTypeHome.Success)
                                            {
                                                ent["new_typeofhomeid"] = new EntityReference("new_typeofhome", resultTypeHome.CrmId);
                                            }
                                            else
                                            {
                                                //resultTypeHome = GeneralHelper.CreateEntity("new_typeofhome", "new_name", dt.Rows[j]["Daire Tipi"].ToString(), service);
                                                resultTypeHome = GeneralHelper.CreateTypeOfHome(dt.Rows[j]["Daire Tipi"].ToString(), ((EntityReference)ent["new_generaltypeofhomeid"]).Id, service);

                                                ent["new_typeofhomeid"] = new EntityReference("new_typeofhome", resultTypeHome.CrmId);
                                            }
                                        }

                                        //if (dt.Rows[j]["Daire Tipi"] != DBNull.Value && dt.Rows[j]["Daire Tipi"] != string.Empty)
                                        //{
                                        //    MsCrmResult resultTypeHome = GeneralHelper.GetEntityIdByAttributeName("new_typeofhome", "new_name", dt.Rows[j]["Daire Tipi"].ToString(), sda);

                                        //    if (resultTypeHome.Success)
                                        //    {
                                        //        ent["new_typeofhomeid"] = new EntityReference("new_typeofhome", resultTypeHome.CrmId);
                                        //    }
                                        //    else
                                        //    {
                                        //        resultTypeHome = GeneralHelper.CreateEntity("new_typeofhome", "new_name", dt.Rows[j]["Daire Tipi"].ToString(), service);
                                        //        ent["new_typeofhomeid"] = new EntityReference("new_typeofhome", resultTypeHome.CrmId);
                                        //    }
                                        //}

                                        #endregion

                                        #region | AKS |

                                        if (dt.Rows[j]["Aks"] != DBNull.Value && dt.Rows[j]["Aks"] != string.Empty)
                                        {
                                            ent["new_aks"] = Convert.ToInt32(dt.Rows[j]["Aks"]);
                                        }

                                        #endregion

                                        #region | LOCATION |

                                        if (dt.Rows[j]["Konum"] != DBNull.Value && dt.Rows[j]["Konum"] != string.Empty)
                                        {
                                            MsCrmResult resultLocation = GeneralHelper.GetEntityIdByAttributeName("new_location", "new_name", dt.Rows[j]["Konum"].ToString(), sda);

                                            if (resultLocation.Success)
                                            {
                                                ent["new_locationid"] = new EntityReference("new_location", resultLocation.CrmId);
                                            }
                                            else
                                            {
                                                resultLocation        = GeneralHelper.CreateEntity("new_location", "new_name", dt.Rows[j]["Konum"].ToString(), service);
                                                ent["new_locationid"] = new EntityReference("new_location", resultLocation.CrmId);
                                            }
                                        }

                                        #endregion

                                        #region | LICENCE NUMBER |

                                        if (dt.Rows[j]["Ruhsat No"] != DBNull.Value && dt.Rows[j]["Ruhsat No"] != string.Empty)
                                        {
                                            ent["new_licencenumber"] = dt.Rows[j]["Ruhsat No"].ToString();
                                        }

                                        #endregion

                                        #region | DESCRIPTION |

                                        if (dt.Rows[j]["Açıklama"] != DBNull.Value && dt.Rows[j]["Açıklama"] != string.Empty)
                                        {
                                            ent["description"] = dt.Rows[j]["Açıklama"].ToString();
                                        }

                                        #endregion


                                        #region | NET M2 |

                                        if (dt.Rows[j]["Net M2"] != DBNull.Value && dt.Rows[j]["Net M2"] != string.Empty)
                                        {
                                            ent["new_netm2"] = Convert.ToDecimal(dt.Rows[j]["Net M2"]);
                                        }

                                        #endregion

                                        #region | BALCONY M2 |

                                        if (dt.Rows[j]["Balkon M2"] != DBNull.Value && dt.Rows[j]["Balkon M2"] != string.Empty)
                                        {
                                            ent["new_balconym2"] = Convert.ToDecimal(dt.Rows[j]["Balkon M2"]);
                                        }

                                        #endregion

                                        #region | TERRACE M2 |

                                        if (dt.Rows[j]["Teras M2"] != DBNull.Value && dt.Rows[j]["Teras M2"] != string.Empty)
                                        {
                                            ent["new_terracegross"] = Convert.ToDecimal(dt.Rows[j]["Teras M2"]);
                                        }

                                        #endregion

                                        #region | WAREHOUSE M2 |

                                        if (dt.Rows[j]["Depo M2"] != DBNull.Value && dt.Rows[j]["Depo M2"] != string.Empty)
                                        {
                                            ent["new_warehousem2"] = Convert.ToDecimal(dt.Rows[j]["Depo M2"]);
                                        }

                                        #endregion

                                        #region | PRICE OPERATIONS |

                                        if (dt.Rows[j]["Liste Fiyatı"] != DBNull.Value && dt.Rows[j]["Liste Fiyatı"] != string.Empty &&
                                            dt.Rows[j]["Para Birimi"] != DBNull.Value && dt.Rows[j]["Para Birimi"] != string.Empty)
                                        {
                                            MsCrmResult resultPriceList = ProductHelper.GetPriceListIdByCurrencySymbol(dt.Rows[j]["Para Birimi"].ToString(), sda);

                                            if (resultPriceList.Success)
                                            {
                                                ent["transactioncurrencyid"] = new EntityReference("transactioncurrency", new Guid(resultPriceList.Result));
                                                ent["price"]                = new Money(Convert.ToDecimal(dt.Rows[j]["Liste Fiyatı"].ToString()));
                                                ent["defaultuomid"]         = new EntityReference("uom", Globals.DefaultUoMId);
                                                ent["defaultuomscheduleid"] = new EntityReference("uomschedule", Globals.DefaultUoMScheduleId);
                                                //ent["pricelevelid"] = new EntityReference("pricelevel", resultPriceList.CrmId);
                                                ent["quantitydecimal"] = 2;
                                            }
                                            else
                                            {
                                                errorCount++;
                                                continue;
                                            }
                                        }

                                        #endregion

                                        #region | GROSS M2 |

                                        if (dt.Rows[j]["Brüt M2"] != DBNull.Value && dt.Rows[j]["Brüt M2"] != string.Empty)
                                        {
                                            ent["new_grossm2"] = Convert.ToDecimal(dt.Rows[j]["Brüt M2"]);
                                        }


                                        #endregion

                                        #region | KDV RATIO |

                                        if (dt.Rows[j]["Kdv"] != DBNull.Value && dt.Rows[j]["Kdv"] != string.Empty)
                                        {
                                            ent["new_kdvratio"] = Convert.ToDecimal(dt.Rows[j]["Kdv"]);
                                        }

                                        #endregion

                                        #region | TAX OF STAMP RATIO |

                                        if (dt.Rows[j]["Damga Vergisi"] != DBNull.Value && dt.Rows[j]["Damga Vergisi"] != string.Empty)
                                        {
                                            ent["new_taxofstamp"] = Convert.ToDecimal(dt.Rows[j]["Damga Vergisi"]);
                                        }

                                        #endregion

                                        #region | SHARE |

                                        if (dt.Rows[j]["Paylaşım"] != DBNull.Value && dt.Rows[j]["Paylaşım"] != string.Empty)
                                        {
                                            MsCrmResult resultShare = GeneralHelper.GetEntityIdByAttributeName("new_share", "new_name", dt.Rows[j]["Paylaşım"].ToString(), sda);

                                            if (resultShare.Success)
                                            {
                                                ent["new_shareid"] = new EntityReference("new_share", resultShare.CrmId);
                                            }
                                            else
                                            {
                                                resultShare        = GeneralHelper.CreateEntity("new_share", "new_name", dt.Rows[j]["Paylaşım"].ToString(), service);
                                                ent["new_shareid"] = new EntityReference("new_share", resultShare.CrmId);
                                            }
                                        }

                                        #endregion

                                        #region | CITY |

                                        if (dt.Rows[j]["İl"] != DBNull.Value && dt.Rows[j]["İl"] != string.Empty)
                                        {
                                            ent["new_city"] = dt.Rows[j]["İl"].ToString();
                                        }

                                        #endregion

                                        #region | DISTRICT |

                                        if (dt.Rows[j]["İlçe"] != DBNull.Value && dt.Rows[j]["İlçe"] != string.Empty)
                                        {
                                            ent["new_district"] = dt.Rows[j]["İlçe"].ToString();
                                        }

                                        #endregion

                                        #region | QUARTER |

                                        if (dt.Rows[j]["Mahalle"] != DBNull.Value && dt.Rows[j]["Mahalle"] != string.Empty)
                                        {
                                            ent["new_quarter"] = dt.Rows[j]["Mahalle"].ToString();
                                        }

                                        #endregion

                                        #region | THREADER (PAFTA) |

                                        if (dt.Rows[j]["Pafta"] != DBNull.Value && dt.Rows[j]["Pafta"] != string.Empty)
                                        {
                                            MsCrmResult resultThreader = GeneralHelper.GetEntityIdByAttributeName("new_threader", "new_name", dt.Rows[j]["Pafta"].ToString(), sda);

                                            if (resultThreader.Success)
                                            {
                                                ent["new_threaderid"] = new EntityReference("new_threader", resultThreader.CrmId);
                                            }
                                            else
                                            {
                                                resultThreader        = GeneralHelper.CreateEntity("new_threader", "new_name", dt.Rows[j]["Pafta"].ToString(), service);
                                                ent["new_threaderid"] = new EntityReference("new_threader", resultThreader.CrmId);
                                            }
                                        }

                                        #endregion

                                        #region | BLOCK OF BUILDING (ADA)-???-OK |

                                        if (dt.Rows[j]["Ada"] != DBNull.Value && dt.Rows[j]["Ada"] != string.Empty)
                                        {
                                            MsCrmResult resultBlockOfBuilding = GeneralHelper.GetEntityIdByAttributeName("new_blockofbuilding", "new_name", dt.Rows[j]["Ada"].ToString(), sda);

                                            if (resultBlockOfBuilding.Success)
                                            {
                                                ent["new_blockofbuildingid"] = new EntityReference("new_blockofbuilding", resultBlockOfBuilding.CrmId);
                                            }
                                            else
                                            {
                                                resultBlockOfBuilding        = GeneralHelper.CreateEntity("new_blockofbuilding", "new_name", dt.Rows[j]["Ada"].ToString(), service);
                                                ent["new_blockofbuildingid"] = new EntityReference("new_blockofbuilding", resultBlockOfBuilding.CrmId);
                                            }
                                        }

                                        //if (dt.Rows[j]["Ada"] != DBNull.Value && dt.Rows[j]["Ada"] != string.Empty)
                                        //{
                                        //    MsCrmResult resultBlockOfBuilding = ProductHelper.CheckBlockOfBuildingExists(dt.Rows[j]["Ada"].ToString(), ((EntityReference)ent["new_threaderid"]).Id, ((EntityReference)ent["new_projectid"]).Id, sda);

                                        //    if (resultBlockOfBuilding.Success)
                                        //    {
                                        //        ent["new_blockofbuildingid"] = new EntityReference("new_blockofbuilding", resultBlockOfBuilding.CrmId);
                                        //    }
                                        //    else
                                        //    {
                                        //        resultBlockOfBuilding = ProductHelper.CreateBlockOfBuilding(dt.Rows[j]["Ada"].ToString(), ((EntityReference)ent["new_threaderid"]).Id, ((EntityReference)ent["new_projectid"]).Id, service);
                                        //        ent["new_blockofbuildingid"] = new EntityReference("new_blockofbuilding", resultBlockOfBuilding.CrmId);
                                        //    }
                                        //}

                                        #endregion

                                        #region | PARCEL-???-OK |
                                        if (dt.Rows[j]["Parsel"] != DBNull.Value && dt.Rows[j]["Parsel"] != string.Empty)
                                        {
                                            MsCrmResult resultParcel = GeneralHelper.GetEntityIdByAttributeName("new_parcel", "new_name", dt.Rows[j]["Parsel"].ToString(), sda);

                                            if (resultParcel.Success)
                                            {
                                                ent["new_parcelid"] = new EntityReference("new_parcel", resultParcel.CrmId);
                                            }
                                            else
                                            {
                                                resultParcel        = GeneralHelper.CreateEntity("new_parcel", "new_name", dt.Rows[j]["Parsel"].ToString(), service);
                                                ent["new_parcelid"] = new EntityReference("new_parcel", resultParcel.CrmId);
                                            }
                                        }

                                        //if (dt.Rows[j]["Parsel"] != DBNull.Value && dt.Rows[j]["Parsel"] != string.Empty)
                                        //{
                                        //    MsCrmResult resultParcel = ProductHelper.CheckParcelExists(dt.Rows[j]["Parsel"].ToString(), ((EntityReference)ent["new_blockofbuildingid"]).Id, ((EntityReference)ent["new_projectid"]).Id, sda);

                                        //    if (resultParcel.Success)
                                        //    {
                                        //        ent["new_parcelid"] = new EntityReference("new_parcel", resultParcel.CrmId);
                                        //    }
                                        //    else
                                        //    {
                                        //        resultParcel = ProductHelper.CreateParcel(dt.Rows[j]["Parsel"].ToString(), ((EntityReference)ent["new_blockofbuildingid"]).Id, ((EntityReference)ent["new_projectid"]).Id, service);
                                        //        ent["new_parcelid"] = new EntityReference("new_parcel", resultParcel.CrmId);
                                        //    }
                                        //}

                                        #endregion

                                        #region BB Genel Brüt Alan
                                        if (dt.Rows[j]["BB Genel Brüt Alan"] != DBNull.Value && dt.Rows[j]["BB Genel Brüt Alan"] != string.Empty)
                                        {
                                            ent["new_bbgeneralgrossarea"] = Convert.ToDecimal(dt.Rows[j]["BB Genel Brüt Alan"]);
                                        }
                                        #endregion

                                        #region Satışa Esas Alan
                                        if (dt.Rows[j]["Satışa Esas Alan"] != DBNull.Value && dt.Rows[j]["Satışa Esas Alan"] != string.Empty)
                                        {
                                            ent["new_satisaesasalan"] = Convert.ToDecimal(dt.Rows[j]["Satışa Esas Alan"]);
                                        }
                                        #endregion

                                        #region Bahçe M2
                                        if (dt.Rows[j]["Bahçe M2"] != DBNull.Value && dt.Rows[j]["Bahçe M2"] != string.Empty)
                                        {
                                            ent["new_garden"] = Convert.ToDecimal(dt.Rows[j]["Bahçe M2"]);
                                        }

                                        #endregion

                                        #region BB NET M2
                                        if (dt.Rows[j]["BB NET M2"] != DBNull.Value && dt.Rows[j]["BB NET M2"] != string.Empty)
                                        {
                                            ent["new_bbnetarea"] = Convert.ToDecimal(dt.Rows[j]["BB NET M2"]);
                                        }
                                        #endregion

                                        #region Yön
                                        if (dt.Rows[j]["Yön"] != DBNull.Value && dt.Rows[j]["Yön"] != string.Empty)
                                        {
                                            if (Convert.ToString(dt.Rows[j]["Yön"]).ToUpper().Equals("BATI"))
                                            {
                                                ent["new_west"]       = true;
                                                ent["new_generalway"] = new OptionSetValue(100000000);
                                            }
                                            if (Convert.ToString(dt.Rows[j]["Yön"]).ToUpper().Equals("DOĞU"))
                                            {
                                                ent["new_east"]       = true;
                                                ent["new_generalway"] = new OptionSetValue(100000001);
                                            }
                                            if (Convert.ToString(dt.Rows[j]["Yön"]).ToUpper().Equals("GÜNEY"))
                                            {
                                                ent["new_south"]      = true;
                                                ent["new_generalway"] = new OptionSetValue(100000002);
                                            }
                                            if (Convert.ToString(dt.Rows[j]["Yön"]).ToUpper().Equals("GÜNEY BATI"))
                                            {
                                                ent["new_southwest"]  = true;
                                                ent["new_generalway"] = new OptionSetValue(100000003);
                                            }
                                            if (Convert.ToString(dt.Rows[j]["Yön"]).ToUpper().Equals("GÜNEY DOĞU"))
                                            {
                                                ent["new_southeast"]  = true;
                                                ent["new_generalway"] = new OptionSetValue(100000004);
                                            }
                                            if (Convert.ToString(dt.Rows[j]["Yön"]).ToUpper().Equals("KUZEY"))
                                            {
                                                ent["new_north"]      = true;
                                                ent["new_generalway"] = new OptionSetValue(100000005);
                                            }
                                            if (Convert.ToString(dt.Rows[j]["Yön"]).ToUpper().Equals("KUZEY BATI"))
                                            {
                                                ent["new_northwest"]  = true;
                                                ent["new_generalway"] = new OptionSetValue(100000006);
                                            }
                                            if (Convert.ToString(dt.Rows[j]["Yön"]).ToUpper().Equals("KUZEY DOĞU"))
                                            {
                                                ent["new_northeast"]  = true;
                                                ent["new_generalway"] = new OptionSetValue(100000007);
                                            }
                                        }
                                        #endregion

                                        #region Teslim Tarihi
                                        if (dt.Rows[j]["Teslim Tarihi"] != DBNull.Value && dt.Rows[j]["Teslim Tarihi"] != string.Empty)
                                        {
                                            string   deliveryDateString = Convert.ToString(dt.Rows[j]["Teslim Tarihi"]);
                                            DateTime deliveryDate       = new DateTime();
                                            DateTime.TryParse(deliveryDateString, out deliveryDate);
                                            ent["new_deliverydate"] = deliveryDate;
                                        }
                                        #endregion


                                        if (existProductId != Guid.Empty)
                                        {
                                            ent["productid"] = existProductId;
                                            service.Update(ent);
                                        }
                                        else
                                        {
                                            newProductId = service.Create(ent);
                                        }

                                        successCount++;
                                    }
                                    catch (Exception ex)
                                    {
                                        errorCount++;
                                    }

                                    sb.AppendLine("Merhaba");
                                    sb.AppendLine("Konut ekleme işlemi tamamlanmıştır.");
                                    #endregion
                                    sb.AppendLine("Hatalı:" + errorCount.ToString());
                                    Console.SetCursorPosition(0, 5);
                                    Console.WriteLine("Hata:" + errorCount.ToString());

                                    sb.AppendLine("Başarılı:" + successCount.ToString());
                                    Console.SetCursorPosition(0, 6);
                                    Console.WriteLine("Başarılı:" + successCount.ToString());
                                }
                            }
                        }

                        ProductHelper.UpdateHouseImportResultsAndClose(lstImports[i].HouseImportId, errorCount, successCount, totalCount, service);
                    }

                    #region Create Email

                    Entity fromParty = new Entity("activityparty");
                    fromParty["partyid"] = new EntityReference("systemuser", Globals.AdministratorId);



                    //Entity toParty = new Entity("activityparty");
                    //toParty["addressused"] = "*****@*****.**";
                    Entity toParty1 = new Entity("activityparty");
                    toParty1["addressused"] = "*****@*****.**";
                    Entity toParty2 = new Entity("activityparty");
                    toParty2["addressused"] = "*****@*****.**";

                    Entity email = new Entity("email");
                    email["to"] = new Entity[] { toParty1, toParty2 };

                    email["from"]          = new Entity[] { fromParty };
                    email["subject"]       = DateTime.Now.ToShortDateString() + "Konut import";
                    email["description"]   = sb.ToString();
                    email["directioncode"] = true;
                    Guid id = service.Create(email);

                    #endregion

                    #region Send Email
                    var req = new SendEmailRequest
                    {
                        EmailId       = id,
                        TrackingToken = string.Empty,
                        IssueSend     = true
                    };

                    try
                    {
                        var res = (SendEmailResponse)service.Execute(req);
                    }
                    catch (Exception ex)
                    {
                    }
                    #endregion

                    returnValue.Success = true;
                    returnValue.Result  = "Listeler işlendi...";
                }
            }
            catch (Exception ex)
            {
                returnValue.Result = ex.Message;
            }

            return(returnValue);
        }
Example #22
0
        public static MsCrmResult Process()
        {
            MsCrmResult returnValue = new MsCrmResult();

            try
            {
                service = MSCRM.GetOrgService(true);

                sda = new SqlDataAccess();
                sda.openConnection(Globals.ConnectionString);

                XElement   CurrencyRate = XElement.Load("http://www.tcmb.gov.tr/kurlar/today.xml");
                string     currentDate  = DateTime.Now.ToShortDateString();
                XAttribute dateRate     = (from p in CurrencyRate.Attributes()
                                           where p.Name.LocalName == "Tarih"
                                           select p).Single();

                if (string.Format("dd/MM/yyyy", dateRate.Value) == string.Format("dd/MM/yyyy", currentDate))
                {
                    #region | USD |
                    XElement dollar = (from p in CurrencyRate.Elements()
                                       where p.Attribute("CurrencyCode").Value == "USD"
                                       select p).Single();

                    ExchangeRate erDollar = new ExchangeRate();
                    erDollar.BuyRate  = Convert.ToDecimal(dollar.Element("BanknoteBuying").Value.Replace('.', ','));
                    erDollar.SaleRate = Convert.ToDecimal(dollar.Element("BanknoteSelling").Value.Replace('.', ','));
                    erDollar.RateDate = DateTime.Now.Date;

                    TransactionCurrency currUsd = CurrencyHelper.GetCurrencyByName("USD", sda);

                    erDollar.Currency = new EntityReference()
                    {
                        Id          = currUsd.TransactionCurrencyId,
                        Name        = "US Dollar",
                        LogicalName = "transactioncurrency"
                    };

                    MsCrmResultObject resultDollar = CurrencyHelper.GetExchangeRateByCurrency(DateTime.Now, erDollar.Currency.Id, sda);

                    if (resultDollar.Success)
                    {
                        #region | TOMORROW |
                        erDollar.RateDate = erDollar.RateDate.AddDays(1);
                        CurrencyHelper.CreateOrUpdateExchangeRate(erDollar, service);

                        #endregion

                        #region | UPDATE TODAY |
                        ExchangeRate eRateDollar = (ExchangeRate)resultDollar.ReturnObject;
                        erDollar.Id = eRateDollar.Id;

                        erDollar.RateDate = erDollar.RateDate.AddDays(-1);
                        CurrencyHelper.CreateOrUpdateExchangeRate(erDollar, service);

                        #endregion
                    }
                    else
                    {
                        #region | CREATE TODAY |
                        CurrencyHelper.CreateOrUpdateExchangeRate(erDollar, service);

                        #endregion

                        #region | TOMORROW |
                        erDollar.RateDate = erDollar.RateDate.AddDays(1);
                        CurrencyHelper.CreateOrUpdateExchangeRate(erDollar, service);

                        #endregion
                    }

                    #endregion

                    #region | EUR |
                    XElement euro = (from p in CurrencyRate.Elements()
                                     where p.Attribute("CurrencyCode").Value == "EUR"
                                     select p).Single();

                    ExchangeRate erEuro = new ExchangeRate();
                    erEuro.BuyRate  = Convert.ToDecimal(euro.Element("BanknoteBuying").Value.Replace('.', ','));
                    erEuro.SaleRate = Convert.ToDecimal(euro.Element("BanknoteSelling").Value.Replace('.', ','));
                    erEuro.RateDate = DateTime.Now.Date;

                    TransactionCurrency currEur = CurrencyHelper.GetCurrencyByName("Euro", sda);

                    erEuro.Currency = new EntityReference()
                    {
                        Id          = currEur.TransactionCurrencyId,
                        Name        = "Euro",
                        LogicalName = "transactioncurrency"
                    };

                    MsCrmResultObject resultEuro = CurrencyHelper.GetExchangeRateByCurrency(DateTime.Now, erEuro.Currency.Id, sda);

                    if (resultEuro.Success)
                    {
                        #region | TOMORROW |
                        erEuro.RateDate = erEuro.RateDate.AddDays(1);
                        CurrencyHelper.CreateOrUpdateExchangeRate(erEuro, service);

                        #endregion

                        #region | UPDATE TODAY |
                        ExchangeRate eRateEuro = (ExchangeRate)resultEuro.ReturnObject;
                        erEuro.Id = eRateEuro.Id;

                        erEuro.RateDate = erEuro.RateDate.AddDays(-1);
                        CurrencyHelper.CreateOrUpdateExchangeRate(erEuro, service);

                        #endregion
                    }
                    else
                    {
                        #region | CREATE TODAY |
                        CurrencyHelper.CreateOrUpdateExchangeRate(erEuro, service);

                        #endregion

                        #region | TOMORROW |
                        erEuro.RateDate = erEuro.RateDate.AddDays(1);
                        CurrencyHelper.CreateOrUpdateExchangeRate(erEuro, service);

                        #endregion
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                returnValue.Result = ex.Message;
            }
            finally
            {
                if (sda != null)
                {
                    sda.closeConnection();
                }
            }

            return(returnValue);
        }
Example #23
0
        public MsCrmResult GetQuote(string QuoteNumber)
        {
            MsCrmResult result = new MsCrmResult();
            QuoteDetail qd     = new QuoteDetail();

            try
            {
                IOrganizationService service = MSCRM.GetOrgService(true);
                ConditionExpression  con1    = new ConditionExpression();
                con1.AttributeName = "quotenumber";
                con1.Operator      = ConditionOperator.Equal;
                con1.Values.Add(QuoteNumber);

                ConditionExpression con2 = new ConditionExpression();
                con2.AttributeName = "statuscode";
                con2.Operator      = ConditionOperator.NotEqual;
                con2.Values.Add(7);//Düzeltilmiş olmayacak

                FilterExpression filter = new FilterExpression();
                filter.FilterOperator = LogicalOperator.And;
                filter.Conditions.Add(con1);
                filter.Conditions.Add(con2);

                QueryExpression Query = new QueryExpression("quote");
                Query.ColumnSet = new ColumnSet(true);
                Query.Criteria.FilterOperator = LogicalOperator.And;
                Query.Criteria.Filters.Add(filter);
                EntityCollection Result = service.RetrieveMultiple(Query);
                if (Result.Entities.Count > 0)
                {
                    Entity q       = Result.Entities[0];
                    Entity product = GetProductByQuoteId(service, q.Id);
                    GetCustomerByQuote(service, q, qd);
                    qd.SalesId = Result.Entities[0].Id.ToString();
                    qd.ApartmentIdentificationNumber = product.Contains("productnumber") ? product.Attributes["productnumber"].ToString() : string.Empty;
                    qd.Block                  = product.Contains("new_blockid") ? ((EntityReference)product.Attributes["new_blockid"]).Name : string.Empty;
                    qd.ContractDate           = q.Contains("new_contractdate") ? ((DateTime)q.Attributes["new_contractdate"]).ToLocalTime() : (DateTime?)null;
                    qd.CustomerName           = q.Contains("customerid") ? ((EntityReference)q.Attributes["customerid"]).Name : string.Empty;
                    qd.HomeNumber             = product.Contains("new_homenumber") ? product.Attributes["new_homenumber"].ToString() : string.Empty;
                    qd.PerQquareMeterAmount   = product.Contains("new_persquaremeter") ? ((Money)product.Attributes["new_persquaremeter"]).Value.ToString("N2") : string.Empty;
                    qd.PrePaymentAmount       = q.Contains("new_prepaymentamount") ? ((Money)q.Attributes["new_prepaymentamount"]).Value.ToString("N2") : string.Empty;
                    qd.ProjectName            = product.Contains("new_projectid") ? ((EntityReference)product.Attributes["new_projectid"]).Name : string.Empty;
                    qd.SalesConsultant        = q.Contains("ownerid") ? ((EntityReference)q.Attributes["ownerid"]).Name : string.Empty;
                    qd.SalesConsultantEmail   = GetSalesConsultantEmail(((EntityReference)q.Attributes["ownerid"]).Id, service);
                    qd.SalesProcessDate       = q.Contains("new_salesprocessdate") ? ((DateTime)q.Attributes["new_salesprocessdate"]).ToLocalTime() : (DateTime?)null;
                    qd.TotalAmountLessFreight = q.Contains("totalamountlessfreight") ? ((Money)q.Attributes["totalamountlessfreight"]).Value.ToString("N2") : string.Empty;
                    qd.TransactionCurrency    = q.Contains("transactioncurrencyid") ? ((EntityReference)q.Attributes["transactioncurrencyid"]).Name : string.Empty;
                    qd.SalesStatus            = q.Contains("statuscode") ? GetOptionSetValue(1084, "statuscode", ((OptionSetValue)q.Attributes["statuscode"]).Value, service) : string.Empty;
                    qd.KonutStatus            = product.Contains("statuscode") ? GetOptionSetValue(1024, "statuscode", ((OptionSetValue)product.Attributes["statuscode"]).Value, service) : string.Empty;
                    qd.HouseCrmLink           = q.Contains("new_productid") ? (Globals.HouseCrmLink + ((EntityReference)q.Attributes["new_productid"]).Id.ToString()) : string.Empty;


                    ConditionExpression con3 = new ConditionExpression();
                    con3.AttributeName = "new_quoteid";
                    con3.Operator      = ConditionOperator.Equal;
                    con3.Values.Add(q.Id);

                    ConditionExpression con4 = new ConditionExpression();
                    con4.AttributeName = "statecode";
                    con4.Operator      = ConditionOperator.Equal;
                    con4.Values.Add(0);

                    FilterExpression filter2 = new FilterExpression();
                    filter2.FilterOperator = LogicalOperator.And;
                    filter2.Conditions.Add(con3);
                    filter2.Conditions.Add(con4);

                    QueryExpression Query2 = new QueryExpression("new_salescanceldetail");
                    Query2.ColumnSet = new ColumnSet(true);
                    Query2.Criteria.FilterOperator = LogicalOperator.And;
                    Query2.Criteria.Filters.Add(filter2);
                    EntityCollection Result2 = service.RetrieveMultiple(Query2);
                    if (Result2.Entities.Count > 0)
                    {
                        Entity r = Result2.Entities[0];
                        qd.CalcelReasonId         = Result2.Entities[0].Id.ToString();
                        qd.SubCanceledReason      = r.Contains("new_subcanceledreasonid") ? ((EntityReference)r.Attributes["new_subcanceledreasonid"]).Name : string.Empty;
                        qd.CanceledReason         = r.Contains("new_canceledreasonid") ? ((EntityReference)r.Attributes["new_canceledreasonid"]).Name : string.Empty;
                        qd.CanceledDate           = r.Contains("createdon") ? ((DateTime)r.Attributes["createdon"]).ToLocalTime() : (DateTime?)null;
                        qd.CanceledDescription    = r.Contains("new_canceldescription") ? r.Attributes["new_canceldescription"].ToString() : string.Empty;
                        qd.ContractAccessOffice   = r.Contains("new_contractaccessoffice") ? r.Attributes["new_contractaccessoffice"].ToString() : string.Empty;
                        qd.contractAccessDate     = r.Contains("new_contractaccessdate") ? ((DateTime)r.Attributes["new_contractaccessdate"]).ToLocalTime() : (DateTime?)null;
                        qd.WageNumber             = r.Contains("new_wagenumber") ? r.Attributes["new_wagenumber"].ToString() : string.Empty;
                        qd.ProtestDate            = r.Contains("new_protestdate") ? ((DateTime)r.Attributes["new_protestdate"]).ToLocalTime() : (DateTime?)null;
                        qd.ContractCanceledOffice = r.Contains("new_contractcanceledoffice") ? r.Attributes["new_contractcanceledoffice"].ToString() : string.Empty;
                        qd.NotaryStatus           = r.Contains("new_notarystatus") ? GetOptionsSetTextFromValue(service, "new_salescanceldetail", "new_notarystatus", ((OptionSetValue)r.Attributes["new_notarystatus"]).Value) : string.Empty;
                    }

                    result.Result  = qd;
                    result.Success = true;
                    result.Message = "Satış Detayları Başarıyla Çekildi.";
                }
                else
                {
                    result.Success = false;
                    result.Message = QuoteNumber + " Numaralı Satış Bulunamadı";
                }
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Message = ex.Message;
            }
            return(result);
        }
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                var operation = context.Request.QueryString["operation"];

                if (context.Request.QueryString["upload"] != null && operation != null && operation != "3")
                {
                    string pathrefer = context.Request.UrlReferrer.ToString();
                    //string Serverpath = @"C:\DO\Web\GK.Web.GkPortal\attachments";
                    //string Serverpath = HttpContext.Current.Server.MapPath("attachments");
                    string Serverpath = @Globals.AttachmentFolder;

                    var postedFile = context.Request.Files[0];

                    string file;

                    //For IE to get file name
                    if (HttpContext.Current.Request.Browser.Browser.ToLower() == "internetexplorer")
                    {
                        string[] files = postedFile.FileName.Split(new char[] { '\\' });
                        file = files[files.Length - 1];
                    }
                    else
                    {
                        file = postedFile.FileName;
                    }


                    if (!Directory.Exists(Serverpath))
                    {
                        Directory.CreateDirectory(Serverpath);
                    }

                    string fileDirectory = Serverpath;
                    if (context.Request.QueryString["fileName"] != null)
                    {
                        file = context.Request.QueryString["fileName"];
                        if (File.Exists(fileDirectory + "\\" + file))
                        {
                            File.Delete(fileDirectory + "\\" + file);
                        }
                    }

                    string ext = Path.GetExtension(fileDirectory + "\\" + file);
                    file = Guid.NewGuid() + ext;

                    fileDirectory = Serverpath + "\\" + file;

                    postedFile.SaveAs(fileDirectory);

                    context.Response.AddHeader("Vary", "Accept");
                    try
                    {
                        if (context.Request["HTTP_ACCEPT"].Contains("application/json"))
                        {
                            context.Response.ContentType = "application/json";
                        }
                        else
                        {
                            context.Response.ContentType = "text/plain";
                        }
                    }
                    catch
                    {
                        context.Response.ContentType = "text/plain";
                    }

                    #region | CRM OPERATIONS AFTER SAVE |

                    if (context.Request.QueryString["operation"] != null)
                    {
                        var relationName = context.Request.QueryString["relationname"];
                        var entityName   = context.Request.QueryString["entityname"];
                        var entityId     = context.Request.QueryString["entityid"];
                        var portalId     = context.Request.QueryString["portalid"];
                        var isImage      = context.Request.QueryString["isimage"];

                        IOrganizationService service = MSCRM.GetOrgService(true);
                        SqlDataAccess        sda     = new SqlDataAccess();
                        sda.openConnection(Globals.ConnectionString);

                        Annotation note = new Annotation();

                        if (operation != "3")
                        {
                            note.FileName = postedFile.FileName;
                            note.FilePath = file;
                            note.MimeType = ext;
                            note.Object   = new EntityReference(entityName, new Guid(entityId));

                            if (operation == "1")
                            {
                                note.Portal = new EntityReference("new_portal", new Guid(portalId));
                            }
                        }

                        if (operation == "1") //Save attachment to entity
                        {
                            MsCrmResult resultCreate = AttachmentFileHelper.CreateAttachmentFile(note, service);

                            AttachmentFileHelper.AssociateAttachmentToEntity(resultCreate.CrmId, note.Object, relationName, service);
                        }
                        else if (operation == "2") //Save Entity Profile Image
                        {
                            string fieldName = "new_imageurl";

                            if (entityName == "new_video" && isImage != "true")
                            {
                                fieldName = "new_videourl";
                            }

                            #region | DELETE PREVIOUS IMAGE FILE |

                            string fileName = AttachmentFileHelper.GetEntityProfileImageFileName(entityId, entityName, fieldName, sda);

                            if (!string.IsNullOrEmpty(fileName))
                            {
                                string filePath = @Globals.AttachmentFolder + @"\" + fileName;

                                if (System.IO.File.Exists(filePath))
                                {
                                    System.IO.File.Delete(filePath);
                                }
                            }

                            #endregion

                            #region | UPDATE CRM ENTITY |

                            Entity ent = new Entity(entityName);
                            ent.Id         = new Guid(entityId);
                            ent[fieldName] = note.FilePath;

                            service.Update(ent);

                            #endregion
                        }
                        //else if (operation == "3") //Delete profile image
                        //{
                        //    string fieldName = "new_imageurl";

                        //    if (entityName == "new_video")
                        //    {
                        //        fieldName = "new_imageurl";
                        //    }

                        //    string fileName = AttachmentFileHelper.GetEntityProfileImageFileName(entityId, entityName, fieldName, sda);

                        //    AttachmentFileHelper.DeleteProfileImage(entityId, entityName, fieldName, fileName);
                        //}
                    }

                    #endregion

                    context.Response.Write(file);
                }
                else if (operation == "3")
                {
                    var entityName = context.Request.QueryString["entityname"];
                    var entityId   = context.Request.QueryString["entityid"];

                    string fieldName = "new_imageurl";

                    if (entityName == "new_video")
                    {
                        fieldName = "new_imageurl";
                    }

                    SqlDataAccess sda = new SqlDataAccess();
                    sda.openConnection(Globals.ConnectionString);

                    string fileName = AttachmentFileHelper.GetEntityProfileImageFileName(new Guid(entityId).ToString(), entityName, fieldName, sda);

                    AttachmentFileHelper.DeleteProfileImage(new Guid(entityId).ToString(), entityName, fieldName, fileName);

                    context.Response.Write("success");
                }
            }
            catch (Exception exp)
            {
                context.Response.Write(exp.StackTrace);
            }
        }
Example #25
0
        public static void Process()
        {
            SqlDataAccess sda = new SqlDataAccess();

            sda.openConnection(Globals.ConnectionString);

            IOrganizationService service = MSCRM.GetOrgService(true);

            string sql = @"SELECT
                                d.new_name AS Name
                                ,d.new_doviz AS Currency
                                ,d.new_tarih AS ExDate
                                ,d.new_kur AS SalesRate
                                ,d.new_aliskuru AS BuyingRate
                            FROM
                            IDEFIX2.KonutSatis_MSCRM.dbo.new_dovizkuru AS d
                            WHERE
                            d.new_name IS NOT NULL
                            AND
                            d.new_doviz IS NOT NULL
                            AND
                            d.new_tarih IS NOT NULL
                            AND
                            d.new_kur IS NOT NULL
                            AND
                            d.new_aliskuru IS NOT NULL ORDER BY d.new_tarih DESC";

            DataTable dt = sda.getDataTable(sql);

            if (dt.Rows.Count > 0)
            {
                int error = 0;

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    try
                    {
                        Entity ent = new Entity("new_exchangerate");

                        ent["new_name"]         = dt.Rows[i]["Name"].ToString();
                        ent["new_currencydate"] = ((DateTime)dt.Rows[i]["ExDate"]).ToLocalTime().Date;

                        if ((int)dt.Rows[i]["Currency"] == 1) //Euro
                        {
                            ent["new_currencyid"] = new EntityReference("transactioncurrency", Globals.CurrencyIdEUR);
                        }
                        else if ((int)dt.Rows[i]["Currency"] == 2) //Usd
                        {
                            ent["new_currencyid"] = new EntityReference("transactioncurrency", Globals.CurrencyIdUSD);
                        }

                        ent["new_salesrate"]  = (decimal)dt.Rows[i]["SalesRate"];
                        ent["new_buyingrate"] = (decimal)dt.Rows[i]["BuyingRate"];

                        service.Create(ent);

                        Console.WriteLine((i + 1).ToString() + "/" + dt.Rows.Count.ToString());
                    }
                    catch (Exception ex)
                    {
                        error++;
                        Console.SetCursorPosition(0, 2);

                        Console.WriteLine("HATA:" + error.ToString());
                    }
                }
            }

            Console.WriteLine("Bitti!");
            Console.ReadKey();
        }
Example #26
0
        public static MsCrmResult Process()
        {
            MsCrmResult returnValue = new MsCrmResult();

            try
            {
                IOrganizationService service = MSCRM.GetOrgService(true);

                SqlDataAccess sda = new SqlDataAccess();
                sda.openConnection(Globals.ConnectionString);

                List <Satislar> satisList = LogoHelper.GetSatisList(sda);

                if (satisList.Count > 0)
                {
                    foreach (Satislar item in satisList)
                    {
                        if (item.SatisDurumu != null)
                        {
                            if (item.SatisDurumu.Equals("İPTAL"))
                            {
                                if (!LogoHelper.ControlQuotePayment(item.SatisID))
                                {
                                    LogoHelper.UpdateLogoAktarimStatus(item.SatisID, "0");
                                    continue;
                                }
                            }
                        }


                        List <LogoAccount> logofirma = LogoHelper.GetLogoFirmalar(item.ProjeID, sda);

                        if (logofirma.Count > 0)
                        {
                            foreach (LogoAccount firma in logofirma)
                            {
                                if (LogoHelper.ExecuteCari(item, firma, sda))
                                {
                                    if (!LogoHelper.SatisKontrol(item))
                                    {
                                        LogoHelper.CreateSatis(item, firma);
                                    }
                                    else
                                    {
                                        LogoHelper.CreateSatis(item, firma);
                                    }

                                    LogoHelper.ExecuteSatisOdemePlani(item.SatisID, item.SatisRef, sda);
                                    LogoHelper.UpdateLogoAktarimStatus(item.SatisID, "0");
                                }
                            }
                        }
                        else if (LogoHelper.ExecuteCari(item, null, sda))
                        {
                            if (!LogoHelper.SatisKontrol(item))
                            {
                                LogoHelper.CreateSatis(item, null);
                            }
                            else
                            {
                                LogoHelper.CreateSatis(item, null);
                            }

                            LogoHelper.ExecuteSatisOdemePlani(item.SatisID, item.SatisRef, sda);
                            LogoHelper.UpdateLogoAktarimStatus(item.SatisID, "0");
                        }
                    }
                }

                returnValue.Success = true;
                returnValue.Result  = "Satış entegrasyonu tamamlandı.";
            }
            catch (Exception ex)
            {
                returnValue.Result = ex.Message;
            }

            return(returnValue);
        }
Example #27
0
        public void ProcessRequest(HttpContext context)
        {
            var op = context.Request.QueryString["operation"];

            if (op != null && op == "1")
            {
                #region İlgili Kişi - Nüfus cüzdanı yükleme
                context.Response.ContentType = "application/json";

                JavaScriptSerializer serializer = new JavaScriptSerializer();

                string message    = string.Empty;
                var    base64Data = context.Request.Form["data"];
                var    contactId  = context.Request.Form["contactid"];

                IOrganizationService service = MSCRM.GetOrgService(true);

                Entity attach = new Entity("annotation");

                attach["filename"]       = context.Request.Form["name"];
                attach["mimetype"]       = context.Request.Form["type"];
                attach["filesize"]       = context.Request.Form["size"];
                attach["subject"]        = context.Request.Form["name"];
                attach["documentbody"]   = base64Data;
                attach["objecttypecode"] = 2;
                attach["isdocument"]     = true;
                attach["objectid"]       = new EntityReference("contact", new Guid(contactId));

                service.Create(attach);

                var data = serializer.Serialize(true);
                context.Response.Write(data);
                #endregion
            }
            else if (op != null && op == "2")
            {
                #region İlgili Kişi - Nüfus cüzdanı indirme
                var id = context.Request.QueryString["id"];
                if (id != null)
                {
                    HttpResponse response = context.Response;
                    Entity       ann      = GetAnnotionByContactId(new Guid(Convert.ToString(id)));
                    if (ann == null)
                    {
                        response.Write("<center><h3>Dosya Bulunamadı.</h3></center>");
                        return;
                    }

                    byte[] toEncryptArray = Convert.FromBase64String(ann.GetAttributeValue <string>("documentbody"));
                    string fileName       = ann.GetAttributeValue <string>("filename");
                    response.ClearContent();
                    response.ContentType  = ann.GetAttributeValue <string>("mimetype");
                    response.CacheControl = "no-cache";
                    response.AddHeader("content-disposition", "attachment;filename=" + fileName);
                    response.AddHeader("Content-Length", toEncryptArray.Length.ToString());
                    response.BinaryWrite(toEncryptArray);
                    response.Buffer = true;
                    response.End();
                }
                #endregion
            }
            else if (op != null && op == "6")
            {
                #region Aktivite - Yer gösterme belgesi örneği indirme
                string serverPath   = HttpContext.Current.Server.MapPath("~");
                string fileLocation = serverPath + "\\RentalDocs\\YerGostermeBelgesi.docx";

                FileInfo fileInfo = new FileInfo(fileLocation);
                if (fileInfo.Exists)
                {
                    context.Response.ClearContent();
                    context.Response.AppendHeader("Content-Disposition", "attachment;filename*=UTF-8''" + Uri.EscapeDataString("Yer Gösterme Belgesi.docx"));
                    context.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                    context.Response.ContentType = "application/octet-stream";
                    context.Response.TransmitFile(fileLocation);
                    context.Response.End();
                }
                #endregion
            }
            else if (op != null && op == "7")
            {
                #region Aktivite - Yer göstermesi belgesi ekleme
                context.Response.ContentType = "application/json";

                JavaScriptSerializer serializer = new JavaScriptSerializer();

                string message      = string.Empty;
                var    base64Data   = context.Request.Form["data"];
                var    activityId   = context.Request.Form["activityid"];
                var    activityType = context.Request.Form["activityType"];

                IOrganizationService service = MSCRM.GetOrgService(true);

                Entity attach = new Entity("annotation");

                attach["filename"]     = "YGB_" + context.Request.Form["name"];
                attach["mimetype"]     = context.Request.Form["type"];
                attach["filesize"]     = context.Request.Form["size"];
                attach["subject"]      = context.Request.Form["name"];
                attach["documentbody"] = base64Data;
                if (activityType.Equals("appointment"))
                {
                    attach["objecttypecode"] = 4201;
                }
                else if (activityType.Equals("phonecall"))
                {
                    attach["objecttypecode"] = 4210;
                }

                attach["isdocument"] = true;

                attach["objectid"] = new EntityReference(activityType, new Guid(activityId));

                service.Create(attach);

                var data = serializer.Serialize(true);
                context.Response.Write(data);
                #endregion
            }
            else if (op != null && op == "8")
            {
                #region Aktivite - Yer göstermesi belgesi indirme
                var id = context.Request.QueryString["id"];
                if (id != null)
                {
                    HttpResponse response = context.Response;
                    Entity       ann      = GetDisplayLocationAnnByActivityId(new Guid(Convert.ToString(id)));
                    if (ann == null)
                    {
                        response.Write("<center><h3>Dosya Bulunamadı.</h3></center>");
                        return;
                    }

                    byte[] toEncryptArray = Convert.FromBase64String(ann.GetAttributeValue <string>("documentbody"));
                    string fileName       = ann.GetAttributeValue <string>("filename");
                    response.ClearContent();
                    response.ContentType  = ann.GetAttributeValue <string>("mimetype");
                    response.CacheControl = "no-cache";
                    response.AddHeader("content-disposition", "attachment;filename=" + fileName);
                    response.AddHeader("Content-Length", toEncryptArray.Length.ToString());
                    response.BinaryWrite(toEncryptArray);
                    response.Buffer = true;
                    response.End();
                }
                #endregion
            }

            if (op != null && op == "9")
            {
                #region Yetki Belgesi Dokümanı Oluşturma
                context.Response.ContentType = "application/json";

                JavaScriptSerializer serializer = new JavaScriptSerializer();

                string message               = string.Empty;
                var    base64Data            = context.Request.Form["data"];
                var    contactId             = context.Request.Form["documentid"];
                IOrganizationService service = MSCRM.GetOrgService(true);

                Entity attach = new Entity("annotation");

                attach["filename"]       = context.Request.Form["name"];
                attach["mimetype"]       = context.Request.Form["type"];
                attach["filesize"]       = context.Request.Form["size"];
                attach["subject"]        = context.Request.Form["name"];
                attach["documentbody"]   = base64Data;
                attach["objecttypecode"] = 10085;
                attach["isdocument"]     = true;
                attach["objectid"]       = new EntityReference("new_registrationdoc", new Guid(contactId));

                service.Create(attach);

                var data = serializer.Serialize(true);
                context.Response.Write(data);
                #endregion
            }
            else if (op != null && op == "10")
            {
                #region Aktivite - Yer göstermesi belgesi indirme
                var id = context.Request.QueryString["id"];
                if (id != null)
                {
                    HttpResponse response = context.Response;
                    Entity       ann      = GetAuthorityDocById(new Guid(Convert.ToString(id)));
                    if (ann == null)
                    {
                        response.Write("<center><h3>Dosya Bulunamadı.</h3></center>");
                        return;
                    }

                    byte[] toEncryptArray = Convert.FromBase64String(ann.GetAttributeValue <string>("documentbody"));
                    string fileName       = ann.GetAttributeValue <string>("filename");
                    response.ClearContent();
                    response.ContentType  = ann.GetAttributeValue <string>("mimetype");
                    response.CacheControl = "no-cache";
                    response.AddHeader("content-disposition", "attachment;filename=" + fileName);
                    response.AddHeader("Content-Length", toEncryptArray.Length.ToString());
                    response.BinaryWrite(toEncryptArray);
                    response.Buffer = true;
                    response.End();
                }
                #endregion
            }
        }
Example #28
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";

            JavaScriptSerializer serializer = new JavaScriptSerializer();

            MsCrmResultObject returnValue = new MsCrmResultObject();

            try
            {
                var base64Data = context.Request.Form["data"];

                if (base64Data != null)
                {
                    #region |ADD CSV TO DATATABLE TO CHECK|

                    CsvParse pars = new CsvParse(base64Data, CsvParser.CsvParse.delimiter.NoktalıVirgül);

                    DataTable dt = new DataTable();

                    dt = pars.GetDataTableFromCSV();

                    #endregion

                    if (dt == null || dt.Rows.Count == 0)
                    {
                        returnValue.Result = "Yanlış içerik veya kayıt yok. <br /> Lütfen kontrol ediniz.";
                    }
                    else
                    {
                        if (isColumnNamesOK(dt))
                        {
                            IOrganizationService service;
                            service = MSCRM.GetOrgService(true);

                            Entity ent = new Entity("new_houseimport");
                            ent["new_name"]   = DateTime.Now.ToString("dd.MM.yyyy HH:mm");
                            ent["statuscode"] = new OptionSetValue(1); //Beklemede

                            Guid importId = service.Create(ent);

                            Entity attach = new Entity("annotation");

                            attach["filename"]       = context.Request.Form["name"];
                            attach["mimetype"]       = context.Request.Form["type"];
                            attach["filesize"]       = context.Request.Form["size"];
                            attach["subject"]        = "Konut Import Dosyası";
                            attach["documentbody"]   = base64Data;
                            attach["objecttypecode"] = Globals.HouseImportObjectTypeCode;
                            attach["isdocument"]     = true;
                            attach["objectid"]       = new EntityReference("new_houseimport", importId);

                            service.Create(attach);

                            returnValue.Success = true;
                            returnValue.Result  = "Dosya başarılı bir şekilde import edildi.<br/> İşlem tamamlandığında mail ile bilgilendirme yapılacaktır.";
                        }
                        else
                        {
                            returnValue.Result = "Dosya içerisindeki kolon isimleri uyuşmuyor.<br/> Lütfen kontrol ediniz.";
                        }
                    }
                }
                else
                {
                    returnValue.Result = "Dosya içeriği gönderilmedi.<br/> Lütfen kontrol ediniz.";
                }
            }
            catch (Exception ex)
            {
                returnValue.Result = ex.Message;
            }

            var data = serializer.Serialize(returnValue);
            context.Response.Write(data);
        }
Example #29
0
        public static MsCrmResult Process()
        {
            MsCrmResult returnValue = new MsCrmResult();

            int totalCount   = 0;
            int errorCount   = 0;
            int successCount = 0;

            IOrganizationService service = MSCRM.GetOrgService(true);

            SqlDataAccess sda = new SqlDataAccess();

            sda.openConnection(Globals.ConnectionString);

            DataTable lstImports = QuoteHelper.GetNotProcessedYellowExcelQuotes(sda);

            Console.SetCursorPosition(0, 1);
            Console.WriteLine("Listeler çekildi. Adet:" + lstImports.Rows.Count.ToString());

            if (lstImports.Rows.Count > 0)
            {
                for (int i = 0; i < lstImports.Rows.Count; i++)
                {
                    Guid quoteId = new Guid(Convert.ToString(lstImports.Rows[i]["QuoteId"]));

                    try
                    {
                        Console.SetCursorPosition(0, 2);
                        Console.WriteLine((i + 1).ToString() + ". Liste İşleniyor.");
                        //HATALI KAYITLARI SİLER
                        PaymentHelper.DeletePaymentsIfExist(quoteId, service, sda);
                        totalCount   = 0;
                        errorCount   = 0;
                        successCount = 0;

                        int     customerIdType      = Convert.ToInt32(lstImports.Rows[i]["CustomerIdType"]);
                        Guid    customerId          = new Guid(Convert.ToString(lstImports.Rows[i]["CustomerId"]));
                        Guid    financialAccount    = new Guid(Convert.ToString(lstImports.Rows[i]["new_financialaccountid"]));
                        Decimal totalAmountQuote    = Convert.ToDecimal(lstImports.Rows[i]["totalamountlessfreight"]);
                        Decimal totalLineItemAmount = Convert.ToDecimal(lstImports.Rows[i]["TotalLineItemAmount"]);

                        MsCrmResult resultProcessing = QuoteHelper.UpdateYellowExcelState(quoteId, 2, service); //İşleniyor

                        if (resultProcessing.Success)
                        {
                            DataTable dt = QuoteHelper.GetNotProcessedYellowExcelData(quoteId, "Sheet1", sda);

                            Console.SetCursorPosition(0, 3);
                            Console.WriteLine((i + 1).ToString() + ". Liste Kayıt sayısı: " + dt.Rows.Count.ToString());

                            if (dt.Rows.Count > 0)
                            {
                                totalCount = dt.Rows.Count;
                                decimal totalAmountExcel = 0;
                                foreach (DataRow currentPayment in dt.Rows)
                                {
                                    if (DBNull.Value != currentPayment["Tutar"])
                                    {
                                        totalAmountExcel += Convert.ToDecimal(currentPayment["Tutar"]);
                                    }
                                }
                                if (totalAmountExcel != totalAmountQuote)
                                {
                                    string message = "İndirimli Konut Fiyatı, Sarı Excel tutar toplamı ile aynı değil. Lütfen kontrol edin.";
                                    message += Environment.NewLine;
                                    message += "Excel Tutar Toplamı : " + totalAmountExcel.ToString("#.##");
                                    message += Environment.NewLine;
                                    message += "İndirimli Konut Fiyatı : " + totalAmountQuote.ToString("#.##");
                                    QuoteHelper.LogYellowExcelError(quoteId, message, service);
                                    SendInformationMail(quoteId, 0, service);
                                    break;
                                }
                                for (int j = 0; j < totalCount; j++)
                                {
                                    Console.SetCursorPosition(0, 4);
                                    Console.WriteLine("Sayaç:" + (j + 1).ToString());

                                    //Satıs tutarı kontrolü geçici bir süre kapatıldı.
                                    //if (j == 0)
                                    //{
                                    //    if (totalLineItemAmount == Convert.ToDecimal(dt.Rows[j]["Satıs Tutarı"]))
                                    //    {

                                    //    }
                                    //}


                                    if ((DBNull.Value == dt.Rows[j]["Tutar"] || Convert.ToDecimal(dt.Rows[j]["Tutar"]) == 0) ||
                                        DBNull.Value == dt.Rows[j]["Vade Gün"] || dt.Rows[j]["Vade Gün"].ToString().Contains("1900"))
                                    {
                                        continue;
                                    }

                                    if (DBNull.Value == dt.Rows[j]["Ödeme Tipi"] || Convert.ToString(dt.Rows[j]["Ödeme Tipi"]).Trim().ToUpper().Equals("KAPARO"))
                                    {
                                        continue;
                                    }


                                    #region | PROCESS ROW |
                                    try
                                    {
                                        SetPayment(dt.Rows[j], quoteId, customerIdType, customerId, financialAccount, service);
                                    }
                                    catch (Exception ex)
                                    {
                                        //Console.WriteLine("hata 1" + ex.Message);
                                        //Console.ReadLine();

                                        QuoteHelper.UpdateYellowExcelState(quoteId, 4, service, ex.Message); //Hata alındı
                                        SendInformationMail(quoteId, 0, service);
                                    }
                                    #endregion

                                    Console.SetCursorPosition(0, 5);
                                    Console.WriteLine("Hata:" + errorCount.ToString());

                                    Console.SetCursorPosition(0, 6);
                                    Console.WriteLine("Başarılı:" + successCount.ToString());
                                }
                            }
                        }
                        QuoteHelper.UpdateYellowExcelState(quoteId, 3, service, "Excel başarılı bir şekilde işlendi."); //İşlendi
                        SendInformationMail(quoteId, 1, service);
                    }
                    catch (Exception ex)
                    {
                        QuoteHelper.LogYellowExcelError(quoteId, ex.Message, service);
                        returnValue.Result = ex.Message;
                        //Console.WriteLine("hata 1" + ex.Message);
                        //Console.ReadLine();
                    }
                }
                returnValue.Success = true;
                returnValue.Result  = "Listeler işlendi...";
            }
            return(returnValue);
        }