Exemple #1
0
    void Start()
    {
        filterchoicememo = filterchoice;
        if (Camera2 != null)
        {
            Camera2tex            = new RenderTexture(Screen.width, Screen.height, 24);
            Camera2.targetTexture = Camera2tex;
        }


        ChangeFilters();
        SCShader = Shader.Find(ShaderName);
        if (!SystemInfo.supportsImageEffects)
        {
            enabled = false;
            return;
        }
    }
        private static void AddFilter(filters filters, string value, string key, string valueKey)
        {
            if (filters.complex_filter == null)
            {
                filters.complex_filter = new complexFilter[0];
            }

            var temp = filters.complex_filter.ToList();

            temp.Add(new complexFilter()
            {
                key = key, value = new associativeEntity()
                {
                    key = valueKey, value = value
                }
            });
            filters.complex_filter = temp.ToArray();
        }
Exemple #3
0
        protected void related_sale(MagentoService mservice, string mlogin, string brand_sql, string search_family, string source_sku)
        {
            filters filter    = new filters();
            string  storeview = "1";

            if (search_family.Contains("OEM"))
            {
                storeview = "3";
            }
            filter = addFilter(filter, "brand", "eq", brand_sql);
            filter = addFilter(filter, "status", "eq", "1");

            var result = mservice.catalogProductList(mlogin, filter, storeview);

            string[] sku_arr = new string[result.Length];

            int i = 0;

            //get result sku
            foreach (catalogProductEntity product in result)
            {
                sku_arr[i] = product.sku;

                i += 1;
            }
            //get stock level
            var result2 = mservice.catalogInventoryStockItemList(mlogin, sku_arr);

            foreach (catalogInventoryStockItemEntity product in result2)
            {
                string qty_sku = product.sku;
                Double qty     = double.Parse(product.qty);
                if (qty > 0)
                {
                    catalogProductLinkEntity assign = new catalogProductLinkEntity();
                    assign.position = "1";

                    // inject related listing
                    mservice.catalogProductLinkUpdate(mlogin, "related", source_sku, qty_sku, assign, "sku");
                }
            }

            mservice.Dispose();
        }
Exemple #4
0
    void SatControls()
    {
        GameObject[] satellites;
        if (Input.GetKeyDown(KeyCode.Space))                    // Pressing Space toggles between overlays, as a test.
        {
            if (activeFilter == filters.None)
            {
                activeFilter = filters.Work;
                satellites   = GameObject.FindGameObjectsWithTag("Satellite");
                foreach (GameObject sat in satellites)
                {
                    sat.GetComponent <Satellite>().ColorOverlay();
                }
            }
            else
            {
                activeFilter = filters.None;
                satellites   = GameObject.FindGameObjectsWithTag("Satellite");
                foreach (GameObject sat in satellites)
                {
                    sat.GetComponent <Satellite>().ColorOverlay();
                }
            }
        }

        //go up or down in orbit
        if (selectedSomething)
        {
            if (Input.GetKey(KeyCode.S))
            {
                satellite.AltitudeChange(0.3f);
            }
            else if (Input.GetKey(KeyCode.W))
            {
                satellite.AltitudeChange(-0.3f);
            }
            else
            {
                satellite.AltitudeChange(0.0f);
            }
        }
    }
    void Start()
    {
        filterchoicememo = filterchoice;
        if (Camera2 != null)
        {
            DestroyImmediate(Camera2.targetTexture);
            Camera2tex            = new RenderTexture(Screen.width, Screen.height, 24);
            Camera2.targetTexture = Camera2tex;
        }

        ChangeValue  = BlendFX;
        ChangeValue2 = SwitchCameraToCamera2;
        ChangeFilters();
        SCShader = Shader.Find(ShaderName);
        if (!SystemInfo.supportsImageEffects)
        {
            enabled = false;
            return;
        }
    }
        public void SetupFieldType_CommonSwitchCaseConstantsConditionField_SetsFieldTypeDropdownListEnableToTrueAndSelectString(string switchCaseConstant)
        {
            // Arrange
            var filter = new filters();
            var fieldTypeDropDownList = CreateDropdownList(false);

            ReflectionHelper.SetValue(filter, "ddlFieldType", fieldTypeDropDownList);

            // Act
            var parameters = new object[] { switchCaseConstant };

            typeof(filters).CallMethod("SetupFieldType", parameters, filter);

            // Assert
            var fieldTypeDropdownList = ReflectionHelper.GetFieldInfoFromInstanceByName(filter, "ddlFieldType").GetValue(filter) as DropDownList;

            fieldTypeDropdownList.ShouldNotBeNull();
            fieldTypeDropdownList.Enabled.ShouldBeTrue();
            fieldTypeDropDownList.SelectedIndex.ShouldBe(StringSelectedIndex);
        }
        public virtual async Task <GetOrdersResponse> GetOrdersAsync(DateTime modifiedFrom, DateTime modifiedTo, Mark mark = null)
        {
            var filters = new filters();

            AddFilter(filters, modifiedFrom.ToSoapParameterString(), "updated_at", "from");
            AddFilter(filters, modifiedTo.ToSoapParameterString(), "updated_at", "to");
            if (!string.IsNullOrWhiteSpace(this.Store))
            {
                AddFilter(filters, this.Store, "store_id", "in");
            }

            return(await this.GetWithAsync(
                       res =>
            {
                //crutch for magento 1.7
                res.result = res.result.Where(x => Extensions.ToDateTimeOrDefault(x.updated_at) >= modifiedFrom && Extensions.ToDateTimeOrDefault(x.updated_at) <= modifiedTo).ToArray();
                return new GetOrdersResponse(res);
            },
                       async ( client, session ) => await client.salesOrderListAsync( session, filters ).ConfigureAwait(false), 600000).ConfigureAwait(false));
        }
Exemple #8
0
        public virtual async Task <SoapGetProductsResponse> GetProductsAsync()
        {
            try
            {
                var filters = new filters {
                    filter = new associativeEntity[0]
                };

                var store = string.IsNullOrWhiteSpace(this.Store) ? null : this.Store;

                const int maxCheckCount    = 2;
                const int delayBeforeCheck = 1800000;

                var res           = new catalogProductListResponse();
                var privateClient = this.CreateMagentoServiceClient(this.BaseMagentoUrl);

                await ActionPolicies.GetAsync.Do(async() =>
                {
                    var statusChecker = new StatusChecker(maxCheckCount);
                    TimerCallback tcb = statusChecker.CheckStatus;

                    if (privateClient.State != CommunicationState.Opened &&
                        privateClient.State != CommunicationState.Created &&
                        privateClient.State != CommunicationState.Opening)
                    {
                        privateClient = this.CreateMagentoServiceClient(this.BaseMagentoUrl);
                    }

                    var sessionId = await this.GetSessionId().ConfigureAwait(false);

                    using (var stateTimer = new Timer(tcb, privateClient, 1000, delayBeforeCheck))
                        res = await privateClient.catalogProductListAsync(sessionId.SessionId, filters, store).ConfigureAwait(false);
                }).ConfigureAwait(false);

                return(new SoapGetProductsResponse(res));
            }
            catch (Exception exc)
            {
                throw new MagentoSoapException(string.Format("An error occured during GetProductsAsync()"), exc);
            }
        }
Exemple #9
0
    void OnValidate()
    {
        if (filterchoice != filterchoicememo)
        {
            ChangeFilters();
            SCShader = Shader.Find(ShaderName);
            DestroyImmediate(SCMaterial);
            if (SCMaterial == null)
            {
                SCMaterial           = new Material(SCShader);
                SCMaterial.hideFlags = HideFlags.HideAndDontSave;
            }
        }


        filterchoicememo = filterchoice;
        if (Camera2 != null)
        {
            Camera2tex            = new RenderTexture(Screen.width, Screen.height, 24);
            Camera2.targetTexture = Camera2tex;
        }
    }
Exemple #10
0
        static void identity_block(input_tensor, kernel_size, filters, stage, block) {
            //KerasSharp.Backends.Current.Switch("KerasSharp.Backends.TensorFlowBackend");
            //
            var bn_axis = 3;
            var filters1, filters2, filters3 = filters;
            var conv_name_base = "res" + str(stage) + block + "_branch";
            var bn_name_base = "bn" + str(stage) + block + "_branch";

            var x = new Conv2D(filters1, (1,1), name:conv_name_base + "2a")(input_tensor);
            x = x.add(new BatchNormalization(axis:bn_axis, name:bn_name_base + "2a")(x));
            x = x.add(new activation: ReLU())(x));

            x = x.add(new Conv2D(filters2, kernel_size, padding:"same", name:conv_name_base + "2b")(x));
            x = x.add(new BatchNormalization(axis:bn_axis, name:bn_name_base + "2b")(x));
            x = x.add(new activation: ReLU())(x));


            x = x.add(new Conv2D(filters3, (1,1), name:conv_name_base + "2c")(x));
            x = x.add(new BatchNormalization(axis:bn_axis, name:bn_name_base + "2c")(x));

            x = x.add(activation: new ReLU())(x));
  
            return x;
        }
Exemple #11
0
        static void Main(string[] args)
        {
            Navision_CustomerListService.CustomerList            nv_Customer = new Navision_CustomerListService.CustomerList();
            Navision_CustomerListService.CustomerList_PortClient client      = new Navision_CustomerListService.CustomerList_PortClient();
            Navision_CustomerListService.CustomerList[]          nv_CustomerLists;
            client.ClientCredentials.UserName.UserName = "******";
            client.ClientCredentials.UserName.Password = "******";
            //client.ClientCredentials.Windows.ClientCredential.UserName = "******";

            //client.ClientCredentials.Windows.ClientCredential.Password = "******";

            //client.ClientCredentials.Windows.ClientCredential.Domain = "122.166.222.116";


            nv_CustomerLists = client.ReadMultiple(null, null, 10000);

            MagentoConnectService.PortTypeClient mage_client = new MagentoConnectService.PortTypeClient();
            DBConnect db = new DBConnect();
            int       newCustomerCreateID = 0;
            int       createAddressID     = 0;
            string    token_id            = "";
            filters   myfilter            = new filters();

            token_id = mage_client.login("webserviceuser", "apikey");

            Hashtable hsc = db.fetch_CustomerMapping();

            for (int i = 0; i < nv_CustomerLists.Length; i++)
            {
                // Create Customer
                customerCustomerEntityToCreate customerCreate = new customerCustomerEntityToCreate();
                try
                {
                    customerCreate.firstname           = nv_CustomerLists[i].Name;
                    customerCreate.lastname            = ".";
                    customerCreate.middlename          = "";
                    customerCreate.password            = "******";
                    customerCreate.store_id            = 1;
                    customerCreate.store_idSpecified   = true;
                    customerCreate.website_id          = 1;
                    customerCreate.website_idSpecified = true;
                    customerCreate.group_id            = 1;
                    customerCreate.group_idSpecified   = true;
                    customerCreate.suffix          = "P";
                    customerCreate.email           = nv_CustomerLists[i].E_Mail;
                    customerCreate.gender          = 1; //1-Male;2-Female
                    customerCreate.genderSpecified = true;
                    //customer address
                    customerAddressEntityCreate customerAddress = new customerAddressEntityCreate();
                    if (nv_CustomerLists[i].Location_Code == null)
                    {
                        customerAddress.city = "NA";
                    }
                    else
                    {
                        customerAddress.city = nv_CustomerLists[i].Location_Code;
                    }
                    customerAddress.region_id          = 2; //CountryID
                    customerAddress.region_idSpecified = true;
                    if (nv_CustomerLists[i].Country_Region_Code == null)
                    {
                        customerAddress.country_id = "NA";
                    }
                    else
                    {
                        customerAddress.country_id = nv_CustomerLists[i].Country_Region_Code;
                    }
                    customerAddress.fax        = nv_CustomerLists[i].Fax_No;
                    customerAddress.firstname  = nv_CustomerLists[i].Name;
                    customerAddress.lastname   = ".";
                    customerAddress.middlename = "";
                    string[] streettxt = { nv_CustomerLists[i].Address };
                    customerAddress.street = streettxt;

                    customerAddress.postcode = nv_CustomerLists[i].Post_Code;
                    customerAddress.prefix   = "M";
                    customerAddress.suffix   = "P";
                    //  customerAddress.street = nv_CustomerLists[i].Address.ToString();
                    if (nv_CustomerLists[i].Phone_No == null)
                    {
                        customerAddress.telephone = "NA";
                    }
                    else
                    {
                        customerAddress.telephone = nv_CustomerLists[i].Phone_No;
                    }
                    //If you specify 'true' for is_default_billing and is_default_shipping. Then this address will be your default shipping and billing. Otherwise none.
                    customerAddress.is_default_billing  = true;
                    customerAddress.is_default_shipping = true;

                    if (db.fetch_Customer(nv_CustomerLists[i].No.ToString()))
                    {
                        mage_client.customerCustomerUpdate(token_id, Convert.ToInt16(hsc[nv_CustomerLists[i].No]), customerCreate);
                    }
                    else
                    {
                        newCustomerCreateID = mage_client.customerCustomerCreate(token_id, customerCreate);
                        createAddressID     = mage_client.customerAddressCreate(token_id, newCustomerCreateID, customerAddress);
                        db.InsertCustomerMapping(nv_CustomerLists[i].No, newCustomerCreateID.ToString(), nv_CustomerLists[i].E_Mail);
                        db.InsertLog("Customer", nv_CustomerLists[i].No, "Navision Customer Code", "SUCCESS");
                    }
                }

                catch (Exception ex)
                {
                    MNC_Product_Sync.ErrorLog errLog = new MNC_Product_Sync.ErrorLog();

                    errLog.LogError("C:\\MNC_Logs", "Customer :" + ex.Message);
                    db.InsertLog("Customer", nv_CustomerLists[i].No, ex.Message, "FAILED");
                }


                finally
                {
                    //mage_client.endSession(token_id);
                }
            }
            mage_client.endSession(token_id);
        }
        protected override string GetSalesMonth(DateTime exportDate, string filename)
        {
            //access Magento store API

            //Get the sales records for the requested month
            DateTime fromDate = new DateTime(exportDate.Year, exportDate.Month, 1);
            DateTime toDate = fromDate.AddMonths(1);
            string result = "\n" + filename + ": ";
            string tempDisplay = ProgressText;
            ProgressText += result + "Exporting...";
            StringBuilder data = new StringBuilder();
            string h2 = "Product ID\tCustomer ID\tQuantity\tDate\r\n"; //sales file second header line
            StringBuilder salesData = new StringBuilder(CommonHeader + h2);

            Mage_Api_Model_Server_V2_HandlerPortTypeClient Mclient = new Mage_Api_Model_Server_V2_HandlerPortTypeClient();
            string MsessionId = "";

            //---------------------SALES MONTH EXPORT----------------------------
            //errors caught by calling function

            //login
            MsessionId = Mclient.login(m_apiUserName, m_apiKey);

            //create filter to get sales for this month only
            filters monthFilter = new filters();
            monthFilter.complex_filter = new complexFilter[2];
            monthFilter.complex_filter[0] = new complexFilter();
            monthFilter.complex_filter[0].key = "created_at";
            monthFilter.complex_filter[0].value = new associativeEntity();
            monthFilter.complex_filter[0].value.key = "from";
            monthFilter.complex_filter[0].value.value = fromDate.ToString("yyyy-MM-dd HH:mm:ss");
            monthFilter.complex_filter[1] = new complexFilter();
            monthFilter.complex_filter[1].key = "created_at";
            monthFilter.complex_filter[1].value = new associativeEntity();
            monthFilter.complex_filter[1].value.key = "to";
            monthFilter.complex_filter[1].value.value = toDate.ToString("yyyy-MM-dd HH:mm:ss");

            //get list of sales orders
            salesOrderEntity[] sorders = Mclient.salesOrderList(MsessionId, monthFilter);
            if (sorders.Length > 0)
            {
                foreach (salesOrderEntity s in sorders)
                {
                    string customerid = s.customer_id;
                    if (s.customer_is_guest.Equals("1"))
                    {
                        customerid = s.customer_email;
                        if (customerid == null || customerid.Length < 1)
                            customerid = s.increment_id;
                    }
                    string date = s.created_at;
                    //get list of items purchased on each sales order
                    salesOrderEntity sinfo = Mclient.salesOrderInfo(MsessionId, s.increment_id);
                    foreach (salesOrderItemEntity item in sinfo.items)
                    {
                        string productid = item.product_id;
                        //TODO: Need to get parent_item_id here if it exists

                        string quantity = item.qty_ordered;
                        int len = quantity.IndexOf(".");
                        if (len > 0)
                            quantity = quantity.Substring(0, len); //remove fractional part

                        //add line to sales data
                        salesData.Append(productid + "\t" + customerid + "\t" + quantity + "\t" + date + "\r\n");
                    }
                }
            }
            //upload sales data
            ProgressText = tempDisplay + result + "Uploading...";
            result += m_boostService.WriteTable(m_alias, filename, data);
            ProgressText = tempDisplay + result;
            return result;
        }
        protected string ApiTest()
        {
            string result = "\n" + CatalogFilename + ": ";
            string tempDisplay = ProgressText;
            ProgressText += result + "Rows to export...";
            StopWatch exportWatch = new StopWatch(true);

            #if MAGENTO_API_AVAILABLE
            #region Static Trevor
            if (static_proxy && m_alias.Equals("Trevor"))
            {
              MagentoService Mclient = new MagentoService();
              string MsessionId = "";

              //---------------------CATALOG EXPORT----------------------------
              try
              {
                MsessionId = Mclient.login(m_apiUserName, m_apiKey);
                catalogProductEntity[] plist = Mclient.catalogProductList(MsessionId, null, "");
                if (plist.Length < 1)
                  throw new Exception("No products available");

                //TODO: create catalog file header
                string type = "";
                foreach (catalogProductEntity p in plist)
                {
                  string pid = p.product_id;
                  if (p.type.Equals("simple")) //only export combined items or else simple items with no parents
                  {
                    bool isChild = false;
                    catalogProductLinkEntity[] plinks = Mclient.catalogProductLinkList(MsessionId, "grouped", pid, "id");
                    foreach (catalogProductLinkEntity pl in plinks)
                      if (pl.type.Equals("configurable"))
                      {
                        isChild = true;
                        break;
                      }
                    if (isChild) continue;
                  }
                  else
                    type += p.type + " ";

                  string pname = p.name;
                  string patt1 = "";
                  bool first = true;
                  foreach (string cid in p.category_ids)
                  {
                    if (first) first = false;
                    else patt1 += ",";
                    patt1 += cid;
                  }

                  catalogProductReturnEntity pinfo = Mclient.catalogProductInfo(MsessionId, pid, "", null, "id");
                  catalogProductReturnEntity pPriceInfo = Mclient.catalogProductGetSpecialPrice(MsessionId, pid, "", "id");
                  string patt2 = "";
                  string pprice = pPriceInfo.price; ;
                  if ((pPriceInfo.special_from_date != null) && (pinfo.special_to_date != null))
                  {
                    DateTime saleStart = DateTime.Parse(pPriceInfo.special_from_date);
                    DateTime saleEnd = DateTime.Parse(pPriceInfo.special_to_date);
                    DateTime now = DateTime.Now;
                    if (now >= saleStart && now <= saleEnd)
                      pprice = pPriceInfo.special_price;
                  }
                  string pfilter = "";
                  string plink = pinfo.url_key;
                  string pimage = "";
                  string psku = pinfo.sku;
                  catalogProductImageEntity pimageinfo = null;
                  try
                  {
                    pimageinfo = Mclient.catalogProductAttributeMediaInfo(MsessionId, pid, "", "", "id");
                  }
                  catch { }
                  if (pimageinfo != null)
                  {
                    pimage = pimageinfo.url;
                  }
                }
              }
              catch { }

              //---------------------SALES EXPORT----------------------------
              try
              {
                //salesOrderEntity[] sorders = Mclient.salesOrderList(MsessionId, null);
                salesOrderEntity[] sorders = Mclient.salesOrderList(MsessionId, null);
                if (sorders.Length > 0)
                {
                  //TODO: create header line for sales export
                  foreach (salesOrderEntity s in sorders)
                  {
                    string customerid = s.customer_id;
                    if (s.customer_is_guest.Equals("1"))
                    {
                      customerid = s.customer_email;
                      if (customerid == null || customerid.Length < 1)
                        customerid = s.increment_id;
                    }
                    string date = s.created_at;
                    salesOrderEntity sinfo = Mclient.salesOrderInfo(MsessionId, s.increment_id);
                    foreach (salesOrderItemEntity item in sinfo.items)
                    {
                      string productid = item.product_id;
                      string quantity = item.qty_ordered;
                      int len = quantity.IndexOf(".");
                      if (len > 0)
                        quantity = quantity.Substring(0, len); //remove fractional part

                      //TODO: add line to sales data here
                    }
                  }
                  //TODO: upload sales data
                }
              }
              catch { }
            }
            #endregion
            #endif

            #region Static GoStore
              Mage_Api_Model_Server_V2_HandlerPortTypeClient Mclient = new Mage_Api_Model_Server_V2_HandlerPortTypeClient();
              string MsessionId = "";

              //---------------------CATALOG EXPORT----------------------------
              try
              {
                //login
                    //MsessionId = Mclient.login(m_apiUserName, m_apiKey);
                    MsessionId = Mclient.login("4Tell", "4tellsoftware"); //condomania

                    //Get API calls available
                    apiEntity[] resources = Mclient.resources(MsessionId);
                    //resultObj = proxy.CallMethod("resources", sessionID);
                    //Type t = resultObj.GetType();
                    //XmlSerializer xs = new XmlSerializer(t);
                    //XElement resources = xs.SerializeAsXElement(resultObj);
                    //TODO: check each CallMethod to make sure it is in this list...

                    //Set product attributes to fetch
                catalogProductRequestAttributes prodAttributes = new catalogProductRequestAttributes();
                    string[] attributes = { "sku", "url_key", "price", "special_price", "special_from_date", "special_to_date", "parent_item_id" };
                prodAttributes.attributes = attributes;

                    //filters prodFilters = new filters();
                    //associativeEntity[] filterList = new associativeEntity[1];
                    //filterList[0].key = "";
                    //filterList[0].value = "";

                //loop through all products
                    StringBuilder data = new StringBuilder(CommonHeader + ProductRecord.Header());
                catalogProductEntity[] plist;
                Mclient.catalogProductList(out plist, MsessionId, null, "");
                string type = "";
                int maxCid = 0;
                foreach (catalogProductEntity p in plist)
                {
                  string pid = p.product_id;

                        if (p.type.Equals("simple")) //only export combined items or else simple items with no parents
                        {
                            //bool isChild = false;
                            //catalogProductLinkEntity[] plinks = Mclient.catalogProductLinkList(MsessionId, "grouped", pid, "id");
                            //foreach (catalogProductLinkEntity pl in plinks)
                            //  if (pl.type.Equals("configurable"))
                            //  {
                            //    isChild = true;
                            //    break;
                            //  }
                            //if (isChild) continue;
                        }
                        else
                            type += p.type + " ";

                  string pname = p.name;
                  string patt1 = "";
                  bool first = true;
                  foreach (string cid in p.category_ids)
                  {
                    if (first) first = false;
                    else patt1 += ",";
                    patt1 += cid;
                    int id = Convert.ToInt32(cid);
                    if (id > maxCid) maxCid = id;
                  }

                  string patt2 = "";
                  catalogProductReturnEntity pinfo = Mclient.catalogProductInfo(MsessionId, pid, "", prodAttributes, "id");
                  string pprice = pinfo.price; ;
                  if ((pinfo.special_from_date != null) && (pinfo.special_to_date != null))
                  {
                    DateTime saleStart = DateTime.Parse(pinfo.special_from_date);
                    DateTime saleEnd = DateTime.Parse(pinfo.special_to_date);
                    DateTime now = DateTime.Now;
                    if (now >= saleStart && now <= saleEnd)
                      pprice = pinfo.special_price;
                  }
                  string pfilter = "";
                  string plink = pinfo.url_key;
                  string pimage = "";
                  string psku = pinfo.sku;
                  catalogProductImageEntity pimageinfo = null;
                        try
                        {
                            pimageinfo = Mclient.catalogProductAttributeMediaInfo(MsessionId, pid, "", "", "id");
                        }
                        catch
                        {
                            try
                            {
                                pimageinfo = Mclient.catalogProductAttributeMediaInfo(MsessionId, psku, "", "", "sku");
                            }
                            catch
                            {
                            }
                        }
                        if (pimageinfo != null)
                        {
                            pimage = pimageinfo.url;
                        }
                  data.Append(pid + "\t" + pname + "\t" + patt1 + "\t" + patt2 + "\t" + pprice + "\t" + pfilter + "\t" + plink + "\t" + pimage + "\t" + psku + "\r\n");
                }
                    result += m_boostService.WriteTable(m_alias, CatalogFilename, data);

                //get cat info
                result += "\n" + Att1Filename + ": ";
                ProgressText = tempDisplay + result + "Exporting...";
                catalogCategoryInfo cinfo;
                    StringBuilder csb = new StringBuilder(CommonHeader + AttributeRecord.Header());
                for (int cid = 1; cid <= maxCid; cid++)
                {
                  try
                  {
                    cinfo = Mclient.catalogCategoryInfo(MsessionId, cid, "", null);
                    csb.Append(cid.ToString() + "\t" + cinfo.name + "\r\n");
                  }
                  catch
                  {
                    csb.Append(cid.ToString() + "\t" + cid.ToString() + "\r\n");
                  }
                }
                    result += m_boostService.WriteTable(m_alias, Att1Filename, csb);
                ProgressText = tempDisplay + result;
              }
              catch { }
                //try
                //{
                //  //catalogCategoryTree ctree = Mclient.catalogCategoryTree(MsessionId, "", "");
                //  catalogCategoryTree ctree = Mclient.catalogCategoryTree(MsessionId, "0", "");
                //}
                //catch { }
                //try
                //{
                //  //catalogCategoryEntityNoChildren[] clist = Mclient.catalogCategoryLevel(MsessionId, "", "", "");
                //  catalogCategoryEntityNoChildren[] clist = Mclient.catalogCategoryLevel(MsessionId, "", "", "");
                //}
                //catch { }
                //try
                //{
                //  //catalogCategoryEntityNoChildren[] clist = Mclient.catalogCategoryLevel(MsessionId, "", "", "");
                //  catalogCategoryEntityNoChildren[] clist = Mclient.catalogCategoryLevel(MsessionId, "", "", "");
                //}
                //catch { }
                //try
                //{
                //  //catalogCategoryInfo cinfo = Mclient.catalogCategoryInfo(MsessionId, 0, "CurrentView", null);
                //  catalogCategoryInfo cinfo = Mclient.catalogCategoryInfo(MsessionId, 4, "", null);
                //}
                //catch { }
                //try
                //{
                //  //catalogProductAttributeSetEntity[] pasList = Mclient.catalogProductAttributeSetList(MsessionId);
                //  //...this one works!
                //  catalogProductAttributeSetEntity[] pasList = Mclient.catalogProductAttributeSetList(MsessionId);
                //}
                //catch { }

              //---------------------SALES EXPORT----------------------------
              try
              {
                    DateTime exportDate = DateTime.Now; //pass this date in
                    string salesFileName = string.Format(SalesFilenameFormat, exportDate.ToString("yyyy-MM"));
                    result += "\n" + salesFileName + ": ";
                    StringBuilder salesData = new StringBuilder(CommonHeader + SalesRecord.Header());

                    //create filter to get sales for this month only
                    string fromDate = string.Format("{0:0000}-{1:00}-01 00:00:00", exportDate.Year, exportDate.Month);
                    string toDate = string.Format("{0:0000}-{1:00}-01 00:00:00", exportDate.Year, exportDate.Month + 1);
                    filters monthFilter = new filters();
                    monthFilter.complex_filter = new complexFilter[2];
                    monthFilter.complex_filter[0] = new complexFilter();
                    monthFilter.complex_filter[0].key = "created_at";
                    monthFilter.complex_filter[0].value = new associativeEntity();
                    monthFilter.complex_filter[0].value.key = "from";
                    monthFilter.complex_filter[0].value.value = fromDate;
                    monthFilter.complex_filter[1] = new complexFilter();
                    monthFilter.complex_filter[1].key = "created_at";
                    monthFilter.complex_filter[1].value = new associativeEntity();
                    monthFilter.complex_filter[1].value.key = "to";
                    monthFilter.complex_filter[1].value.value = toDate;

                    //get list of sales orders
                salesOrderEntity[] sorders = Mclient.salesOrderList(MsessionId, monthFilter);
                if (sorders.Length > 0)
                {
                  //TODO: create header line for sales export
                  foreach (salesOrderEntity s in sorders)
                  {
                    string customerid = s.customer_id;
                    if (s.customer_is_guest.Equals("1"))
                    {
                      customerid = s.customer_email;
                      if (customerid == null || customerid.Length < 1)
                        customerid = s.increment_id;
                    }
                    string date = s.created_at;
                            //get list of items purchased on each sales order
                    salesOrderEntity sinfo = Mclient.salesOrderInfo(MsessionId, s.increment_id);
                    foreach (salesOrderItemEntity item in sinfo.items)
                    {
                      string productid = item.product_id;
                      string quantity = item.qty_ordered;
                      int len = quantity.IndexOf(".");
                      if (len > 0)
                        quantity = quantity.Substring(0, len); //remove fractional part

                      //add line to sales data
                                salesData.Append(customerid + "\t" + productid + "\t" + quantity + "\t" + date + "\r\n");
                    }
                  }
                  //upload sales data
                        result += m_boostService.WriteTable(m_alias, salesFileName, salesData);

                }
              }
              catch { }
            #endregion

            return result;
        }
    void Start()
    {
        filterchoicememo = filterchoice;
        ChangeFilters ();
        SCShader = Shader.Find(ShaderName);

        if(!SystemInfo.supportsImageEffects)
        {
        enabled = false;
        return;
        }
    }
Exemple #15
0
        public HttpResponseMessage AtualizarBanco()
        {
            try
            {
                var res = BinanceRestApi.GetExchangeInfo();
                //var jsonObj = JsonConvert.DeserializeObject<ExchangeInfo>(content, new JsonSerializerSettings() { DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore });
                if (res.IsSuccessStatusCode)
                {
                    var content = res.Content.ReadAsStringAsync().Result;
                    var jsonObj = JsonConvert.DeserializeObject <ExchangeInfo>(content);
                    foreach (var item in jsonObj.symbols)
                    {
                        var dbsymbol = _ISymbolRepo.GetBySymbol(item.symbol.ToLower());
                        if (dbsymbol == null)
                        {
                            var symbol = new Symbol();
                            symbol.symbol                 = item.symbol.ToLower();
                            symbol.status                 = item.status;
                            symbol.baseAsset              = item.baseAsset;
                            symbol.baseAssetPrecision     = item.baseAssetPrecision;
                            symbol.quoteAsset             = item.quoteAsset;
                            symbol.quotePrecision         = item.quotePrecision;
                            symbol.orderTypes             = item.orderTypes;
                            symbol.icebergAllowed         = item.icebergAllowed;
                            symbol.ocoAllowed             = item.ocoAllowed;
                            symbol.isSpotTradingAllowed   = item.isSpotTradingAllowed;
                            symbol.isMarginTradingAllowed = item.isMarginTradingAllowed;
                            _ISymbolRepo.Add(symbol);
                            foreach (var filteritem in item.filters)
                            {
                                var filters = new filters();
                                filters.Symbol_Id  = symbol.Id;
                                filters.filterType = filteritem.filterType;
                                //PRICE_FILTER
                                filters.minPrice = filteritem.minPrice;
                                filters.maxPrice = filteritem.maxPrice;
                                filters.tickSize = filteritem.tickSize;
                                //PERCENT_PRICE
                                filters.multiplierUp   = filteritem.multiplierUp;
                                filters.multiplierDown = filteritem.multiplierDown;
                                //LOT_SIZE & MARKET_LOT_SIZE
                                filters.minQty   = filteritem.minQty;
                                filters.maxQty   = filteritem.maxQty;
                                filters.stepSize = filteritem.stepSize;
                                //MIN_NOTIONAL
                                filters.minNotional   = filteritem.minNotional;
                                filters.applyToMarket = filteritem.applyToMarket;
                                //MIN_NOTIONAL & PERCENT_PRICE
                                filters.avgPriceMins = filteritem.avgPriceMins;
                                //ICEBERG_PARTS & MAX_NUM_ORDERS
                                filters.limit = filteritem.limit;
                                //MAX_NUM_ALGO_ORDERS
                                filters.maxNumAlgoOrders = filteritem.maxNumAlgoOrders;
                                //MAX_NUM_ICEBERG_ORDERS
                                filters.maxNumIcebergOrders = filteritem.maxNumIcebergOrders;
                                _IFiltersRepo.Add(filters);
                            }
                        }
                        else
                        {
                            var updatesymbol = dbsymbol;
                            updatesymbol.status                 = item.status;
                            updatesymbol.baseAsset              = item.baseAsset;
                            updatesymbol.baseAssetPrecision     = item.baseAssetPrecision;
                            updatesymbol.quoteAsset             = item.quoteAsset;
                            updatesymbol.quotePrecision         = item.quotePrecision;
                            updatesymbol.orderTypes             = item.orderTypes;
                            updatesymbol.icebergAllowed         = item.icebergAllowed;
                            updatesymbol.ocoAllowed             = item.ocoAllowed;
                            updatesymbol.isSpotTradingAllowed   = item.isSpotTradingAllowed;
                            updatesymbol.isMarginTradingAllowed = item.isMarginTradingAllowed;
                            if (updatesymbol != dbsymbol)
                            {
                                _ISymbolRepo.Update(dbsymbol);
                            }

                            foreach (var filteritem in item.filters)
                            {
                                var oldFilter     = _IFiltersRepo.GetBySymbol_Type(filteritem.filterType, updatesymbol.Id);
                                var Updatefilters = (oldFilter != null) ? oldFilter : new filters();
                                Updatefilters.Symbol_Id  = updatesymbol.Id;
                                Updatefilters.filterType = filteritem.filterType;
                                //PRICE_FILTER
                                Updatefilters.minPrice = filteritem.minPrice;
                                Updatefilters.maxPrice = filteritem.maxPrice;
                                Updatefilters.tickSize = filteritem.tickSize;
                                //PERCENT_PRICE
                                Updatefilters.multiplierUp   = filteritem.multiplierUp;
                                Updatefilters.multiplierDown = filteritem.multiplierDown;
                                //LOT_SIZE & MARKET_LOT_SIZE
                                Updatefilters.minQty   = filteritem.minQty;
                                Updatefilters.maxQty   = filteritem.maxQty;
                                Updatefilters.stepSize = filteritem.stepSize;
                                //MIN_NOTIONAL
                                Updatefilters.minNotional   = filteritem.minNotional;
                                Updatefilters.applyToMarket = filteritem.applyToMarket;
                                //MIN_NOTIONAL & PERCENT_PRICE
                                Updatefilters.avgPriceMins = filteritem.avgPriceMins;
                                //ICEBERG_PARTS & MAX_NUM_ORDERS
                                Updatefilters.limit = filteritem.limit;
                                //MAX_NUM_ALGO_ORDERS
                                Updatefilters.maxNumAlgoOrders = filteritem.maxNumAlgoOrders;
                                //MAX_NUM_ICEBERG_ORDE    RS
                                Updatefilters.maxNumIcebergOrders = filteritem.maxNumIcebergOrders;
                                if (Updatefilters != oldFilter && oldFilter != null)
                                {
                                    _IFiltersRepo.Update(Updatefilters);
                                }
                                else if (oldFilter == null)
                                {
                                    _IFiltersRepo.Add(Updatefilters);
                                }
                            }
                        }
                    }
                    return(Request.CreateResponse(HttpStatusCode.OK, jsonObj.symbols.Count()));
                }
                else
                {
                    var BinanceErrorObj = Helper.GetBinanceErrorObj(res);
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, BinanceErrorObj));
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message));
            }
        }
    public List<ParcelItem> GetPendingOrders()
    {
        try
        {
            if (UserAccountCode != 0)
            {
                List<ParcelItem> items = new List<ParcelItem>();
                DataModelEntities context = new DataModelEntities();
                UserAccount userAccount = context.UserAccounts.First(u => u.User_Account_Code == UserAccountCode);

                MagentoService service = new MagentoService();
                service.Url = userAccount.Application_Name;

                string sessionID = service.login(userAccount.Config_Value1, userAccount.Config_Value2);
                List<associativeEntity> listAssociatedEntity = new List<associativeEntity>();
                listAssociatedEntity.Add(new associativeEntity() { key = "status", value = "pending" });

                filters filters = new filters();
                filters.filter = listAssociatedEntity.ToArray();

                salesOrderListEntity[] orders = service.salesOrderList(sessionID, filters);

                List<ChargeCode> chargeCodes = context.ChargeCodes.Where(u => u.Is_Active == true && u.User_Code == UserCode).ToList();

                foreach (salesOrderListEntity order in orders)
                {
                    salesOrderEntity orderDetail = service.salesOrderInfo(sessionID, order.increment_id);

                    foreach (salesOrderItemEntity lineItem in orderDetail.items)
                    {

                        ParcelItem item = new ParcelItem();

                        item.Type = "MAGENTO";
                        item.AccountID = userAccount.User_Account_Code.ToString();
                        item.RecordNumber = orderDetail.order_id;
                        item.ItemID = lineItem.item_id;
                        item.TransactionID = orderDetail.increment_id;
                        item.ItemName = lineItem.name;
                        item.CustomLabel = lineItem.sku;
                        item.CustomLabelText = lineItem.sku;

                        string state = orderDetail.shipping_address.region;
                        string stateCode = orderDetail.shipping_address.region_id;

                        if (StateHelper.States.Where(s => s.Key == stateCode).Count() > 0)
                            item.State = StateHelper.States[stateCode];
                        else
                            item.State = state;

                        item.BuyerName = orderDetail.customer_firstname + " " + orderDetail.customer_lastname;
                        item.EmailAddress = orderDetail.customer_email;
                        item.BuyerID = orderDetail.customer_id;

                        item.Street2 = orderDetail.shipping_address.street;
                        item.Street3 = string.Empty;
                        item.City = orderDetail.shipping_address.city;
                        item.PostalCode = orderDetail.shipping_address.postcode;
                        item.Country = orderDetail.shipping_address.country_id;
                        item.Phone = orderDetail.shipping_address.telephone;

                        item.Quantity = lineItem.qty_ordered == string.Empty ? 0 : (int)decimal.Parse(lineItem.qty_ordered);
                        if (orderDetail.shipping_amount != string.Empty)
                            item.ShippingCost = double.Parse(orderDetail.shipping_amount);
                        item.SaleRecordId = orderDetail.increment_id;

                        // insurance details //

                        item.Currency = orderDetail.order_currency_code;
                        item.Price = double.Parse(lineItem.price);

                        item.ShippingMethod = orderDetail.shipping_description;

                        string shippingCode = orderDetail.shipping_description;
                        ChargeCode code = chargeCodes.FirstOrDefault(u => shippingCode.ToLower().Contains(u.Ebay_Code.ToLower()) == true);
                        if (code != null && code.Charge_Code_Name.ToLower() == "ignore")
                        {
                            continue; // ignore the item
                        }

                        bool IspostCodeOK = Common.VerifyPostCode(orderDetail.shipping_address.postcode, orderDetail.shipping_address.city);
                        if (IspostCodeOK)
                            item.PostCodeImageURL = Constant.tickURL;
                        else
                            item.PostCodeImageURL = Constant.crossURL;

                        items.Add(item);
                    }
                }

                return items;
            }
            else
            {
                return null;
            }
        }
        catch (Exception ex)
        {
            return null;
        }
    }
Exemple #17
0
        public void globafun(filters par)
        {
            int[,] now = new int[3, 3];
            if (par == filters.blur)
            {
                now = Kernel.blur;
            }
            else if (par == filters.sharp)
            {
                now = Kernel.sharp;
            }
            else if (par == filters.hor)
            {
                now = Kernel.hor;
            }
            else if (par == filters.ver)
            {
                now = Kernel.ver;
            }
            else if (par == filters.diag)
            {
                now = Kernel.diag;
            }
            else if (par == filters.all)
            {
                now = Kernel.all;
            }
            else if (par == filters.east)
            {
                now = Kernel.east;
            }
            else if (par == filters.south)
            {
                now = Kernel.south;
            }
            else if (par == filters.southeast)
            {
                now = Kernel.southeast;
            }

            //Color[,] alter = new Color[this.Height, this.Width];
            byte[] temp = new byte[underlyingBytes.ByteArray.Length];
            Array.Copy(underlyingBytes.ByteArray, temp, temp.Length);

            for (int i = 0; i < this.Height - 2; ++i)
            {
                for (int j = 0; j < this.Width - 2; j++)
                {
                    int[,] matRed   = new int[3, 3];
                    int[,] matGreen = new int[3, 3];
                    int[,] matBlue  = new int[3, 3];
                    for (int a = 0; a < 3; a++)
                    {
                        for (int b = 0; b < 3; b++)
                        {
                            Color color = GetPixelRowColumn(i + a, j + b);
                            matRed[a, b]   = color.R;
                            matGreen[a, b] = color.G;
                            matBlue[a, b]  = color.B;
                        }
                    }

                    byte newRed   = (byte)Utility.Clamp(0, 255, multiplication(now, matRed));
                    byte newGreen = (byte)Utility.Clamp(0, 255, multiplication(now, matGreen));
                    byte newBlue  = (byte)Utility.Clamp(0, 255, multiplication(now, matBlue));

                    SetPixelRowColumnOfArray(i + 1, j + 1, Color.FromArgb(newRed, newGreen, newBlue), temp);
                    //alter[i + 1, j + 1] = Color.FromArgb(newRed, newGreen, newBlue);
                }
            }

            Array.Copy(temp, underlyingBytes.ByteArray, temp.Length);

            //COPY ALTER TO THIS
            //for (int i = 1; i < Height - 2; i++)
            //{
            //    for (int j = 1; j < Width - 2; j++)
            //    {
            //        SetPixelRowColumn(i, j, alter[i, j]);
            //    }
            //}
        }
    void Start()
    {
        filterchoicememo = filterchoice;
        if (Camera2 !=null)
        {
            DestroyImmediate(Camera2.targetTexture);
            Camera2tex=new RenderTexture(Screen.width,Screen.height, 24);
            Camera2.targetTexture=Camera2tex;
        }

        ChangeValue = BlendFX;
        ChangeValue2=SwitchCameraToCamera2;
        ChangeFilters ();
        SCShader = Shader.Find(ShaderName);
        if(!SystemInfo.supportsImageEffects)
        {
            enabled = false;
            return;
        }
    }
    void OnValidate()
    {
        if (filterchoice != filterchoicememo)
        {
            ChangeFilters();
            SCShader = Shader.Find(ShaderName);
            DestroyImmediate(SCMaterial);
            if(SCMaterial == null)
            {
                SCMaterial = new Material(SCShader);
                SCMaterial.hideFlags = HideFlags.HideAndDontSave;
            }

        }

        filterchoicememo = filterchoice;
        if (Camera2 != null)
        {
            DestroyImmediate(Camera2.targetTexture);
            Camera2tex=new RenderTexture(Screen.width,Screen.height, 24);
            Camera2.targetTexture = Camera2tex;
        }
        ChangeValue=BlendFX;
        ChangeValue2=SwitchCameraToCamera2;
    }
    public static void MainOrders(string[] args)
    {
        MNC_Product_Sync.Navision_SalesOrder_Service.SalesOrder_PortClient client = new MNC_Product_Sync.Navision_SalesOrder_Service.SalesOrder_PortClient();



        client.ClientCredentials.Windows.ClientCredential.UserName = "******";

        client.ClientCredentials.Windows.ClientCredential.Password = "******";

        client.ClientCredentials.Windows.ClientCredential.Domain = "122.166.222.116";

        DBConnect db = new DBConnect();

        MNC_Product_Sync.MagentoConnectService.PortTypeClient mage_client = new MNC_Product_Sync.MagentoConnectService.PortTypeClient();

        string token_id = null;


        try
        {
            ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);

            token_id    = mage_client.login("webserviceuser", "apikey");
            _stateCodes = mage_client.directoryRegionList(token_id, "US");

            filters filtres = new filters();

            filtres.complex_filter = new complexFilter[]
            {
                new complexFilter()
                {
                    //key = "created_at",
                    //value = new associativeEntity
                    //{
                    //    key = "gt",
                    //    value = "2015-07-28 08:00:00"
                    //}

                    key   = "status",
                    value = new associativeEntity
                    {
                        key   = "eq",
                        value = "pending"
                    }
                }
            };

            salesOrderListEntity[] salesOrders = mage_client.salesOrderList(token_id, filtres);

            Hashtable hsc = db.fetch_Customer1Mapping();


            foreach (salesOrderListEntity orderHeader in salesOrders)
            {
                if (!db.fetch_Order(orderHeader.increment_id.ToString(), "1"))
                {
                    MNC_Product_Sync.Navision_SalesOrder_Service.SalesOrder so = new MNC_Product_Sync.Navision_SalesOrder_Service.SalesOrder();

                    MNC_Product_Sync.Navision_SalesOrder_Service.Sales_Order_Line[] sls = new MNC_Product_Sync.Navision_SalesOrder_Service.Sales_Order_Line[50];
                    salesOrderEntity        orderDetail   = mage_client.salesOrderInfo(token_id, orderHeader.increment_id);
                    salesOrderAddressEntity billToAddress = orderDetail.billing_address;
                    salesOrderAddressEntity shipToAddress = orderDetail.shipping_address;
                    so.Bill_to_Address       = billToAddress.street + " " + billToAddress.region + " " + billToAddress.postcode;
                    so.Ship_to_Address       = billToAddress.street + " " + billToAddress.region + " " + billToAddress.postcode;
                    so.Bill_to_Name          = billToAddress.firstname + " " + billToAddress.lastname + " ";
                    so.Ship_to_Name          = shipToAddress.firstname + " " + shipToAddress.lastname;
                    so.Bill_to_Contact       = billToAddress.telephone;
                    so.Sell_to_Customer_No   = hsc[orderDetail.customer_id].ToString();
                    so.Ship_to_Contact       = billToAddress.telephone;
                    so.External_Document_No  = orderHeader.increment_id;
                    so.Bill_to_Customer_No   = hsc[orderDetail.customer_id].ToString();
                    so.Sell_to_Customer_Name = orderHeader.customer_firstname + " " + orderHeader.customer_lastname;
                    so.Order_Date            = DateTime.Parse(orderHeader.created_at);
                    so.VAT_Bus_Posting_Group = "FOREIGN";



                    int i = 0;

                    foreach (salesOrderItemEntity li in orderDetail.items)
                    {
                        if (!db.fetch_Order(orderHeader.increment_id.ToString(), (i + 1).ToString()))
                        {
                            MNC_Product_Sync.Navision_SalesOrder_Service.Sales_Order_Line sl = new MNC_Product_Sync.Navision_SalesOrder_Service.Sales_Order_Line();
                            sl.Quantity = decimal.Parse(li.qty_ordered);
                            sl.VAT_Prod_Posting_Group = "DOMESTIC";
                            sl.No                = li.sku;
                            sl.Description       = li.name;
                            sl.Unit_Price        = decimal.Parse(li.base_price);
                            sl.Line_Amount       = decimal.Parse(li.base_row_total);
                            sl.TypeSpecified     = true;
                            sl.Sales_Header_Repl = decimal.Parse(li.base_price).ToString();
                            sl.QuantitySpecified = true;
                            sl.Type              = MNC_Product_Sync.Navision_SalesOrder_Service.Type.Item;
                            sl.Line_No           = i + 1;
                            sls[i]               = sl;


                            i = i + 1;
                            db.InsertOrderMapping(so.No, sl.Line_No.ToString(), orderHeader.increment_id, sl.Line_No.ToString(), orderHeader.customer_id);
                        }
                    }
                    if (!db.fetch_Order(orderHeader.increment_id.ToString(), (i + 1).ToString()))
                    {
                        try {
                            so.SalesLines = sls;
                            client.Create(ref so);
                            if (so.No != null)
                            {
                                db.UpdateOrder(orderHeader.increment_id, so.No);
                                db.InsertLog("Order", so.No, "Navision Order Number", "SUCCESS");
                            }
                        }
                        catch (Exception ex)
                        {
                            db.deleteOrder(orderHeader.increment_id);
                            db.InsertLog("Order", orderHeader.increment_id, ex.Message, "FAILED");
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            db.InsertLog("Order", "", ex.Message.ToString(), "FAILED");
            MNC_Product_Sync.ErrorLog errLog = new MNC_Product_Sync.ErrorLog();

            errLog.LogError("C:\\MNC_Logs", "Order : " + ex.Message);
        }
        finally
        {
            mage_client.endSession(token_id);
        }
    }
        public virtual async Task <GetOrdersResponse> GetOrdersAsync(DateTime modifiedFrom, DateTime modifiedTo, Mark mark = null)
        {
            try
            {
                filters filters;

                if (string.IsNullOrWhiteSpace(this.Store))
                {
                    filters = new filters {
                        complex_filter = new complexFilter[2]
                    }
                }
                ;
                else
                {
                    filters = new filters {
                        complex_filter = new complexFilter[3]
                    };
                    filters.complex_filter[2] = new complexFilter {
                        key = "store_id", value = new associativeEntity {
                            key = "in", value = this.Store
                        }
                    };
                }

                filters.complex_filter[1] = new complexFilter {
                    key = "updated_at", value = new associativeEntity {
                        key = "from", value = modifiedFrom.ToSoapParameterString()
                    }
                };
                filters.complex_filter[0] = new complexFilter {
                    key = "updated_at", value = new associativeEntity {
                        key = "to", value = modifiedTo.ToSoapParameterString()
                    }
                };

                const int maxCheckCount    = 2;
                const int delayBeforeCheck = 1800000;

                var res = new salesOrderListResponse();

                var privateClient = this._clientFactory.GetClient();

                await ActionPolicies.GetAsync.Do(async() =>
                {
                    var statusChecker = new StatusChecker(maxCheckCount);
                    TimerCallback tcb = statusChecker.CheckStatus;

                    privateClient = this._clientFactory.RefreshClient(privateClient);

                    var sessionId = await this.GetSessionId().ConfigureAwait(false);

                    using (var stateTimer = new Timer(tcb, privateClient, 1000, delayBeforeCheck))
                        res = await privateClient.salesOrderListAsync(sessionId.SessionId, filters).ConfigureAwait(false);
                }).ConfigureAwait(false);

                //crutch for magento 1.7
                res.result = res.result.Where(x => Extensions.ToDateTimeOrDefault(x.updated_at) >= modifiedFrom && Extensions.ToDateTimeOrDefault(x.updated_at) <= modifiedTo).ToArray();

                return(new GetOrdersResponse(res));
            }
            catch (Exception exc)
            {
                throw new MagentoSoapException(string.Format("An error occured during GetOrdersAsync(modifiedFrom:{0},modifiedTo{1})", modifiedFrom, modifiedTo), exc);
            }
        }
        protected virtual async Task <SoapGetProductsResponse> GetProductsAsync(string productType, bool productTypeShouldBeExcluded, string productIdLike, DateTime?updatedFrom)

        {
            Func <bool, Task <catalogProductListResponse> > call = async(keepAlive) =>
            {
                var filtersTemp = new filters();

                if (productType != null)
                {
                    AddFilter(filtersTemp, productType, "type", productTypeShouldBeExcluded ? "neq" : "eq");
                }
                if (updatedFrom.HasValue)
                {
                    AddFilter(filtersTemp, updatedFrom.Value.ToSoapParameterString(), "updated_at", "from");
                }
                if (!string.IsNullOrWhiteSpace(productIdLike))
                {
                    AddFilter(filtersTemp, productIdLike, "product_id", "like");
                }

                var filters = filtersTemp;
                //var filters = new MagentoSoapServiceReference_v_1_14_1_EE.filters { filter = new MagentoSoapServiceReference_v_1_14_1_EE.associativeEntity[1]{associativeEntity} };
                var store = string.IsNullOrWhiteSpace(this.Store) ? null : this.Store;
                var res   = new catalogProductListResponse();

                const int     maxCheckCount    = 2;
                const int     delayBeforeCheck = 1800000;
                var           privateClient    = this._clientFactory.GetClient(keepAlive);
                var           statusChecker    = new StatusChecker(maxCheckCount);
                TimerCallback tcb = statusChecker.CheckStatus;

                privateClient = this._clientFactory.RefreshClient(privateClient, keepAlive);

                var sessionId = await this.GetSessionId().ConfigureAwait(false);

                using (var stateTimer = new Timer(tcb, privateClient, 1000, delayBeforeCheck))
                    res = await privateClient.catalogProductListAsync(sessionId.SessionId, filters, store).ConfigureAwait(false);

                return(res);
            };

            try
            {
                // keep alive is a crutch for 1 client, which has server that sloses connection after few minutes.
                var keepAlive = false;
                var res       = new catalogProductListResponse();
                await ActionPolicies.GetAsync.Do(async() =>
                {
                    try
                    {
                        res = await call(keepAlive).ConfigureAwait(false);
                        return;
                    }
                    catch (CommunicationException)
                    {
                        keepAlive = !keepAlive;
                    }
                    res = await call(keepAlive).ConfigureAwait(false);
                }).ConfigureAwait(false);

                return(new SoapGetProductsResponse(res));
            }
            catch (Exception exc)
            {
                if (exc is CommunicationException)                  //crunch for fbeauty
                {
                    var r = exc as CommunicationException;
                    if (r.InnerException.Message.Contains("403"))
                    {
                        if (productIdLike.Contains("00"))
                        {
                            return(null);
                        }
                    }
                }
                throw new MagentoSoapException(string.Format("An error occured during GetProductsAsync()"), exc);
            }
        }
        public virtual async Task <GetOrdersResponse> GetOrdersAsync(IEnumerable <string> ordersIds)
        {
            var ordersIdsAgregated = string.Empty;

            try
            {
                ordersIdsAgregated = string.Join(",", ordersIds);

                filters filters;
                if (string.IsNullOrWhiteSpace(this.Store))
                {
                    filters = new filters {
                        complex_filter = new complexFilter[1]
                    }
                }
                ;
                else
                {
                    filters = new filters {
                        complex_filter = new complexFilter[2]
                    };
                    filters.complex_filter[1] = new complexFilter {
                        key = "store_id", value = new associativeEntity {
                            key = "in", value = this.Store
                        }
                    };
                }

                filters.complex_filter[0] = new complexFilter {
                    key = "increment_id", value = new associativeEntity {
                        key = "in", value = ordersIdsAgregated
                    }
                };

                const int maxCheckCount    = 2;
                const int delayBeforeCheck = 1800000;

                var res = new salesOrderListResponse();

                var privateClient = this._clientFactory.GetClient();

                await ActionPolicies.GetAsync.Do(async() =>
                {
                    var statusChecker = new StatusChecker(maxCheckCount);
                    TimerCallback tcb = statusChecker.CheckStatus;

                    privateClient = this._clientFactory.RefreshClient(privateClient);

                    var sessionId = await this.GetSessionId().ConfigureAwait(false);

                    using (var stateTimer = new Timer(tcb, privateClient, 1000, delayBeforeCheck))
                        res = await privateClient.salesOrderListAsync(sessionId.SessionId, filters).ConfigureAwait(false);
                }).ConfigureAwait(false);

                return(new GetOrdersResponse(res));
            }
            catch (Exception exc)
            {
                throw new MagentoSoapException(string.Format("An error occured during GetOrdersAsync({0})", ordersIdsAgregated), exc);
            }
        }
Exemple #24
0
        private void bbDownload_Click(object sender, EventArgs e)
        {
            if (cbLoja.SelectedItem == null)
            {
                MessageBox.Show("Obrigatório selecionar loja.", "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Information);
                cbLoja.Focus();
                return;
            }
            if (string.IsNullOrEmpty((cbLoja.SelectedItem as TRegistro_LojaVirtual).UserName))
            {
                MessageBox.Show("Não existe USERNAME cadastrado para loja.", "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (string.IsNullOrEmpty((cbLoja.SelectedItem as TRegistro_LojaVirtual).ApiKey))
            {
                MessageBox.Show("Não existe APIKEY cadastrado para loja.", "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            MagentoService api    = new MagentoService();
            string         sessao = string.Empty;

            try
            {
                sessao = api.login((cbLoja.SelectedItem as TRegistro_LojaVirtual).UserName, (cbLoja.SelectedItem as TRegistro_LojaVirtual).ApiKey);
                filters         mf  = new filters();
                complexFilter[] cpf = new complexFilter[0];
                if (cbStatus.SelectedIndex > 0)
                {
                    complexFilter mcpf = new complexFilter();
                    mcpf.key = "status";
                    associativeEntity mas = new associativeEntity();
                    mas.key    = "=";
                    mas.value  = cbStatus.SelectedValue.ToString();
                    mcpf.value = mas;
                    Array.Resize(ref cpf, cpf.Length + 1);
                    cpf[cpf.Length - 1] = mcpf;
                }
                if (!string.IsNullOrEmpty(dt_ini.Text.SoNumero()))
                {
                    complexFilter mcpf = new complexFilter();
                    mcpf.key = "created_at";
                    associativeEntity mas = new associativeEntity();
                    mas.key    = "from";
                    mas.value  = DateTime.Parse(dt_ini.Text).ToString("yyyy-MM-dd") + " 00:00:00";
                    mcpf.value = mas;
                    Array.Resize(ref cpf, cpf.Length + 1);
                    cpf[cpf.Length - 1] = mcpf;
                }
                mf.complex_filter = cpf;
                salesOrderListEntity[] lista = api.salesOrderList(sessao, mf);
                if (lista.Length > 0)
                {
                    TList_Pedido lPedido = new TList_Pedido();
                    lista.ToList().ForEach(p =>
                    {
                        object obj = new TCD_Pedido().BuscarEscalar(
                            new TpBusca[]
                        {
                            new TpBusca()
                            {
                                vNM_Campo = "a.Nr_PedidoOrigem",
                                vOperador = "=",
                                vVL_Busca = "'" + p.increment_id.Trim() + "'"
                            }
                        }, "a.nr_pedido");
                        lPedido.Add(new TRegistro_Pedido()
                        {
                            Nr_PedidoOrigem = p.increment_id,
                            Vl_totalpedido  = decimal.Divide(int.Parse(p.grand_total.SoNumero()), 10000),
                            StatusMagento   = p.status,
                            NM_Clifor       = p.firstname.Trim() + " " + p.lastname.Trim(),
                            Nr_pedido       = obj == null ? 0 : decimal.Parse(obj.ToString()),
                            DT_Pedido       = DateTime.Parse(p.created_at)
                        });
                    });
                    bsPedLoja.DataSource = lPedido;
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message.Trim(), "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error); }
            finally
            {
                if (!string.IsNullOrWhiteSpace(sessao))
                {
                    api.endSession(sessao);
                }
            }
        }