Ejemplo n.º 1
0
        public ActionResult PostFeedComment(FormCollection formCollection)
        {
            try
            {
                var comment = formCollection["comment"];
                if (string.IsNullOrWhiteSpace(comment))
                {
                    return(RedirectToAction("Index"));
                }

                comment = comment.TrimStart(',');
                OsbideWebService client = new OsbideWebService();
                Authentication   auth   = new Authentication();
                string           key    = auth.GetAuthenticationKey();
                if (string.IsNullOrEmpty(comment) == false)
                {
                    EventLog log = new EventLog();
                    log.SenderId = CurrentUser.Id;
                    log.LogType  = FeedPostEvent.Name;
                    FeedPostEvent commentEvent = new FeedPostEvent();
                    commentEvent.Comment = comment;
                    log.Data.BinaryData  = EventFactory.ToZippedBinary(commentEvent);
                    log = client.SubmitLog(log, CurrentUser);

                    //find all of this user's subscribers and send them an email
                    List <OsbideUser> observers = new List <OsbideUser>();

                    observers = (from subscription in Db.UserSubscriptions
                                 join user in Db.Users on
                                 new { InstitutionId = subscription.ObserverInstitutionId, SchoolId = subscription.ObserverSchoolId }
                                 equals new { InstitutionId = user.InstitutionId, SchoolId = user.SchoolId }
                                 where subscription.SubjectSchoolId == CurrentUser.SchoolId &&
                                 subscription.SubjectInstitutionId == CurrentUser.InstitutionId &&
                                 user.ReceiveEmailOnNewFeedPost == true
                                 select user).ToList();
                    if (observers.Count > 0)
                    {
                        string url  = StringConstants.GetActivityFeedDetailsUrl(log.Id);
                        string body = "Greetings,<br />{0} posted a new item to the activity feed:<br />\"{1}\"<br />To view this "
                                      + "conversation online, please visit {2} or visit your OSBIDE user profile.<br /><br />Thanks,\nOSBIDE<br /><br />"
                                      + "These automated messages can be turned off by editing your user profile.";
                        body = string.Format(body, CurrentUser.FirstAndLastName, comment, url);
                        List <MailAddress> to = new List <MailAddress>();
                        foreach (OsbideUser user in observers)
                        {
                            to.Add(new MailAddress(user.Email));
                        }
                        Email.Send("[OSBIDE] New Activity Post", body, to);
                    }
                }
            }
            catch (Exception ex)
            {
                LogErrorMessage(ex);
            }

            return(RedirectToAction("Index"));
        }
Ejemplo n.º 2
0
 public static void InitializeSystem()
 {
     if (!isInitialized)
     {
         Strings       = new StringConstants();
         LMS           = new Library();
         isInitialized = true;
         CurrentUser   = new Admin("admin");
     }
 }
Ejemplo n.º 3
0
 private void CheckIfEmpty()
 {
     ContinueBtn.Enabled = CarBrandEt.Text.Length >= 3 &&
                           CarModelEt.Text.Length >= 2 &&
                           CarColorEt.Text.Length >= 3 &&
                           CarYearEt.Text.Length == 4 &&
                           ConditionEt.Text.Length >= 3 &&
                           DriverLicenceEt.EditText.Text.Length >= 3 &&
                           StringConstants.IsCarNumMatch(RegNoEt.EditText.Text);
 }
Ejemplo n.º 4
0
        public void UnicodeCharacterFileParsing()
        {
            StringConstants        constants           = new StringConstants();
            Dictionary <int, char> characterDictionary = constants.GetMapping(RandomUtils.Enums.StringType.AlphaNumeric);

            //Assert.IsTrue(characterDictionary[032] == ' ');
            //Assert.IsTrue(characterDictionary[035] == '#');
            Assert.IsTrue(characterDictionary[048] == '0');
            Assert.IsTrue(characterDictionary[065] == 'A');
            Assert.IsTrue(characterDictionary[097] == 'a');
            //Assert.IsTrue(characterDictionary[414] == 'ƞ');
        }
Ejemplo n.º 5
0
        private CurveFamilyF GenerateAdiabaticSaturationFamily()
        {
            double             dewPoint;
            double             ysat;
            double             wetBulb;
            double             temperature;
            double             ih;
            double             tsat;
            double             maxTemp;
            HumidGasCalculator humidGasCalculator = GetHumidGasCalculator();
            double             p           = (double)pressure.Value;
            double             cg          = humidGasCalculator.GetSpecificHeatOfDryGas();
            double             cv          = humidGasCalculator.GetSpecificHeatOfVapor();
            double             r0          = humidGasCalculator.GetEvaporationHeat(273.15);
            double             dewPoint1   = humidGasCalculator.GetDewPointFromDryBulbAndRelativeHumidity(xVar.Max, 1.0);
            double             dewPoint2   = humidGasCalculator.GetDewPointFromHumidityAndPressure(yVar.Max, p);
            double             dewPointMin = Math.Min(dewPoint1, dewPoint2);
            int numOfCurves = (int)((dewPointMin - xVar.Min) / 5.0) + 1;

            CurveF[] curves = new CurveF[numOfCurves];
            double   y;

            for (int i = 0; i < numOfCurves; i++)
            {
                tsat     = xVar.Min + i * 5.0;
                dewPoint = humidGasCalculator.GetDewPointFromDryBulbAndRelativeHumidity(tsat, 1.0);
                ysat     = humidGasCalculator.GetHumidityFromDewPointAndPressure(dewPoint, p);
                wetBulb  = humidGasCalculator.GetWetBulbFromDryBulbHumidityAndPressure(tsat, ysat, p);
                PointF[] dataPoints = new PointF[11];
                maxTemp = humidGasCalculator.GetDryBulbFromWetBulbHumidityAndPressure(wetBulb, 0.0, p);
                if (maxTemp > xVar.Max)
                {
                    maxTemp = xVar.Max;
                }
                if (ysat > yVar.Max)
                {
                    tsat = humidGasCalculator.GetDryBulbFromWetBulbHumidityAndPressure(wetBulb, yVar.Max, p);
                }
                ih = (cg + cv * ysat) * (tsat - 273.15) + r0 * ysat;
                for (int j = 0; j <= 10; j++)
                {
                    temperature = tsat + (maxTemp - tsat) / 10.0 * j;
                    //iso-enthalpy line
                    y             = (ih - cg * (temperature - 273.15)) / (r0 + cv * (temperature - 273.15));
                    dataPoints[j] = new PointF((float)temperature, (float)y);
                }
                curves[i] = new CurveF(StringConstants.GetTypeName(StringConstants.ADIABATIC_SATURATION), (float)tsat, dataPoints);
            }

            CurveFamilyF curveFamily = new CurveFamilyF(StringConstants.GetTypeName(StringConstants.ADIABATIC_SATURATION), PhysicalQuantity.Temperature, curves);

            return(curveFamily);
        }
Ejemplo n.º 6
0
        private CurveFamilyF GenerateRelativeHumidityFamily()
        {
            double dewPoint;
            double humidity;
            double temperature;
            double maxTemp;

            CurveF[]           curves = new CurveF[16];
            double             relativeHumidity;
            HumidGasCalculator humidGasCalculator = GetHumidGasCalculator();

            for (int i = 0; i < 16; i++)
            {
                //from 0.0% to 10%--interval 2%
                if (i < 5)
                {
                    relativeHumidity = (i + 1) * 0.02;
                }
                //from 10 to 50%--interval 5%
                else if (i < 9)
                {
                    relativeHumidity = 0.1 + (i - 4) * 0.05;
                }
                //from 30 to 100%--interval 10%
                else
                {
                    relativeHumidity = 0.3 + (i - 8) * 0.1;
                }

                dewPoint = humidGasCalculator.GetDewPointFromHumidityAndPressure(yVar.Max, pressure.Value);
                maxTemp  = humidGasCalculator.GetDryBulbFromDewPointAndRelativeHumidity(dewPoint, relativeHumidity);
                if (maxTemp > xVar.Max)
                {
                    maxTemp = xVar.Max;
                }
                PointF[] dataPoints = new PointF[101];
                for (int j = 0; j <= 100; j++)
                {
                    temperature   = xVar.Min + j * (maxTemp - xVar.Min) / 100;
                    dewPoint      = humidGasCalculator.GetDewPointFromDryBulbAndRelativeHumidity(temperature, relativeHumidity);
                    humidity      = humidGasCalculator.GetHumidityFromDewPointAndPressure(dewPoint, (double)pressure.Value);
                    dataPoints[j] = new PointF((float)temperature, (float)humidity);
                }
                curves[i] = new CurveF(StringConstants.GetTypeName(StringConstants.RELATIVE_HUMIDITY), (float)relativeHumidity, dataPoints);
            }

            CurveFamilyF curveFamily = new CurveFamilyF(StringConstants.GetTypeName(StringConstants.RELATIVE_HUMIDITY), PhysicalQuantity.Fraction, curves);

            return(curveFamily);
        }
Ejemplo n.º 7
0
        private bool CheckSpecialPermission()
        {
            bool permissionGranted = false;

            if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessFineLocation) != Android.Content.PM.Permission.Granted &&
                ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessCoarseLocation) != Android.Content.PM.Permission.Granted)
            {
                RequestPermissions(StringConstants.GetLocationPermissiongroup(), RequestID);
            }
            else
            {
                permissionGranted = true;
            }

            return(permissionGranted);
        }
Ejemplo n.º 8
0
        private CurveF GenerateHumidHeatCurve()
        {
            double humidity;
            double humidHeat;

            PointF[]           dataPoints         = new PointF[10];
            HumidGasCalculator humidGasCalculator = GetHumidGasCalculator();

            for (int i = 0; i < 10; i++)
            {
                humidity      = yVar.Min + (yVar.Max - yVar.Min) / 10.0 * i;
                humidHeat     = humidGasCalculator.GetHumidHeat(humidity);
                dataPoints[i] = new PointF((float)humidity, (float)humidHeat);
            }
            return(new CurveF(StringConstants.GetTypeName(StringConstants.HUMID_HEAT), 273.15f, dataPoints));
        }
Ejemplo n.º 9
0
        private CurveF GenerateEvaporationHeatCurve()
        {
            double temperature;
            double evapHeat;

            PointF[]           dataPoints         = new PointF[10];
            HumidGasCalculator humidGasCalculator = GetHumidGasCalculator();

            for (int i = 0; i < 10; i++)
            {
                temperature   = (xVar.Max - xVar.Min) / 10.0 * i;
                evapHeat      = humidGasCalculator.GetEvaporationHeat(temperature);
                dataPoints[i] = new PointF((float)temperature, (float)evapHeat);
            }
            return(new CurveF(StringConstants.GetTypeName(StringConstants.EVAPORATION_HEAT), 0.1f, dataPoints));
        }
Ejemplo n.º 10
0
        private CurveF GenerateSpecificVolumeDryAirCurve()
        {
            double temperature;
            double specificVolumeDryAir;

            PointF[]           dataPoints         = new PointF[10];
            HumidGasCalculator humidGasCalculator = GetHumidGasCalculator();

            for (int i = 0; i < 10; i++)
            {
                temperature          = (xVar.Max - xVar.Min) / 10.0 * i;
                specificVolumeDryAir = humidGasCalculator.GetHumidVolume(temperature, 0.0, (double)pressure.Value);
                dataPoints[i]        = new PointF((float)temperature, (float)specificVolumeDryAir);
            }
            return(new CurveF(StringConstants.GetTypeName(StringConstants.SPECIFIC_VOLUME_DRY_AIR), 0.1f, dataPoints));
        }
        //----------------------------------------------------------------//

        public static void AppendCollection <T, T2>(this StringBuilder builder, IEnumerable <T> enumerable,
                                                    Func <T, T2, string> func, T2 arg2, string delimeter)
        {
            IEnumerator <T> enumerator = enumerable.GetEnumerator();
            bool            hasNext    = enumerator.MoveNext();

            while (hasNext)
            {
                builder.Append(func(enumerator.Current, arg2));
                hasNext = enumerator.MoveNext();
                if (!string.IsNullOrEmpty(delimeter) && hasNext)
                {
                    builder.Append(StringConstants.SeparatorWithSpaces(delimeter));
                }
            }
        }
Ejemplo n.º 12
0
        internal override ErrorMessage CheckSpecifiedValueInContext(ProcessVarDouble pv, double aValue)
        {
            ErrorMessage retValue = null;

            if (pv.VarTypeName == StringConstants.GetTypeName(StringConstants.VAPOR_FRACTION) && aValue < 0.9999)
            {
                retValue = CreateSimpleGenericInappropriateSpecifiedValueErrorMessage(pv.VarTypeName + " of an inlet or outlet in a steam jet ejector cannot be less than 1.0.");
            }
            else if (pv == dischargeOutlet.Pressure)
            {
                if (motiveInlet.Pressure.IsSpecifiedAndHasValue && aValue >= motiveInlet.Pressure.Value)
                {
                    retValue = CreateSimpleGenericInappropriateSpecifiedValueErrorMessage(pv.VarTypeName + " of discharge outlet cannot be greater than that of motive inlet.");
                }
                else if (suctionInlet.Pressure.IsSpecifiedAndHasValue && aValue <= suctionInlet.Pressure.Value)
                {
                    retValue = CreateSimpleGenericInappropriateSpecifiedValueErrorMessage(pv.VarTypeName + " of discharge outlet cannot be smaller than that of suction inlet.");
                }
            }
            else if (pv == suctionInlet.Pressure)
            {
                if (motiveInlet.Pressure.IsSpecifiedAndHasValue && aValue >= motiveInlet.Pressure.Value)
                {
                    retValue = CreateSimpleGenericInappropriateSpecifiedValueErrorMessage(pv.VarTypeName + " of suction inlet cannot be greater than that of motive inlet.");
                }
                else if (dischargeOutlet.Pressure.IsSpecifiedAndHasValue && aValue <= dischargeOutlet.Pressure.Value)
                {
                    retValue = CreateSimpleGenericInappropriateSpecifiedValueErrorMessage(pv.VarTypeName + " of suction inlet cannot be greater than that of discharge outlet.");
                }
            }
            else if (pv == motiveInlet.Pressure)
            {
                if (dischargeOutlet.Pressure.IsSpecifiedAndHasValue && aValue <= dischargeOutlet.Pressure.Value)
                {
                    retValue = CreateSimpleGenericInappropriateSpecifiedValueErrorMessage(pv.VarTypeName + " of motive inlet cannot be smaller than that of discharge outlet.");
                }
                else if (suctionInlet.Pressure.IsSpecifiedAndHasValue && aValue <= suctionInlet.Pressure.Value)
                {
                    retValue = CreateSimpleGenericInappropriateSpecifiedValueErrorMessage(pv.VarTypeName + " of motive inlet cannot be smaller than that of suction inlet.");
                }
            }

            return(retValue);
        }
Ejemplo n.º 13
0
        public async override void OnViewCreated(View view, Bundle savedInstanceState)
        {
            base.OnViewCreated(view, savedInstanceState);

            ContinueBtn.Click += ContinueBtn_Click;

            CarsApi = RestService.For <ICarsApi>(StringConstants.GetGateway());
            try
            {
                var MyResult = await CarsApi.GetWelcome();

                var make = MyResult.Results.Select(car => car.Make).ToList();
                brandAdapter = ArrayAdapterClass.CreateArrayAdapter(Activity, make);

                var model = MyResult.Results.Select(car => car.Model).ToList();
                modelAdapter = ArrayAdapterClass.CreateArrayAdapter(Activity, model);
            }
            catch (Exception e)
            {
                Log.Error("car_reg_fragment", e.Message);
            }

            CarYearEt.Adapter      = ArrayAdapterClass.CreateArrayAdapter(Activity, CarPropsUtil.GetModelYears());
            CarYearEt.TextChanged += TextChanged;
            CarYearEt.Validator    = new Validator(CarYearEt);

            CarBrandEt.Adapter      = brandAdapter;
            CarBrandEt.TextChanged += TextChanged;

            CarModelEt.Adapter      = modelAdapter;
            CarModelEt.TextChanged += TextChanged;

            CarColorEt.Adapter      = ArrayAdapterClass.CreateArrayAdapter(Activity, CarPropsUtil.GetColorList());
            CarColorEt.TextChanged += TextChanged;
            CarColorEt.Validator    = new Validator(CarColorEt);

            ConditionEt.Adapter      = ArrayAdapterClass.CreateArrayAdapter(Activity, conditions);
            ConditionEt.TextChanged += TextChanged;
            ConditionEt.Validator    = new Validator(ConditionEt);

            RegNoEt.EditText.TextChanged         += TextChanged;
            DriverLicenceEt.EditText.TextChanged += TextChanged;
        }
Ejemplo n.º 14
0
        private CurveF GenerateSaturationVolumeCurve()
        {
            double             temperature;
            double             dewPoint;
            double             humidity;
            double             saturationVolume;
            HumidGasCalculator humidGasCalculator = GetHumidGasCalculator();

            PointF[] dataPoints = new PointF[10];
            for (int i = 0; i < 10; i++)
            {
                temperature      = (xVar.Max - xVar.Min) / 10.0 * i;
                dewPoint         = humidGasCalculator.GetDewPointFromDryBulbAndRelativeHumidity(temperature, 1.0);
                humidity         = humidGasCalculator.GetHumidityFromDewPointAndPressure(dewPoint, (double)pressure.Value);
                saturationVolume = humidGasCalculator.GetHumidVolume(temperature, humidity, (double)pressure.Value);
                dataPoints[i]    = new PointF((float)temperature, (float)saturationVolume);
            }
            return(new CurveF(StringConstants.GetTypeName(StringConstants.SATURATION_VOLUME), 0.1f, dataPoints));
        }
Ejemplo n.º 15
0
 public UserManagementRepository(IMSDbContext iMSDbContext,
                                 UserManager <ApplicationUser> userManager,
                                 IEmailService emailService,
                                 IOptions <EmailConfiguration> emailConfiguration,
                                 IOptions <SystemRoles> systemRoles,
                                 IOptions <StringConstants> stringConstants,
                                 IInstituteUserMappingHelperService instituteUserMappingHelperService,
                                 ITimeTableManagementRepository timeTableManagementRepository,
                                 INotificationManagementRepository notificationManagementRepository,
                                 IStaffActivityManagementRepository staffActivityManagementRepository)
 {
     _iMSDbContext       = iMSDbContext;
     _userManager        = userManager;
     _emailService       = emailService;
     _emailConfiguration = emailConfiguration.Value;
     _systemRoles        = systemRoles.Value;
     _stringConstants    = stringConstants.Value;
     _instituteUserMappingHelperService = instituteUserMappingHelperService;
     _timeTableManagementRepository     = timeTableManagementRepository;
     _notificationManagementRepository  = notificationManagementRepository;
     _staffActivityManagementRepository = staffActivityManagementRepository;
 }
Ejemplo n.º 16
0
        private void OnSaveBook(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(titleBox.Text) && !string.IsNullOrWhiteSpace(isbnBox.Text) &&
                !string.IsNullOrWhiteSpace(publisherBox.Text) && !string.IsNullOrWhiteSpace(authorListBox.Text) &&
                !string.IsNullOrWhiteSpace(genreBox.Text) && !string.IsNullOrWhiteSpace(qtyBox.Text))
            {
                BookGenre  genres  = new BookGenre();
                List <int> authors = new List <int>();
                int.TryParse(qtyBox.Text, out int qty);

                foreach (var genre in genreBox.CheckedItems)
                {
                    genres = genres | (BookGenre)Enum.Parse(typeof(BookGenre), genre.ToString());
                }

                foreach (Author author in authorListBox.SelectedItems)
                {
                    authors.Add(author.ID);
                }

                for (int i = 0; i < qty; i++)
                {
                    Book = new Book(title: titleBox.Text, isbn: isbnBox.Text, authorID: authors,
                                    publisher: publisherBox.Text, genre: genres, description: descriptionBox.Text);

                    NewBook?.Invoke(this, new BookRelatedEventArgs {
                        Book = Book
                    });
                }
                MessageBox.Show(StringConstants.BookRegistered(titleBox.Text, isbnBox.Text));
                RefreshAndClear();
            }
            else
            {
                MessageBox.Show(StringConstants.missingInfo);
            }
            AutomaticFormPosition.SaveFormStatus(this);
        }
Ejemplo n.º 17
0
 public IActionResult Login([FromBody] LoginModel req)
 {
     try
     {
         LoginCredentials   user            = new LoginCredentials();
         LoginResponseModel response        = new LoginResponseModel();
         StringConstants    stringConstants = new StringConstants();
         if (ModelState.IsValid)
         {
             //string password = Helper.Helper.Encrypt(req.password);
             user = _dbContext.LoginCredentials.FirstOrDefault(q => q.EmailId == req.email && q.Password == req.password);
             if (user != null)
             {
                 if (user.IsActive == true)
                 {
                     var token = Helper.Helper.Token(_configuration["Issuer"], _configuration["Audience"], _configuration["SigninKey"], req.email, user.UserId.ToString(), user.RoleId);
                     response.Token      = new JwtSecurityTokenHandler().WriteToken(token);
                     response.StatusCode = (int)Helper.EnumList.ResponseType.Success;
                 }
                 else
                 {
                     response.StatusCode = (int)Helper.EnumList.ResponseType.Isinactive;
                 }
             }
             else
             {
                 response.StatusCode = (int)Helper.EnumList.ResponseType.Error;
                 response.Message    = stringConstants.LoginCredentailWrong;
             }
         }
         return(Ok(response));
     }
     catch (Exception e)
     {
         return(StatusCode((int)HttpStatusCode.ExpectationFailed));
     }
 }
Ejemplo n.º 18
0
        protected override ErrorMessage CheckSpecifiedValueRange(ProcessVarDouble pv, double aValue)
        {
            ErrorMessage retValue = base.CheckSpecifiedValueRange(pv, aValue);

            if (retValue != null)
            {
                return(retValue);
            }

            if (pv == massConcentration)
            {
                if (materialStateType != MaterialStateType.Liquid)
                {
                    throw new IllegalFunctionCallException("Solid material stream should not have its mass concentration variable specified.");
                }
                if (aValue != Constants.NO_VALUE && !vaporFraction.HasValue && (aValue < 0 || aValue > 1.0))
                {
                    retValue = CreateOutOfRangeZeroToOneErrorMessage(pv);
                }
                else if (aValue != Constants.NO_VALUE && vaporFraction.HasValue && (aValue < 0 || aValue > (1.0 - vaporFraction.Value)))
                {
                    retValue = new ErrorMessage(ErrorType.SimpleGeneric, StringConstants.INAPPROPRIATE_SPECIFIED_VALUE, StringConstants.GetTypeName(StringConstants.MASS_CONCENTRATION) + " can not be out of the range of 0 to " + (1.0 - vaporFraction.Value) + " under current conditions");
                }
            }
            else if (pv == vaporFraction)
            {
                if (materialStateType != MaterialStateType.Liquid)
                {
                    throw new IllegalFunctionCallException("Solid material stream should not have its vapor fraction variable specified.");
                }

                if (aValue != Constants.NO_VALUE && massConcentration.HasValue && aValue > (1.0 - massConcentration.Value))
                {
                    retValue = new ErrorMessage(ErrorType.SimpleGeneric, StringConstants.INAPPROPRIATE_SPECIFIED_VALUE, StringConstants.GetTypeName(StringConstants.VAPOR_FRACTION) + " must be less than " + StringConstants.GetTypeName(StringConstants.MOISTURE_CONTENT_WET) + " under current conditions");
                }
            }

            return(retValue);
        }
 public BudgetCategoryController(PersonalBudgetContext context,
                                 IDataProtectionProvider protectionprovider, StringConstants strconsts)
 {
     this.protector = protectionprovider.CreateProtector(strconsts.IdQryStr);
     _context       = context;
 }
Ejemplo n.º 20
0
        public EventLog SubmitLog(EventLog log, OsbideUser user)
        {
            LocalErrorLog errorLogger = new LocalErrorLog();

            errorLogger.SenderId = user.Id;
            errorLogger.Content  = "About to save log " + log.LogType + " to DB.  ";
            errorLogger.LogDate  = DateTime.Now;

            log.Sender       = null;
            log.SenderId     = user.Id;
            log.DateReceived = DateTime.UtcNow;
            log.EventTypeId  = Convert.ToInt32(Enum.Parse(typeof(EventTypes), log.LogType));

            //insert into the DB
            Db.EventLogs.Add(log);
            try
            {
                Db.SaveChanges();
                errorLogger.Content += "Item saved.  ";
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
            {
                errorLogger.Content += "Error saving:  ";
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        System.Diagnostics.Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                        errorLogger.Content += string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                    }
                }
                Db.LocalErrorLogs.Add(errorLogger);
                Db.SaveChanges();
                return(null);
            }
            catch (Exception ex)
            {
                errorLogger.Content += "Error saving: " + ex.Message;
                System.Diagnostics.Trace.TraceInformation(ex.Message);
                Db.LocalErrorLogs.Add(errorLogger);
                Db.SaveChanges();
                return(null);
            }

            //Tease apart log information and insert into the appropriate DB table
            IOsbideEvent evt = null;

            try
            {
                errorLogger.Content += "About to unzip event.";
                evt            = EventFactory.FromZippedBinary(log.Data.BinaryData, new OsbideDeserializationBinder());
                evt.EventLogId = log.Id;
            }
            catch (Exception)
            {
                errorLogger.Content += "Error unzipping event.";
                Db.LocalErrorLogs.Add(errorLogger);
                Db.SaveChanges();
                return(null);
            }

            var hashtags = string.Empty;
            var usertags = string.Empty;

            if (log.LogType == AskForHelpEvent.Name)
            {
                Db.AskForHelpEvents.Add((AskForHelpEvent)evt);
                AskForHelpEvent ask = evt as AskForHelpEvent;

                //send email to interested parties
                //find all of this user's subscribers and send them an email
                List <OsbideUser> observers = new List <OsbideUser>();

                observers = (from subscription in Db.UserSubscriptions
                             join dbUser in Db.Users on
                             new { InstitutionId = subscription.ObserverInstitutionId, SchoolId = subscription.ObserverSchoolId }
                             equals new { InstitutionId = user.InstitutionId, SchoolId = user.SchoolId }
                             where subscription.SubjectSchoolId == user.SchoolId &&
                             subscription.SubjectInstitutionId == user.InstitutionId &&
                             dbUser.ReceiveEmailOnNewFeedPost == true
                             select dbUser).ToList();
                if (observers.Count > 0)
                {
                    string url  = StringConstants.GetActivityFeedDetailsUrl(log.Id);
                    string body = "Greetings,<br />{0} asked for help regarding the following item:<br />\"{1}\"<br />To view this "
                                  + "conversation online, please visit {2} or visit your OSBIDE user profile.<br /><br />Thanks,<br />OSBIDE<br /><br />"
                                  + "These automated messages can be turned off by editing your user profile.";
                    body = string.Format(body, user.FirstAndLastName, ask.UserComment, url);
                    List <MailAddress> to = new List <MailAddress>();
                    foreach (OsbideUser observer in observers)
                    {
                        to.Add(new MailAddress(observer.Email));
                    }
                    Email.Send("[OSBIDE] Someone has asked for help!", body, to);
                }
            }
            else if (log.LogType == BuildEvent.Name)
            {
                BuildEvent build = (BuildEvent)evt;
                Db.BuildEvents.Add(build);

                string pattern = "error ([^:]+)";

                //strip out non-critical errors
                List <BuildEventErrorListItem> errorItems = build.ErrorItems.Where(e => e.ErrorListItem.CriticalErrorName.Length > 0).ToList();
                build.ErrorItems.Clear();
                build.ErrorItems = errorItems;

                //log all errors in their own DB for faster search
                List <string> errors = new List <string>();
                Dictionary <string, ErrorType> errorTypes = new Dictionary <string, ErrorType>();
                foreach (BuildEventErrorListItem item in build.ErrorItems)
                {
                    Match match = Regex.Match(item.ErrorListItem.Description, pattern);

                    //ignore bad matches
                    if (match.Groups.Count == 2)
                    {
                        string    errorCode = match.Groups[1].Value.ToLower().Trim();
                        ErrorType type      = Db.ErrorTypes.Where(t => t.Name == errorCode).FirstOrDefault();
                        if (type == null)
                        {
                            if (errorTypes.ContainsKey(errorCode) == false)
                            {
                                type = new ErrorType()
                                {
                                    Name = errorCode
                                };
                                Db.ErrorTypes.Add(type);
                            }
                            else
                            {
                                type = errorTypes[errorCode];
                            }
                        }
                        if (errorCode.Length > 0 && errors.Contains(errorCode) == false)
                        {
                            errors.Add(errorCode);
                        }
                        errorTypes[errorCode] = type;
                    }
                }
                Db.SaveChanges();
                foreach (string errorType in errors)
                {
                    Db.BuildErrors.Add(new BuildError()
                    {
                        BuildErrorTypeId = errorTypes[errorType].Id,
                        LogId            = log.Id
                    });
                }
            }
            else if (log.LogType == CutCopyPasteEvent.Name)
            {
                Db.CutCopyPasteEvents.Add((CutCopyPasteEvent)evt);
            }
            else if (log.LogType == DebugEvent.Name)
            {
                Db.DebugEvents.Add((DebugEvent)evt);
            }
            else if (log.LogType == EditorActivityEvent.Name)
            {
                Db.EditorActivityEvents.Add((EditorActivityEvent)evt);
            }
            else if (log.LogType == ExceptionEvent.Name)
            {
                Db.ExceptionEvents.Add((ExceptionEvent)evt);
            }
            else if (log.LogType == FeedPostEvent.Name)
            {
                hashtags = string.Join(",", ParseHashtags(((FeedPostEvent)evt).Comment));
                usertags = string.Join(",", ParseUserTags(((FeedPostEvent)evt).Comment));
                Db.FeedPostEvents.Add((FeedPostEvent)evt);
            }
            else if (log.LogType == HelpfulMarkGivenEvent.Name)
            {
                Db.HelpfulMarkGivenEvents.Add((HelpfulMarkGivenEvent)evt);
            }
            else if (log.LogType == LogCommentEvent.Name)
            {
                Db.LogCommentEvents.Add((LogCommentEvent)evt);
            }
            else if (log.LogType == SaveEvent.Name)
            {
                Db.SaveEvents.Add((SaveEvent)evt);
            }
            else if (log.LogType == SubmitEvent.Name)
            {
                errorLogger.Content += "Submit event detected.  ";
                Db.SubmitEvents.Add((SubmitEvent)evt);
            }
            try
            {
                errorLogger.Content += "Attempting to save to DB.  ";
                Db.SaveChanges();

                /*
                 * if(hashtags.Length >= 0 || usertags.Length >= 0 )
                 *
                 * using (var context = new OsbideProcs())
                 * {
                 *  context.InsertPostTags(log.Id, usertags, hashtags);
                 * }
                 * */
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
            {
                errorLogger.Content += "Error saving to DB:  ";
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        System.Diagnostics.Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                        errorLogger.Content += string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                        Db.LocalErrorLogs.Add(errorLogger);
                        Db.SaveChanges();
                    }
                }
                return(null);
            }
            catch (Exception ex)
            {
                errorLogger.Content += "Error saving to DB: " + ex.Message;
                Db.LocalErrorLogs.Add(errorLogger);
                Db.SaveChanges();
                System.Diagnostics.Trace.TraceInformation(ex.Message);
                return(null);
            }

            //Db.LocalErrorLogs.Add(errorLogger);
            //Db.SaveChanges();
            return(log);
        }
Ejemplo n.º 21
0
        protected override ErrorMessage CheckSpecifiedValueRange(ProcessVarDouble pv, double aValue)
        {
            ErrorMessage retValue = base.CheckSpecifiedValueRange(pv, aValue);

            if (retValue != null)
            {
                return(retValue);
            }

            //if (pv.VarTypeName == StringConstants.GetTypeName(StringConstants.DRY_BULB_TEMPERATURE)) {
            if (pv == temperature)
            {
                if (aValue != Constants.NO_VALUE && wetBulbTemperature.HasValue && aValue < wetBulbTemperature.Value)
                {
                    retValue = new ErrorMessage(ErrorType.SimpleGeneric, StringConstants.INAPPROPRIATE_SPECIFIED_VALUE, pv.VarTypeName + " can not be less than " + StringConstants.GetTypeName(StringConstants.WET_BULB_TEMPERATURE));
                }
                else if (aValue != Constants.NO_VALUE && dewPoint.HasValue && aValue < dewPoint.Value)
                {
                    retValue = new ErrorMessage(ErrorType.SimpleGeneric, StringConstants.INAPPROPRIATE_SPECIFIED_VALUE, pv.VarTypeName + " can not be less than " + StringConstants.GetTypeName(StringConstants.DEW_POINT));
                }
            }
            //else if (pv.VarTypeName == StringConstants.GetTypeName(StringConstants.WET_BULB_TEMPERATURE))
            else if (pv == wetBulbTemperature)
            {
                if (aValue != Constants.NO_VALUE && temperature.HasValue && aValue > temperature.Value)
                {
                    retValue = new ErrorMessage(ErrorType.SimpleGeneric, StringConstants.INAPPROPRIATE_SPECIFIED_VALUE, pv.VarTypeName + " can not be greater than " + StringConstants.GetTypeName(StringConstants.DRY_BULB_TEMPERATURE));
                }
                else if (aValue != Constants.NO_VALUE && dewPoint.HasValue && aValue < dewPoint.Value)
                {
                    retValue = new ErrorMessage(ErrorType.SimpleGeneric, StringConstants.INAPPROPRIATE_SPECIFIED_VALUE, pv.VarTypeName + " can not be less than than " + StringConstants.GetTypeName(StringConstants.DEW_POINT));
                }
            }
            //else if (pv.VarTypeName == StringConstants.GetTypeName(StringConstants.DEW_POINT))
            else if (pv == dewPoint)
            {
                if (aValue != Constants.NO_VALUE && temperature.HasValue && aValue > temperature.Value)
                {
                    retValue = new ErrorMessage(ErrorType.SimpleGeneric, StringConstants.INAPPROPRIATE_SPECIFIED_VALUE, pv.VarTypeName + " can not be greater than " + StringConstants.GetTypeName(StringConstants.DRY_BULB_TEMPERATURE));
                }
                else if (aValue != Constants.NO_VALUE && wetBulbTemperature.HasValue && aValue > wetBulbTemperature.Value)
                {
                    retValue = new ErrorMessage(ErrorType.SimpleGeneric, StringConstants.INAPPROPRIATE_SPECIFIED_VALUE, pv.VarTypeName + " can not be greater than " + StringConstants.GetTypeName(StringConstants.WET_BULB_TEMPERATURE));
                }
            }
            //else if (pv.VarTypeName == StringConstants.GetTypeName(StringConstants.HUMIDITY))
            else if (pv == Humidity)
            {
                if (aValue != Constants.NO_VALUE && aValue < 0)
                {
                    retValue = CreateLessThanZeroErrorMessage(pv);
                }
                else if (aValue != Constants.NO_VALUE && pressure.HasValue)
                {
                    double maxHumidity = 1000.0;

                    HumidGasCalculator humidGasCalculator = GetHumidGasCalculator();
                    if (temperature.HasValue)
                    {
                        maxHumidity = humidGasCalculator.GetHumidityFromDewPointAndPressure(temperature.Value, pressure.Value);
                    }
                    else if (wetBulbTemperature.HasValue)
                    {
                        maxHumidity = humidGasCalculator.GetHumidityFromDewPointAndPressure(wetBulbTemperature.Value, pressure.Value);
                    }
                    else if (dewPoint.HasValue)
                    {
                        maxHumidity = humidGasCalculator.GetHumidityFromDewPointAndPressure(dewPoint.Value, pressure.Value);
                    }

                    if (aValue > maxHumidity)
                    {
                        aValue   = maxHumidity;
                        retValue = new ErrorMessage(ErrorType.SimpleGeneric, StringConstants.INAPPROPRIATE_SPECIFIED_VALUE, "The maximum humidity under current conditions is " + aValue.ToString());
                    }
                }
            }
            //else if (pv.VarTypeName == StringConstants.GetTypeName(StringConstants.RELATIVE_HUMIDITY))
            else if (pv == relativeHumidity)
            {
                if (aValue != Constants.NO_VALUE && (aValue < 0 || aValue > 1.0))
                {
                    retValue = CreateOutOfRangeZeroToOneErrorMessage(pv);
                }
            }

            return(retValue);
        }
Ejemplo n.º 22
0
 private void OnExistingUserRecognised(object sender, FaceRecognisedEventArgs e)
 {
     User = LibraryDataIO.Instance.FindUser(e.Label);
     MessageBox.Show(StringConstants.ExistingUserErrorString(User.Name, User.Surname));
     BeginInvoke(new Action(() => Close()));
 }
Ejemplo n.º 23
0
        /// <summary>
        /// Helper method for posting a comment.  Will return true if everything went OK, false otherwise
        /// </summary>
        /// <param name="logId"></param>
        /// <param name="comment"></param>
        /// <returns></returns>
        protected bool PostComment(string logId, string comment)
        {
            int id = -1;

            if (Int32.TryParse(logId, out id) == true)
            {
                //comments made on comments or mark helpful events need to be routed back to the original source
                IOsbideEvent checkEvent = Db.LogCommentEvents.Where(l => l.EventLogId == id).FirstOrDefault();
                if (checkEvent != null)
                {
                    id = (checkEvent as LogCommentEvent).SourceEventLogId;
                }
                else
                {
                    checkEvent = Db.HelpfulMarkGivenEvents.Where(l => l.EventLogId == id).FirstOrDefault();
                    if (checkEvent != null)
                    {
                        id = (checkEvent as HelpfulMarkGivenEvent).LogCommentEvent.SourceEventLogId;
                    }
                }

                LogCommentEvent logComment = new LogCommentEvent()
                {
                    Content          = comment,
                    SourceEventLogId = id,
                    SolutionName     = "OSBIDE"
                };
                OsbideWebService client = new OsbideWebService();
                Authentication   auth   = new Authentication();
                string           key    = auth.GetAuthenticationKey();
                EventLog         log    = null;
                if (string.IsNullOrEmpty(comment) == false)
                {
                    log = new EventLog(logComment, CurrentUser);
                    log = client.SubmitLog(log, CurrentUser);
                }
                else
                {
                    return(false);
                }
                logComment = Db.LogCommentEvents.Where(l => l.EventLogId == log.Id).FirstOrDefault();

                //the code below performs two functions:
                // 1. Send interested parties email notifications
                // 2. Log the comment in the social activity log (displayed on an individual's profile page)

                //find others that have posted on this same thread
                List <OsbideUser> interestedParties = Db.LogCommentEvents
                                                      .Where(l => l.SourceEventLogId == id)
                                                      .Where(l => l.EventLog.SenderId != CurrentUser.Id)
                                                      .Select(l => l.EventLog.Sender)
                                                      .ToList();

                //(email only) find those that are subscribed to this thread
                List <OsbideUser> subscribers = (from logSub in Db.EventLogSubscriptions
                                                 join user in Db.Users on logSub.UserId equals user.Id
                                                 where logSub.LogId == id &&
                                                 logSub.UserId != CurrentUser.Id &&
                                                 user.ReceiveNotificationEmails == true
                                                 select user).ToList();

                //check to see if the author wants to be notified of posts
                OsbideUser eventAuthor = Db.EventLogs.Where(l => l.Id == id).Select(l => l.Sender).FirstOrDefault();

                //master list shared between email and social activity log
                Dictionary <int, OsbideUser> masterList = new Dictionary <int, OsbideUser>();
                if (eventAuthor != null)
                {
                    masterList.Add(eventAuthor.Id, eventAuthor);
                }
                foreach (OsbideUser user in interestedParties)
                {
                    if (masterList.ContainsKey(user.Id) == false)
                    {
                        masterList.Add(user.Id, user);
                    }
                }

                //add the current user for activity log tracking, but not for emails
                OsbideUser creator = new OsbideUser(CurrentUser);
                creator.ReceiveNotificationEmails = false;  //force no email send on the current user
                if (masterList.ContainsKey(creator.Id) == true)
                {
                    masterList.Remove(creator.Id);
                }
                masterList.Add(creator.Id, creator);

                //update social activity
                foreach (OsbideUser user in masterList.Values)
                {
                    CommentActivityLog social = new CommentActivityLog()
                    {
                        TargetUserId      = user.Id,
                        LogCommentEventId = logComment.Id
                    };
                    Db.CommentActivityLogs.Add(social);
                }
                Db.SaveChanges();

                //form the email list
                SortedDictionary <int, OsbideUser> emailList = new SortedDictionary <int, OsbideUser>();

                //add in interested parties from our master list
                foreach (OsbideUser user in masterList.Values)
                {
                    if (user.ReceiveNotificationEmails == true)
                    {
                        if (emailList.ContainsKey(user.Id) == false)
                        {
                            emailList.Add(user.Id, user);
                        }
                    }
                }

                //add in subscribers to email list
                foreach (OsbideUser user in subscribers)
                {
                    if (emailList.ContainsKey(user.Id) == false)
                    {
                        emailList.Add(user.Id, user);
                    }
                }

                //send emails
                if (emailList.Count > 0)
                {
                    //send email
                    string url  = StringConstants.GetActivityFeedDetailsUrl(id);
                    string body = "Greetings,<br />{0} has commented on a post that you have previously been involved with:<br />\"{1}\"<br />To view this "
                                  + "conversation online, please visit {2} or visit your OSBIDE user profile.<br /><br />Thanks,<br />OSBIDE<br /><br />"
                                  + "These automated messages can be turned off by editing your user profile.";
                    body = string.Format(body, logComment.EventLog.Sender.FirstAndLastName, logComment.Content, url);
                    List <MailAddress> to = new List <MailAddress>();
                    foreach (OsbideUser user in emailList.Values)
                    {
                        to.Add(new MailAddress(user.Email));
                    }
                    Email.Send("[OSBIDE] Activity Notification", body, to);
                }
            }
            return(true);
        }
Ejemplo n.º 24
0
 private string NavUriString(double lat, double lng) => $"{StringConstants.GetNavigateBaseGateway()}{lat},{lng}";
Ejemplo n.º 25
0
        public async Task Verify(string option = "")
        {
            var user = Context.User;

            if (_verificationService.IsUserVerified(user.Id))
            {
                Context.Message.DeleteAsync();
                user.SendMessageAsync("Your discord account is already verified!");
                return;
            }

            if (Context.Guild != null)
            {
                Context.Message.DeleteAsync();
                user.SendMessageAsync(StringConstants.GetVerificationCmdDescription(user.Mention));
                return;
            }

            var guildUser = Context.Client.GetGuild(_guildId).GetUser(user.Id);

            if (guildUser == null)
            {
                ReplyAsync($"I couldn't find you on {Context.Client.GetGuild(_guildId).Name}. If you are on the server, try changing your status, if not, join and then try your luck verifying!");
                return;
            }

            var userVerificationState = _cacheService.GetUserVerificationState(user.Id);

            switch (option.ToLower().Trim())
            {
            case "done":
                if (userVerificationState == VerificationStates.None)
                {
                    ReplyAsync("Your verification state is not known, type `/verify` to start your verification process.");
                    return;
                }

                int    cachedProfile = _cacheService.GetUserForumId(user.Id);
                string cachedToken   = _cacheService.GetUserToken(user.Id);
                if (cachedProfile == -1 ||
                    cachedToken == "" ||
                    userVerificationState != VerificationStates.WaitingConfirm)
                {
                    _cacheService.ClearCache(user.Id);
                    ReplyAsync("Your verification process hasn't been initiated, type `/verify` to start your verification process.");
                    return;
                }

                string forumName = _verificationService.GetForumProfileNameIfContainsToken(cachedProfile, cachedToken);
                if (forumName == string.Empty)
                {
                    _userService.SetUserCooldown(user.Id, 15);
                    ReplyAsync("I couldn't find the token in your profile. Make sure your profile is set to public and the token is in your biography section." +
                               "\n" +
                               ":no_entry: You are allowed to check again in 15 seconds.");
                    return;
                }

                // if for some reason something is f****d and the forum id is found as linked, deny process and clear everything
                if (_verificationService.IsForumProfileLinked(cachedProfile))
                {
                    _cacheService.ClearCache(user.Id);
                    ReplyAsync("Sorry! This profile is already found to be linked with a discord account!");
                    return;
                }

                _cacheService.ClearCache(user.Id);
                _verificationService.StoreUserVerification(
                    user.Id,
                    cachedProfile,
                    forumName,
                    user.Username);

                var discordServer = Context.Client.GetGuild(_guildId);
                discordServer
                .GetTextChannel(_adminChannelId)
                .SendMessageAsync($"{guildUser.Mention} ({guildUser.Username}) has successfully verified to **{forumName}** <{_forumProfileUrl}{cachedProfile}>");

                ReplyAsync(StringConstants.GetVerificationSuccessMessage(user.Mention, cachedProfile));

                guildUser.AddRoleAsync(discordServer.GetRole(_verifiedRoleId));
                break;

            case "cancel":
                if (userVerificationState == VerificationStates.None)
                {
                    ReplyAsync("Nothing to cancel!");
                    return;
                }

                _cacheService.ClearCache(user.Id);
                ReplyAsync("Session successfully cleared. You can start the verification process again by typing `/verify <profile id>`");
                break;

            default:
                if (userVerificationState != VerificationStates.None)
                {
                    ReplyAsync("Your verification is awaiting you to place the token in your profile biography. `/verify done` once done or `/verify cancel` to cancel the process.");
                    return;
                }

                if (option == string.Empty)
                {
                    ReplyAsync(StringConstants.GetVerificationCmdDescription(user.Mention));
                    return;
                }

                int profile_id = -1;
                if (!Int32.TryParse(option, out profile_id))
                {
                    ReplyAsync(StringConstants.GetVerificationCmdDescription(user.Mention));
                    return;
                }

                if (profile_id < 1)
                {
                    ReplyAsync("Sorry! This doesn't look like a valid profile id to me.");
                    return;
                }

                if (_verificationService.IsForumProfileLinked(profile_id))
                {
                    _cacheService.ClearCache(user.Id);
                    await ReplyAsync("This profile is already linked to a discord account!");

                    return;
                }

                string token = StringHelper.GenerateRandom(10);

                _cacheService.SetUserVerificationState(user.Id, VerificationStates.WaitingConfirm);
                _cacheService.SetUserToken(user.Id, token);
                _cacheService.SetUserForumId(user.Id, profile_id);

                ReplyAsync(StringConstants.GetVerificationWaitingMessage(user.Mention, profile_id, token));
                break;
            }
        }
Ejemplo n.º 26
0
 private void UI_Shown(object sender, EventArgs e)
 {
     Speaker.TellUser(StringConstants.AIGreeting(User.Name));
 }