Наследование: System.Web.UI.Page
        public static WorkgroupVendorViewModel Create(IRepositoryWithTypedId<Vendor, string> vendorRepository, WorkgroupVendor workgroupVendor = null, Vendor vendor = null, VendorAddress vendorAddress = null, bool? newVendor = null)
        {
            Check.Require(vendorRepository != null, "Repository must be supplied");

            var addresses = vendor != null ? new MultiSelectList(vendor.VendorAddresses.Select(a => new { TypeCode = a.TypeCode, Name = string.Format("{0} ({1}, {2}, {3} {4})", a.Name, a.Line1, a.City, a.State, a.Zip) }).ToList(), "TypeCode", "Name") : new MultiSelectList(new List<VendorAddress>(), "TypeCode", "Name");

            var viewModel = new WorkgroupVendorViewModel
                                {
                                    WorkgroupVendor = workgroupVendor ?? new WorkgroupVendor(),
                                    Vendor = vendor,
                                    VendorAddress = vendorAddress,
                                    //Vendors = vendorRepository.Queryable.OrderBy(a => a.Name).ToList(),
                                    VendorAddresses = addresses,
                                    NewVendor = newVendor
                                };
            if(viewModel.WorkgroupVendor.VendorId != null && string.IsNullOrWhiteSpace(viewModel.WorkgroupVendor.Name))
            {
                var locVendor = vendorRepository.Queryable.First(a => a.Id == viewModel.WorkgroupVendor.VendorId);
                if(locVendor != null)
                {
                    viewModel.WorkgroupVendor.Name = locVendor.Name;
                }
            }
            return viewModel;
        }
Пример #2
0
        public void SingleObjectCompareTest()
        {
            Vendor vendor = new Vendor()
            {
                Code = "123",
                Description = "desc vendor 1",
                Name = "name vendor 1",
                VendorID = "vendorID1",
                CreateDate = DateTime.Now
            };

            Vendor newVendor = new Vendor()
            {
                Description = "desc vendor 2",
                Name = "name vendor 2",
                VendorID = "vendorID1",
                CreateDate = DateTime.Now.AddDays(-1)
            };

            ObjectCompareResult result = ObjectCompareHelper.CompareObject(vendor, newVendor);

            OutpuCompareResult(result);

            //CreateDate不参与比较
            Assert.IsTrue(result.AreDifferent);
            Assert.AreEqual(3, result.Count);
        }
        /// <summary>
        /// Makes deep copy of Product.
        /// Entity Framework cannot keep track of 1 item in 2 contexts, so in order to
        /// export something and import it in other database it needs deep copy of it.
        /// </summary>
        /// <param name="product">Product for copy.</param>
        /// <param name="vendor">Product's vendor.</param>
        /// <returns>Deep copy of the product</returns>
        private static Product DeepCopyProduct(Product product, Vendor vendor)
        {
            var incomes = product.Incomes
                .Select(income => new Income()
                {
                    Quantity = income.Quantity,
                    SalePrice = income.SalePrice
                })
                .ToList();

            var expenses = product.Vendor.Expenses
                .Select(expense => new Expense()
                {
                    Amount = expense.Amount,
                })
                .ToList();

            foreach (var expense in expenses)
            {
                vendor.Expenses.Add(expense);
            }

            var deepCopyProduct = new Product()
            {
                Name = product.Name,
                BuyingPrice = product.BuyingPrice,
                Incomes = incomes,
                Vendor = vendor
            };

            return deepCopyProduct;
        }
Пример #4
0
 public static bool DeactivateVendor(Vendor vendor, SqlConnection myConnection)
 {
     myConnection = myConnection ?? GetInventoryDbConnection();
     try
     {
         SqlCommand mySqlCommand = new SqlCommand("proc_DeactivateVendor", myConnection);
         mySqlCommand.CommandType = CommandType.StoredProcedure;
         mySqlCommand.Parameters.AddWithValue("@VendorID", vendor.Id);
         myConnection.Open();
         if (mySqlCommand.ExecuteNonQuery() == 1)
         {
             return true;
         }
     }
     catch (DataException ex)
     {
         Console.WriteLine(ex.Message);
         throw new ApplicationException(Messeges.GetMessage("DatabaseException"), ex);
     }
     catch (SqlException ex)
     {
         Console.WriteLine(ex.Message);
         throw new ApplicationException(Messeges.GetMessage("SqlException"), ex);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
         throw new ApplicationException(Messeges.GetMessage("Exception"), ex);
     }
     finally
     {
         myConnection.Close();
     }
     return false;
 }
Пример #5
0
 public JobBuilder(OrderModel order, UserModel userModel, IHRIDService hridService, Vendor vendor = null)
 {
     job = new Job(order, hridService.NextId("Job"));
     job.User = userModel;
     job.Vendor = vendor;
     job.ProfitShareResult = vendor?.Strategy?.Calculate(order.OrderCart.TotalToPay.Value);
 }
Пример #6
0
        public FrmVendorAddUpdate(AccessToken acctkn, Vendor vendor)
        {
            InitializeComponent();

            _myAccessToken = acctkn;
            _myVendor = vendor;

            this.Text = "Update Vendor: " + vendor.Name;
            btMorph.Text = "Update Vendor";

            PopulateStateCombo();
            PopulateCountryCombo();

            txtVendorID.Text = vendor.Id.ToString();
            txtVendorName.Text = vendor.Name;
            txtVendorAddress.Text = vendor.Address;
            txtVendorCity.Text = vendor.City;
            cbVendorState.Text = vendor.State;
            cbVendorCountry.Text = vendor.Country;
            txtVendorZipCode.Text = vendor.Zip;

            txtVendorContact.Text = vendor.Contact;
            txtVendorContactEmail.Text = vendor.ContactEmail;
            txtVendorContactPhone.Text = vendor.Phone;
            Instance = this;
        }
        /// <summary>
        /// Imports Products to MySql.
        /// </summary>
        public static void ImportToMySql(IEnumerable<Product> products)
        {
            var mysqlManager = new MysqlDBManager();
            var mySqlContext = mysqlManager.MySqlContext;

            foreach (var product in products)
            {
                var vendorName = product.Vendor.Name;
                var vendor = mySqlContext.Vendors.FirstOrDefault(v => v.Name == vendorName);
                if (vendor == null)
                {
                    vendor = new Vendor()
                    {
                        Name = vendorName,
                        Expenses = new List<Expense>()
                    };
                }

                var mySqlProduct = DeepCopyProduct(product, vendor);
                mySqlContext.Products.AddOrUpdate(mySqlProduct);
                mySqlContext.SaveChanges();
            }

            Console.WriteLine("Data imported to MySQL!");
        }
Пример #8
0
        public void XmlSerializationWithSingleObjectCompareTest()
        {
            Vendor vendor = new Vendor()
            {
                Code = "123",
                Description = "desc vendor 1",
                Name = "name vendor 1",
                VendorID = "vendorID1",
                CreateDate = DateTime.Now
            };

            Vendor newVendor = new Vendor()
            {
                Description = "desc vendor 2",
                Name = "name vendor 2",
                VendorID = "vendorID1",
                CreateDate = DateTime.Now.AddDays(-1)
            };

            ObjectCompareResult result = ObjectCompareHelper.CompareObject(vendor, newVendor);

            OutpuCompareResult(result);

            XElement root = result.ToXElement();

            ObjectCompareResult deserizlized = new ObjectCompareResult();

            deserizlized.FromXElement(root);

            Assert.AreEqual(root.ToString(), deserizlized.ToXElement().ToString());
        }
        public virtual int SendProductInquery(Product product,Vendor vendor,string from,string phone, string email,string msg, int languageId)
        {
            if (product == null)
                throw new ArgumentNullException("product");

            var store = _storeContext.CurrentStore;
            languageId = EnsureLanguageIsActive(languageId, store.Id);

            var messageTemplate = GetActiveMessageTemplate("Product.Inqure", store.Id);
            if (messageTemplate == null)
                return 0;

            //email account
            var emailAccount = GetEmailAccountOfMessageTemplate(messageTemplate, languageId);

            //tokens
            var tokens = new List<Token>();
            _messageTokenProvider.AddStoreTokens(tokens, store, emailAccount);

            tokens.Add(new Token("Product.ProductUrl", store.Url + product.Name.Trim().Replace(" ", "-")));
            tokens.Add(new Token("Product.ProductName", product.Name));
            tokens.Add(new Token("From", from));
            tokens.Add(new Token("Phone", phone));
            tokens.Add(new Token("Email", email));
            tokens.Add(new Token("Msg", msg));

            //event notification
            _eventPublisher.MessageTokensAdded(messageTemplate, tokens);

            var toEmail = vendor.Email;
            var toName = vendor.Name;
            return SendNotification(messageTemplate, emailAccount,
                languageId, tokens,
                toEmail, toName);
        }
Пример #10
0
        public JobBuilder(OrderModel order, UserModel userModel, UserModel adminUserModel, IHRIDService hridService, Vendor vendor = null) 
            : this(order, userModel, hridService, vendor)
        {
            if (adminUserModel == null)
                throw new ArgumentNullException(nameof(adminUserModel));

            job.JobServedBy = adminUserModel;
        }
        /// <summary>
        /// Save data for one vendor. disregard test
        /// </summary>
        /// <param name="vendor">Instance of the vendor to save.</param>
        /// <returns></returns>
        public bool Save(Vendor vendor)
        {
            var success = true;

            // Code that saves the vendor

            return success;
        }
Пример #12
0
        public AddEditVendorModel()
        {
            CompositionInitializer.SatisfyImports(this);

            mVendor = new Vendor{ SiteId = CMS.SelectedSiteId};

            OkButtonCommand = new DelegateCommand<object>(OkButtonHander, CanExecuteOkButtonHandler);
            CancelButtonCommand = new DelegateCommand<object>(CancelButtonHander, x => true);
        }
Пример #13
0
 public Vendor GetVendorByName(Vendor vendor)
 {
     //return base.DataContext.Vendors.SingleOrDefault<Vendor>(v => v.VendorName == vendorName);
     foreach (Vendor v in base.DataContext.Vendors)
     {
         if (v.Equals(vendor))
             return v;
     }
     return null;
 }
Пример #14
0
        public async Task<Vendor> Update(Vendor profile)
        {
            var user = (await accountManager.FindByIdAsync(profile.UserId) as EnterpriseUser);
            if (string.IsNullOrWhiteSpace(user.VendorId))
                throw new InvalidOperationException($"{user.Id} is not a vendor, please subscribe as a vendor first");

            var result = await Collection.FindOneAndReplaceAsync(x => x.UserId == profile.UserId && x.Id == profile.Id, profile);
            if (result == null)
                throw new EntityUpdateException(typeof(Vendor), profile.Id);
            return result;
        }
Пример #15
0
        // PUT api/awbuildversion/5
        public void Put(Vendor value)
        {
            var GetActionType = Request.Headers.Where(x => x.Key.Equals("ActionType")).FirstOrDefault();

            if (GetActionType.Key != null)
            {
                if (GetActionType.Value.ToList()[0].Equals("DELETE"))
                    adventureWorks_BC.VendorDelete(value);
                if (GetActionType.Value.ToList()[0].Equals("UPDATE"))
                    adventureWorks_BC.VendorUpdate(value);
            }
        }
Пример #16
0
        public static Vendor ToShopifyModel(this StorefrontModel.Vendor storefrontModel)
        {
            var shopifyModel = new Vendor();

            shopifyModel.InjectFrom<NullableAndEnumValueInjecter>(storefrontModel);

            var shopifyAddressModels = storefrontModel.Addresses.Select(a => a.ToShopifyModel());
            shopifyModel.Addresses = new MutablePagedList<Address>(shopifyAddressModels);
            shopifyModel.DynamicProperties = storefrontModel.DynamicProperties;

            return shopifyModel;
        }
Пример #17
0
		/// <summary>
		/// Inserts a mock Vendor entity into the database.
		/// </summary>
		private void Step_01_Insert_Generated()
		{
			using (TransactionManager tm = CreateTransaction())
			{
				mock = CreateMockInstance(tm);
				Assert.IsTrue(DataRepository.VendorProvider.Insert(tm, mock), "Insert failed");
										
				System.Console.WriteLine("DataRepository.VendorProvider.Insert(mock):");			
				System.Console.WriteLine(mock);			
				
				//normally one would commit here
				//tm.Commit();
				//IDisposable will Rollback Transaction since it's left uncommitted
			}
		}
Пример #18
0
        public int AddVendor(Vendor newVendor)
        {
            Vendor existingObj = GetVendorByName(newVendor);
            if (existingObj == null)
            {
                base.DataContext.Vendors.InsertOnSubmit(newVendor);
                base.DataContext.SubmitChanges();

                return newVendor.VendorId;
            }
            else
            {
                return existingObj.VendorId;
            }
        }
        /// <summary>
        /// Retrieve one vendor.
        /// </summary>
        /// <param name="vendorId">Id of the vendor to retrieve.</param>
        public Vendor Retrieve(int vendorId)
        {
            // Create the instance of the Vendor class
            Vendor vendor = new Vendor();

            // Code that retrieves the defined customer

            // Temporary hard coded values to return 
            if (vendorId == 1)
            {
                vendor.VendorId = 1;
                vendor.CompanyName = "ABC Corp";
                vendor.Email = "*****@*****.**";
            }
            return vendor;
        }
Пример #20
0
        public static Boolean AddVendor(Vendor vendor, SqlConnection myConnection)
        {
            myConnection = myConnection ?? GetInventoryDbConnection();
            try
            {
                SqlCommand mySqlCommand = new SqlCommand("proc_InsertIntoVendor", myConnection);
                mySqlCommand.CommandType = CommandType.StoredProcedure;
                mySqlCommand.Parameters.AddWithValue("@Name", vendor.Name);
                mySqlCommand.Parameters.AddWithValue("@Address", vendor.Address);
                mySqlCommand.Parameters.AddWithValue("@City", vendor.City);
                mySqlCommand.Parameters.AddWithValue("@State", vendor.State);
                mySqlCommand.Parameters.AddWithValue("@Country", vendor.Country);
                mySqlCommand.Parameters.AddWithValue("@Zip", vendor.Zip);
                mySqlCommand.Parameters.AddWithValue("@Phone", vendor.Phone);
                mySqlCommand.Parameters.AddWithValue("@Contact", vendor.Contact);
                mySqlCommand.Parameters.AddWithValue("@ContactEmail", vendor.ContactEmail);

                myConnection.Open();
                if (mySqlCommand.ExecuteNonQuery() == 1)
                {
                    return true;
                }

            }
            catch (DataException ex)
            {
                Console.WriteLine(ex.Message);
                throw new ApplicationException(Messeges.GetMessage("DatabaseException"), ex);
            }
            catch (SqlException ex)
            {
                Console.WriteLine(ex.Message);
                throw new ApplicationException(Messeges.GetMessage("SqlException"), ex);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw new ApplicationException(Messeges.GetMessage("Exception"), ex);
            }
            finally
            {
                myConnection.Close();
            }
            return false;
        }
        public OpenCLMiner(OpenCLManager OCLMan, Vendor vendor, int deviceIndex, bool shouldUseVectors)
        {
            this.vendor = vendor;
            this.deviceIndex = deviceIndex;

            this.OCLMan = OCLMan;
            Device device = OCLMan.Context.Devices[deviceIndex];
            Name = device.Vendor + ":" + device.Name + " (" + deviceIndex + ")";

            OCLMan.Defines += "\r\n#define OUTPUT_SIZE 256";
            OCLMan.Defines += "\r\n#define OUTPUT_MASK 255";
            if (device.Extensions.Contains("cl_amd_media_ops"))
            {
                OCLMan.Defines += "\r\n#define BITALIGN 1";
                // note: defining BFI_INT resulted in invalid calculations on my Barts (8760)
                //if (Array.IndexOf(AMD_Devices, device.Name) != -1)
                //    OCLMan.Defines += "\r\n#define BFI_INT 1";
            }

            if (shouldUseVectors)
                OCLMan.Defines += "\r\n#define VECTORS 1";
            _shouldUseVectors = shouldUseVectors;

            searchKernel = OCLMan.CompileFile("General.cl").CreateKernel("search");

            unsafe
            {
                IntPtr size = (IntPtr)8;
                long[] values = new long[1];
                long[] sizeTest = new long[1];

                fixed (long* valuep = &values[0])
                {
                    IntPtr sizeOuts;

                    OpenCL.GetKernelWorkGroupInfo(searchKernel.KernelID, device.DeviceID, KernelWorkGroupInfo.WORK_GROUP_SIZE, size, (void*)valuep, out sizeOuts);
                    workGroupSize = (uint)values[0];
                }
            }

            unit = workGroupSize * 256u;
            globalThreads = (uint)(unit * 10);
            Initialized = true;
        }
Пример #22
0
        public static void CreateManyToManyRelationship(Vendor Vendor, int[] CategoryIds)
        {
            var categoryService = EngineContext.Current.Resolve<ICategoryService>();
            List<Category> Categories = new List<Category>();

            foreach(var CategoryId in CategoryIds)
            {
                var Category = categoryService.GetCategoryById(CategoryId);
                Categories.Add(Category);
            }

            foreach (var Category in Categories)
            {
                if (Category.Id.Equals(0))
                {
                    categoryService.InsertCategory(Category);
                }
            }

        }
Пример #23
0
        // viewOnly mode
        public FrmVendorAddUpdate(AccessToken acctkn, Vendor vendor, Boolean viewOnly)
        {
            InitializeComponent();

            _myAccessToken = acctkn;
            _myVendor = vendor;

            this.Text = "Vendor: " + vendor.Name;
            btMorph.Text = "Done";

            PopulateStateCombo();
            PopulateCountryCombo();

            txtVendorID.Text = vendor.Id.ToString();
            txtVendorName.Text = vendor.Name;
            txtVendorAddress.Text = vendor.Address;
            txtVendorCity.Text = vendor.City;
            cbVendorState.Text = vendor.State;
            cbVendorCountry.Text = vendor.Country;
            txtVendorZipCode.Text = vendor.Zip;

            txtVendorContact.Text = vendor.Contact;
            txtVendorContactEmail.Text = vendor.ContactEmail;
            txtVendorContactPhone.Text = vendor.Phone;

            txtVendorID.Enabled = false;
            txtVendorName.Enabled = false;
            txtVendorAddress.Enabled = false;
            txtVendorCity.Enabled = false;
            cbVendorState.Enabled = false;
            cbVendorCountry.Enabled = false;
            txtVendorZipCode.Enabled = false;

            txtVendorContact.Enabled = false;
            txtVendorContactEmail.Enabled = false;
            txtVendorContactPhone.Enabled = false;

            btnEditVendor.Visible = true;

            Instance = this;
        }
Пример #24
0
        public async Task<SubscriptionResult> Subscribe(Vendor vendor)
        {
            var user = (await accountManager.FindByIdAsync(vendor.UserId) as EnterpriseUser);
            if (!string.IsNullOrWhiteSpace(user.VendorId))
                throw new InvalidOperationException($"{user.Id} is already a vendor");

            if (user == null || user.Type != IdentityTypes.ENTERPRISE)
                throw new NotSupportedException($"User {vendor.UserId} is not an enterprise user");

            if (string.IsNullOrWhiteSpace(user.VendorId))
            {
                user.VendorSubscriptionDate = DateTime.UtcNow;
                var result = await accountManager.UpdateAsync(user);
                var insertionResult = await Insert(vendor);
                user.VendorId = vendor.Id;
                if (result.Succeeded && insertionResult != null)
                    return SubscriptionResult.SUCCESS;
                else return SubscriptionResult.FAILED;
            }
            return SubscriptionResult.NOT_MODIFIED;
        }
Пример #25
0
        public AddEditVendorModel(int vendorId)
        {
            if (DesignerProperties.IsInDesignTool) { return; }
            CompositionInitializer.SatisfyImports(this);

            CmsWebServiceClient cmsWebServiceClient = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);

            cmsWebServiceClient.GetVendorCompleted += (s1, e1) =>
                {
                    mVendor = e1.Result;
                    if (DataLoaded!=null)
                    {
                        mVendor = e1.Result;
                        DataLoaded();
                    }
                };
            cmsWebServiceClient.GetVendorAsync(vendorId);

            OkButtonCommand = new DelegateCommand<object>(OkButtonHander, CanExecuteOkButtonHandler);
            CancelButtonCommand = new DelegateCommand<object>(CancelButtonHander, x => true);
        }
Пример #26
0
        private IEnumerable<Vendor> ReadData(XmlNodeList nodeList)
        {
            var vendors = new HashSet<Vendor>();

            foreach (XmlNode product in nodeList)
            {
                var newVendor = new Vendor();
                newVendor.VendorName = product.Attributes.Item(0).InnerText;

                foreach (XmlNode expense in product.ChildNodes)
                {
                    newVendor.ExpensesSum += decimal.Parse(expense.InnerText);
                }

                if (!vendors.Contains(newVendor))
                {
                    vendors.Add(newVendor);
                }
            }

            return vendors;
        }
Пример #27
0
        private static Vendor FindNearestVendor(Vendor.VendorType vendorType)
        {
            var results = new List<Vendor>();

            WoWPoint loc = StyxWoW.Me.Location;

            using (SQLiteDataReader reader = GetSqliteDataReader(SqlCmd_NearestVendor, StyxWoW.Me.MapId, (uint)vendorType.AsNpcFlag(), loc.X, loc.Y, loc.Z))
            {
                while (reader.Read())
                {
                    Vendor result = GetVendor(reader, vendorType);
                    var factionId = (uint)reader.GetInt32(reader.GetOrdinal("faction"));
                    if (StyxWoW.Me.FactionTemplate.GetReactionTowards(WoWFactionTemplate.FromId(factionId)) >= WoWUnitReaction.Neutral && !VendorBlacklist.Contains(result.Entry) &&
                        Navigator.CanNavigateFully(loc, result.Location))
                    {
                        results.Add(result);
                        if (results.Count >= 5)
                            break;
                    }
                }
            }
            return results.Any() ? results.OrderBy(r => r.Location.DistanceSqr(loc)).FirstOrDefault() : null;
        }
Пример #28
0
        private static Vendor FindOrCreateVendor(RotoTrackDb db, string QBListId, string QBEditSequence, string TimeCreated, string TimeModified, string Name, string IsActive)
        {
            Vendor o = null;
            if (db.Vendors.Any(f => f.QBListId == QBListId))
            {
                o = db.Vendors.First(f => f.QBListId == QBListId);
            }
            else
            {
                o = new Vendor();
                db.Vendors.Add(o);
            }

            o.QBListId = QBListId;
            o.QBEditSequence = QBEditSequence;
            DateTime createdDate;
            if (DateTime.TryParse(TimeCreated, out createdDate)) o.TimeCreated = createdDate;
            DateTime modifiedDate;
            if (DateTime.TryParse(TimeModified, out modifiedDate)) o.TimeModified = modifiedDate;
            o.Name = Name;
            o.IsActive = (IsActive == "true") ? true : false;

            return o;
        }
        public ActionResult New(int vendorId)
        {
            Vendor vendor = Vendor.Find(vendorId);

            return(View(vendor));
        }
Пример #30
0
        public ActionResult Index()
        {
            List <Vendor> vendorList = Vendor.GetAll();

            return(View(vendorList));
        }
Пример #31
0
 public void UpdateVendor(Vendor vendor)
 {
     _vendorRepo.Update(vendor);
 }
Пример #32
0
 public void UpdateVendor(Vendor vendor)
 {
     DataContext.Table <Vendor>().UpdateRecord(vendor);
 }
Пример #33
0
        public ActionResult AllOrders(Guid ID)
        {
            Vendor vendorOrders = Store.Instance().FindVendorByID(ID);

            return(View(vendorOrders));
        }
Пример #34
0
        public void DoWork(Transaction orgTxn, bool WaitForData = false)
        {
            Transaction Txn = null;


            Txn = orgTxn;


            if (Txn.CommandEncodeStr.Equals("GetMappingDummy"))
            {
                string mappingData = "";
                if (Txn.NodeName.Equals("LOADPORT01"))
                {
                    //mappingData = "1111111111111111111111111";
                    mappingData = SystemConfig.Get().FakeDataP1;
                }
                else if (Txn.NodeName.Equals("LOADPORT02"))
                {
                    mappingData = SystemConfig.Get().FakeDataP2;
                }
                else if (Txn.NodeName.Equals("LOADPORT03"))
                {
                    mappingData = SystemConfig.Get().FakeDataP3;
                }
                else if (Txn.NodeName.Equals("LOADPORT04"))
                {
                    mappingData = SystemConfig.Get().FakeDataP4;
                }

                CommandReturnMessage cm = new CommandReturnMessage();
                //cm.CommandType = Transaction.Command.LoadPortType.GetMapping;
                cm.Value = mappingData;
                //Txn.Method= Transaction.Command.LoadPortType.GetMapping;
                _ReportTarget.On_Command_Excuted(NodeManagement.Get(Txn.NodeName), Txn, cm);
            }
            //conn.WaitForData(WaitForData);

            // lock (TransactionList)
            List <CommandReturnMessage> msgList = _Decoder.GetMessage(Txn.CommandEncodeStr);


            if (!Txn.NodeType.Equals("OCR"))
            {
                if (msgList.Count != 0)
                {
                    Txn.Type = msgList[0].Command;
                    //Txn.CommandType = msgList[0].CommandType;
                }
            }
            else
            {
                Txn.Type = "";
                //Txn.CommandType = "";
            }
            string key = "";

            if (Vendor.ToUpper().Equals("KAWASAKI"))
            {
                key = Txn.Seq;
            }
            if (DeviceType.ToUpper().Equals("SMARTTAG"))
            {
                key = "00";
            }
            else if (Vendor.ToUpper().Equals("HST") || Vendor.ToUpper().Equals("COGNEX"))
            {
                key = "1" + Txn.Type;
            }

            else if (Vendor.ToUpper().Equals("SANWA") || Vendor.ToUpper().Equals("ATEL_NEW"))
            {
                key = Txn.AdrNo + Txn.Type;
                //支援同時多發命令
                for (int seq = 0; seq <= 99; seq++)
                {
                    string tmpKey = key + seq.ToString("00");

                    if (!TransactionList.ContainsKey(tmpKey))
                    {
                        key = tmpKey;
                        break;
                    }
                    if (seq == 99)
                    {
                        logger.Error("seq is run out!");
                    }
                }
            }
            else
            {
                if (Vendor.ToUpper().Equals("SANWA_MC"))
                {
                    if (orgTxn.CommandEncodeStr.Contains("MCR:"))
                    {
                        Txn.CommandType = "CMD";
                    }
                    if (Txn.Method == Transaction.Command.LoadPortType.Reset)
                    {
                        key = "0";
                    }
                    else
                    {
                        key = Txn.AdrNo;
                    }
                    //}
                    //else
                    //{
                    //    key = "0" + msgList[0].Command;
                    //}
                }
                else
                {
                    key = Txn.AdrNo + Txn.Type;
                }
            }

            if (TransactionList.TryAdd(key, Txn) || Txn.Method.Equals("Stop"))
            {
                Txn.SetTimeOutReport(this);
                Txn.SetTimeOutMonitor(true);



                //if (Vendor.ToUpper().Equals("ACDT"))
                //{
                //    byte[] byteAry = Encoding.UTF8.GetBytes(Txn.CommandEncodeStr);


                //    logger.Debug(DeviceName + " Send:" + BitConverter.ToString(byteAry) + " Wafer:" + waferids);
                //}
                //else
                //{

                if (Txn.CommandType.Equals(""))
                {
                    Txn.CommandType = _Decoder.GetMessage(Txn.CommandEncodeStr)[0].CommandType;
                }
                //if (Txn.CommandType.Equals("GET") || Txn.CommandType.IndexOf("FS") != -1)
                //{

                //}
                if (Txn.Method.Equals(Transaction.Command.LoadPortType.Reset))
                {
                    Txn.SetTimeOut(15000);
                }
                else
                {
                    Txn.SetTimeOut(Txn.AckTimeOut);
                }
                try
                {
                    //logger.Info(DeviceName + " Send:" + Txn.CommandEncodeStr.Replace("\r", ""));
                    //if (!this.Vendor.ToUpper().Equals("MITSUBISHI_PLC"))
                    //{
                    //    _ReportTarget.On_Message_Log("CMD", DeviceName + " Send:" + Txn.CommandEncodeStr.Replace("\r", ""));
                    //}
                    //if (this.Vendor.Equals("SMARTTAG8200") || this.Vendor.Equals("SMARTTAG8400"))
                    //{
                    //    //if (Txn.Method == Transaction.Command.SmartTagType.GetLCDData)
                    //    //{
                    //    //    conn.WaitForData(true);
                    //    //}
                    //    ThreadPool.QueueUserWorkItem(new WaitCallback(conn.SendHexData), Txn.CommandEncodeStr);

                    //}
                    //else
                    //{

                    //    ThreadPool.QueueUserWorkItem(new WaitCallback(conn.Send), Txn.CommandEncodeStr);
                    //}
                    if (Txn.NodeName.ToUpper().Equals("SMIF1"))
                    {
                        ch1Send = Txn.CommandEncodeStr;
                    }
                    else if (Txn.NodeName.ToUpper().Equals("SMIF2"))
                    {
                        ch2Send = Txn.CommandEncodeStr;
                    }
                }
                catch (Exception eex)
                {
                    logger.Error(eex.StackTrace);
                    _ReportTarget.On_Message_Log("CMD", DeviceName + " Err:" + eex.StackTrace);
                    Txn.SetTimeOutMonitor(false);
                    Transaction tmp;
                    TransactionList.TryRemove(key, out tmp);
                    CommandReturnMessage rm = new CommandReturnMessage();
                    rm.Value = "ConnectionError";
                    _ReportTarget.On_Command_Error(NodeManagement.Get(Txn.NodeName), Txn, rm);
                }
            }
            else
            {
                Transaction workingTxn;
                TransactionList.TryRemove(key, out workingTxn);
                logger.Debug(DeviceName + "(DoWork " + IPAdress + ":" + Port.ToString() + ":" + Txn.CommandEncodeStr + ") Same type command " + workingTxn.CommandEncodeStr + " is already excuting.");
                _ReportTarget.On_Message_Log("CMD", DeviceName + "(DoWork " + IPAdress + ":" + Port.ToString() + ":" + Txn.CommandEncodeStr + ") Same type command " + workingTxn.CommandEncodeStr + " is already excuting.");
                Txn.SetTimeOutMonitor(false);
                CommandReturnMessage rm = new CommandReturnMessage();
                rm.Value = "AlreadyExcuting";
                _ReportTarget.On_Command_Error(NodeManagement.Get(Txn.NodeName), Txn, rm);
            }
        }
 public int SavePatchChanges(Vendor vendor)
 {
     _db.Vendor.Update(vendor);
     return(_db.SaveChanges());
 }
Пример #36
0
        public void On_Transaction_TimeOut(Transaction Txn)
        {
            logger.Debug(DeviceName + "(On_Transaction_TimeOut Txn is timeout:" + Txn.Method);
            _ReportTarget.On_Message_Log("CMD", DeviceName + "(On_Transaction_TimeOut Txn is timeout:" + Txn.Method);
            string key = "";

            if (Vendor.ToUpper().Equals("KAWASAKI"))
            {
                key = Txn.Seq;
            }
            else if (Vendor.ToUpper().Equals("HST") || Vendor.ToUpper().Equals("COGNEX"))
            {
                key = "1";
            }

            else if (Vendor.ToUpper().Equals("SANWA") || Vendor.ToUpper().Equals("ATEL_NEW"))
            {
                key = Txn.AdrNo + Txn.Method;
                for (int seq = 0; seq <= 99; seq++)
                {
                    string tmpKey = key + seq.ToString("00");

                    if (TransactionList.ContainsKey(tmpKey))
                    {
                        key = tmpKey;
                        break;
                    }
                    if (seq == 99)
                    {
                        logger.Error("seq is run out!");
                    }
                }
            }
            else
            {
                key = Txn.AdrNo;
            }
            Txn.SetTimeOutMonitor(false);

            if (TransactionList.ContainsKey(key))
            {
                if (TransactionList.TryRemove(key, out Txn))
                {
                    //Node Node = NodeManagement.GetByController(DeviceName, Txn.AdrNo);
                    Node Node = NodeManagement.Get(Txn.NodeName);
                    Node.IsExcuting = false;
                    if (Node.State.Equals("Pause"))
                    {
                        logger.Debug("Txn timeout,but state is pause. ignore this.");
                        TransactionList.TryAdd(key, Txn);
                        return;
                    }
                    //if (Node != null)
                    //{
                    //    _ReportTarget.On_Command_TimeOut(Node, Txn);
                    //}
                    //else
                    //{
                    //    logger.Debug(DeviceName + "(On_Transaction_TimeOut Get Node fail.");
                    //}
                }
                else
                {
                    logger.Debug(DeviceName + "(On_Transaction_TimeOut TryRemove Txn fail.");
                }
            }
            _ReportTarget.On_Command_TimeOut(NodeManagement.Get(Txn.NodeName), Txn);
        }
Пример #37
0
        public void On_Connection_Message(object MsgObj)
        {
            try
            {
                string Msg = (string)MsgObj;
                //if (Vendor.ToUpper().Equals("ACDT"))
                //{
                //    byte[] byteAry = Encoding.ASCII.GetBytes(Msg);


                //    logger.Debug(DeviceName + " Recieve:" + BitConverter.ToString(byteAry));
                //}
                //else
                //{

                //}
                //Node Target = null;

                List <CommandReturnMessage> ReturnMsgList = _Decoder.GetMessage(Msg);
                foreach (CommandReturnMessage ReturnMsg in ReturnMsgList)
                {
                    //logger.Info(DeviceName + " Recieve:" + ReturnMsg.OrgMsg);
                    if (!this.Vendor.ToUpper().Equals("MITSUBISHI_PLC"))
                    {
                        _ReportTarget.On_Message_Log("CMD", DeviceName + " Recieve:" + ReturnMsg.OrgMsg);
                    }
                    try
                    {
                        Transaction Txn  = null;
                        Node        Node = null;
                        if (ReturnMsg != null)
                        {
                            lock (TransactionList)
                            {
                                if (ReturnMsg.Command != null)
                                {
                                    if (ReturnMsg.Command.Equals("PAUSE"))
                                    {
                                        foreach (Transaction t in TransactionList.Values)
                                        {
                                            t.SetTimeOutMonitor(false);
                                        }
                                    }
                                    if (ReturnMsg.Command.Equals("CONT_"))
                                    {
                                        foreach (Transaction t in TransactionList.Values)
                                        {
                                            t.SetTimeOutMonitor(true);
                                        }
                                    }
                                }


                                string key = "";
                                if (Vendor.ToUpper().Equals("KAWASAKI"))
                                {
                                    key = ReturnMsg.Seq;
                                }
                                else if (Vendor.ToUpper().Equals("HST") || Vendor.ToUpper().Equals("COGNEX"))
                                {
                                    key = "1" + ReturnMsg.Command;
                                }

                                else if (Vendor.ToUpper().Equals("SANWA") || Vendor.ToUpper().Equals("ATEL_NEW"))
                                {
                                    key = ReturnMsg.NodeAdr + ReturnMsg.Command;
                                    for (int seq = 0; seq <= 99; seq++)
                                    {
                                        string tmpKey = key + seq.ToString("00");

                                        if (TransactionList.ContainsKey(tmpKey))
                                        {
                                            key = tmpKey;
                                            break;
                                        }
                                        if (seq == 99)
                                        {
                                            logger.Error("seq is run out!");
                                        }
                                    }
                                }
                                else if (Vendor.ToUpper().Equals("SANWA_MC"))
                                {
                                    //if (ReturnMsg.Command.Equals("MCR__"))
                                    //{
                                    if (ReturnMsg.Command.Equals("RESET"))
                                    {
                                        key = "0";
                                    }
                                    else
                                    {
                                        key = ReturnMsg.NodeAdr;
                                    }
                                    //}
                                    //else
                                    //{
                                    //    key = "0" + ReturnMsg.Command;
                                    //}
                                }
                                else if (DeviceType.Equals("SMARTTAG"))
                                {
                                    key = "00";
                                }
                                else
                                {
                                    key = (ReturnMsg.NodeAdr + ReturnMsg.Command).Equals("") ? "0" : ReturnMsg.NodeAdr + ReturnMsg.Command;
                                }

                                if (Vendor.ToUpper().Equals("KAWASAKI"))
                                {
                                    if (TransactionList.TryGetValue(key, out Txn))
                                    {
                                        Node = NodeManagement.Get(Txn.NodeName);

                                        if (!Txn.CommandType.Equals("CMD"))
                                        {
                                            if (ReturnMsg.Type.Equals(CommandReturnMessage.ReturnType.Excuted))
                                            {
                                                continue;
                                            }
                                            else if (ReturnMsg.Type.Equals(CommandReturnMessage.ReturnType.Finished))
                                            {
                                                ReturnMsg.Type = CommandReturnMessage.ReturnType.Excuted;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        logger.Debug("Transaction not exist:key=" + key);
                                        return;
                                    }
                                }
                                else if (Vendor.ToUpper().Equals("TDK"))
                                {
                                    if (TransactionList.TryGetValue(key, out Txn))
                                    {
                                        Node = NodeManagement.Get(Txn.NodeName);
                                        if (Txn.CommandType.Equals("SET") && ReturnMsg.Type.Equals(CommandReturnMessage.ReturnType.Excuted))
                                        {
                                            //continue;
                                        }
                                    }
                                    else
                                    {
                                        Node = NodeManagement.GetByController(DeviceName, ReturnMsg.NodeAdr);
                                    }
                                }
                                else
                                {
                                    //if (ReturnMsg.NodeAdr.Equals("") || ReturnMsg.Command.Equals("RESET") || ReturnMsg.Command.Equals("SP___") || ReturnMsg.Command.Equals("PAUSE") || ReturnMsg.Command.Equals("CONT_") || ReturnMsg.Command.Equals("STOP_") || ReturnMsg.Command.Equals("TGEVT"))
                                    //{
                                    //    Node = NodeManagement.GetFirstByController(DeviceName);
                                    //}
                                    //else
                                    //{
                                    //    Node = NodeManagement.GetByController(DeviceName, ReturnMsg.NodeAdr);
                                    //}
                                    Node = NodeManagement.GetByController(DeviceName, ReturnMsg.NodeAdr.Equals("") ? "0" : ReturnMsg.NodeAdr);
                                    if (Node == null)
                                    {
                                        Node = NodeManagement.GetOCRByController(DeviceName);
                                    }
                                    if (Node == null)
                                    {
                                        Node = NodeManagement.GetFirstByController(DeviceName);
                                    }
                                }
                                //lock (TransactionList)
                                //{
                                //lock (Node)
                                //{
                                //Target = Node;
                                if (Node.Vendor.ToUpper().Equals("COGNEX"))
                                {
                                    if (ReturnMsg.Type == CommandReturnMessage.ReturnType.UserName)
                                    {
                                        //conn.Send("admin\r\n");
                                        continue;
                                    }
                                    if (ReturnMsg.Type == CommandReturnMessage.ReturnType.Password)
                                    {
                                        //conn.Send("\r\n");
                                        continue;
                                    }
                                }
                                if (ReturnMsg.Type == CommandReturnMessage.ReturnType.Event)
                                {
                                    //_ReportTarget.On_Event_Trigger(Node, ReturnMsg);
                                }
                                else if ((ReturnMsg.Type == CommandReturnMessage.ReturnType.Information && Node.Vendor.ToUpper().Equals("TDK") && !TransactionList.ContainsKey(key)))
                                {
                                    if (ReturnMsg.Type.Equals(CommandReturnMessage.ReturnType.Information))
                                    {
                                        //ThreadPool.QueueUserWorkItem(new WaitCallback(conn.Send), ReturnMsg.FinCommand);
                                        //conn.Send(ReturnMsg.FinCommand);
                                        //isWaiting = false;
                                        logger.Debug(DeviceName + " Send:" + ReturnMsg.FinCommand);
                                    }
                                }
                                else if (TransactionList.TryRemove(key, out Txn))
                                {
                                    // Node.InitialComplete = false;
                                    Node = NodeManagement.Get(Txn.NodeName);
                                    switch (ReturnMsg.Type)
                                    {
                                    case CommandReturnMessage.ReturnType.Excuted:
                                        if (!Txn.CommandType.Equals("CMD") && !Txn.CommandType.Equals("MOV") && !Txn.CommandType.Equals("HCS"))
                                        {
                                            logger.Debug("Txn timmer stoped.");
                                            Txn.SetTimeOutMonitor(false);
                                            lock (Node.ExcuteLock)
                                            {
                                                Node.IsExcuting = false;
                                            }
                                        }
                                        else
                                        {
                                            //if (Txn.Method.Equals(Transaction.Command.LoadPortType.Reset))
                                            //{
                                            //    logger.Debug("Txn timmer stoped.");
                                            //    Txn.SetTimeOutMonitor(false);

                                            //}
                                            //else if (Txn.Method.Equals(Transaction.Command.RobotType.OrginSearch))
                                            //{
                                            //    logger.Debug("Txn timmer stoped.");
                                            //    Txn.SetTimeOutMonitor(false);
                                            //    //Node.IsExcuting = false;
                                            //    TransactionList.TryAdd(key, Txn);
                                            //}
                                            //else
                                            //{
                                            Txn.SetTimeOutMonitor(false);
                                            Txn.SetTimeOut(Txn.MotionTimeOut);
                                            Txn.SetTimeOutMonitor(true);
                                            TransactionList.TryAdd(key, Txn);

                                            //}
                                        }
                                        //_ReportTarget.On_Command_Excuted(Node, Txn, ReturnMsg);
                                        break;

                                    case CommandReturnMessage.ReturnType.Finished:
                                        logger.Debug("Txn timmer stoped.");
                                        Txn.SetTimeOutMonitor(false);
                                        lock (Node.ExcuteLock)
                                        {
                                            Node.IsExcuting = false;
                                        }
                                        //_ReportTarget.On_Command_Finished(Node, Txn, ReturnMsg);
                                        break;

                                    case CommandReturnMessage.ReturnType.Error:
                                        logger.Debug("Txn timmer stoped.");
                                        Txn.SetTimeOutMonitor(false);
                                        lock (Node.ExcuteLock)
                                        {
                                            Node.IsExcuting = false;
                                        }
                                        //_ReportTarget.On_Command_Error(Node, Txn, ReturnMsg);
                                        if (Vendor.ToUpper().Equals("TDK") || DeviceType.ToUpper().Equals("SMARTTAG"))
                                        {
                                            //conn.Send(ReturnMsg.FinCommand);
                                            logger.Debug(DeviceName + " Send:" + ReturnMsg.FinCommand);
                                        }
                                        break;

                                    case CommandReturnMessage.ReturnType.Information:
                                        logger.Debug("Txn timmer stoped.");
                                        Txn.SetTimeOutMonitor(false);
                                        lock (Node.ExcuteLock)
                                        {
                                            Node.IsExcuting = false;
                                        }
                                        if (Vendor.ToUpper().Equals("TDK") && Txn.CommandType.Equals("SET"))
                                        {
                                            ReturnMsg.Type = CommandReturnMessage.ReturnType.Excuted;
                                        }
                                        else
                                        {
                                            ReturnMsg.Type = CommandReturnMessage.ReturnType.Finished;
                                            //Node.IsExcuting = false;
                                        }
                                        SpinWait.SpinUntil(() => false, 50);
                                        //ThreadPool.QueueUserWorkItem(new WaitCallback(conn.Send), ReturnMsg.FinCommand);
                                        //conn.Send(ReturnMsg.FinCommand);

                                        logger.Debug(DeviceName + " Send:" + ReturnMsg.FinCommand);

                                        break;
                                    }
                                }
                                else
                                {
                                    if (ReturnMsg.Type != null)
                                    {
                                        if (ReturnMsg.Type.Equals(CommandReturnMessage.ReturnType.Information))
                                        {
                                            //ThreadPool.QueueUserWorkItem(new WaitCallback(conn.Send), ReturnMsg.FinCommand);
                                            //conn.Send(ReturnMsg.FinCommand);

                                            logger.Debug(DeviceName + " Send:" + ReturnMsg.FinCommand);
                                        }
                                        else
                                        {
                                            if (ReturnMsg.Type == CommandReturnMessage.ReturnType.Error)
                                            {
                                                Txn = TransactionList.First().Value;

                                                logger.Debug("Txn timmer stoped.");
                                                Txn.SetTimeOutMonitor(false);
                                                lock (Node.ExcuteLock)
                                                {
                                                    Node.IsExcuting = false;
                                                }
                                                //_ReportTarget.On_Command_Error(Node, Txn, ReturnMsg);
                                                if (Vendor.ToUpper().Equals("TDK") || DeviceType.ToUpper().Equals("SMARTTAG"))
                                                {
                                                    //conn.Send(ReturnMsg.FinCommand);
                                                    logger.Debug(DeviceName + " Send:" + ReturnMsg.FinCommand);
                                                }

                                                TransactionList.TryRemove(TransactionList.First().Key, out Txn);
                                            }
                                            else
                                            {
                                                logger.Debug(DeviceName + "(On_Connection_Message Txn is not found. msg:" + Msg);
                                                continue;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        logger.Debug(DeviceName + "(On_Connection_Message Return type is null. msg:" + Msg);
                                        continue;
                                    }
                                }
                                //}
                            }
                            switch (ReturnMsg.Type)
                            {
                            case CommandReturnMessage.ReturnType.Information:
                            case CommandReturnMessage.ReturnType.Event:
                                Transaction t = new Transaction();
                                t.NodeName         = Node.Name;
                                t.NodeType         = Node.Type;
                                t.Value            = ReturnMsg.Value;
                                t.CommandEncodeStr = ReturnMsg.OrgMsg;
                                t.Method           = ReturnMsg.Command;

                                //TransactionRecord.AddDetail(TransactionRecord.GetUUID(), Node.Name,Node.Type,ReturnMsg.Type,ReturnMsg.Value);
                                _ReportTarget.On_Event_Trigger(Node, ReturnMsg);
                                break;

                            case CommandReturnMessage.ReturnType.Excuted:

                                _ReportTarget.On_Command_Excuted(Node, Txn, ReturnMsg);
                                if (Txn.CommandType.Equals("CMD") && !Node.Type.Equals("LOADPORT"))
                                {
                                    _ReportTarget.On_Node_State_Changed(Node, "Busy");
                                }
                                break;

                            case CommandReturnMessage.ReturnType.Finished:

                                //if (Node.Type.Equals("LOADPORT"))
                                //{
                                //    Node.InterLock = false;
                                //}

                                _ReportTarget.On_Command_Finished(Node, Txn, ReturnMsg);
                                if (!Node.Type.Equals("LOADPORT"))
                                {
                                    _ReportTarget.On_Node_State_Changed(Node, "StandBy");
                                }


                                break;

                            case CommandReturnMessage.ReturnType.Error:

                                //if (Node.Type.Equals("LOADPORT"))
                                //{
                                //    Node.InterLock = false;
                                //}
                                _ReportTarget.On_Command_Error(Node, Txn, ReturnMsg);

                                break;
                            }
                        }
                        else
                        {
                            logger.Debug(DeviceName + "(On_Connection_Message Message decode fail:" + Msg);
                        }
                    }
                    catch (Exception e)
                    {
                        logger.Error(DeviceName + "(On_Connection_Message " + IPAdress + ":" + Port.ToString() + ")" + e.Message + "\n" + e.StackTrace);
                    }
                }
            }
            catch (Exception e)
            {
                logger.Error(DeviceName + "(On_Connection_Message " + IPAdress + ":" + Port.ToString() + ")" + e.Message + "\n" + e.StackTrace);
            }
        }
Пример #38
0
 public static Vendor ToEntity(this VendorModel model, Vendor destination)
 {
     return(model.MapTo(destination));
 }
Пример #39
0
        public async Task Create(BookOrderDTO book)
        {
            Work work = await _unitOfWork.WorkRepository.GetByIdAsync(book.WorkId);

            Customer customer = await _unitOfWork.CustomerRepository.GetByIdAsync(book.CustomerId);

            Location location = null;

            work.Orders = work.Orders + 1;
            _unitOfWork.WorkRepository.Update(work);

            if (book.Location.Id == -1)
            {
                location = new Location()
                {
                    IsDeleted = false,
                    City      = book.Location.City,
                    Adress    = book.Location.Adress,
                    Latitude  = book.Location.Latitude,
                    Longitude = book.Location.Longitude,
                    PostIndex = book.Location.PostIndex
                };
            }
            else
            {
                location = await _unitOfWork.LocationRepository.GetByIdAsync(book.Location.Id);
            }

            Company company = null;
            Vendor  vendor  = null;

            if (book.Profile.ToLower() == "company")
            {
                company = await _unitOfWork.CompanyRepository.GetByIdAsync(book.ProfileId);
            }
            else
            {
                vendor = await _unitOfWork.VendorRepository.Query
                         .Include(v => v.Person)
                         .Include(v => v.Person.Account)
                         .SingleAsync(v => v.Id == book.ProfileId);
            }

            Book _book = new Book()
            {
                IsDeleted     = false,
                Company       = company,
                Customer      = customer,
                CustomerPhone = book.CustomerPhone,
                Date          = book.Date,
                EndDate       = book.EndDate,
                Description   = book.Description,
                Location      = location,
                Status        = BookStatus.Pending,
                Vendor        = vendor,
                Work          = work
            };

            _unitOfWork.BookRepository.Create(_book);
            await _unitOfWork.SaveAsync();

            /* Send Notification */
            var notification = new NotificationDTO()
            {
                Title        = $"New order for {_book.Work.Name}",
                Description  = $"{_book.Customer.Person.Name} {_book.Customer.Person.Surname} booked {_book.Work?.Name}. Check your dashboard to find out details.",
                SourceItemId = _book.Id,
                Time         = DateTime.Now,
                Type         = NotificationType.TaskNotification
            };



            var receiverId = vendor != null ? vendor.Person.Account.Id : company.Account.Id;
            await _notificationService.CreateAsync(receiverId, notification);


            /* Send Message */
            string msg           = EmailTemplate.NewOrderTemplate(_book.Customer.Person.Name, _book.Customer.Person.Surname, _book.Work?.Name, book.CustomerId);
            string receiverEmail = vendor != null ? vendor.Person.Account.Email : company.Account.Email;

            _mailService.Send(new EmailMessage
            {
                ReceiverEmail = receiverEmail,
                Subject       = "You have a new order",
                Body          = msg,
                IsHtml        = true
            });
        }
Пример #40
0
        async Task ProcessProducts(dynamic items)
        {
            Logger.LogInformation("Enterring ProcessProducts");

            List <Brand> brands = await Context.Brands.ToListAsync();

            List <Vendor> vendors = await Context.Vendors.ToListAsync();

            List <Category> categories = await Context.Categories.ToListAsync();

            List <Unit> units = await Context.Units.ToListAsync();

            List <ItemCategory> pcs = new List <ItemCategory>();

            List <Item> data = await Context.Items.ToListAsync();

            foreach (dynamic item in items)
            {
                if (!data.Any(b => b.Name == (string)item.Name))                 // && b.Count == (int)item.Count))
                {
                    Brand brand = brands.FirstOrDefault(b => b.Name == (string)item.Brand);

                    if (brand == null)
                    {
                        string name = item.Name;
                        Logger.LogError("invalid item", name);
                        return;
                    }
                    Item p = new Item
                    {
//						Id = item.Id,
                        Name  = item.Name,
                        Brand = brand
                    };
                    p.BrandId         = p.Brand.Id;
                    p.Description     = item.Description;
                    p.PictureFileName = item.PictureFileName;

                    foreach (dynamic variant in item.Variants)
                    {
                        Variant v = new Variant
                        {
                            Item = p
                        };
                        Unit   unit   = units.FirstOrDefault(b => b.Name == (string)variant.Unit);
                        Vendor vendor = vendors.FirstOrDefault(b => b.Name == (string)variant.Vendor);
                        v.Count = variant.Count;
                        //p.Unit = unit;
                        v.UnitId = unit.Id;

                        //p.Vendor = vendor;
                        v.VendorId          = vendor.Id;
                        v.AvailableStock    = variant.AvailableStock;
                        v.Cost              = variant.Cost;
                        v.MaxStockThreshold = variant.MaxStockThreshold;
                        v.Price             = variant.Price;
                        v.RestockThreshold  = variant.RestockThreshold;
                        v.SuggestPrice      = variant.SuggestPrice;
                        p.Variants.Add(v);
                    }


                    await Context.Items.AddAsync(p);

                    //					await context.SaveChangesAsync();

                    foreach (string category in item.Categories)
                    {
                        ItemCategory pc = new ItemCategory
                        {
                            ItemId   = p.Id,
                            Category = categories.FirstOrDefault(c => c.Name == category)
                        };
                        p.ItemCategories.Add(pc);
                    }
                }
            }
            //			await context.ProductCategories.AddRangeAsync(pcs);
            await Context.SaveChangesAsync();
        }
 public int Delete(Vendor vendor)
 {
     _db.Vendor.Remove(vendor);
     return(_db.SaveChanges());
 }
        public void setCustomVendor(Vendor customVendor)
        {
            var androidVendor = (AndroidVendor)customVendor.getNativeVendor();

            getInstance().Call("setCustomVendor", androidVendor.getVendor());
        }
 public Vendor Patch(Vendor vendor)
 {
     _db.Vendor.Update(vendor);
     _db.SaveChanges();
     return(vendor);
 }
        public async Task <bool> SaveAsync(Vendor model)
        {
            var query = $"INSERT INTO `ps_vn_vendor` VALUES ('{model.VendorId}','{model.Name}','{model.Contact}',SYSDATE(),'{model.Email}',0,{model.Active});";

            return(await _dbContext.ExecuteQueryAsync(query));
        }
Пример #45
0
        public virtual ContactVendorModel PrepareContactVendorModel(ContactVendorModel model, Vendor vendor, bool excludeProperties)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            if (vendor == null)
            {
                throw new ArgumentNullException("vendor");
            }

            if (!excludeProperties)
            {
                model.Email    = _workContext.CurrentCustomer.Email;
                model.FullName = _workContext.CurrentCustomer.GetFullName();
            }

            model.SubjectEnabled = _commonSettings.SubjectFieldOnContactUsForm;
            model.DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnContactUsPage;
            model.VendorId       = vendor.Id;
            model.VendorName     = vendor.GetLocalized(x => x.Name);

            return(model);
        }
        public async Task <bool> UpdateAsync(Vendor model)
        {
            var query = $"UPDATE `ps_vn_vendor` SET `name` = '{model.Name}',`contactNumber` = '{model.Contact}',`email` = '{model.Email}' ,`active` ='{model.Active}' WHERE `vendorId` = '{model.VendorId}';";

            return(await _dbContext.ExecuteQueryAsync(query));
        }
Пример #47
0
 public void AddNewVendor(Vendor vendor)
 {
     DataContext.Table <Vendor>().AddNewRecord(vendor);
 }
        public ActionResult ApplyVendorSubmit(ApplyVendorModel model, bool captchaValid, HttpPostedFileBase uploadedFile)
        {
            if (!_vendorSettings.AllowCustomersToApplyForVendorAccount)
            {
                return(RedirectToRoute("HomePage"));
            }

            if (!_workContext.CurrentCustomer.IsRegistered())
            {
                return(new HttpUnauthorizedResult());
            }

            //validate CAPTCHA
            if (_captchaSettings.Enabled && _captchaSettings.ShowOnApplyVendorPage && !captchaValid)
            {
                ModelState.AddModelError("", _captchaSettings.GetWrongCaptchaMessage(_localizationService));
            }

            int pictureId = 0;

            if (uploadedFile != null && !string.IsNullOrEmpty(uploadedFile.FileName))
            {
                try
                {
                    var contentType         = uploadedFile.ContentType;
                    var vendorPictureBinary = uploadedFile.GetPictureBits();
                    var picture             = _pictureService.InsertPicture(vendorPictureBinary, contentType, null);

                    if (picture != null)
                    {
                        pictureId = picture.Id;
                    }
                }
                catch (Exception)
                {
                    ModelState.AddModelError("", _localizationService.GetResource("Vendors.ApplyAccount.Picture.ErrorMessage"));
                }
            }

            if (ModelState.IsValid)
            {
                var description = Core.Html.HtmlHelper.FormatText(model.Description, false, false, true, false, false, false);
                //disabled by default
                var vendor = new Vendor
                {
                    Name  = model.Name,
                    Email = model.Email,
                    //some default settings
                    PageSize = 6,
                    AllowCustomersToSelectPageSize = true,
                    PageSizeOptions = _vendorSettings.DefaultVendorPageSizeOptions,
                    PictureId       = pictureId,
                    Description     = description
                };
                _vendorService.InsertVendor(vendor);
                //search engine name (the same as vendor name)
                var seName = vendor.ValidateSeName(vendor.Name, vendor.Name, true);
                _urlRecordService.SaveSlug(vendor, seName, 0);

                //associate to the current customer
                //but a store owner will have to manually add this customer role to "Vendors" role
                //if he wants to grant access to admin area
                _workContext.CurrentCustomer.VendorId = vendor.Id;
                _customerService.UpdateCustomer(_workContext.CurrentCustomer);

                //update picture seo file name
                UpdatePictureSeoNames(vendor);

                //notify store owner here (email)
                _workflowMessageService.SendNewVendorAccountApplyStoreOwnerNotification(_workContext.CurrentCustomer,
                                                                                        vendor, _localizationSettings.DefaultAdminLanguageId);

                model.DisableFormInput = true;
                model.Result           = _localizationService.GetResource("Vendors.ApplyAccount.Submitted");
                return(View(model));
            }

            //If we got this far, something failed, redisplay form
            model.DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnApplyVendorPage;
            return(View(model));
        }
Пример #49
0
        public ActionResult Create(string vendorName, string vendorPhone, string contactName, string businessType, string email)
        {
            Vendor newVendor = new Vendor(vendorName, vendorPhone, contactName, businessType, email);

            return(RedirectToAction("Index"));
        }
Пример #50
0
        /// <summary>
        /// Prepare the contact vendor model
        /// </summary>
        /// <param name="model">Contact vendor model</param>
        /// <param name="vendor">Vendor</param>
        /// <param name="excludeProperties">Whether to exclude populating of model properties from the entity</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the contact vendor model
        /// </returns>
        public virtual async Task <ContactVendorModel> PrepareContactVendorModelAsync(ContactVendorModel model, Vendor vendor, bool excludeProperties)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (vendor == null)
            {
                throw new ArgumentNullException(nameof(vendor));
            }

            if (!excludeProperties)
            {
                model.Email    = (await _workContext.GetCurrentCustomerAsync()).Email;
                model.FullName = await _customerService.GetCustomerFullNameAsync(await _workContext.GetCurrentCustomerAsync());
            }

            model.SubjectEnabled = _commonSettings.SubjectFieldOnContactUsForm;
            model.DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnContactUsPage;
            model.VendorId       = vendor.Id;
            model.VendorName     = await _localizationService.GetLocalizedAsync(vendor, x => x.Name);

            return(model);
        }
Пример #51
0
        public void AddPurchaseInvoice(PurchaseInvoiceHeader purchaseIvoice, int?purchaseOrderId)
        {
            #region Auto create purchase order
            if (!purchaseOrderId.HasValue)
            {
                var po = new PurchaseOrderHeader()
                {
                    Date        = purchaseIvoice.Date,
                    No          = GetNextNumber(SequenceNumberTypes.PurchaseOrder).ToString(),
                    Vendor      = purchaseIvoice.Vendor,
                    VendorId    = purchaseIvoice.VendorId.Value,
                    Description = purchaseIvoice.Description,
                    CreatedBy   = purchaseIvoice.CreatedBy,
                    CreatedOn   = purchaseIvoice.CreatedOn,
                    ModifiedBy  = purchaseIvoice.ModifiedBy,
                    ModifiedOn  = purchaseIvoice.ModifiedOn
                };
                foreach (var line in purchaseIvoice.PurchaseInvoiceLines)
                {
                    var item = _itemRepo.GetById(line.ItemId);

                    po.PurchaseOrderLines.Add(new PurchaseOrderLine()
                    {
                        ItemId        = item.Id,
                        MeasurementId = line.MeasurementId,
                        Quantity      = line.Quantity,
                        Cost          = item.Cost.Value,
                        Discount      = line.Discount.HasValue ? line.Discount.Value : 0,
                        Amount        = item.Cost.Value * line.Quantity,
                        CreatedBy     = line.CreatedBy,
                        CreatedOn     = line.CreatedOn,
                        ModifiedBy    = line.ModifiedBy,
                        ModifiedOn    = line.ModifiedOn
                    });
                }
                purchaseIvoice.PurchaseOrders.Add(po);

                var poReceipt = new PurchaseReceiptHeader()
                {
                    Date     = DateTime.Now,
                    Vendor   = po.Vendor,
                    VendorId = po.VendorId,
                    PurchaseOrderHeaderId = po.Id,
                    CreatedBy             = po.CreatedBy,
                    CreatedOn             = DateTime.Now,
                    ModifiedBy            = po.ModifiedBy,
                    ModifiedOn            = DateTime.Now
                };

                foreach (var line in purchaseIvoice.PurchaseInvoiceLines)
                {
                    poReceipt.PurchaseReceiptLines.Add(new PurchaseReceiptLine()
                    {
                        ItemId           = line.ItemId,
                        MeasurementId    = line.MeasurementId,
                        Quantity         = line.Quantity,
                        ReceivedQuantity = (line.ReceivedQuantity.HasValue ? line.ReceivedQuantity.Value : 0),
                        Cost             = line.Cost.Value,
                        Amount           = line.Cost.Value * (line.ReceivedQuantity.HasValue ? line.ReceivedQuantity.Value : 0),
                        CreatedBy        = po.CreatedBy,
                        CreatedOn        = DateTime.Now,
                        ModifiedBy       = po.ModifiedBy,
                        ModifiedOn       = DateTime.Now
                    });
                }

                po.PurchaseReceipts.Add(poReceipt);

                AddPurchaseOrderReceipt(poReceipt);
            }
            #endregion

            var glHeader = _financialService.CreateGeneralLedgerHeader(DocumentTypes.PurchaseInvoice, purchaseIvoice.Date, purchaseIvoice.Description);

            decimal taxAmount = 0;
            var     taxes     = new List <KeyValuePair <int, decimal> >();
            foreach (var line in purchaseIvoice.PurchaseInvoiceLines)
            {
                var lineAmount = line.Quantity * line.Cost;
                //var item = _inventoryService.GetItemById(line.ItemId);
                //foreach (var tax in item.ItemTaxGroup.ItemTaxGroupTax)
                //{
                //    if(!tax.IsExempt)
                //    {
                //        var lineTaxAmount = (tax.Tax.Rate / 100) * lineAmount;
                //        taxAmount += lineTaxAmount.Value;
                //        taxes.Add(new KeyValuePair<int, decimal>(tax.Tax.PurchasingAccountId.Value, lineTaxAmount.Value));
                //    }
                //}
                var lineTaxes = _financialService.ComputeInputTax(line.ItemId, line.Quantity, line.Cost.Value);
                foreach (var t in lineTaxes)
                {
                    taxes.Add(t);
                }
            }

            decimal totalAmount   = purchaseIvoice.PurchaseInvoiceLines.Sum(d => d.Amount);
            decimal totalDiscount = 0;

            Vendor vendor = _vendorRepo.GetById(purchaseIvoice.VendorId.Value);
            var    creditVendorAccount = _financialService.CreateGeneralLedgerLine(TransactionTypes.Cr, vendor.AccountsPayableAccountId.Value, totalAmount + taxAmount);
            glHeader.GeneralLedgerLines.Add(creditVendorAccount);

            var creditGRNClearingAccount = _financialService.CreateGeneralLedgerLine(TransactionTypes.Dr, GetGeneralLedgerSetting().GoodsReceiptNoteClearingAccountId.Value, totalAmount);
            glHeader.GeneralLedgerLines.Add(creditGRNClearingAccount);

            if (taxAmount > 0)
            {
                var groupedTaxes = from t in taxes
                                   group t by t.Key into grouped
                                   select new
                {
                    Key   = grouped.Key,
                    Value = grouped.Sum(t => t.Value)
                };

                foreach (var tax in groupedTaxes)
                {
                    var tx = _financialService.GetTaxes().Where(t => t.Id == tax.Key).FirstOrDefault();
                    var debitPurchaseTaxAccount = _financialService.CreateGeneralLedgerLine(TransactionTypes.Dr, tx.SalesAccountId.Value, tax.Value);
                    glHeader.GeneralLedgerLines.Add(debitPurchaseTaxAccount);
                }
            }

            if (totalDiscount > 0)
            {
            }

            if (_financialService.ValidateGeneralLedgerEntry(glHeader))
            {
                purchaseIvoice.GeneralLedgerHeader = glHeader;

                purchaseIvoice.No = GetNextNumber(SequenceNumberTypes.PurchaseInvoice).ToString();
                _purchaseInvoiceRepo.Insert(purchaseIvoice);

                // TODO: Look for another way to update the purchase order's invoice header id field so that it shall be in a single transaction along with purchase invoice saving
                var purchOrder = _purchaseOrderRepo.GetById(purchaseOrderId.Value);
                purchOrder.PurchaseInvoiceHeaderId = purchaseIvoice.Id;
                purchOrder.ModifiedBy = purchaseIvoice.ModifiedBy;
                purchOrder.ModifiedOn = purchaseIvoice.ModifiedOn;
                _purchaseOrderRepo.Update(purchOrder);
            }
        }
Пример #52
0
        public async Task <HttpStatusCode> PostReservationToVendor(int reservationId, [FromBody] EmailMessage emailMsg)
        {
            // retrieve reservation via reservationId
            Reservation reservation = await _reservationQuery.GetById(reservationId);

            // check if reservation is returned
            if (reservation == null)
            {
                return(HttpStatusCode.NotFound);
            }

            int    vendorId = reservation.vendorId ?? default(int);
            Vendor vendor   = await _vendorQuery.GetById(vendorId);

            if (vendor == null)
            {
                return(HttpStatusCode.NotFound);
            }

            int            vendorServiceId = reservation.vendorServiceId ?? default(int);
            VendorServices vendorService   = await _vendorServiceQuery.GetById(vendorServiceId);

            if (vendorService == null)
            {
                return(HttpStatusCode.NotFound);
            }

            Boolean isSuccessful = true;

            // create to list and set
            List <EmailPersonalization> personalizations = new List <EmailPersonalization>();
            List <EmailRecipient>       emailTos         = new List <EmailRecipient>();
            List <EmailContent>         emailContents    = new List <EmailContent>();
            EmailPersonalization        personalization  = new EmailPersonalization();

            emailTos.Add(new EmailRecipient(vendor.name, vendor.userName));
            personalization.to = emailTos;
            personalizations.Add(personalization);
            emailMsg.personalizations = personalizations;

            // Update Content
            String hostname = _emailQuery.getBaseUrlForEmail(HttpContext);

            EmailContent emailContent = new EmailContent();

            emailContent.type = "text/html";

            StringBuilder htmlBuilder = new StringBuilder();

            htmlBuilder.AppendLine("<div>").Append("Hello, ").Append(vendor.name).Append(". You have a requested reservation for the ");
            htmlBuilder.Append(vendorService.serviceName).Append(" waiting for you via Occasions.</div>");
            htmlBuilder.AppendLine("Please click ").Append("<a href='").Append(hostname).Append("/reservations-vendor'>here</a>").Append(" to view it.");
            emailContent.value = htmlBuilder.ToString();
            Console.WriteLine(htmlBuilder.ToString());
            emailContents.Add(emailContent);
            emailMsg.content = emailContents;

            Task <HttpStatusCode> response = _emailQuery.sendEmailViaPostAsync(emailMsg);

            if (response.Result.Equals(HttpStatusCode.Accepted))
            {
                Console.WriteLine("Successfully sent email to " + vendor.userName);
            }
            else
            {
                isSuccessful = false;
                Console.WriteLine("Error sending email to " + vendor.userName);
            }

            if (isSuccessful)
            {
                return(HttpStatusCode.Accepted);
            }
            else
            {
                return(HttpStatusCode.BadRequest);
            }
        }
Пример #53
0
 public void AddVendor(Vendor vendor)
 {
     _vendorRepo.Insert(vendor);
 }
 public Vendor Insert(Vendor vendor)
 {
     _db.Vendor.Add(vendor);
     _db.SaveChanges();
     return(vendor);
 }
Пример #55
0
    //Function called externally from UI buttons to display the vendor screen
    public void DisplayVendor(int typeOfVendor_)
    {
        //Reference to the vendor that we're going to display
        Vendor vendorToDisplay = null;

        //Getting the vendor type enum from the int given (since unity can't have enums as variables in UnityEvents)
        VendorTypes vendorToVisit = VendorTypes.GenderalStore;

        switch (typeOfVendor_)
        {
        case 0:
            vendorToVisit = VendorTypes.GenderalStore;
            break;

        case 1:
            vendorToVisit = VendorTypes.Blacksmith;
            break;

        case 2:
            vendorToVisit = VendorTypes.Tavern;
            break;

        case 3:
            vendorToVisit = VendorTypes.MageTower;
            break;

        case 4:
            vendorToVisit = VendorTypes.Church;
            break;

        case 5:
            vendorToVisit = VendorTypes.DarkTemple;
            break;

        case 6:
            vendorToVisit = VendorTypes.Castle;
            break;

        default:
            vendorToVisit = VendorTypes.GenderalStore;
            break;
        }

        //Looping through each of the vendors on this location
        CityLocation city = this.playerTileLocation as CityLocation;

        foreach (Vendor v in city.cityVendors)
        {
            //If the current vendor's type matches the one we're looking for, it's the one we display
            if (v.type == vendorToVisit)
            {
                vendorToDisplay = v;
                break;
            }
        }

        //If the city doesn't have that type of vendor, nothing happens (this SHOULDN'T happen, but just in case)
        if (vendorToDisplay == null)
        {
            return;
        }

        //Telling the vendor panel UI which vendor we're displaying
        VendorPanelUI.globalReference.vendorToDisplay = vendorToDisplay;

        //Turning the vendor canvas object on
        this.vendorUICanvas.SetActive(true);
    }
Пример #56
0
        /// <summary>
        /// Add the Employee(s) info as a recipient(s) in the Email template generated by Appointment.
        /// </summary>
        private static void AddEmployeeStaffRecipient(
            AppointmentEntry graphAppointmentEntry,
            int?bAccountID,
            string type,
            NotificationRecipient recSetup,
            RecipientList recipients)
        {
            NotificationRecipient recipient = null;
            bool?   appNotification         = false;
            Contact contactRow = null;

            if (type == BAccountType.EmployeeType)
            {
                EPEmployee epEmployeeRow = PXSelect <EPEmployee,
                                                     Where <
                                                         EPEmployee.bAccountID, Equal <Required <EPEmployee.bAccountID> > > >
                                           .Select(graphAppointmentEntry, bAccountID);

                FSxEPEmployee fsxEpEmployeeRow = PXCache <EPEmployee> .GetExtension <FSxEPEmployee>(epEmployeeRow);

                appNotification = fsxEpEmployeeRow.SendAppNotification;

                contactRow = PXSelectJoin <Contact,
                                           InnerJoin <BAccount,
                                                      On <BAccount.parentBAccountID, Equal <Contact.bAccountID>,
                                                          And <BAccount.defContactID, Equal <Contact.contactID> > > >,
                                           Where <
                                               BAccount.bAccountID, Equal <Required <BAccount.bAccountID> >,
                                               And <BAccount.type, Equal <Required <BAccount.type> > > > >
                             .Select(graphAppointmentEntry, bAccountID, type);
            }
            else if (type == BAccountType.VendorType)
            {
                Vendor vendorRow = PXSelect <Vendor,
                                             Where <
                                                 Vendor.bAccountID, Equal <Required <Vendor.bAccountID> > > >
                                   .Select(graphAppointmentEntry, bAccountID);

                FSxVendor fsxVendorRow = PXCache <Vendor> .GetExtension <FSxVendor>(vendorRow);

                appNotification = fsxVendorRow.SendAppNotification;

                contactRow = PXSelectJoin <Contact,
                                           InnerJoin <BAccount,
                                                      On <Contact.contactID, Equal <BAccount.defContactID> > >,
                                           Where <
                                               BAccount.bAccountID, Equal <Required <BAccount.bAccountID> >,
                                               And <BAccount.type, Equal <Required <BAccount.type> > > > >
                             .Select(graphAppointmentEntry, bAccountID, type);
            }

            if (appNotification == true)
            {
                if (contactRow != null && contactRow.EMail != null)
                {
                    recipient = new NotificationRecipient()
                    {
                        Active = true,
                        Email  = contactRow.EMail,
                        Hidden = recSetup.Hidden,
                        Format = recSetup.Format
                    };
                    if (recipient != null)
                    {
                        recipients.Add(recipient);
                    }
                }
            }
        }
        public virtual void AddVendorTokens(IList<Token> tokens, Vendor vendor)
        {
            tokens.Add(new Token("Vendor.Name", vendor.Name));
            tokens.Add(new Token("Vendor.Email", vendor.Email));

            //event notification
            _eventPublisher.EntityTokensAdded(vendor, tokens);
        }
Пример #58
0
        public GenericCPU(int processorIndex, CPUID[][] cpuid, ISettings settings)
        {
            this.cpuid = cpuid;

            this.vendor = cpuid[0][0].Vendor;

            this.family   = cpuid[0][0].Family;
            this.model    = cpuid[0][0].Model;
            this.stepping = cpuid[0][0].Stepping;

            this.processorIndex = processorIndex;
            this.coreCount      = cpuid.Length;
            this.name           = cpuid[0][0].Name;

            // check if processor has a TSC
            if (cpuid[0][0].Data.GetLength(0) > 1 &&
                (cpuid[0][0].Data[1, 3] & 0x10) != 0)
            {
                hasTimeStampCounter = true;
            }
            else
            {
                hasTimeStampCounter = false;
            }

            // check if processor supports an invariant TSC
            if (cpuid[0][0].ExtData.GetLength(0) > 7 &&
                (cpuid[0][0].ExtData[7, 3] & 0x100) != 0)
            {
                isInvariantTimeStampCounter = true;
            }
            else
            {
                isInvariantTimeStampCounter = false;
            }

            if (coreCount > 1)
            {
                totalLoad = new Sensor("CPU Total", 0, SensorType.Load, this, settings);
            }
            else
            {
                totalLoad = null;
            }
            coreLoads = new Sensor[coreCount];
            for (int i = 0; i < coreLoads.Length; i++)
            {
                coreLoads[i] = new Sensor(CoreString(i), i + 1,
                                          SensorType.Load, this, settings);
            }
            cpuLoad = new CPULoad(cpuid);
            if (cpuLoad.IsAvailable)
            {
                foreach (Sensor sensor in coreLoads)
                {
                    ActivateSensor(sensor);
                }
                if (totalLoad != null)
                {
                    ActivateSensor(totalLoad);
                }
            }

            if (hasTimeStampCounter)
            {
                estimatedTimeStampCounterFrequency =
                    EstimateTimeStampCounterFrequency();

                // set initial values
                uint lsb, msb;
                WinRing0.RdtscTx(out lsb, out msb, (UIntPtr)1);
                lastTime           = Stopwatch.GetTimestamp();
                lastTimeStampCount = ((ulong)msb << 32) | lsb;
            }
            else
            {
                estimatedTimeStampCounterFrequency = 0;

                lastTime           = 0;
                lastTimeStampCount = 0;
            }

            timeStampCounterFrequency = estimatedTimeStampCounterFrequency;
        }
        /// <summary>
        /// Sends an order paid notification to a vendor
        /// </summary>
        /// <param name="order">Order instance</param>
        /// <param name="vendor">Vendor instance</param>
        /// <param name="languageId">Message language identifier</param>
        /// <returns>Queued email identifier</returns>
        public virtual int SendOrderPaidVendorNotification(Order order, Vendor vendor, int languageId)
        {
            if (order == null)
                throw new ArgumentNullException("order");

            if (vendor == null)
                throw new ArgumentNullException("vendor");

            var store = _storeService.GetStoreById(order.StoreId) ?? _storeContext.CurrentStore;
            languageId = EnsureLanguageIsActive(languageId, store.Id);

            var messageTemplate = GetActiveMessageTemplate("OrderPaid.VendorNotification", store.Id);
            if (messageTemplate == null)
                return 0;

            //email account
            var emailAccount = GetEmailAccountOfMessageTemplate(messageTemplate, languageId);

            //tokens
            var tokens = new List<Token>();
            _messageTokenProvider.AddStoreTokens(tokens, store, emailAccount);
            _messageTokenProvider.AddOrderTokens(tokens, order, languageId, vendor.Id);
            _messageTokenProvider.AddCustomerTokens(tokens, order.Customer);

            //event notification
            _eventPublisher.MessageTokensAdded(messageTemplate, tokens);

            var toEmail = vendor.Email;
            var toName = vendor.Name;
            return SendNotification(messageTemplate, emailAccount,
                languageId, tokens,
                toEmail, toName);
        }
Пример #60
0
 public static VendorModel ToModel(this Vendor entity)
 {
     return(entity.MapTo <Vendor, VendorModel>());
 }