예제 #1
0
        public IHttpActionResult PutADDRESS(short id, ADDRESS aDDRESS)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != aDDRESS.ADDRESS_ID)
            {
                return(BadRequest());
            }

            db.Entry(aDDRESS).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ADDRESSExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
예제 #2
0
        public static RadComboBox SetLocationList(RadComboBox ddl, List <BusinessLocation> locationList, decimal plantID, bool enableBUSelect)
        {
            ddl.Items.Clear();
            RadComboBoxItem item     = null;
            ADDRESS         address  = null;
            decimal         busOrgID = 0;

            int numOrgs = locationList.Select(l => l.Plant.BUS_ORG_ID).Distinct().Count();

            foreach (BusinessLocation loc in locationList.OrderBy(l => l.Plant.BUS_ORG_ID).ThenBy(l => l.Plant.PLANT_NAME).ToList())
            {
                if (numOrgs > 1 && loc.Plant.BUS_ORG_ID != busOrgID)
                {
                    busOrgID = (decimal)loc.Plant.BUS_ORG_ID;
                    item     = new RadComboBoxItem(loc.BusinessOrg.ORG_NAME, ("BU" + loc.BusinessOrg.BUS_ORG_ID.ToString()));
                    if (enableBUSelect)
                    {
                        item.BackColor = System.Drawing.Color.Linen;
                        item.ToolTip   = loc.BusinessOrg.DUNS_CODE;
                    }
                    else
                    {
                        item.IsSeparator = true;
                        if (ddl.CheckBoxes)
                        {
                            item.Checked = false;
                        }
                    }
                    item.ImageUrl = "~/images/defaulticon/16x16/sitemap.png";
                    ddl.Items.Add(item);
                }

                item             = new RadComboBoxItem(loc.Plant.PLANT_NAME, loc.Plant.PLANT_ID.ToString());
                item.IsSeparator = false;
                if ((address = loc.Plant.ADDRESS.FirstOrDefault()) != null)
                {
                    item.ToolTip = address.STREET1 + " " + address.CITY;
                }
                if (plantID < 0)
                {
                    item.Checked = true;
                }
                ddl.Items.Add(item);
            }
            //ddl.Items.Insert(0, new RadComboBoxItem("", ""));

            if (plantID > 0 && ddl.Items.FindItemByValue(plantID.ToString()) != null)
            {
                if (ddl.CheckBoxes)
                {
                    ddl.FindItemByValue(plantID.ToString()).Checked = true;
                }
                else
                {
                    ddl.SelectedValue = plantID.ToString();
                }
            }

            return(ddl);
        }
예제 #3
0
        public string getStringToMap(string campusId, string accommoId)
        {
            ADDRESS fromAddressObj = null;
            ADDRESS toAddressObj   = null;

            try
            {
                using (HotelManagementServerDataContext db = new HotelManagementServerDataContext())
                {
                    var innJoin1 =
                        from campus in db.CITies
                        where campus.CITY_ID.Equals(Convert.ToInt32(campusId))
                        join address in db.ADDRESSes on campus.ADDRESS_ID equals address.ADDRESS_ID
                        select address;

                    var innJoin2 =
                        from acc in db.HOTELs
                        where acc.HOTEL_ID.Equals(Convert.ToInt32(accommoId))
                        join address in db.ADDRESSes on acc.ADDRESS_ID equals address.ADDRESS_ID
                        select address;

                    fromAddressObj = innJoin1.Single();
                    toAddressObj   = innJoin2.Single();

                    string fromAddress = fromAddressObj.STREET + " " + fromAddressObj.TOWN + " " + fromAddressObj.CITY;
                    string toAddress   = toAddressObj.STREET + " " + toAddressObj.TOWN + " " + toAddressObj.CITY;

                    return(fromAddress + " to " + toAddress);
                }
            }
            catch (Exception)
            {
                return("Failed Cannot map to and from addresses");
            }
        }
        protected void lnkPlantView_Click(object sender, EventArgs e)
        {
            PLANT plant = (PLANT)SessionManager.EffLocation.Plant;

            TextBox tbPlantName    = (TextBox)hfBase.FindControl("tbPlantName"); tbPlantName.Text = plant.PLANT_NAME;
            TextBox tbPlantDesc    = (TextBox)hfBase.FindControl("tbPlantDesc"); tbPlantDesc.Text = plant.DISP_PLANT_NAME;
            TextBox tbPlantLocCode = (TextBox)hfBase.FindControl("tbPlantLocCode"); tbPlantLocCode.Text = plant.DUNS_CODE;

            cbTrackFinData.Checked = (bool)plant.TRACK_FIN_DATA;
            cbTrackEWData.Checked  = (bool)plant.TRACK_EW_DATA;
            Label lblLastUpdate = (Label)hfBase.FindControl("lblPlantLastUpdate"); lblLastUpdate.Text = plant.LAST_UPD_BY;

            lblPlantLastUpdateDate.Text = SQMBasePage.FormatDate(WebSiteCommon.LocalTime((DateTime)plant.LAST_UPD_DT, SessionManager.UserContext.TimeZoneID), "d", false);
            // Label lblLastUpdateDate = (Label)hfBase.FindControl("lblPlantLastUpdateDate"); lblLastUpdateDate.Text = WebSiteCommon.LocalTime((DateTime)plant.LAST_UPD_DT, SessionManager.UserContext.TimeZoneID).ToString();

            LoadPlantSelects(plant);

            if (plant.ADDRESS != null)
            {
                ADDRESS address = plant.ADDRESS.FirstOrDefault();
                if (address != null)
                {
                    tbAddress1.Text = address.STREET1;
                    tbAddress2.Text = address.STREET2;
                    tbCity.Text     = address.CITY;
                    tbState.Text    = address.STATE_PROV;
                    tbPostal.Text   = address.POSTAL_CODE;
                }
            }

            LocalOrg().EditObject = plant;
        }
예제 #5
0
        private void FillMetersForModel(TownUtilityBillSystemV2Entities context, ADDRESS addressDB)
        {
            var metersDB = context.METERs.Where(m => m.ADDRESS_ID == addressDB.ID).ToList();

            foreach (var m in metersDB)
            {
                var meterTypeDB = context.METER_TYPEs.Where(mt => mt.ID == m.METER_TYPE_ID).FirstOrDefault();

                var utilityDB = context.UTILITYs.Where(u => u.ID == meterTypeDB.UTILITY_ID).FirstOrDefault();

                var utility = new Utility()
                {
                    Id = utilityDB.ID, Name = utilityDB.NAME
                };

                var meterType = new MeterType()
                {
                    Id = meterTypeDB.ID, Name = meterTypeDB.NAME, Utility = utility
                };

                Meters.Add(new Meter()
                {
                    Id = m.ID, SerialNumber = m.SERIAL_NUMBER, ReleaseDate = m.RELEASE_DATE, VarificationDate = m.VARIFICATION_DATE, MeterType = meterType
                });
            }
        }
        public ADDRESS GetAddress()
        {
            ADDRESS addr = new ADDRESS();

            addr.Address1  = txtAddress.Text;
            addr.Name      = txtName.Text;
            addr.Location  = txtLocation.Text;
            addr.PostCode  = txtPostal.Text;
            addr.Telephone = txtTel.Text;

            if (ddlAddrType.SelectedValue != "-1")
            {
                addr.TypeID = Int32.Parse(ddlAddrType.SelectedValue);
            }

            if (ddlCities.SelectedValue != "-1")
            {
                addr.City     = Int32.Parse(ddlCities.SelectedValue);
                addr.CityName = ddlCities.SelectedItem.Text;
            }

            if (CustomerID != 0)
            {
                addr.CustomerID = CustomerID;
            }

            return(addr);
        }
예제 #7
0
 public static string InsertStore(string userid, string longitude, string latitude, string storeName, string phone, string street_number, string route, string city, string state, string postal_code, string country, string price, string website, string description)
 {
     try
     {
         if (string.IsNullOrEmpty(longitude) || string.IsNullOrEmpty(latitude) || string.IsNullOrEmpty(street_number) || string.IsNullOrEmpty(route) || string.IsNullOrEmpty(city) || string.IsNullOrEmpty(state) || string.IsNullOrEmpty(postal_code) || string.IsNullOrEmpty(country))
         {
             return Strings.StoreAlert_Location;
         }
         if (string.IsNullOrEmpty(storeName) || string.IsNullOrEmpty(phone) || string.IsNullOrEmpty(price))
         {
             return Strings.StoreAlert_Info;
         }
         LOCATION location = mydb.LOCATIONs.SingleOrDefault(l => l.LATITUDE == Convert.ToDouble(latitude) && l.LONGITUDE == Convert.ToDouble(longitude));
         if (location == null)
         {
             location = new LOCATION() { LONGITUDE = Convert.ToDouble(longitude), LATITUDE = Convert.ToDouble(latitude) };
             mydb.LOCATIONs.InsertOnSubmit(location);
         }
         ADDRESS address = mydb.ADDRESSes.SingleOrDefault(a => a.ADDRESS_LINE1 == street_number + " " + route && a.CITY == city && a.STATE_PROVINCE_REGION == state && a.POSTAL_CODE == postal_code && a.COUNTRY == country);
         if (address == null)
         {
             address = new ADDRESS() { ADDRESS_LINE1 = street_number + " " + route, CITY = city, STATE_PROVINCE_REGION = state, POSTAL_CODE = postal_code, COUNTRY = country };
             mydb.ADDRESSes.InsertOnSubmit(address);
         }
         STORE store = new STORE() { NAME = storeName, DESCRIPTION = description, PHONE = phone, WEBSITE = website, OWNER = userid, PRICE_LEVEL = Convert.ToInt32(price) };
         store.LOCATION = location;
         store.ADDRESS = address;
         mydb.SubmitChanges();
         return Strings.StoreAlert_Success;
     }
     catch (Exception e)
     {
         return e.Message;
     }
 }
예제 #8
0
        public static RadComboBox SetPlantList(RadComboBox ddl, List <PLANT> plantList, decimal plantID)
        {
            ddl.Items.Clear();
            RadComboBoxItem item    = null;
            ADDRESS         address = null;

            foreach (PLANT plant in plantList.OrderBy(l => l.BUS_ORG_ID).ThenBy(l => l.PLANT_NAME).ToList())
            {
                item = new RadComboBoxItem(plant.PLANT_NAME, plant.PLANT_ID.ToString());
                if ((address = plant.ADDRESS.FirstOrDefault()) != null)
                {
                    item.ToolTip = address.STREET1 + " " + address.CITY;
                }
                if (plantID < 0)
                {
                    item.Checked = true;
                }
                ddl.Items.Add(item);
            }
            //ddl.Items.Insert(0, new RadComboBoxItem("", ""));

            if (plantID > 0 && ddl.Items.FindItemByValue(plantID.ToString()) != null)
            {
                ddl.SelectedValue = plantID.ToString();
            }

            return(ddl);
        }
예제 #9
0
        /// <summary>
        /// Writes the address.
        /// </summary>
        /// <param name="orderDettId">The order dett id.</param>
        /// <param name="phOrd">The ph ord.</param>
        /// <param name="miniTitlesFontStyleIns">The mini titles font style ins.</param>
        private static void WriteAddress(int?orderDettId, ref Phrase phOrd, Font miniTitlesFontStyleIns)
        {
            if (orderDettId.HasValue)
            {
                var addressShipp = new ADDRESS(ApplicationContext.Current.Orders.GetAddress(orderDettId.Value));
                {
                    string addSh = string.Format(
                        @"{0}
{1}
{2}
{3}
{4}
{5}", addressShipp.Name,
                        addressShipp.Address1,
                        addressShipp.Location,
                        addressShipp.PostCode,
                        addressShipp.StateName,
                        addressShipp.Telephone);
                    phOrd = new Phrase(addSh, miniTitlesFontStyleIns);
                }
            }
            else
            {
                phOrd = new Phrase(" ", miniTitlesFontStyleIns);
            }
        }
예제 #10
0
        public ActionResult AddAddress(ADDRESS aDDRESS)
        {
            string user_id = Session["user_id"].ToString();

            db.ADDRESS.Add(aDDRESS);
            db.SaveChanges();

            return(Redirect("~/Address/index?id=" + user_id));
        }
예제 #11
0
 //Delete address
 public void DeleteAddress(int[] addrIds)
 {
     foreach (int i in addrIds)
     {
         ADDRESS temp = db.ADDRESS.Find(i);
         db.ADDRESS.Remove(temp);
     }
     db.SaveChanges();
 }
예제 #12
0
        public void DeleteAddressById(int id)
        {
            var obj = new ADDRESS()
            {
                ID = id
            };

            DeleteAddress(obj);
        }
        public void Save(bool fromPage)
        {
            if (IsValid())
            {
                ADDRESS addr = GetAddress();

                string operation = String.Empty;
                try
                {
                    // not a new address
                    if (AddrID != 0)
                    {
                        addr.ID = AddrID;
                        if (!DisableOriginal)
                        {
                            ApplicationContext.Current.Customers.UpdateAddress(addr);
                        }
                        else
                        {
                            ADDRESSINFO addrInfo = new ADDRESSINFO(addr);
                            ApplicationContext.Current.Orders.UpdateAddress(addrInfo);
                        }

                        operation = "updated";
                    }
                    else
                    {
                        ApplicationContext.Current.Customers.InsertAddress(addr);
                        operation = "inserted";
                        AddrID    = addr.ID;
                    }
                    loadAddress(addr);

                    if (!InOrder)
                    {
                        lnkDelAddr.Visible   = true;
                        imgDelete.Visible    = true;
                        imgSeparator.Visible = true;
                    }
                    if (Saving != null)
                    {
                        Saving(null, null);
                    }
                    ChangeSelectedPanel(0);
                }
                catch (Exception ex)
                {
                    BasePage.Log(ex, ex.Message, ex.StackTrace, "CustomerAddressControl.Save");
                    writeError(ex.Message);
                }
            }
            else
            {
                Page.Validate(UniqueValidationGroup);
            }
        }
예제 #14
0
        protected void lnkPlantView_Click(object sender, EventArgs e)
        {
            PLANT plant = (PLANT)SessionManager.EffLocation.Plant;

            TextBox tbPlantName    = (TextBox)hfBase.FindControl("tbPlantName"); tbPlantName.Text = plant.PLANT_NAME;
            TextBox tbPlantDesc    = (TextBox)hfBase.FindControl("tbPlantDesc"); tbPlantDesc.Text = plant.DISP_PLANT_NAME;
            TextBox tbPlantLocCode = (TextBox)hfBase.FindControl("tbPlantLocCode"); tbPlantLocCode.Text = plant.DUNS_CODE;
            TextBox tbAltPlantCode = (TextBox)hfBase.FindControl("tbAltPlantCode"); tbAltPlantCode.Text = plant.ALT_DUNS_CODE;

            cbTrackFinData.Checked = (bool)plant.TRACK_FIN_DATA;
            cbTrackEWData.Checked  = (bool)plant.TRACK_EW_DATA;
            Label lblLastUpdate = (Label)hfBase.FindControl("lblPlantLastUpdate"); lblLastUpdate.Text = plant.LAST_UPD_BY;

            lblPlantLastUpdateDate.Text = SQMBasePage.FormatDate(WebSiteCommon.LocalTime((DateTime)plant.LAST_UPD_DT, SessionManager.UserContext.TimeZoneID), "d", false);
            // Label lblLastUpdateDate = (Label)hfBase.FindControl("lblPlantLastUpdateDate"); lblLastUpdateDate.Text = WebSiteCommon.LocalTime((DateTime)plant.LAST_UPD_DT, SessionManager.UserContext.TimeZoneID).ToString();

            LoadPlantSelects(plant);

            if (plant.ADDRESS != null)
            {
                ADDRESS address = plant.ADDRESS.FirstOrDefault();
                if (address != null)
                {
                    tbAddress1.Text = address.STREET1;
                    tbAddress2.Text = address.STREET2;
                    tbCity.Text     = address.CITY;
                    tbState.Text    = address.STATE_PROV;
                    tbPostal.Text   = address.POSTAL_CODE;
                }
            }

            int[] recList = new int[5] {
                30, 40, 45, 50, 90
            };
            PLANT_ACTIVE        pa = null;
            List <PLANT_ACTIVE> plantActiveList = new List <PLANT_ACTIVE>();

            foreach (int recType in recList)
            {
                PLANT_ACTIVE plantActive = new PLANT_ACTIVE();
                plantActive.PLANT_ID     = plant.PLANT_ID;
                plantActive.RECORD_TYPE  = recType;
                plantActive.ENABLE_EMAIL = true;
                if ((pa = plant.PLANT_ACTIVE.Where(p => p.RECORD_TYPE == recType).FirstOrDefault()) != null)
                {
                    plantActive.EFF_START_DATE       = pa.EFF_START_DATE;
                    plantActive.EFF_END_DATE         = pa.EFF_END_DATE;
                    plantActive.ENABLE_EMAIL         = pa.ENABLE_EMAIL;
                    plantActive.ENABLE_INACTIVE_HIST = pa.ENABLE_INACTIVE_HIST;
                }
                plantActiveList.Add(plantActive);
            }
            BindPlantActive(plantActiveList);

            LocalOrg().EditObject = plant;
        }
예제 #15
0
 public ActionResult AddAddress(ADDRESS model)
 {
     if (ModelState.IsValid)
     {
         _db.ADDRESSes.Add(model);
         _db.SaveChanges();
         Session["ID"] = Convert.ToInt32(model.AddressId);
         return(RedirectToAction("AddSeller", "AdminHome"));
     }
     return(View(model));
 }
예제 #16
0
        public IHttpActionResult GetADDRESS(short id)
        {
            ADDRESS aDDRESS = db.ADDRESSES.Find(id);

            if (aDDRESS == null)
            {
                return(NotFound());
            }

            return(Ok(aDDRESS));
        }
예제 #17
0
        //public int Get(ADDRESS pot = ADDRESS.POT_0)
        //{
        //    try
        //    {
        //        this._spiEngine.Select();

        //        int result     = -1;
        //        var cmd        = build_command(pot, COMMAND.READ);
        //        var r          = _spiEngine.Transfer(cmd);
        //        var b0         = r.ReadBuffer[0];
        //        bool valid     = WinUtil.BitUtil.IsSet(b0, CMDERR_MASK);

        //        if (valid)
        //        {
        //            var dataByte = build_data(0);
        //            var r2  = _spiEngine.Transfer(dataByte);
        //            result  = r2.ReadBuffer[0];
        //        }
        //        return result;
        //    }
        //    finally {
        //        this._spiEngine.Unselect();
        //    }
        //}

        public int Get(ADDRESS pot = ADDRESS.POT_0)
        {
            try {
                this._spiEngine.Select();
                var r = new SPIResult();
                r = Transfer(pot, COMMAND.READ, 0);
                return(r.Succeeded ? r.Value : -1);
            }
            finally {
                this._spiEngine.Unselect();
            }
        }
예제 #18
0
        public IHttpActionResult PostADDRESS(ADDRESS aDDRESS)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.ADDRESSES.Add(aDDRESS);
            db.SaveChanges();

            return(CreatedAtRoute("DefaultApi", new { id = aDDRESS.ADDRESS_ID }, aDDRESS));
        }
예제 #19
0
        public static RadMenu SetLocationList(RadMenu mnu, List <BusinessLocation> locationList, decimal plantID, string topLabel, string topValue, bool enableBUSelect)
        {
            ADDRESS address = null;
            int     numOrgs = locationList.Select(l => l.Plant.BUS_ORG_ID).Distinct().Count();

            Telerik.Web.UI.RadMenuItem miTop = new Telerik.Web.UI.RadMenuItem();
            miTop.Text      = topLabel;
            miTop.Value     = "TOP";
            miTop.Font.Bold = true;
            mnu.Items.Add(miTop);

            decimal busOrgID = 0;

            Telerik.Web.UI.RadMenuItem miBU = null;
            foreach (BusinessLocation loc in locationList.OrderBy(l => l.Plant.BUS_ORG_ID).ThenBy(l => l.Plant.PLANT_NAME).ToList())
            {
                if (loc.Plant.BUS_ORG_ID != busOrgID)
                {
                    if (miBU != null)
                    {
                        miTop.Items.Add(miBU);
                    }
                    busOrgID      = (decimal)loc.Plant.BUS_ORG_ID;
                    miBU          = new Telerik.Web.UI.RadMenuItem();
                    miBU.ImageUrl = "~/images/defaulticon/16x16/sitemap.png";
                    miBU.Text     = loc.BusinessOrg.ORG_NAME; miBU.Value = "BU" + loc.BusinessOrg.BUS_ORG_ID.ToString();
                    if (!enableBUSelect)
                    {
                        ; // how to disable selecting ??
                    }
                }
                Telerik.Web.UI.RadMenuItem miLoc = new Telerik.Web.UI.RadMenuItem();
                miLoc.Text  = loc.Plant.PLANT_NAME;
                miLoc.Value = loc.Plant.PLANT_ID.ToString();
                if ((address = loc.Plant.ADDRESS.FirstOrDefault()) != null)
                {
                    miLoc.ToolTip = address.STREET1 + " " + address.CITY;
                }
                miBU.Items.Add(miLoc);
                if (plantID > 0 && plantID.ToString() == miLoc.Value)  // is default plant
                {
                    miLoc.Selected    = true;
                    mnu.Items[0].Text = miLoc.Text;
                }
            }
            if (miBU != null)
            {
                miTop.Items.Add(miBU);
            }

            return(mnu);
        }
예제 #20
0
        public IHttpActionResult DeleteADDRESS(short id)
        {
            ADDRESS aDDRESS = db.ADDRESSES.Find(id);

            if (aDDRESS == null)
            {
                return(NotFound());
            }

            db.ADDRESSES.Remove(aDDRESS);
            db.SaveChanges();

            return(Ok(aDDRESS));
        }
예제 #21
0
        public bool ValidateOperation(SPIResult result, ADDRESS address, COMMAND command, int?value = null)
        {
            // We cannot read an answer from the MCP4131. MISO and MOSI pins are combined
            // and we cannot make it work. So always return true
            if (this.GetType().Name == "MCP4131")
            {
                return(true);
            }

            var r = false;

            // See datasheet http://exploringarduino.com/wp-content/uploads/2013/06/MCP4231-datasheet.pdf
            // Page 48
            //   Value Function MOSI (SDI pin) MISO (SDO pin) (2)
            //   00h Volatile Wiper 0 Write Data nn nnnn nnnn 0000 00nn nnnn nnnn 1111 1111 1111 1111
            //   Read Data nn nnnn nnnn 0000 11nn nnnn nnnn 1111 111n nnnn nnnn
            //   Increment Wiper — 0000 0100 1111 1111
            //   Decrement Wiper — 0000 1000 1111 1111
            //   01h Volatile Wiper 1 Write Data nn nnnn nnnn 0001 00nn nnnn nnnn 1111 1111 1111 1111
            //   Read Data nn nnnn nnnn 0001 11nn nnnn nnnn 1111 111n nnnn nnnn
            //   Increment Wiper — 0001 0100 1111 1111
            //   Decrement Wiper — 0001 1000 1111 1111
            //   02h Reserved — — — —
            //   03h Reserved — — — —
            //   04h Volatile
            //   TCON Register
            //   Write Data nn nnnn nnnn 0100 00nn nnnn nnnn 1111 1111 1111 1111
            //   Read Data nn nnnn nnnn 0100 11nn nnnn nnnn 1111 111n nnnn nnnn
            //   05h Status Register Read Data nn nnnn nnnn 0101 11nn nnnn nnnn 1111 111n nnnn nnnn
            //   06h-0Fh Reserved — — — —
            //   Note 1: The Data Memory is only 9-bits wide, so the MSb is ignored by the device.
            //   2: All these Address/Command combinations are valid, so the CMDERR bit is s
            switch (command)
            {
            case COMMAND.WRITE: r = (result.Buffer.Count == 2) && (result.Buffer[0] == 255) && result.Buffer[1] == 255; break;

            case COMMAND.DECREMENT:
            case COMMAND.INCREMENT: r = (result.Buffer.Count == 1) && (result.Buffer[0] == 255); break;

            case COMMAND.READ:
                r = (result.Buffer.Count == 2) && (result.Buffer[0] >= 254);
                if (r)
                {
                    result.Value = result.Buffer[1];
                }
                break;
            }
            return(r);
        }
        private void loadAddress(ADDRESS addr)
        {
            txtAddress.Text  = addr.Address1;
            txtLocation.Text = addr.Location;
            txtName.Text     = addr.Name;
            txtPostal.Text   = addr.PostCode;
            txtTel.Text      = addr.Telephone;

            litName.Text = addr.Name;
            if (!String.IsNullOrWhiteSpace(addr.Telephone))
            {
                litTel.Text = " Tel: " + addr.Telephone + "<br />";
            }
            litAddress.Text = addr.Address1;
            litOther.Text   = addr.Location + ", " + (addr.CityName == null ? ddlCities.SelectedItem.Text : addr.CityName) + ", " + addr.PostCode;
        }
예제 #23
0
        public ActionResult DeleteConfirmed(long id)
        {
            SELLER seller = db.SELLERs.Find(id);

            while (true) //To delete the product related to the seller
            {
                var product = db.PRODUCTs.Where(p => p.ProductSellerId == seller.SellerId).FirstOrDefault();
                if (product == null)
                {
                    break;
                }
                //return Redirect("/AdminProductView/Delete/" + product.ProductId);
                PRODUCTDESCRIPTION productDescrption = db.PRODUCTDESCRIPTIONs.Where(d => d.ProductId == product.ProductId).FirstOrDefault();
                if (productDescrption != null)
                {
                    db.PRODUCTDESCRIPTIONs.Remove(productDescrption);
                }

                while (true)
                {
                    PRODUCTPICTURE productPicture = db.PRODUCTPICTUREs.Where(d => d.ProductId == product.ProductId).FirstOrDefault();
                    if (productPicture == null)
                    {
                        break;
                    }
                    db.PRODUCTPICTUREs.Remove(productPicture);
                    db.SaveChanges();
                }
                db.PRODUCTs.Remove(product);
                db.SaveChanges();
                //finish
            }

            var count = db.SELLERs.Where(a => a.SellerAddressId == seller.SellerAddressId).Count(); //To check if the multiple seller beelong to that address

            if (count == 1)                                                                         //if only on seller belong to that address  then delete the address with the seller
            {
                ADDRESS address = db.ADDRESSes.Where(a => a.AddressId == seller.SellerAddressId).FirstOrDefault();
                db.ADDRESSes.Remove(address);
            }
            db.SELLERs.Remove(seller);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
예제 #24
0
        private void Create_Click(object sender, RoutedEventArgs e)
        {
            USERS User = new USERS()
            {
                LOGIN = "******", PASSWORD = "******"
            };

            ADDRESS Adress = new ADDRESS()
            {
                CITY    = "Минск",
                FLAT    = 33,
                HOUSE   = "2",
                HOUSING = "-",
                STREET  = "Яна Чечота",
                STATE   = "Беларусь"
            };

            CLIENTS Client = new CLIENTS()
            {
                FIRSTNAME   = "Настя",
                FATHERSNAME = "Павловна",
                BDAY        = DateTime.Now,
                GENDER      = "ж",
                PHONE       = "37544429181",
                ID_PASSPORT = "2131231231231",
                SURNAME     = "Стальмашенко",
                ADDRESS     = Adress,
            };

            Client.USERS.Add(User);
            //BALANCE Bal = new BALANCE()
            //{
            //    Bal
            //}
            using (Context db = new Context())
            {
                db.CLIENTS.Add(Client);
                db.SaveChanges();
            }
            Close();
            workplace work = new workplace();

            work.ShowDialog();
        }
        public void ReloadControl(bool PageLoad)
        {
            ADDRESS addr = null;

            if (AddrID != 0)
            {
                if (!DisableOriginal)
                {
                    addr = ApplicationContext.Current.Customers.GetAddressById(AddrID);
                }
                else
                {
                    ADDRESSINFO a = ApplicationContext.Current.Orders.GetAddress(AddrID);
                    addr = new ADDRESS(a);
                }

                loadAddress(addr);
                if (!InOrder)
                {
                    lnkDelAddr.Visible   = true;
                    imgDelete.Visible    = true;
                    imgSeparator.Visible = true;
                }
            }

            if (PageLoad)
            {
                // viewstate of dropdown is enabled, so there is no need to reload it on every postback
                LoadDDLs(addr == null ? null : addr.City, addr == null ? null : addr.TypeID);
            }
            else
            {
                // ddl already loaded, the values must be re-set
                if (addr != null && addr.City.HasValue)
                {
                    ddlCities.SelectedValue = addr.City.Value.ToString();
                }

                if (addr != null && addr.TypeID.HasValue)
                {
                    ddlAddrType.SelectedValue = addr.TypeID.Value.ToString();
                }
            }
        }
예제 #26
0
        public static List <ADDRESS> getLista(int idUser)
        {
            string sql = "SELECT idAddress, address FROM ADDRESS WHERE idUser = " + idUser;

            DataTable      dt   = ConnectionDB.ExecuteQuery(sql);
            List <ADDRESS> list = new List <ADDRESS>();

            foreach (DataRow row in dt.Rows)
            {
                ADDRESS ad = new ADDRESS();
                ad.idAddress = Convert.ToInt32(row[0].ToString());
                ad.address   = row[1].ToString();
                ad.idUser    = idUser;

                list.Add(ad);
            }

            return(list);
        }
예제 #27
0
        public static List <ADDRESS> getLista()
        {
            string sql = "select * from ADDRESS";

            DataTable dt = ConexionBD.ExecuteQuery(sql);

            List <ADDRESS> lista = new List <ADDRESS>();

            foreach (DataRow fila in dt.Rows)
            {
                ADDRESS u = new ADDRESS();
                u.idaddress = Convert.ToInt32(fila[0].ToString());
                u.iduser    = Convert.ToInt32(fila[1].ToString());
                u.address   = fila[2].ToString();

                lista.Add(u);
            }
            return(lista);
        }
예제 #28
0
        public void CanSetNextStatementMatchingPc()
        {
            const ulong  ADDRESS    = 0xdeadbeef;
            const string NAME       = "test";
            var          threadId   = 1u;
            var          mockThread = Substitute.For <RemoteThread>();

            mockThread.GetThreadId().Returns(threadId);
            var    mockStackFrame = Substitute.For <IDebugStackFrame2>();
            string name;

            mockStackFrame.GetName(out name).Returns(x =>
            {
                x[0] = NAME;
                return(VSConstants.S_OK);
            });
            IDebugThread2 outThread;
            IDebugThread  thread = CreateDebugThread <IDebugThread>(mockThread);

            mockStackFrame.GetThread(out outThread).Returns(x =>
            {
                x[0] = thread;
                return(VSConstants.S_OK);
            });
            var mockCodeContext = Substitute.For <IDebugCodeContext2>();

            mockCodeContext
            .GetInfo(enum_CONTEXT_INFO_FIELDS.CIF_ADDRESS |
                     enum_CONTEXT_INFO_FIELDS.CIF_FUNCTION,
                     Arg.Do <CONTEXT_INFO[]>(infos =>
            {
                infos[0].bstrAddress  = "0x" + ADDRESS.ToString("x16");
                infos[0].bstrFunction = NAME;
            }))
            .Returns(VSConstants.S_OK);
            var mockFrame = Substitute.For <RemoteFrame>();

            mockFrame.GetPC().Returns(ADDRESS);
            mockThread.GetFrameAtIndex(0).Returns(mockFrame);
            Assert.AreEqual(VSConstants.S_OK,
                            thread.CanSetNextStatement(mockStackFrame, mockCodeContext));
        }
예제 #29
0
        public static List <ADDRESS> GetListaDAd(int iduser)
        {
            string sql = String.Format(
                "select * from address where iduser= {0};",
                iduser);

            DataTable dt = ConexionBD.ExecuteQuery(sql);

            List <ADDRESS> lista = new List <ADDRESS>();

            foreach (DataRow fila in dt.Rows)
            {
                ADDRESS u = new ADDRESS();
                u.idaddress = Convert.ToInt32(fila[0].ToString());
                u.iduser    = Convert.ToInt32(fila[1].ToString());
                u.address   = fila[2].ToString();

                lista.Add(u);
            }
            return(lista);
        }
예제 #30
0
        public SPIResult Decrement(int times = 1, ADDRESS pot = ADDRESS.POT_0)
        {
            var r = new SPIResult();

            if (times > 1)
            {
                for (var i = 0; i < times; i++)
                {
                    r = this.Decrement(1);
                }
            }
            else
            {
                if (this.DigitalValue > this.MinDigitalValue)
                {
                    this.DigitalValue--;
                    this.Transfer(pot, COMMAND.DECREMENT);
                }
            }
            return(r);
        }
예제 #31
0
        private SPIResult Transfer(ADDRESS address, COMMAND command, int?value = null)
        {
            var l = new List <byte>();

            if (value.HasValue)
            {
                l.Add(build_command(address, command));
                l.Add(((byte)(value & DATA_MASK_WORD)));
            }
            else
            {
                l.Add(build_command(address, command));
            }
            var r = _spiEngine.Transfer(l);

            if (r.Succeeded)
            {
                r.Succeeded = this.ValidateOperation(r, address, command, value);
            }
            return(r);
        }
예제 #32
0
 ADDRESS GetAddressByName(string pName,
     bool bNoTypeOK /* = false */)
 {
     var Val = new SymValue ();
     bool bSuccess = ValueByName(pName, ref Val, bNoTypeOK);
     if (bSuccess)
     {
         m_iLastSize = Val.iSymSize;
         m_uLastAddr = Val.uSymAddr;
         return Val.uSymAddr;
     }
     else return NO_ADDRESS;
 }
예제 #33
0
 // Note: this function overrides a simple "return 0" function in the base class (i.e. BinaryFile::SymbolByAddress())
 string SymbolByAddress(ADDRESS dwAddr)
 {
     string sym;
     if (m_SymTab.TryGetValue(dwAddr, out sym))
         return sym;
     return null;
 }
예제 #34
0
        // FIXME: this function is way off the rails. It seems to always overwrite the relocation entry with the 32 bit value
        // from the symbol table. Totally invalid for SPARC, and most X86 relocations!
        // So currently not called
        private void AddRelocsAsSyms(int relSecIdx)
        {
#if NYI
            SectionInfo pSect = m_pSections[relSecIdx];
            if (pSect == null) return;
            // Calc number of relocations
            int nRelocs = pSect.uSectionSize / pSect.uSectionEntrySize;
            m_pReloc = (Elf32_Rel)pSect.uHostAddr; // Pointer to symbols
            int symSecIdx = m_sh_link[relSecIdx];
            int strSecIdx = m_sh_link[symSecIdx];

            // Index 0 is a dummy entry
            for (int i = 1; i < nRelocs; i++)
            {
                ADDRESS val = (ADDRESS)elfRead4((int*)&m_pReloc[i].r_offset);
                int symIndex = elfRead4(&m_pReloc[i].r_info) >> 8;
                int flags = elfRead4(&m_pReloc[i].r_info);
                if ((flags & 0xFF) == R_386_32)
                {
                    // Lookup the value of the symbol table entry
                    ADDRESS a = elfRead4((int*)&m_pSym[symIndex].st_value);
                    if (m_pSym[symIndex].st_info & STT_SECTION)
                        a = GetSectionInfo(elfRead2(&m_pSym[symIndex].st_shndx))->uNativeAddr;
                    // Overwrite the relocation value... ?
                    writeNative4(val, a);
                    continue;
                }
                if ((flags & R_386_PC32) == 0)
                    continue;
                if (symIndex == 0) /* Silly symbols with no names */ continue;
                string str = GetStrPtr(strSecIdx, elfRead4(&m_pSym[symIndex].st_name));
                // Hack off the "@@GLIBC_2.0" of Linux, if present
                uint pos;
                if ((pos = str.IndexOf("@@")) >= 0)
                    str = str.Remove(pos);
                // Linear search!
                foreach (var it in m_SymTab)
                    if (it.Value == str)
                        break;
                if (!m_SymTab.ContainsValue(str))
                {
                // Add new extern
                    m_SymTab[next_extern] = str;
                    it = m_SymTab.find(next_extern);
                    next_extern += 4;
                }
                writeNative4(val, (*it).first - val - 4);
            }
            return;
#endif
        }
예제 #35
0
        // Like a replacement for elf_strptr()
 

        // Search the .rel[a].plt section for an entry with symbol table index i.
        // If found, return the native address of the associated PLT entry.
        // A linear search will be needed. However, starting at offset i and searching backwards with wraparound should
        // typically minimise the number of entries to search
        ADDRESS findRelPltOffset(uint i, ADDRESS addrRelPlt, uint sizeRelPlt, uint numRelPlt, ADDRESS addrPlt)
        {
            uint first = i;
            if (first >= numRelPlt)
                first = numRelPlt - 1;
            uint curr = first;
            do
            {
                // Each entry is sizeRelPlt bytes, and will contain the offset, then the info (addend optionally follows)
                var pEntry = CreateImageReader(addrRelPlt + (curr * sizeRelPlt));
                pEntry.ReadInt32();
                int entry = pEntry.ReadInt32(); // Read pEntry[1]
                int sym = entry >> 8; // The symbol index is in the top 24 bits (Elf32 only)
                if (sym == i)
                {
                    // Found! Now we want the native address of the associated PLT entry.
                    // For now, assume a size of 0x10 for each PLT entry, and assume that each entry in the .rel.plt section
                    // corresponds exactly to an entry in the .plt (except there is one dummy .plt entry)
                    return addrPlt + 0x10u * (curr + 1);
                }
                if (--curr < 0)
                    curr = numRelPlt - 1;
            } while (curr != first); // Will eventually wrap around to first if not present
            return 0; // Exit if this happens
        }
예제 #36
0
        /*==============================================================================
         * FUNCTION:	  ElfBinaryFile::GetImportStubs
         * OVERVIEW:	  Get an array of addresses of imported function stubs
         *					This function relies on the fact that the symbols are sorted by address, and that Elf PLT
         *					entries have successive addresses beginning soon after m_PltMin
         * PARAMETERS:	  numImports - reference to integer set to the number of these
         * RETURNS:		  An array of native ADDRESSes
         *============================================================================*/
        ADDRESS GetImportStubs(out int numImports)
        {
            int n = 0;
#if NYI
            ADDRESS a = m_uPltMin;
            std_map<ADDRESS, string>.iterator aa = m_SymTab.find(a);
            std_map<ADDRESS, string>.iterator ff = aa;
            bool delDummy = false;
            if (aa == m_SymTab.end())
            {
                // Need to insert a dummy entry at m_uPltMin
                delDummy = true;
                m_SymTab[a] = "";
                ff = m_SymTab.find(a);
                aa = ff;
                aa++;
            }
            while ((aa != m_SymTab.end()) && (a < m_uPltMax))
            {
                n++;
                a = aa.first;
                aa++;
            }
            // Allocate an array of ADDRESSESes
            m_pImportStubs = new ADDRESS[n];
            aa = ff; // Start at first
            a = aa.first;
            int i = 0;
            while ((aa != m_SymTab.end()) && (a < m_uPltMax))
            {
                m_pImportStubs[i++] = a;
                a = aa.first;
                aa++;
            }
            if (delDummy)
                m_SymTab.erase(ff); // Delete dummy entry
#endif
            numImports = n;
            return 0; //m_pImportStubs[];
        }
예제 #37
0
        public MadeInTheUSB.spi.SPIEngine.SPIResult Decrement(int times = 1, ADDRESS pot = ADDRESS.POT_0)
        {
            var r = new MadeInTheUSB.spi.SPIEngine.SPIResult();
            if (times > 1) {

                for (var i = 0; i < times; i++)
                {
                    r = this.Decrement(1);
                }
            }
            else { 
                if(this.DigitalValue > this.MinDigitalValue )
                {
                    this.DigitalValue--;
                    this.Transfer(pot, COMMAND.DECREMENT);
                }
            }
            return r;
        }
예제 #38
0
 // FIXME: the below assumes a fixed delta
 ADDRESS NativeToHostAddress(ADDRESS uNative)
 {
     if (m_iNumSections == 0) return 0;
     return m_pSections[1].uHostAddr - m_pSections[1].uNativeAddr + uNative;
 }
예제 #39
0
        public MadeInTheUSB.spi.SPIEngine.SPIResult Set(int digitalValue, ADDRESS pot = ADDRESS.POT_0)
        {
            try { 
                this._spiEngine.Select();

                var r = new MadeInTheUSB.spi.SPIEngine.SPIResult();
                if((digitalValue < this.MinDigitalValue)||(digitalValue > this.MaxDigitalValue))
                    return r;
                this.DigitalValue = digitalValue;
                r = Transfer(pot, COMMAND.WRITE, digitalValue);
            
                //// Verify that the command error flag is off
                //var b0         = r.ReadBuffer[0];
                //bool valid     = !WinUtil.BitUtil.IsSet(b0, CMDERR_MASK);
                //r.Succeeded = r.Succeeded && valid;

                return r;
            }
            finally { 
                this._spiEngine.Unselect();
            }
        }
예제 #40
0
        //public int Get(ADDRESS pot = ADDRESS.POT_0)
        //{
        //    try
        //    {
        //        this._spiEngine.Select();

        //        int result     = -1;
        //        var cmd        = build_command(pot, COMMAND.READ);
        //        var r          = _spiEngine.Transfer(cmd);
        //        var b0         = r.ReadBuffer[0];
        //        bool valid     = WinUtil.BitUtil.IsSet(b0, CMDERR_MASK);
            
        //        if (valid)
        //        {
        //            var dataByte = build_data(0);
        //            var r2  = _spiEngine.Transfer(dataByte);
        //            result  = r2.ReadBuffer[0];
        //        }
        //        return result;
        //    }
        //    finally { 
        //        this._spiEngine.Unselect();
        //    }
        //}

        public int Get(ADDRESS pot = ADDRESS.POT_0)
        {
            try { 
                this._spiEngine.Select();
                var r = new MadeInTheUSB.spi.SPIEngine.SPIResult();
                r = Transfer(pot, COMMAND.READ, 0);
                return r.Succeeded ? r.Value : -1;
            }
            finally { 
                this._spiEngine.Unselect();
            }
        }
예제 #41
0
        public static void InsertGoogleStore(string storejson)
        {
            Store s = myConvert.Deserialize<Store>(storejson);
            try
            {
                if (s == null)
                { return; }
                Random r = new Random();
                int i = r.Next(0, 6);
                //string[] users = new string[6] { "gdabli", "harshisame", "nari.dontula", "rungta.sachin", "SiChen", "YongZhuang" };
                string[] users = new string[6] { "Gaurav_Dabli", "Harshita_Gupta", "Harshita_Gupta", "Nari_Dontula", "Nari_Dontula", "Yong_Zhuang" };
                if (mydb.STOREs.SingleOrDefault(ss => ss.PLACE_ID == s.place_id) != null)
                {
                    return;
                }
                //{ "geometry": { "location": { "k": 42.360128, "B": -71.055454 } }, "name": "Cheers", "types": ["cafe", "bar", "restaurant", "food", "establishment"], "vicinity": "1 S Market St, Boston", "html_attributions": [] }
                STORE store = new STORE() { NAME = s.name, PLACE_ID = s.place_id, PRICE_LEVEL = s.price_level, RATING = s.rating, PHONE = s.formatted_phone_number, WEBSITE = s.website, OWNER = users[i], GOOGLE_URL = s.url };
                LOCATION location = new LOCATION() { LATITUDE = s.geometry.location.k, LONGITUDE = s.geometry.location.B };
                mydb.LOCATIONs.InsertOnSubmit(location);
                store.LOCATION = location;
                ADDRESS address = new ADDRESS() { ADDRESS_LINE1 = s.vicinity.Split(',')[0], CITY = s.vicinity.Split(',')[1] };
                if (s.address_components != null)
                {
                    foreach (Address_Components ad in s.address_components)
                    {
                        foreach (string type in ad.types)
                        {
                            switch (type)
                            {
                                case "country":
                                    {
                                        address.COUNTRY = ad.long_name;
                                        break;
                                    }
                                case "postal_code":
                                    {
                                        address.POSTAL_CODE = ad.long_name;
                                        break;
                                    }
                                case "administrative_area_level_1":
                                    {
                                        address.STATE_PROVINCE_REGION = ad.long_name;
                                        break;
                                    }
                            }
                        }
                    }
                }
                mydb.ADDRESSes.InsertOnSubmit(address);
                store.ADDRESS = address;
                if (s.opening_hours != null)
                {
                    foreach (Period period in s.opening_hours.periods)
                    {
                        PERIOD p = new PERIOD() { OPEN_DAY = period.open.day, CLOSE_DAY = period.close.day, OPEN_TIME = Convert.ToDateTime(period.open.hours + ":" + period.open.minutes).TimeOfDay, CLOSE_TIME = Convert.ToDateTime(period.close.hours + ":" + period.close.minutes).TimeOfDay };
                        store.PERIODs.Add(p);
                    }
                }
                if (s.reviews != null)
                {
                    foreach (Review review in s.reviews)
                    {
                        if (string.IsNullOrEmpty(review.author_name) || review.author_name == "A Google User")
                        {
                            continue;
                        }
                        USER user = mydb.USERs.SingleOrDefault(u => u.FIRST_NAME + " " + u.LAST_NAME == review.author_name);
                        if (user == null)
                        {
                            string[] name = review.author_name.Split(' ');
                            if (name.Length > 1)
                            {
                                user = new USER() { FIRST_NAME = name[0], LAST_NAME = name[1], USER_ID = name[0] + "_" + name[1], EMAIL = name[0] + "." + name[1] + "@gmail.com", PASSWORD = "******", ROLE = "0", REGISTER_DATE = DateTime.Now };
                            }
                            else if (name.Length > 0)
                            {
                                user = new USER() { FIRST_NAME = name[0], LAST_NAME = "", USER_ID = name[0], EMAIL = name[0] + "@gmail.com", PASSWORD = "******", ROLE = "0", REGISTER_DATE = DateTime.Now };
                            }
                            mydb.USERs.InsertOnSubmit(user);
                        }
                        if (user != null)
                        {
                            FEEDBACK feed = new FEEDBACK() { COMMENT = review.text, RATING = review.rating  };
                            feed.IS_LIKED = feed.RATING > 2.5 ? 1 : 0;
                            feed.USER = user;
                            feed.STORE = store;
                            mydb.FEEDBACKs.InsertOnSubmit(feed);
                        }
                    }
                }
                if (s.types != null)
                {
                    foreach (string type in s.types)
                    {
                        CATEGORY catergory = mydb.CATEGORies.SingleOrDefault(c => c.NAME == type);
                        if (catergory == null)
                        {
                            catergory = new CATEGORY() { NAME = type, LAYER = 1, PARENT = 0 };
                            mydb.CATEGORies.InsertOnSubmit(catergory);
                        }
                        STORE_CATEGORY s_c = new STORE_CATEGORY();
                        s_c.CATEGORY = catergory;
                        s_c.STORE = store;
                        mydb.STORE_CATEGORies.InsertOnSubmit(s_c);
                    }
                }
                mydb.SubmitChanges();

            }
            catch (Exception e)
            {
                throw e;
            }
        }
예제 #42
0
 public bool ValidateOperation(MadeInTheUSB.spi.SPIEngine.SPIResult result, ADDRESS address, COMMAND command, int? value = null)
 {
     var r = false;
     // See datasheet http://exploringarduino.com/wp-content/uploads/2013/06/MCP4231-datasheet.pdf
     // Page 48
     //   Value Function MOSI (SDI pin) MISO (SDO pin) (2)
     //   00h Volatile Wiper 0 Write Data nn nnnn nnnn 0000 00nn nnnn nnnn 1111 1111 1111 1111
     //   Read Data nn nnnn nnnn 0000 11nn nnnn nnnn 1111 111n nnnn nnnn
     //   Increment Wiper — 0000 0100 1111 1111
     //   Decrement Wiper — 0000 1000 1111 1111
     //   01h Volatile Wiper 1 Write Data nn nnnn nnnn 0001 00nn nnnn nnnn 1111 1111 1111 1111
     //   Read Data nn nnnn nnnn 0001 11nn nnnn nnnn 1111 111n nnnn nnnn
     //   Increment Wiper — 0001 0100 1111 1111
     //   Decrement Wiper — 0001 1000 1111 1111
     //   02h Reserved — — — —
     //   03h Reserved — — — —
     //   04h Volatile
     //   TCON Register
     //   Write Data nn nnnn nnnn 0100 00nn nnnn nnnn 1111 1111 1111 1111
     //   Read Data nn nnnn nnnn 0100 11nn nnnn nnnn 1111 111n nnnn nnnn
     //   05h Status Register Read Data nn nnnn nnnn 0101 11nn nnnn nnnn 1111 111n nnnn nnnn
     //   06h-0Fh Reserved — — — —
     //   Note 1: The Data Memory is only 9-bits wide, so the MSb is ignored by the device.
     //   2: All these Address/Command combinations are valid, so the CMDERR bit is s
     switch (command)
     {
         case COMMAND.WRITE     : r = (result.ReadBuffer.Count == 2) && (result.ReadBuffer[0] == 255) && result.ReadBuffer[1] == 255; break;
         case COMMAND.DECREMENT :
         case COMMAND.INCREMENT : r = (result.ReadBuffer.Count == 1) && (result.ReadBuffer[0] == 255); break;
         case COMMAND.READ      : 
             r = (result.ReadBuffer.Count == 2) && (result.ReadBuffer[0] >= 254); 
             if(r)
                 result.Value = result.ReadBuffer[1];
             break;
     }
     return r;
 }
예제 #43
0
        // A map for extra symbols, those not in the usual Elf symbol tables

        private void AddSymbol(ADDRESS uNative, string pName)
        {
            //m_SymTab[uNative] = pName;
        }
예제 #44
0
 internal Elf32_SHdr GetSectionInfoByAddr(ADDRESS r_offset)
 {
     return
         (from sh in this.SectionHeaders
          where sh.sh_addr <= r_offset && r_offset < sh.sh_addr + sh.sh_size
          select sh)
         .FirstOrDefault();
 }
예제 #45
0
 int GetSizeByName(string pName, bool bNoTypeOK /* = false */)
 {
     SymValue Val = new SymValue();
     bool bSuccess = ValueByName(pName, ref Val, bNoTypeOK);
     if (bSuccess)
     {
         m_iLastSize = Val.iSymSize;
         m_uLastAddr = Val.uSymAddr;
         return Val.iSymSize;
     }
     else return 0;
 }
예제 #46
0
 bool IsDynamicLinkedProc(ADDRESS uNative)
 {
     if (uNative > unchecked((uint)-1024) && uNative != ~0U)
         return true; // Say yes for fake library functions
     if (first_extern <= uNative && uNative < next_extern)
         return true; // Yes for externs (not currently used)
     if (m_uPltMin == 0) return false;
     return (uNative >= m_uPltMin) && (uNative < m_uPltMax); // Yes if a call to the PLT (false otherwise)
 }
예제 #47
0
 byte build_command(ADDRESS address, COMMAND command) 
 {
     var r = ((((int)address) << 4) & ADDRESS_MASK) | ((((int)command) << 2) & COMMAND_MASK) | CMDERR_MASK;
     return (byte)r;
 }
예제 #48
0
 ADDRESS GetRelocatedAddress(ADDRESS uNative)
 {
     // Not implemented yet. But we need the function to make it all link
     return 0;
 }
예제 #49
0
        public override ProgramImage Load(Address addrLoad)
        {
            int i;

            m_lImageSize = RawImage.Length;

            m_pImage = RawImage;
            pHeader = ReadElfHeaderStart();
            arch = GetProcessorArchitecture();
            platform = GetPlatform();

            if (pHeader.e_ident != ELF_MAGIC)   
                throw new BadImageFormatException("Incorrect ELF header.");

            if (pHeader.e_phoff != 0)
                m_pPhdrs = LoadProgramHeaders(pHeader.e_phnum, pHeader.e_phoff);

            if (pHeader.e_shoff != 0)
                m_pShdrs = LoadSectionHeaders(pHeader.e_shnum, pHeader.e_shoff);

            // Set up section header string table pointer
            if (pHeader.e_shstrndx != 0)
                stringTableOffset = m_pShdrs[pHeader.e_shstrndx].sh_offset;

            i = 1; // counter - # sects. Start @ 1, total m_iNumSections

            // Number of sections
            m_iNumSections = pHeader.e_shnum;

            // Allocate room for all the Elf sections (including the silly first one)
            m_pSections = new SectionInfo[m_iNumSections];

            // Set up the m_sh_link and m_sh_info arrays
            m_sh_link = new int[m_iNumSections];
            m_sh_info = new int[m_iNumSections];

            // Number of elf sections
            bool bGotCode = false; // True when have seen a code sect

            Address arbitaryLoadAddr = Address.Ptr32(addrLoad.Linear);
            var rdr = CreateImageReader(pHeader.e_shoff);
            for (i = 0; i < m_iNumSections; i++)
            {
                var pShdr = m_pShdrs[i];
                string pName = ReadAsciiString(m_pShdrs[pHeader.e_shstrndx].sh_offset + pShdr.sh_name);
                var sect = new SectionInfo();
                m_pSections[i] = sect;
                m_pSections[i].pSectionName = pName;
                var off = pShdr.sh_offset;
                if (pShdr.sh_offset != 0)
                    sect.uHostAddr = off;
                sect.uNativeAddr = pShdr.sh_addr;
                sect.uSectionSize = pShdr.sh_size;
                if (sect.uNativeAddr == 0 && pName.StartsWith(".rel"))
                {
                    int align = pShdr.sh_addralign;
                    if (align > 1)
                    {
                        if ((arbitaryLoadAddr.Linear % align) != 0)
                            arbitaryLoadAddr += (int)(align - (arbitaryLoadAddr.Linear % align));
                    }
                    sect.uNativeAddr = arbitaryLoadAddr.Offset;
                    arbitaryLoadAddr += sect.uSectionSize;
                }
                sect.uType = pShdr.sh_type;
                m_sh_link[i] = pShdr.sh_link;
                m_sh_info[i] = pShdr.sh_info;
                sect.uSectionEntrySize = pShdr.sh_entsize;
                if (sect.uNativeAddr + sect.uSectionSize > next_extern)
                    first_extern = next_extern = sect.uNativeAddr + sect.uSectionSize;
                if ((pShdr.sh_flags & SectionFlags.SHF_WRITE) == 0)
                    sect.IsReadOnly = true;
                // Can't use the SHF_ALLOC bit to determine bss section; the bss section has SHF_ALLOC but also SHT_NOBITS.
                // (But many other sections, such as .comment, also have SHT_NOBITS). So for now, just use the name
                //      if ((elfRead4(&pShdr.sh_flags) & SHF_ALLOC) == 0)
                if (pName == ".bss")
                    sect.IsBss = true;
                if ((pShdr.sh_flags & SectionFlags.SHF_EXECINSTR) != 0)
                {
                    sect.IsCode = true;
                    bGotCode = true; // We've got to a code section
                }
                // Deciding what is data and what is not is actually quite tricky but important.
                // For example, it's crucial to flag the .exception_ranges section as data, otherwise there is a "hole" in the
                // allocation map, that means that there is more than one "delta" from a read-only section to a page, and in the
                // end using -C results in a file that looks OK but when run just says "Killed".
                // So we use the Elf designations; it seems that ALLOC.!EXEC -> data
                // But we don't want sections before the .text section, like .interp, .hash, etc etc. Hence bGotCode.
                // NOTE: this ASSUMES that sections appear in a sensible order in the input binary file:
                // junk, code, rodata, data, bss
                if (bGotCode &&
                    (pShdr.sh_flags & (SectionFlags.SHF_EXECINSTR | SectionFlags.SHF_ALLOC)) == SectionFlags.SHF_ALLOC &&
                       pShdr.sh_type != SectionType.SHT_NOBITS)
                    sect.bData = true;
                
                sect.Dump();
                Debug.WriteLine("");

            } // for each section

            // assign arbitary addresses to .rel.* sections too
            for (i = 0; i < m_iNumSections; i++)
            {
                if (m_pSections[i].uNativeAddr == 0 && m_pSections[i].pSectionName.StartsWith(".rel"))
                {
                    m_pSections[i].uNativeAddr = arbitaryLoadAddr.Offset;
                    arbitaryLoadAddr += m_pSections[i].uSectionSize;
                }
            }

            // Add symbol info. Note that some symbols will be in the main table only, and others in the dynamic table only.
            // So the best idea is to add symbols for all sections of the appropriate type
            for (i = 1; i < m_iNumSections; ++i)
            {
                var uType = m_pSections[i].uType;
                if (uType == SectionType.SHT_SYMTAB || uType == SectionType.SHT_DYNSYM)
                    AddSyms(i);
            }

            // Save the relocation to symbol table info
            SectionInfo pRel = GetSectionInfoByName(".rela.text");
            if (pRel != null)
            {
                m_bAddend = true; // Remember its a relA table
                m_pReloc =   (Elf32_Rel*)pRel.uHostAddr; // Save pointer to reloc table
            }
            else
            {
                m_bAddend = false;
                pRel = GetSectionInfoByName(".rel.text");
                if (pRel != null)
                {
                    SetRelocInfo(pRel);
                    m_pReloc = (Elf32_Rel*)pRel.uHostAddr; // Save pointer to reloc table
                }
            }

            // Find the PLT limits. Required for IsDynamicLinkedProc(), e.g.
            SectionInfo pPlt = GetSectionInfoByName(".plt");
            if (pPlt != null)
            {
                m_uPltMin = pPlt.uNativeAddr;
                m_uPltMax = pPlt.uNativeAddr + pPlt.uSectionSize;
            }
            return new ProgramImage(addrLoad, new byte[arbitaryLoadAddr - addrLoad]);
        }
예제 #50
0
        bool IsRelocationAt(ADDRESS uNative)
        {
#if NYI
            //int nextFakeLibAddr = -2;			// See R_386_PC32 below; -1 sometimes used for main
            if (m_pImage == 0) return false; // No file loaded
            int machine = elfRead2(&((Elf32_Ehdr*)m_pImage)->e_machine);
            int e_type = elfRead2(&((Elf32_Ehdr*)m_pImage)->e_type);
            switch (machine)
            {
            case EM_SPARC:
                break; // Not implemented yet
            case EM_386:
                {
                    for (int i = 1; i < m_iNumSections; ++i)
                    {
                        SectionInfo ps = &m_pSections[i];
                        if (ps.uType == SHT_REL)
                        {
                            // A section such as .rel.dyn or .rel.plt (without an addend field).
                            // Each entry has 2 words: r_offet and r_info. The r_offset is just the offset from the beginning
                            // of the section (section given by the section header's sh_info) to the word to be modified.
                            // r_info has the type in the bottom byte, and a symbol table index in the top 3 bytes.
                            // A symbol table offset of 0 (STN_UNDEF) means use value 0. The symbol table involved comes from
                            // the section header's sh_link field.
                            int* pReloc = (int*)ps.uHostAddr;
                            uint size = ps.uSectionSize;
                            // NOTE: the r_offset is different for .o files (E_REL in the e_type header field) than for exe's
                            // and shared objects!
                            ADDRESS destNatOrigin = 0, destHostOrigin;
                            if (e_type == E_REL)
                            {
                                int destSection = m_sh_info[i];
                                destNatOrigin = m_pSections[destSection].uNativeAddr;
                                destHostOrigin = m_pSections[destSection].uHostAddr;
                            }
                            //int symSection = m_sh_link[i];			// Section index for the associated symbol table
                            //int strSection = m_sh_link[symSection];	// Section index for the string section assoc with this
                            //string pStrSection = (char*)m_pSections[strSection].uHostAddr;
                            //Elf32_Sym* symOrigin = (Elf32_Sym*) m_pSections[symSection].uHostAddr;
                            for (uint u = 0; u < size; u += 2 * sizeof(uint))
                            {
                                uint r_offset = elfRead4(pReloc++);
                                //unsigned info	= elfRead4(pReloc);
                                pReloc++;
                                //byte relType = (byte) info;
                                //unsigned symTabIndex = info >> 8;
                                ADDRESS pRelWord; // Pointer to the word to be relocated
                                if (e_type == E_REL)
                                    pRelWord = destNatOrigin + r_offset;
                                else
                                {
                                    if (r_offset == 0) continue;
                                    SectionInfo destSec = GetSectionInfoByAddr(r_offset);
                                    pRelWord = destSec.uNativeAddr + r_offset;
                                    destNatOrigin = 0;
                                }
                                if (uNative == pRelWord)
                                    return true;
                            }
                        }
                    }
                }
            default:
                break; // Not implemented
            }
#endif
            return false;
        }
예제 #51
0
 private MadeInTheUSB.spi.SPIEngine.SPIResult Transfer(ADDRESS address, COMMAND command, int? value = null)
 {
     var l = new List<byte>();
     if(value.HasValue) {
         l.Add(build_command(address, command));
         l.Add(((byte)(value & DATA_MASK_WORD)));  
     }
     else {
         l.Add(build_command(address, command));
     }
     var r = _spiEngine.Transfer(l);
     if(r.Succeeded)
         r.Succeeded = this.ValidateOperation(r, address, command, value);
     return r;
 }
예제 #52
0
        public ElfLoader(IServiceProvider sp, byte[] rawImage)
            : base(sp, rawImage)
        {
            next_extern = 0;
            m_pImage = null;
            m_pPhdrs = null; // No program headers
            m_pShdrs = null; // No section headers
            stringTableOffset = 0; // No strings
            m_pReloc = null;
            m_pSym = null;
            m_uPltMin = 0; // No PLT limits
            m_uPltMax = 0;
            m_iLastSize = 0;
            m_pImportStubs = 0;

            m_SymTab = new Dictionary<ADDRESS, string>();
        }
예제 #53
0
 /// <summary>
 /// Return a 2 byte (16 bits int)
 /// </summary>
 /// <param name="address"></param>
 /// <param name="command"></param>
 /// <param name="data"></param>
 /// <returns></returns>
 ushort build_command(ADDRESS address, COMMAND command, ushort data)
 {
     int i = (build_command(address, command) << 8) | (data & DATA_MASK_WORD);
     return (ushort)i;
 }