Ejemplo n.º 1
0
 /// <summary>
 /// Handles the UnhandledException event of the CurrentDomain control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
 private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
 {
     Exception ex = (Exception)e.ExceptionObject;
     ErrorLogging logError = new ErrorLogging(ref ex, sender);
     MessageBox.Show("An error log has been saved to" + logError.LogFile, "Unhandled Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
     Process.Start(Paths.SilverMonkeyErrorLogPath);
     Application.Exit();
 }
        public ActionResult Create(EventModel EventModel, HttpPostedFileBase file)
        {
            UserPermissionAction("event", RoleAction.view.ToString());
            CheckPermission();
            TempData["ShowMessage"] = "";
            TempData["MessageBody"] = "";
            try
            {
                if (ModelState.IsValid)
                {
                    if (string.IsNullOrEmpty(EventModel.EventDate.ToString()))
                    {
                        TempData["ShowMessage"] = "error";
                        TempData["MessageBody"] = "Please select a valid Event Date.";
                        return(View("Create", EventModel));
                    }

                    if (string.IsNullOrEmpty(EventModel.EventName))
                    {
                        TempData["ShowMessage"] = "error";
                        TempData["MessageBody"] = "Please Fill Event Name.";
                        return(View("Create", EventModel));
                    }

                    if (string.IsNullOrEmpty(EventModel.EventDescription))
                    {
                        TempData["ShowMessage"] = "error";
                        TempData["MessageBody"] = "Please Fill  EventDescription.";
                        return(View("Create", EventModel));
                    }
                    //CultureInfo culture = new CultureInfo("en-US");
                    //DateTime TodayDate = Convert.ToDateTime(DateTime.Now.ToString("MM/dd/yyyy"), culture);
                    //if (Convert.ToDateTime(EventModel.EventDate.ToString("MM/dd/yyyy"), culture) < TodayDate)
                    //{

                    //    TempData["ShowMessage"] = "error";
                    //    TempData["MessageBody"] = "You cannot add old date event.";
                    //    return View("Create", EventModel);
                    //}

                    Mapper.CreateMap <CommunicationApp.Models.EventModel, CommunicationApp.Entity.Event>();
                    CommunicationApp.Entity.Event Event = Mapper.Map <CommunicationApp.Models.EventModel, CommunicationApp.Entity.Event>(EventModel);
                    string EventImage = "";
                    if (file != null)
                    {
                        if (Event.EventImage != "")
                        {   //Delete Old Image
                            string pathDel = Server.MapPath("~/EventPhoto");

                            FileInfo objfile = new FileInfo(pathDel);
                            if (objfile.Exists) //check file exsit or not
                            {
                                objfile.Delete();
                            }
                            //End :Delete Old Image
                        }

                        //Save the photo in Folder
                        var    fileExt  = Path.GetExtension(file.FileName);
                        string fileName = Guid.NewGuid() + fileExt;
                        var    subPath  = Server.MapPath("~/EventPhoto");

                        //Check SubPath Exist or Not
                        if (!Directory.Exists(subPath))
                        {
                            Directory.CreateDirectory(subPath);
                        }
                        //End : Check SubPath Exist or Not

                        var path = Path.Combine(subPath, fileName);
                        file.SaveAs(path);

                        EventImage = CommonCls.GetURL() + "/EventPhoto/" + fileName;
                    }

                    Event.CustomerId = Convert.ToInt32(Session["CustomerId"]);//CutomerId
                    Event.IsActive   = true;
                    Event.CreatedOn  = DateTime.Now;
                    Event.EventImage = EventImage;
                    _EventService.InsertEvent(Event);
                    List <int> CustomerIds = new List <int>();
                    var        Customers   = new List <Customer>();
                    try
                    {
                        if (EventModel.All == true)
                        {
                            EventModel.SelectedCustomer = null;
                            Customers = _CustomerService.GetCustomers().ToList();
                            foreach (var Customer in Customers)
                            {
                                CustomerIds.Add(Convert.ToInt32(Customer.CustomerId));
                                EventCustomer EventCustomer = new Entity.EventCustomer();
                                EventCustomer.EventId    = Event.EventId;
                                EventCustomer.CustomerId = Customer.CustomerId;
                                _EventCustomerService.InsertEventCustomer(EventCustomer);
                            }
                        }
                        else if (EventModel.SelectedCustomer != null)
                        {
                            foreach (var Customer in EventModel.SelectedCustomer)
                            {
                                CustomerIds.Add(Convert.ToInt32(Customer));
                                EventCustomer EventCustomer = new Entity.EventCustomer();
                                EventCustomer.EventId    = Event.EventId;
                                EventCustomer.CustomerId = Event.CustomerId;
                                _EventCustomerService.InsertEventCustomer(EventCustomer);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ErrorLogging.LogError(ex);
                        throw;
                    }



                    string Flag    = "12";//status for Event;
                    var    Message = "New event saved.";
                    //send notification
                    try
                    {
                        var CustomerList = _CustomerService.GetCustomers().Where(c => CustomerIds.Contains(c.CustomerId) && c.CustomerId != EventModel.CustomerId && c.IsActive == true).ToList();
                        foreach (var Customer in CustomerList)
                        {
                            if (Customer != null)
                            {
                                if (Customer.ApplicationId != null && Customer.ApplicationId != "")
                                {
                                    bool NotificationStatus = true;

                                    string JsonMessage = "{\"Flag\":\"" + Flag + "\",\"Message\":\"" + Message + "\"}";
                                    try
                                    {
                                        //Save Notification
                                        Notification Notification = new Notification();
                                        Notification.NotificationSendBy = 1;
                                        Notification.NotificationSendTo = Convert.ToInt32(Customer.CustomerId);
                                        Notification.IsRead             = false;
                                        Notification.Flag           = Convert.ToInt32(Flag);
                                        Notification.RequestMessage = Message;
                                        _Notification.InsertNotification(Notification);
                                        if (Customer.DeviceType == EnumValue.GetEnumDescription(EnumValue.DeviceType.Android))
                                        {
                                            CommonCls.SendGCM_Notifications(Customer.ApplicationId, JsonMessage, true);
                                        }
                                        else
                                        {
                                            int count = _Notification.GetNotifications().Where(c => c.NotificationSendTo == Convert.ToInt32(Customer.CustomerId) && c.IsRead == false).ToList().Count();
                                            //Dictionary<string, object> Dictionary = new Dictionary<string, object>();
                                            //Dictionary.Add("Flag", Flag);
                                            //Dictionary.Add("Message", Message);
                                            //NotificationStatus = PushNotificatinAlert.SendPushNotification(Customer.ApplicationId, Message, Flag, JsonMessage, Dictionary, 1, Convert.ToBoolean(Customer.IsNotificationSoundOn));
                                            CommonCls.TestSendFCM_Notifications(Customer.ApplicationId, JsonMessage, Message, count, true);
                                            ////Save Notification
                                            //Notification Notification = new Notification();
                                            //Notification.NotificationSendBy = 1;
                                            //Notification.NotificationSendTo = Customer.CustomerId;
                                            //Notification.IsRead = false;
                                            //Notification.RequestMessage = Message;
                                            //_Notification.InsertNotification(Notification);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        CommonCls.ErrorLog(ex.ToString());
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ErrorLogging.LogError(ex);
                        throw;
                    }

                    TempData["ShowMessage"] = "success";
                    TempData["MessageBody"] = "Event successfully saved.";
                    return(RedirectToAction("Index"));
                }
                var errors           = ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => new { x.Key, x.Value.Errors }).ToArray();
                var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);
                var CustomerList1    = _CustomerService.GetCustomers();
                EventModel.CustomersList = CustomerList1.Select(x => new SelectListItem {
                    Value = x.CustomerId.ToString(), Text = x.FirstName
                }).ToList();
                EventModel.CustomerId = 1;
                return(View(EventModel));
            }
            catch (Exception ex)
            {
                ErrorLogging.LogError(ex);

                return(View(EventModel));
            }
        }
Ejemplo n.º 3
0
        public ActionResult Create([Bind(Include = "CurrencyName,CountryID,CountryName,CreatedOn,IsActive,ISOAlpha2,ISOAlpha3,ISONumeric,CurrencyCode,CurrrencySymbol,CountryFlag,SubUnitName,SubUnitValue")] CountryModel countrymodel, HttpPostedFileBase file)
        {
            try
            {
                TempData["ShowMessage"] = "error";
                TempData["MessageBody"] = "Please fill the required field with valid data";
                UserPermissionAction("Country", RoleAction.create.ToString());
                CheckPermission();
                var checkcountry = _CountryService.GetCountries().Where(c => c.CountryName == countrymodel.CountryName).FirstOrDefault();
                if (ModelState.IsValid)
                {
                    if (checkcountry == null)
                    {
                        Mapper.CreateMap <EveryWhereCars.Models.CountryModel, EveryWhereCars.Entity.Country>();
                        EveryWhereCars.Entity.Country countrytype = Mapper.Map <EveryWhereCars.Models.CountryModel, EveryWhereCars.Entity.Country>(countrymodel);
                        // countrytype.CompanyID = 1;
                        var    fileExt  = Path.GetExtension(file.FileName);
                        string fileName = Guid.NewGuid() + fileExt;
                        var    subPath  = Server.MapPath("~/CountryFlags");

                        //Check SubPath Exist or Not
                        if (!Directory.Exists(subPath))
                        {
                            Directory.CreateDirectory(subPath);
                        }
                        //End : Check SubPath Exist or Not

                        var path = Path.Combine(subPath, fileName);
                        file.SaveAs(path);
                        string URL = "/CountryFlags/" + fileName;
                        countrytype.CountryFlag = URL;
                        _CountryService.InsertCountry(countrytype);
                        TempData["ShowMessage"] = "success";
                        TempData["MessageBody"] = "country is saved successfully.";
                        return(RedirectToAction("Index"));
                    }
                    else
                    {
                        TempData["ShowMessage"] = "error";
                        if (checkcountry.CountryName == countrymodel.CountryName.Trim())
                        {
                            TempData["MessageBody"] = countrymodel.CountryName + " is already exists.";
                        }

                        else
                        {
                            TempData["MessageBody"] = "Please fill the required field with valid data";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorLogging.LogError(ex);
                TempData["ShowMessage"] = "error";
                TempData["MessageBody"] = "Some unknown problem occured while proccessing save operation on " + countrymodel.CountryName;
            }



            return(View(countrymodel));
        }
        public ActionResult Create([Bind(Include = "MessageId,CustomerIds,Messages,Heading,CreatedOn,LastUpdatedOn,IsActive,SelectedCustomer")] MessageModel MessageModel, HttpPostedFileBase[] files)
        {
            UserPermissionAction("message", RoleAction.create.ToString());
            CheckPermission();
            string PhotoPath = "";

            try
            {
                int AdminId = Convert.ToInt32(Session["CustomerID"]) == null ? 0 : Convert.ToInt32(Session["CustomerID"]);
                TempData["ShowMessage"] = "";
                TempData["MessageBody"] = "";
                if (ModelState.IsValid)
                {
                    var Customerids = "";
                    Mapper.CreateMap <CommunicationApp.Models.MessageModel, CommunicationApp.Entity.Message>();
                    CommunicationApp.Entity.Message Message = Mapper.Map <CommunicationApp.Models.MessageModel, CommunicationApp.Entity.Message>(MessageModel);
                    if (MessageModel.SelectedCustomer != null)
                    {
                        Customerids = string.Join(",", MessageModel.SelectedCustomer);
                    }
                    else
                    {
                        var CustomerIdList = _CustomerService.GetCustomers().Select(c => c.CustomerId);
                        Customerids = string.Join(",", CustomerIdList);
                    }
                    if (Customerids != null && Customerids != "")
                    {
                        Message.CustomerIds = Customerids;
                    }
                    Message.CreatedOn = DateTime.Now;
                    Message.AdminId   = AdminId;
                    Message.IsActive  = true;

                    _MessageService.InsertMessage(Message);
                    if (files[0] != null)
                    {
                        foreach (HttpPostedFileBase file in files)
                        {
                            MessageImage MessageImage = new MessageImage();
                            MessageImage.MessageId = Message.MessageId;;
                            MessageImage.ImageUrl  = SaveFile(PhotoPath, file);
                            _MessageImageService.InsertMessageImage(MessageImage);
                        }
                    }
                    JobScheduler.SendMessageNotification(AdminId.ToString(), Customerids, Message.Messages, Message.Heading, Message.ImageUrl, MessageModel.IsWithImage.ToString());

                    TempData["ShowMessage"] = "success";
                    TempData["MessageBody"] = "message is saved successfully.";
                    return(RedirectToAction("Index"));
                }
                var errors           = ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => new { x.Key, x.Value.Errors }).ToArray();
                var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);
            }
            catch (Exception ex)
            {
                ErrorLogging.LogError(ex);

                TempData["ShowMessage"] = "error";
                TempData["MessageBody"] = "Some unknown problem occured while proccessing save operation on Tip.";
            }
            var CustomerList1 = _CustomerService.GetCustomers();

            MessageModel.CustomersList = CustomerList1.Select(x => new SelectListItem {
                Value = x.CustomerId.ToString(), Text = x.FirstName
            }).ToList();
            return(View(MessageModel));
        }
Ejemplo n.º 5
0
 public void Update(ErrorLogging item)
 {
     _context.ErrorLogging.Update(item);
 }
Ejemplo n.º 6
0
 public void Add(ErrorLogging item)
 {
     _context.ErrorLogging.Add(item);
 }
Ejemplo n.º 7
0
 public UploadToFTP(Config config, ErrorLogging error)
 {
     _config = config;
     _error  = error;
 }
Ejemplo n.º 8
0
        private string GetPB(string game, bool isCurrentGame, string category, string level, Dictionary <string, string> subcategories, Dictionary <string, string> variables)
        {
            try
            {
                SetParameters(ref isCurrentGame, ref category, ref level, ref subcategories, ref variables);

                var srSearch = new SpeedrunComClient();
                var srGame   = srSearch.Games.SearchGame(game);

                if (srGame == null)
                {
                    return("No game was found");
                }
                else
                {
                    //Levels generally have different category, so they need a seperate look up
                    if (level != "")
                    {
                        Category srCategory;
                        if (category == "")
                        {
                            srCategory = srGame.LevelCategories.ElementAt(0);
                        }
                        else
                        {
                            srCategory = srGame.LevelCategories.FirstOrDefault(cat => cat.Name.ToLower().StartsWith(category.ToLower()));
                        }

                        if (srCategory == null)
                        {
                            return("No category was found");
                        }

                        var srLevel = srGame.Levels.FirstOrDefault(lvl => lvl.Name.ToLower().StartsWith(level.ToLower()));
                        if (srLevel == null)
                        {
                            return("No level was found");
                        }

                        var pbs = srSearch.Users.GetPersonalBests(Speedrunusername, gameId: srGame.ID);

                        var levelPBs = pbs.Where(x => x.LevelID == srLevel.ID);
                        if (levelPBs.Count() > 0)
                        {
                            var SRVariables = GetVariablesForLevel(ref subcategories, ref variables, ref srCategory, ref srLevel);

                            var bestPBsInCategory = levelPBs.Where(x => x.Category.ID == srCategory.ID);
                            if (SRVariables != null)
                            {
                                for (int i = 0; i < SRVariables.Count; i++)
                                {
                                    bestPBsInCategory = bestPBsInCategory.Where(x => x.VariableValues.Contains(SRVariables[i]));
                                }
                            }

                            var bestPBInCategory = bestPBsInCategory.FirstOrDefault();

                            if (bestPBInCategory != null)
                            {
                                return(string.Format("Streamer\'s PB for {0} ({1}) in level \"{2}\" is {3} - {4}", srGame.Name, srCategory.Name, srLevel.Name, bestPBInCategory.Times.Primary.ToString(), bestPBInCategory.WebLink));
                            }
                            else
                            {
                                return(string.Format("No PB in category {0} for level {1} was found.", srCategory.Name, srLevel.Name));
                            }
                        }
                        else
                        {
                            return("No PBs found for this level");
                        }
                    }
                    else                                         //Full-game run
                    {
                        Category srCategory;
                        if (category == "")
                        {
                            srCategory = srGame.FullGameCategories.ElementAt(0);
                        }
                        else
                        {
                            srCategory = srGame.FullGameCategories.FirstOrDefault(cat => cat.Name.ToLower().StartsWith(category.ToLower()));
                        }

                        if (srCategory == null)
                        {
                            return("No category was found");
                        }

                        var pbs = srSearch.Users.GetPersonalBests(Speedrunusername, gameId: srGame.ID);

                        if (pbs.Count > 0)
                        {
                            var SRVariables = GetVariablesForFullGameCategory(ref subcategories, ref variables, ref srCategory);

                            var bestPBsInCategory = pbs.Where(x => x.Category.ID == srCategory.ID);
                            if (SRVariables != null)
                            {
                                for (int i = 0; i < SRVariables.Count; i++)
                                {
                                    bestPBsInCategory = bestPBsInCategory.Where(x => x.VariableValues.Contains(SRVariables[i]));
                                }
                            }

                            if (bestPBsInCategory.Count() > 0)
                            {
                                return(string.Format("Streamer\'s PB for {0} ({1}) is {2} - {3}",
                                                     srGame.Name,
                                                     srCategory.Name,
                                                     bestPBsInCategory.ElementAt(0).Times.Primary.ToString(),
                                                     bestPBsInCategory.ElementAt(0).WebLink));
                            }
                            else
                            {
                                return("Stremer doesn\'t seem to have any PBs in category " + srCategory.Name);
                            }
                        }
                        else
                        {
                            return("Streamer doesn\'t have any PBs in this game.");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                ErrorLogging.WriteLine(e.ToString());
                return("Error looking for a game on speedrun.com");
            }
        }
 public HttpResponseMessage PurchaseProduct(PurchaseModel PurchaseModel)
 {
     try
     {
         if (PurchaseModel.ProductId == 0)
         {
             return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Product Id is blank."), Configuration.Formatters.JsonFormatter));
         }
         if (PurchaseModel.CustomerId == new Guid())
         {
             return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Customer Id is blank."), Configuration.Formatters.JsonFormatter));
         }
         if (PurchaseModel.Size == "" || PurchaseModel.Size == null)
         {
             return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Size is blank."), Configuration.Formatters.JsonFormatter));
         }
         if (PurchaseModel.Size != EnumValue.GetEnumDescription(EnumValue.ProductSizes.L) && PurchaseModel.Size != EnumValue.GetEnumDescription(EnumValue.ProductSizes.M) && PurchaseModel.Size != EnumValue.GetEnumDescription(EnumValue.ProductSizes.XL) && PurchaseModel.Size != EnumValue.GetEnumDescription(EnumValue.ProductSizes.XXL))
         {
             return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Size is wrong."), Configuration.Formatters.JsonFormatter));
         }
         if (PurchaseModel.Quantity == 0)
         {
             return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Product Id is blank."), Configuration.Formatters.JsonFormatter));
         }
         if (PurchaseModel.Latitude == 0)
         {
             return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Latitude is blank."), Configuration.Formatters.JsonFormatter));
         }
         if (PurchaseModel.Longitude == 0)
         {
             return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Longitude is blank."), Configuration.Formatters.JsonFormatter));
         }
         if (PurchaseModel.PaymentId == 0)
         {
             return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Payment Id is blank."), Configuration.Formatters.JsonFormatter));
         }
         var Customer = _CustomerService.GetCustomer(PurchaseModel.CustomerId);
         if (Customer != null)
         {
             if (Customer.IsActive)
             {
                 var products = _ProductService.GetProducts().Where(p => p.ProductId == PurchaseModel.ProductId).FirstOrDefault();
                 if (products != null)
                 {
                     Mapper.CreateMap <PurchaseModel, Purchase>();
                     var purchase = Mapper.Map <PurchaseModel, Purchase>(PurchaseModel);
                     _PurchaseService.InsertPurchase(purchase);
                     return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("success", "Successfully purchased."), Configuration.Formatters.JsonFormatter));
                 }
                 else
                 {
                     return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "no products found."), Configuration.Formatters.JsonFormatter));
                 }
             }
             else
             {
                 return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "User not found."), Configuration.Formatters.JsonFormatter));
             }
         }
         else
         {
             return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "User not found."), Configuration.Formatters.JsonFormatter));
         }
     }
     catch (Exception ex)
     {
         string ErrorMsg = ex.Message.ToString();
         ErrorLogging.LogError(ex);
         return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Try again later."), Configuration.Formatters.JsonFormatter));
     }
 }
        public static Object setNewPatternAndProcessFile(string PATTERNNAME, string FILENAME)
        {
            Int32         patternID = 0;
            List <string> data      = new List <string>();
            Int32         rowCount;
            DateTime      now = DateTime.Now;

            try
            {
                ZXPUserData zxpUD          = ZXPUserData.GetZXPUserDataFromCookie();
                string[]    newFileAndPath = TransportHelperFunctions.ProcessFileAndData(FILENAME, "PATTERN");

                if (2 == newFileAndPath.Length)
                {
                    using (var scope = new TransactionScope())
                    {
                        string sqlCmdText;
                        //sql_connStr = new TruckScheduleConfigurationKeysHelper().sql_connStr;

                        sqlCmdText = "SELECT COUNT (*) FROM dbo.Patterns " +
                                     "WHERE PatternName = @PatternName AND isHidden = 'false'";
                        rowCount = Convert.ToInt32(SqlHelper.ExecuteScalar(sql_connStr, CommandType.Text, sqlCmdText, new SqlParameter("@PatternName", PATTERNNAME)));

                        if (rowCount <= 0)
                        {
                            sqlCmdText = "INSERT INTO dbo.Patterns (FileNameOld, FileNameNew, FilePath, PatternName, isHidden) VALUES (@FileNameOld, @FileNameNew, @FilePath, @PatternName, 'false'); " +
                                         "SELECT CAST(scope_identity() AS int)";

                            patternID = Convert.ToInt32(SqlHelper.ExecuteScalar(sql_connStr, CommandType.Text, sqlCmdText, new SqlParameter("@FileNameOld", FILENAME),
                                                                                new SqlParameter("@FileNameNew", newFileAndPath[1]),
                                                                                new SqlParameter("@FilePath", newFileAndPath[0]),
                                                                                new SqlParameter("@PatternName", PATTERNNAME)));

                            ChangeLog cl = new ChangeLog(ChangeLog.ChangeLogChangeType.INSERT, "Patterns", "isHidden", now, zxpUD._uid, ChangeLog.ChangeLogDataType.BIT, "'false'", null, "PatternID", patternID.ToString());
                            cl.CreateChangeLogEntryIfChanged();
                            cl = new ChangeLog(ChangeLog.ChangeLogChangeType.INSERT, "Patterns", "FileNameOld", now, zxpUD._uid, ChangeLog.ChangeLogDataType.NVARCHAR, FILENAME.ToString(), null, "PatternID", patternID.ToString());
                            cl.CreateChangeLogEntryIfChanged();
                            cl = new ChangeLog(ChangeLog.ChangeLogChangeType.INSERT, "Patterns", "FileNameNew", now, zxpUD._uid, ChangeLog.ChangeLogDataType.NVARCHAR, newFileAndPath[1].ToString(), null, "PatternID", patternID.ToString());
                            cl.CreateChangeLogEntryIfChanged();
                            cl = new ChangeLog(ChangeLog.ChangeLogChangeType.INSERT, "Patterns", "PatternName", now, zxpUD._uid, ChangeLog.ChangeLogDataType.NVARCHAR, PATTERNNAME.ToString(), null, "PatternID", patternID.ToString());
                            cl.CreateChangeLogEntryIfChanged();
                            cl = new ChangeLog(ChangeLog.ChangeLogChangeType.INSERT, "Patterns", "FilePath", now, zxpUD._uid, ChangeLog.ChangeLogDataType.NVARCHAR, PATTERNNAME.ToString(), null, "PatternID", patternID.ToString());
                            cl.CreateChangeLogEntryIfChanged();

                            data.Add(patternID.ToString());
                            data.Add(newFileAndPath[0]);
                            data.Add(newFileAndPath[1]);
                        }
                        else
                        {
                            throw new Exception("Pattern name already exist");
                        }
                        scope.Complete();
                    }
                }
                else
                {
                    throw new Exception("renameAndMoveFile returned null or empty string");
                }
            }
            catch (Exception ex)
            {
                string strErr = " Exception Error in Admin_Patterns setNewPatternAndProcessFile(). Details: " + ex.ToString();
                ErrorLogging.WriteEvent(strErr, EventLogEntryType.Error);
                System.Web.HttpContext.Current.Session["ErrorNum"] = 1;
                ErrorLogging.sendtoErrorPage(1);
                throw ex;
            }
            return(data);
        }
Ejemplo n.º 11
0
 private void AdControl_ErrorOccurred(object sender, Microsoft.Advertising.AdErrorEventArgs e)
 {
     ErrorLogging.Log(this.GetType().ToString(), e.Error.Message, string.Empty, string.Empty);
 }
        public ActionResult Edit([Bind(Include = "RewardId,Title,Description,Smileys")] RewardModel RewardModel, HttpPostedFileBase file)
        {
            UserPermissionAction("Category", RoleAction.view.ToString());
            CheckPermission();
            try
            {
                if (string.IsNullOrWhiteSpace(RewardModel.Title))
                {
                    ModelState.AddModelError("Title", "Please enter Title.");
                }
                if (string.IsNullOrWhiteSpace(RewardModel.Description))
                {
                    ModelState.AddModelError("Description", "Please enter Description.");
                }
                if (RewardModel.Smileys == 0)
                {
                    ModelState.AddModelError("Smileys", "Please enter smileys.");
                }

                if (ModelState.IsValid)
                {
                    //Reward RewardFound = _RewardService.GetRewards().Where(x => x.Name == RewardModel.Name && x.RewardId != RewardModel.RewardId).FirstOrDefault();
                    var existingReward = _RewardService.GetRewards().Where(c => c.RewardId == RewardModel.RewardId).FirstOrDefault();
                    Mapper.CreateMap <RewardModel, Reward>();
                    var Reward = Mapper.Map <RewardModel, Reward>(RewardModel);
                    if (file != null && file.ContentLength > 0)
                    {
                        try
                        {
                            if (existingReward.ImagePath != "")
                            {
                                DeleteImage(existingReward.ImagePath);
                            }

                            string path = Path.Combine(Server.MapPath("~/RewardImage"), Path.GetFileName(file.FileName));
                            file.SaveAs(path);

                            string URL = CommonCls.GetURL() + "/RewardImage/" + file.FileName;
                            Reward.ImagePath = URL;
                        }
                        catch (Exception ex)
                        {
                            ViewBag.Message = "ERROR:" + ex.Message.ToString();
                        }
                    }
                    else
                    {
                        Reward.ImagePath = existingReward.ImagePath;
                    }

                    if (existingReward != null)
                    {
                        _RewardService.UpdateReward(Reward);

                        TempData["ShowMessage"] = "success";
                        TempData["MessageBody"] = " Reward update  successfully.";
                        return(RedirectToAction("Index"));
                        // end  Update CompanyEquipments
                    }

                    else
                    {
                        TempData["MessageBody"] = "reward not found.";
                    }
                }
                else
                {
                    return(View(RewardModel));
                }
            }
            catch (Exception ex)
            {
                string ErrorMsg = ex.Message.ToString();//
                ErrorLogging.LogError(ex);
            }
            //ViewBag.Category = new SelectList(_CategoryService.GetCategories(), "CategoryId", "Name", RewardModel.RewardId);
            var errors           = ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => new { x.Key, x.Value.Errors }).ToArray();
            var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);

            return(View(RewardModel));
        }
        public ActionResult Create([Bind(Include = "Title,Description,Smileys")] RewardModel RewardModel, HttpPostedFileBase file)
        {
            UserPermissionAction("Category", RoleAction.view.ToString());
            CheckPermission();
            try
            {
                if (string.IsNullOrWhiteSpace(RewardModel.Title))
                {
                    ModelState.AddModelError("Title", "Please enter Title.");
                }
                if (string.IsNullOrWhiteSpace(RewardModel.Description))
                {
                    ModelState.AddModelError("Description", "Please enter Description.");
                }
                if (RewardModel.Smileys == 0)
                {
                    ModelState.AddModelError("Smileys", "Please enter smileys.");
                }

                if (ModelState.IsValid)
                {
                    string URL = "";
                    if (file != null && file.ContentLength > 0)
                    {
                        try
                        {
                            if (file != null && file.ContentLength > 0)
                            {
                                string path = Path.Combine(Server.MapPath("~/RewardImage"), Path.GetFileName(file.FileName));
                                file.SaveAs(path);
                                URL = CommonCls.GetURL() + "/RewardImage/" + file.FileName;
                            }
                        }
                        catch (Exception ex)
                        {
                            ViewBag.Message = "ERROR:" + ex.Message.ToString();
                        }
                    }
                    Mapper.CreateMap <RewardModel, Reward>();
                    var Reward = Mapper.Map <RewardModel, Reward>(RewardModel);
                    Reward.ImagePath = URL;
                    _RewardService.InsertReward(Reward);

                    TempData["ShowMessage"] = "success";
                    TempData["MessageBody"] = " Reward save  successfully.";
                    return(RedirectToAction("Index"));
                }
                else
                {
                    return(View(RewardModel));
                }
            }


            catch (Exception ex)
            {
                string ErrorMsg = ex.Message.ToString();//
                ErrorLogging.LogError(ex);
            }
            var errors           = ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => new { x.Key, x.Value.Errors }).ToArray();
            var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);

            return(View(RewardModel));
        }
Ejemplo n.º 14
0
        protected void btnRegister_Click(object sender, EventArgs e)
        {
            ELibraryDocumentBL docBL   = new ELibraryDocumentBL();
            UserDetails        userObj = new UserDetails();
            StringBuilder      sb      = new StringBuilder();

            try
            {
                userObj.UserID    = txtUserId.Text;
                Session["UserId"] = userObj.UserID;
                userObj.FirstName = txtFirstName.Text;
                userObj.LastName  = txtLastName.Text;
                DateTime dob;
                bool     isValidDate = DateTime.TryParse(txtDateOfBirth.Text, out dob);
                if (isValidDate)
                {
                    userObj.DateOfBirth = dob;
                }
                else
                {
                    throw new ELibraryException("Please enter date of birth");
                }

                if (rblGender.SelectedValue == "Male")
                {
                    userObj.Gender = "M";
                }

                else
                {
                    userObj.Gender = "F";
                }
                userObj.UserAddress    = txtAddress.Text;
                userObj.LandLineNumber = txtLandlineNumber.Text;
                userObj.MobileNumber   = txtboxMobileNumber.Text;
                userObj.Pasword        = txtPassword.Text;



                for (int i = 0; i < chklAreasofInterest.Items.Count; i++)
                {
                    if (chklAreasofInterest.Items[i].Selected)
                    {
                        int j = 0;
                        j = i + 1;
                        var name = docBL.GetDisciplineNameBL(j);
                        sb.Append(name + ",");
                    }
                }
                int itemsSelected = 0;
                foreach (ListItem li in chklAreasofInterest.Items)
                {
                    if (li.Selected)
                    {
                        itemsSelected = itemsSelected + 1;
                    }
                }
                if (itemsSelected == 0)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please select atleast one checkbox')", true);
                    //Response.Write("<script>alert('Please select atleast one checkbox')</script>");
                }



                userObj.AreaOfInterest = sb.ToString();

                userObj.DateOfRegistration = DateTime.Now;
                userObj.UserType           = "Non Scubscriber";

                ELibraryUserBL userBL = new ELibraryUserBL();

                bool isAdded = userBL.RegisterBL(userObj);
                if (isAdded)
                {
                    lblException.Text = "Registered";
                }
                if (chksubscribe.Checked == true)
                {
                    Session["Amount"]    = 1000;
                    Session["Subscribe"] = true;
                    PaymentForm payForm = new PaymentForm();
                    Response.Redirect("PaymentForm.aspx");
                }
            }
            catch (ELibraryException ex)
            {
                ErrorLogging erLog = new ErrorLogging();
                erLog.LogError(ex.Message);
                ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + ex.Message + "')", true);
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Channel Parser
        /// RegEx Style Processing here
        /// </summary>
        /// <param name="data"></param>
        /// <remarks></remarks>
        public void ChannelProcess(ref string data, bool Handled)
        {
        //Strip the trigger Character
        // page = engine.LoadFromString(cBot.MS_Script)
        data = data.Remove(0, 1);
        bool psCheck = false;
        string SpecTag = "";
        Channel = Regex.Match(data, ChannelNameFilter).Groups(1).Value;
        string Color = Regex.Match(data, EntryFilter).Groups(1).Value;
        string User = "";
        string Desc = "";
        string Text = "";
        if (!Handled) {
        Text = Regex.Match(data, EntryFilter).Groups(2).Value;
        User = Regex.Match(data, NameFilter).Groups(3).Value;
        if (!string.IsNullOrEmpty(User))
            Player = NametoFurre(User, true);
        Player.Message = "";
        Desc = Regex.Match(data, DescFilter).Groups(2).Value;
        Regex mm = new Regex(Iconfilter);
        System.Text.RegularExpressions.Match ds = mm.Match(Text);
        Text = mm.Replace(Text, "[" + ds.Groups(1).Value + "] ");
        Regex s = new Regex(ChannelNameFilter);
        Text = s.Replace(Text, "");
        } else {
        User = Player.Name;
        Text = Player.Message;
        }
        DiceSides = 0;
        DiceCount = 0;
        DiceCompnentMatch = "";
        DiceModifyer = 0;
        DiceResult = 0;

        lock (Lock) {
        ErrorMsg = "";
        ErrorNum = 0;
        }
        if (Channel == "@news" | Channel == "@spice") {
        try {
            sndDisplay(Text);
        } catch (Exception eX) {
            ErrorLogging logError = new ErrorLogging(eX, this);
        }
        if (smProxy.IsClientConnected)
            smProxy.SendClient("(" + data + Constants.vbLf);
        return;
        } else if (Color == "success") {

            return;

        } else if (Channel == "@roll") {
        Regex DiceREGEX = new Regex(DiceFilter, RegexOptions.IgnoreCase);
        System.Text.RegularExpressions.Match DiceMatch = DiceREGEX.Match(data);

        //Matches, in order:
        //1:      shortname()
        //2:      full(name)
        //3:      dice(count)
        //4:      sides()
        //5: +/-#
        //6: +/-  (component match)
        //7:      additional(Message)
        //8:      Final(result)

        Player = NametoFurre(DiceMatch.Groups(3).Value, true);
        Player.Message = DiceMatch.Groups(7).Value;
        MainMSEngine.PageSetVariable(Main.VarPrefix + "MESSAGE", DiceMatch.Groups(7).Value);
        double.TryParse(DiceMatch.Groups(4).Value, DiceSides);
        double.TryParse(DiceMatch.Groups(3).Value, DiceCount);
        DiceCompnentMatch = DiceMatch.Groups(6).Value;
        DiceModifyer = 0.0;
        double.TryParse(DiceMatch.Groups(5).Value, DiceModifyer);
        double.TryParse(DiceMatch.Groups(8).Value, DiceResult);

        if (IsBot(Player)) {
            MainMSEngine.PageExecute(130, 131, 132, 136);
        } else {
            MainMSEngine.PageExecute(133, 134, 135, 136);
        }

        if (smProxy.IsClientConnected)
            smProxy.SendClient("(" + data + Constants.vbLf);
        return;
        } else if (Channel == "@dragonspeak" || Channel == "@emit" || Color == "emit") {
        try {
            //(<font color='dragonspeak'><img src='fsh://system.fsh:91' alt='@emit' /><channel name='@emit' /> Furcadian Academy</font>
            sndDisplay(Text, fColorEnum.Emit);

            MainMSEngine.PageSetVariable(Main.VarPrefix + "MESSAGE", Text.Substring(5));
            // Execute (0:21) When someone emits something
            MainMSEngine.PageExecute(21, 22, 23);
            // Execute (0:22) When someone emits {...}
            //' Execute (0:23) When someone emits something with {...} in it

        } catch (Exception eX) {
            ErrorLogging logError = new ErrorLogging(eX, this);
        }
        if (smProxy.IsClientConnected)
            smProxy.SendClient("(" + data + Constants.vbLf);
        return;
        //'BCast (Advertisments, Announcments)
        } else if (Color == "bcast") {
        string AdRegEx = "<channel name='(.*)' />";

        string chan = Regex.Match(data, AdRegEx).Groups(1).Value;

        try {
            switch (chan) {
                case "@advertisements":
                    if (cMain.Advertisment)
                        return;

                    AdRegEx = "\\[(.*?)\\] (.*?)</font>";
                    string adMessage = Regex.Match(data, AdRegEx).Groups(2).Value;
                    sndDisplay(Text);
                    break;
                case "@bcast":
                    if (cMain.Broadcast)
                        return;

                    string u = Regex.Match(data, "<channel name='@(.*?)' />(.*?)</font>").Groups(2).Value;
                    sndDisplay(Text);
                    break;
                case "@announcements":
                    if (cMain.Announcement)
                        return;

                    string u = Regex.Match(data, "<channel name='@(.*?)' />(.*?)</font>").Groups(2).Value;
                    sndDisplay(Text);
                    break;
                default:
                    #if DEBUG
                    Console.WriteLine("Unknown ");
                    Console.WriteLine("BCAST:" + data);
                    #endif
                    break;
            }

        } catch (Exception eX) {
            ErrorLogging logError = new ErrorLogging(eX, this);
        }
        if (smProxy.IsClientConnected)
            smProxy.SendClient("(" + data + Constants.vbLf);
        return;
        //'SAY
        } else if (Color == "myspeech") {
        try {
            Regex t = new Regex(YouSayFilter);
            string u = t.Match(data).Groups(1).ToString;
            Text = t.Match(data).Groups(2).ToString;
            if (SpeciesTag.Count() > 0) {
                SpecTag = SpeciesTag.Peek;
                SpeciesTag.Dequeue();
                Player.Color = SpecTag;
                if (DREAM.List.ContainsKey(Player.ID))
                    DREAM.List.Item(Player.ID) = Player;
            }

            sndDisplay("You " + u + ", \"" + Text + "\"", fColorEnum.Say);
            Player.Message = Text;
            MainMSEngine.PageSetVariable(Main.VarPrefix + "MESSAGE", Text);
            // Execute (0:5) When some one says something
            //MainMSEngine.PageExecute(5, 6, 7, 18, 19, 20)
            //' Execute (0:6) When some one says {...}
            //' Execute (0:7) When some one says something with {...} in it
            //' Execute (0:18) When someone says or emotes something
            //' Execute (0:19) When someone says or emotes {...}
            //' Execute (0:20) When someone says or emotes something with {...} in it
        } catch (Exception eX) {
            ErrorLogging logError = new ErrorLogging(eX, this);
        }
        if (smProxy.IsClientConnected)
            smProxy.SendClient("(" + data + Constants.vbLf);
        return;
        } else if (!string.IsNullOrEmpty(User) & string.IsNullOrEmpty(Channel) & string.IsNullOrEmpty(Color) & Regex.Match(data, NameFilter).Groups(2).Value != "forced") {
        System.Text.RegularExpressions.Match tt = Regex.Match(data, "\\(you see(.*?)\\)", RegexOptions.IgnoreCase);
        Regex t = new Regex(NameFilter);

        if (!tt.Success) {
            try {
                Text = t.Replace(data, "");
                Text = Text.Remove(0, 2);

                if (SpeciesTag.Count() > 0) {
                    SpecTag = SpeciesTag.Peek;
                    SpeciesTag.Clear();
                    Player.Color = SpecTag;
                    if (DREAM.List.ContainsKey(Player.ID))
                        DREAM.List.Item(Player.ID) = Player;
                }
                Channel = "say";
                sndDisplay(User + " says, \"" + Text + "\"", fColorEnum.Say);
                MainMSEngine.PageSetVariable(MS_Name, User);
                MainMSEngine.PageSetVariable("MESSAGE", Text);
                Player.Message = Text;
                // Execute (0:5) When some one says something
                MainMSEngine.PageExecute(5, 6, 7, 18, 19, 20);
                // Execute (0:6) When some one says {...}
                // Execute (0:7) When some one says something with {...} in it
                // Execute (0:18) When someone says or emotes something
                // Execute (0:19) When someone says or emotes {...}
                // Execute (0:20) When someone says or emotes something with {...} in it

            } catch (Exception eX) {
                ErrorLogging logError = new ErrorLogging(eX, this);

            }

            if (smProxy.IsClientConnected)
                smProxy.SendClient("(" + data + Constants.vbLf);
            return;
        } else {
            try {
                //sndDisplay("You See '" & User & "'")
                Look = true;
            } catch (Exception eX) {
                ErrorLogging logError = new ErrorLogging(eX, this);
            }
        }

        } else if (!string.IsNullOrEmpty(Desc)) {
        try {
            string DescName = Regex.Match(data, DescFilter).Groups(1).ToString();

            Player = NametoFurre(DescName, true);
            if (LookQue.Count > 0) {
                string colorcode = LookQue.Peek;
                if (colorcode.StartsWith("t")) {
                    colorcode = colorcode.Substring(0, 14);

                } else if (colorcode.StartsWith("u")) {
                } else if (colorcode.StartsWith("v")) {
                    //RGB Values
                }
                Player.Color = colorcode;
                LookQue.Dequeue();
            }
            if (BadgeTag.Count() > 0) {
                SpecTag = BadgeTag.Peek;
                BadgeTag.Clear();
                Player.Badge = SpecTag;
            } else if (!string.IsNullOrEmpty(Player.Badge)) {
                Player.Badge = "";
            }
            Player.Desc = Desc.Substring(6);
            if (DREAM.List.ContainsKey(Player.ID))
                DREAM.List.Item(Player.ID) = Player;
            MainMSEngine.PageSetVariable(MS_Name, DescName);
            MainMSEngine.PageExecute(600);
            //sndDisplay)
            if (string.IsNullOrEmpty(Player.Tag)) {
                sndDisplay("You See '" + Player.Name + "'\\par" + Desc);
            } else {
                sndDisplay("You See '" + Player.Name + "'\\par" + Player.Tag + " " + Desc);
            }
            Look = false;
        } catch (Exception eX) {
            ErrorLogging logError = new ErrorLogging(eX, this);
        }
        if (smProxy.IsClientConnected)
            smProxy.SendClient("(" + data + Constants.vbLf);
        return;
        } else if (Color == "shout") {
        //'SHOUT
        try {
            Regex t = new Regex(YouSayFilter);
            string u = t.Match(data).Groups(1).ToString;
            Text = t.Match(data).Groups(2).ToString;
            if (string.IsNullOrEmpty(User)) {
                sndDisplay("You " + u + ", \"" + Text + "\"", fColorEnum.Shout);
            } else {
                Text = Regex.Match(data, "shouts: (.*)</font>").Groups(1).ToString();
                sndDisplay(User + " shouts, \"" + Text + "\"", fColorEnum.Shout);
            }
            if (!IsBot(Player)) {
                MainMSEngine.PageSetVariable(Main.VarPrefix + "MESSAGE", Text);
                Player.Message = Text;
                // Execute (0:8) When some one shouts something
                MainMSEngine.PageExecute(8, 9, 10);
                // Execute (0:9) When some one shouts {...}
                // Execute (0:10) When some one shouts something with {...} in it

            }
        } catch (Exception eX) {
            ErrorLogging logError = new ErrorLogging(eX, this);
        }
        if (smProxy.IsClientConnected)
            smProxy.SendClient("(" + data + Constants.vbLf);
        return;
        } else if (Color == "query") {
        string QCMD = Regex.Match(data, "<a.*?href='command://(.*?)'>").Groups(1).ToString;
        //Player = NametoFurre(User, True)
        switch (QCMD) {
            case "summon":
                //'JOIN
                try {
                    sndDisplay(User + " requests to join you.");
                    //If Not IsBot(Player) Then
                    MainMSEngine.PageExecute(34, 35);
                    //End If
                } catch (Exception eX) {
                    ErrorLogging logError = new ErrorLogging(eX, this);
                }
                break;
            case "join":
                //'SUMMON
                try {
                    sndDisplay(User + " requests to summon you.");
                    //If Not IsBot(Player) Then
                    MainMSEngine.PageExecute(32, 33);
                    //End If
                } catch (Exception eX) {
                    ErrorLogging logError = new ErrorLogging(eX, this);
                }
                break;
            case "follow":
                //'LEAD
                try {
                    sndDisplay(User + " requests to lead.");
                    //If Not IsBot(Player) Then
                    MainMSEngine.PageExecute(36, 37);
                    //End If
                } catch (Exception eX) {
                    ErrorLogging logError = new ErrorLogging(eX, this);
                }
                break;
            case "lead":
                //'FOLLOW
                try {
                    sndDisplay(User + " requests the bot to follow.");
                    //If Not IsBot(Player) Then
                    MainMSEngine.PageExecute(38, 39);
                    //End If
                } catch (Exception eX) {
                    ErrorLogging logError = new ErrorLogging(eX, this);
                }
                break;
            case "cuddle":
                try {
                    sndDisplay(User + " requests the bot to cuddle.");
                    //If Not IsBot(Player) Then
                    MainMSEngine.PageExecute(40, 41);
                    //End If
                } catch (Exception eX) {
                    ErrorLogging logError = new ErrorLogging(eX, this);
                }
                break;
            default:
                sndDisplay("## Unknown " + Channel + "## " + data);
                break;
        }

        //NameFilter

        if (smProxy.IsClientConnected)
            smProxy.SendClient("(" + data + Constants.vbLf);
        return;
        } else if (Color == "whisper") {
        //'WHISPER
        try {
            string WhisperFrom = Regex.Match(data, "whispers, \"(.*?)\" to you").Groups(1).Value;
            string WhisperTo = Regex.Match(data, "You whisper \"(.*?)\" to").Groups(1).Value;
            string WhisperDir = Regex.Match(data, string.Format("<name shortname='(.*?)' src='whisper-(.*?)'>")).Groups(2).Value;
            if (WhisperDir == "from") {
                //Player = NametoFurre(User, True)
                Player.Message = WhisperFrom;
                if (BadgeTag.Count() > 0) {
                    SpecTag = BadgeTag.Peek;
                    BadgeTag.Clear();
                    Player.Badge = SpecTag;
                } else {
                    Player.Badge = "";
                }

                if (DREAM.List.ContainsKey(Player.ID))
                    DREAM.List.Item(Player.ID) = Player;

                sndDisplay(User + " whispers\"" + WhisperFrom + "\" to you.", fColorEnum.Whisper);
                if (!IsBot(Player)) {
                    MainMSEngine.PageSetVariable(Main.VarPrefix + "MESSAGE", Player.Message);
                    // Execute (0:15) When some one whispers something
                    MainMSEngine.PageExecute(15, 16, 17);
                    // Execute (0:16) When some one whispers {...}
                    // Execute (0:17) When some one whispers something with {...} in it
                }

            } else {
                WhisperTo = WhisperTo.Replace("<wnd>", "");
                sndDisplay("You whisper\"" + WhisperTo + "\" to " + User + ".", fColorEnum.Whisper);
            }
        } catch (Exception eX) {
            ErrorLogging logError = new ErrorLogging(eX, this);
        }
        if (smProxy.IsClientConnected)
            smProxy.SendClient("(" + data + Constants.vbLf);
        return;
        } else if (Color == "warning") {

        return;
        } else if (Color == "trade") {

        return;
        } else if (Color == "emote") {

        return;
        } else if (Color == "channel") {

        return;
        } else if (Color == "notify") {
        string NameStr = "";
        if (Text.StartsWith("Players banished from your dreams: ")) {
            //Banish-List
            //[notify> Players banished from your dreams:
            //`(0:54) When the bot sees the banish list
            BanishString.Clear();
            string[] tmp = Text.Substring(35).Split(',');
            foreach (string t in tmp) {
                BanishString.Add(t);
            }
            MainMSEngine.PageSetVariable(VarPrefix + "BANISHLIST", string.Join(" ", BanishString.ToArray));
            MainMSEngine.PageExecute(54);

        } else if (Text.StartsWith("The banishment of player ")) {
            //banish-off <name> (on list)
            //[notify> The banishment of player (.*?) has ended.

            //(0:56) When the bot successfully removes a furre from the banish list,
            //(0:58) When the bot successfully removes the furre named {...} from the banish list,
            Regex t = new Regex("The banishment of player (.*?) has ended.");
            NameStr = t.Match(data).Groups(1).Value;
            MainMSEngine.PageSetVariable("BANISHNAME", NameStr);
            MainMSEngine.PageExecute(56, 56);
            for (int I = 0; I <= BanishString.Count - 1; I++) {
                if (BanishString.Item(I).ToString.ToFurcShortName == NameStr.ToFurcShortName) {
                    BanishString.RemoveAt(I);
                    break; // TODO: might not be correct. Was : Exit For
                }
            }
            MainMSEngine.PageSetVariable("BANISHLIST", string.Join(" ", BanishString.ToArray));
        }

        sndDisplay("[notify> " + Text, fColorEnum.DefaultColor);
        if (smProxy.IsClientConnected)
            smProxy.SendClient("(" + data + Constants.vbLf);
        return;
        } else if (Color == "error") {
        lock (Lock) {
            ErrorMsg = Text;
            ErrorNum = 2;
        }
        MainMSEngine.PageExecute(800);
        string NameStr = "";
        if (Text.Contains("There are no furres around right now with a name starting with ")) {
            //Banish <name> (Not online)
            //Error:>>  There are no furres around right now with a name starting with (.*?) .

            //(0:50) When the Bot fails to banish a furre,
            //(0:51) When the bot fails to banish the furre named {...},
            Regex t = new Regex("There are no furres around right now with a name starting with (.*?) .");
            NameStr = t.Match(data).Groups(1).Value;
            MainMSEngine.PageSetVariable("BANISHNAME", NameStr);
            MainMSEngine.PageExecute(50, 51);
            MainMSEngine.PageSetVariable("BANISHLIST", string.Join(" ", BanishString.ToArray));
        } else if (Text == "Sorry, this player has not been banished from your dreams.") {
            //banish-off <name> (not on list)
            //Error:>> Sorry, this player has not been banished from your dreams.

            //(0:55) When the Bot fails to remove a furre from the banish list,
            //(0:56) When the bot fails to remove the furre named {...} from the banish list,
            NameStr = BanishName;
            MainMSEngine.PageSetVariable("BANISHNAME", NameStr);
            MainMSEngine.PageSetVariable("BANISHLIST", string.Join(" ", BanishString.ToArray));
            MainMSEngine.PageExecute(50, 51);
        } else if (Text == "You have not banished anyone.") {
            //banish-off-all (empty List)
            //Error:>> You have not banished anyone.

            //(0:59) When the bot fails to see the banish list,
            BanishString.Clear();
            MainMSEngine.PageExecute(59);
            MainMSEngine.PageSetVariable(VarPrefix + "BANISHLIST", "");
        } else if (Text == "You do not have any cookies to give away right now!") {
            MainMSEngine.PageExecute(95);
        }

        sndDisplay("Error:>> " + Text);
        if (smProxy.IsClientConnected)
            smProxy.SendClient("(" + data + Constants.vbLf);
        return;
        } else if (data.StartsWith("Communication")) {
        sndDisplay("Error: Communication Error.  Aborting connection.");
        ProcExit = false;
        DisconnectBot();
        //LogSaveTmr.Enabled = False

        } else if (Channel == "@cookie") {
        // <font color='emit'><img src='fsh://system.fsh:90' alt='@cookie' /><channel name='@cookie' /> Cookie <a href='http://www.furcadia.com/cookies/Cookie%20Economy.html'>bank</a> has currently collected: 0</font>
        // <font color='emit'><img src='fsh://system.fsh:90' alt='@cookie' /><channel name='@cookie' /> All-time Cookie total: 0</font>
        // <font color='success'><img src='fsh://system.fsh:90' alt='@cookie' /><channel name='@cookie' /> Your cookies are ready.  http://furcadia.com/cookies/ for more info!</font>
        //<img src='fsh://system.fsh:90' alt='@cookie' /><channel name='@cookie' /> You eat a cookie.

        Regex CookieToMe = new Regex(string.Format("{0}", CookieToMeREGEX));
        if (CookieToMe.Match(data).Success) {
            MainMSEngine.PageSetVariable(MS_Name, CookieToMe.Match(data).Groups(2).Value);
            MainMSEngine.PageExecute(42, 43);
        }
        Regex CookieToAnyone = new Regex(string.Format("<name shortname='(.*?)'>(.*?)</name> just gave <name shortname='(.*?)'>(.*?)</name> a (.*?)"));
        if (CookieToAnyone.Match(data).Success) {
            //MainMSEngine.PageSetVariable(VarPrefix & MS_Name, CookieToAnyone.Match(data).Groups(3).Value)
            if (callbk.IsBot(NametoFurre(CookieToAnyone.Match(data).Groups(3).Value, true))) {
                MainMSEngine.PageExecute(42, 43);
            } else {
                MainMSEngine.PageExecute(44);
            }

        }
        Regex CookieFail = new Regex(string.Format("You do not have any (.*?) left!"));
        if (CookieFail.Match(data).Success) {
            MainMSEngine.PageExecute(45);
        }
        Regex EatCookie = new Regex(Regex.Escape("<img src='fsh://system.fsh:90' alt='@cookie' /><channel name='@cookie' /> You eat a cookie.") + "(.*?)");
        if (EatCookie.Match(data).Success) {
            MainMSEngine.PageSetVariable(Main.VarPrefix + "MESSAGE", "You eat a cookie." + EatCookie.Replace(data, ""));
            Player.Message = "You eat a cookie." + EatCookie.Replace(data, "");
            MainMSEngine.PageExecute(49);

        }
        sndDisplay(Text, fColorEnum.DefaultColor);
        if (smProxy.IsClientConnected)
            smProxy.SendClient("(" + data + Constants.vbLf);
        return;
        } else if (data.StartsWith("PS")) {
        Int16 PS_Stat = 0;
        //(PS Ok: get: result: bank=200, clearance=10, member=1, message='test', stafflv=2, sys_lastused_date=1340046340
        MainMSEngine.PageSetVariable(Main.VarPrefix + "MESSAGE", data);
        Player.Message = data;
        Regex psResult = new Regex(string.Format("^PS (\\d+)? ?Ok: get: result: (.*)$"));
        //Regex: ^\(PS Ok: get: result: (.*)$
        System.Text.RegularExpressions.Match psMatch = psResult.Match(string.Format("{0}", data));
        if (psMatch.Success) {
            Int16.TryParse(psMatch.Groups(1).Value.ToString, PS_Stat);
            Regex psResult1 = new Regex("^<empty>$");
            System.Text.RegularExpressions.Match psMatch2 = psResult1.Match(psMatch.Groups(2).Value);
            if (psMatch2.Success & CurrentPS_Stage == PS_BackupStage.GetAlphaNumericList) {
                if (NextLetter != '{') {
                    ServerStack.Enqueue("ps get character." + incrementLetter(NextLetter) + "*");
                } else {
                    psCheck = ProcessPSData(1, PSinfo, data);
                }

            } else {

                //Add "," to the end of match #1.
                //Input: "bank=200, clearance=10, member=1, message='test', stafflv=2, sys_lastused_date=1340046340,"
                string input = psMatch.Groups(2).Value.ToString + ",";
                //Regex: ( ?([^=]+)=('?)(.+?)('?)),
                lock (ChannelLock) {
                    if (CurrentPS_Stage != PS_BackupStage.GetAlphaNumericList)
                        PSinfo.Clear();
                    MatchCollection mc = Regex.Matches(input, "\\s?(.*?)=('?)(\\d+|.*?)(\\2),?");
                    int i = 0;
                    for (i = 0; i <= mc.Count - 1; i++) {
                        System.Text.RegularExpressions.Match m = mc.Item(i);
                        if (!PSinfo.ContainsKey(m.Groups(1).Value))
                            PSinfo.Add(m.Groups(1).Value.ToString, m.Groups(3).Value);
                        //Match(1) : Value(Name)
                        //Match 2: Empty if number, ' if string
                        //Match(3) : Value()
                    }
                    //Int16.TryParse(psMatch.Groups(1).Value.ToString, PS_Stat)
                    if (CurrentPS_Stage != PS_BackupStage.GetAlphaNumericList) {
                        try {
                            psCheck = ProcessPSData(PS_Stat, PSinfo, data);
                        } catch (Exception ex) {
                            ErrorLogging e = new ErrorLogging(ex, this);
                        }
                    } else if (CurrentPS_Stage == PS_BackupStage.GetAlphaNumericList & NextLetter != '{') {
                        System.Text.RegularExpressions.Match m = mc.Item(mc.Count - 1);
                        NextLetter = incrementLetter(m.Groups(1).Value.ToString);
                        if (NextLetter != '{') {
                            ServerStack.Enqueue("ps get character." + NextLetter + "*");
                        } else {
                            psCheck = ProcessPSData(1, PSinfo, data);
                        }
                    } else if (CurrentPS_Stage == PS_BackupStage.GetAlphaNumericList & NextLetter == '{') {
                        //CurrentPS_Stage = PS_BackupStage.GetList
                        try {
                            psCheck = ProcessPSData(PS_Stat, PSinfo, data);
                        } catch (Exception ex) {
                            ErrorLogging e = new ErrorLogging(ex, this);
                        }
                    }
                }
            }
        }

        psResult = new Regex(string.Format("^PS (\\d+)? ?Ok: get: multi_result (\\d+)/(\\d+): (.+)$"));
        //Regex: ^\(PS Ok: get: result: (.*)$
        psMatch = psResult.Match(string.Format("{0}", data));

        if (psMatch.Success) {
            Int16.TryParse(psMatch.Groups(1).Value.ToString, PS_Stat);
            if (psMatch.Groups(2).Value.ToString == "1" & CurrentPS_Stage == PS_BackupStage.GetList) {
                pslen = 0;
                PSinfo.Clear();
                PS_Page = "";
            } else if (CurrentPS_Stage == PS_BackupStage.GetAlphaNumericList) {
                pslen = 0;
            }

            //Add "," to the end of match #1.
            //Input: "bank=200, clearance=10, member=1, message='test', stafflv=2, sys_lastused_date=1340046340,"
            //Dim input As String = psMatch.Groups(4).Value.ToString
            PS_Page += psMatch.Groups(4).Value.ToString;
            pslen += data.Length + 1;
            //Regex: ( ?([^=]+)=('?)(.+?)('?)),

            if (psMatch.Groups(2).Value == psMatch.Groups(3).Value) {
                //PS_Page += ","

                lock (ChannelLock) {
                    MatchCollection mc = Regex.Matches(string.Format(PS_Page), string.Format("\\s?(.*?)=('?)(\\d+|.*?)(\\2),?"), RegexOptions.IgnorePatternWhitespace);
                    if (CurrentPS_Stage != PS_BackupStage.GetAlphaNumericList)
                        PSinfo.Clear();
                    for (int i = 0; i <= mc.Count - 1; i++) {
                        System.Text.RegularExpressions.Match m = mc.Item(i);
                        if (!PSinfo.ContainsKey(m.Groups(1).Value))
                            PSinfo.Add(m.Groups(1).Value, m.Groups(3).Value);
                        //Match(1) : Value(Name)
                        //Match 2: Empty if number, ' if string
                        //Match(3) : Value()
                    }
                    int test = 1000 * psMatch.Groups(3).Value.ToInteger;
                    if (pslen > 1000 * psMatch.Groups(3).Value.ToInteger & CurrentPS_Stage == PS_BackupStage.GetList) {
                        CurrentPS_Stage = PS_BackupStage.GetAlphaNumericList;
                        System.Text.RegularExpressions.Match m = mc.Item(mc.Count - 1);
                        ServerStack.Enqueue("ps get character." + m.Groups(1).Value.Substring(0, 1) + "*");

                    } else if (CurrentPS_Stage != PS_BackupStage.GetAlphaNumericList) {
                        try {
                            psCheck = ProcessPSData(PS_Stat, PSinfo, data);
                        } catch (Exception ex) {
                            ErrorLogging e = new ErrorLogging(ex, this);
                        }
                    } else if (CurrentPS_Stage == PS_BackupStage.GetAlphaNumericList & NextLetter != '{') {
                        System.Text.RegularExpressions.Match m = mc.Item(mc.Count - 1);
                        NextLetter = incrementLetter(m.Groups(1).Value.ToString);
                        if (NextLetter != '{') {
                            ServerStack.Enqueue("ps get character." + NextLetter + "*");
                        } else {
                            psCheck = ProcessPSData(1, PSinfo, data);
                        }
                    } else if (CurrentPS_Stage == PS_BackupStage.GetAlphaNumericList & NextLetter == '{') {
                        //CurrentPS_Stage = PS_BackupStage.GetList
                        try {
                            psCheck = ProcessPSData(PS_Stat, PSinfo, data);
                        } catch (Exception ex) {
                            ErrorLogging e = new ErrorLogging(ex, this);
                        }
                    }
                }
            }
            //(PS 5 Error: get: Query error: Field 'Bob' does not exist

        }

        psResult = new Regex("^PS (\\d+)? ?Ok: set: Ok$");
        //^PS (\d+)? ?Ok: set: Ok
        psMatch = psResult.Match(data);
        if (psMatch.Success) {
            PSinfo.Clear();
            Int16.TryParse(psMatch.Groups(1).Value.ToString, PS_Stat);
            try {
                ProcessPSData(PS_Stat, PSinfo, data);
            } catch (Exception ex) {
                ErrorLogging e = new ErrorLogging(ex, this);
            }
        }
        //PS (\d+) Error: Sorry, PhoenixSpeak commands are currently not available in this dream.
        psResult = new Regex("^PS (\\d+)? ?Error: (.*?)");
        psMatch = psResult.Match(data);
        if (psMatch.Success) {
            psResult = new Regex("^PS (\\d+)? ?Error: Sorry, PhoenixSpeak commands are currently not available in this dream.$");
            //Regex: ^\(PS Ok: get: result: (.*)$
            //PS (\d+)? ?Error: get: Query error: (.+) Unexpected character '(.+)' at column (\d+)
            System.Text.RegularExpressions.Match psMatch2 = psResult.Match(data);
            Regex psResult2 = new Regex("^PS (\\d+)? ?Error: set");
            System.Text.RegularExpressions.Match psmatch3 = psResult2.Match(data);
            Regex psResult3 = new Regex("PS (\\d+)? ?Error: set: Query error: Only (\\d+) rows allowed.");
            System.Text.RegularExpressions.Match psmatch4 = psResult3.Match(data);
            if (psMatch2.Success | psmatch3.Success | psmatch4.Success) {
                PS_Abort();
                if (psmatch4.Success) {
                    MainEngine.MSpage.Execute(503);
                }
            } else {
                Int16.TryParse(psMatch.Groups(1).Value.ToString, PS_Stat);

                if (CurrentPS_Stage == PS_BackupStage.off) {
                    MainMSEngine.PageExecute(80, 81, 82);

                } else if (CurrentPS_Stage == PS_BackupStage.GetList) {
                    if (PS_Stat != CharacterList.Count) {
                        string str = "ps " + (PS_Stat + 1).ToString + " get character." + CharacterList(PS_Stat).name + ".*";
                        ServerStack.Enqueue(str);
                        psSendCounter = Convert.ToInt16(PS_Stat + 1);

                        psReceiveCounter = PS_Stat;

                    } else if (PS_Stat == CharacterList.Count) {
                        CurrentPS_Stage = PS_BackupStage.off;

                    }
                } else if (CurrentPS_Stage == PS_BackupStage.GetTargets & psSendCounter == psReceiveCounter + 1) {
                    if (PS_Stat != CharacterList.Count) {
                        string str = "ps " + (PS_Stat + 1).ToString + " get character." + CharacterList(PS_Stat).name + ".*";
                        ServerStack.Enqueue(str);
                        psSendCounter = Convert.ToInt16(PS_Stat + 1);
                        psReceiveCounter = PS_Stat;
                    } else if (PS_Stat == CharacterList.Count) {
                        CurrentPS_Stage = PS_BackupStage.off;
                        PSBackupRunning = false;
                        CharacterList.Clear();
                        psReceiveCounter = 0;
                        psSendCounter = 1;
                        //(0:501) When the bot completes backing up the characters Phoenix Speak,
                        SendClientMessage("SYSTEM:", "Completed Backing up Dream Characters set.");
                        MainEngine.MSpage.Execute(501);
                    }

                } else if (CurrentPS_Stage == PS_BackupStage.RestoreAllCharacterPS & PS_Stat <= PSS_Stack.Count - 1 & psSendCounter == psReceiveCounter + 1) {
                    if (PS_Stat != PSS_Stack.Count - 1) {
                        LastSentPS = 0;
                        PSS_Struct ss = new PSS_Struct();
                        ss = PSS_Stack(PS_Stat);
                        ServerStack.Enqueue(ss.Cmd);
                        psSendCounter = Convert.ToInt16(PS_Stat + 1);
                        psReceiveCounter = PS_Stat;

                    } else if (PS_Stat == PSS_Stack.Count - 1) {
                        PSRestoreRunning = false;
                        SendClientMessage("SYSTEM:", "Completed Character restoration to the dream");
                        //(0:501) When the bot completes backing up the characters Phoenix Speak,
                        MainEngine.MSpage.Execute(503);
                        CurrentPS_Stage = PS_BackupStage.off;
                    }
                } else if (CurrentPS_Stage == PS_BackupStage.GetSingle & PS_Stat <= CharacterList.Count & psSendCounter == psReceiveCounter + 1) {
                    if (PS_Stat != CharacterList.Count) {
                        string str = "ps " + (PS_Stat + 1).ToString + " get character." + CharacterList(PS_Stat).name + ".*";
                        ServerStack.Enqueue(str);
                        psSendCounter = Convert.ToInt16(PS_Stat + 1);
                        psReceiveCounter = PS_Stat;
                    } else if (PS_Stat == CharacterList.Count) {
                        CurrentPS_Stage = PS_BackupStage.off;
                        CharacterList.Clear();
                        psReceiveCounter = 0;
                        psSendCounter = 1;
                        PSBackupRunning = false;
                    }
                }
            }
        }

        return;

        } else if (data.StartsWith("(You enter the dream of")) {

        return;

        } else {
        //default
        return;
        }
        // If smProxy.IsClientConnected Then smProxy.SendClient("(" + data + vbLf)
        // Exit Sub
        }
        protected void btnFilter_Click(object sender, EventArgs e)
        {
            gvGlance.DataSource = null;
            lblDisplay.Text     = "";
            List <DocumentDetails> documentList = new List <DocumentDetails>();
            ELibraryDocumentBL     docBL        = new ELibraryDocumentBL();
            DataTable dt = new DataTable();

            dt.Columns.Add(new DataColumn("Title", typeof(string)));
            dt.Columns.Add(new DataColumn("Author", typeof(string)));
            dt.Columns.Add(new DataColumn("Description", typeof(string)));
            dt.Columns.Add(new DataColumn("Type", typeof(string)));
            dt.Columns.Add(new DataColumn("Price", typeof(string)));
            dt.Columns.Add(new DataColumn("", typeof(Control)));
            dt.Columns.Add(new DataColumn("Path", typeof(string)));
            dt.Columns.Add(new DataColumn("DocumentID", typeof(string)));

            try
            {
                int itemsSelected = 0;
                foreach (ListItem li in chklasideBar.Items)
                {
                    if (li.Selected)
                    {
                        itemsSelected = itemsSelected + 1;
                    }
                }
                if (itemsSelected == 0)
                {
                    throw new ELibraryException("Please select a check box");
                }
                for (int i = 0; i < chklasideBar.Items.Count; i++)
                {
                    List <DocumentDetails> documentDiscList = null;

                    if (chklasideBar.Items[i].Selected)
                    {
                        documentDiscList = null;
                        string discipline = chklasideBar.Items[i].Text;
                        documentDiscList = docBL.ViewDocumentsByDisciplineBL(discipline);
                        if (documentDiscList != null)
                        {
                            foreach (DocumentDetails doc in documentDiscList)
                            {
                                documentList.Add(doc);
                            }
                        }
                    }
                }
                if (documentList.Count > 0)
                {
                    foreach (DocumentDetails doc in documentList)
                    {
                        DataRow dr = dt.NewRow();
                        dr["Title"]       = doc.Title;
                        dr["Author"]      = doc.Author;
                        dr["Type"]        = docBL.GetDocumentTypeBL(doc.DocumentTypeID);
                        dr["Description"] = doc.DocumentDescription;
                        dr["Path"]        = doc.DocumentPath;
                        dr["Price"]       = doc.Price;
                        dr["DocumentID"]  = doc.DocumentID;
                        dt.Rows.Add(dr);
                    }
                    gvGlance.DataSource = dt;
                    gvGlance.DataBind();
                }
            }
            catch (ELibraryException ex)
            {
                ErrorLogging erLog = new ErrorLogging();
                erLog.LogError(ex.Message);
                ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please select atleast one checkbox')", true);
            }
            catch (Exception ex)
            {
                ErrorLogging erLog = new ErrorLogging();
                erLog.LogError(ex.Message);
            }
        }
Ejemplo n.º 17
0
 public MakeArchiveFile(Config config, ErrorLogging error)
 {
     _config = config;
     _error  = error;
 }
Ejemplo n.º 18
0
 private void App_DispatcherUnhandledException1(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
 {
     ErrorLogging.LogError(e.Exception.Message + "\n" + e.Exception.StackTrace);
 }
        public HttpResponseMessage UpdateLocation([FromBody] LocationModel LocationModel)
        {
            try
            {
                if (LocationModel.CustomerId == 0)
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Customer Id is blank"), Configuration.Formatters.JsonFormatter));
                }
                var customer = _CustomerService.GetCustomers().Where(c => c.CustomerId == LocationModel.CustomerId && c.IsActive == true).FirstOrDefault();
                if (customer == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Customer not found."), Configuration.Formatters.JsonFormatter));
                }
                if (LocationModel.LocationId == 0)
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Location Id is blank"), Configuration.Formatters.JsonFormatter));
                }
                var location = _LocationService.GetLocations().Where(l => l.LocationId == LocationModel.LocationId && l.CustomerId == LocationModel.CustomerId).FirstOrDefault();
                if (location == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Location not found."), Configuration.Formatters.JsonFormatter));
                }
                else
                {
                    location.Title       = ((LocationModel.Title != null && LocationModel.Title != "") ? LocationModel.Title : location.Title);
                    location.Description = ((LocationModel.Description != null && LocationModel.Description != "") ? LocationModel.Description : location.Description);
                    //if (LocationModel.ContactInfo != null && LocationModel.ContactInfo != "")
                    //{
                    //    string[] contactDetails = LocationModel.ContactInfo.Split('|');
                    //    location.EmailId = contactDetails[1];
                    //    location.MobileNo = contactDetails[0];
                    //}
                    location.EmailId  = ((LocationModel.EmailId != null && LocationModel.EmailId != "") ? LocationModel.EmailId : location.EmailId);
                    location.MobileNo = ((LocationModel.MobileNo != null && LocationModel.MobileNo != "") ? LocationModel.MobileNo : location.MobileNo);
                    location.State    = ((LocationModel.State != null && LocationModel.State != "") ? LocationModel.State : location.State);
                    location.City     = ((LocationModel.City != null && LocationModel.City != "") ? LocationModel.City : location.City);
                    location.Country  = ((LocationModel.Country != null && LocationModel.Country != "") ? LocationModel.Country : location.Country);
                    location.Street   = ((LocationModel.Street != null && LocationModel.Street != "") ? LocationModel.Street : location.Street);
                    location.Ratings  = (LocationModel.Ratings != null ? LocationModel.Ratings : location.Ratings);
                    if (LocationModel.CategoryIds != null && LocationModel.CategoryIds != "")
                    {
                        string[] categoryIds = LocationModel.CategoryIds.Split(',');

                        List <int> CatIds = _CategoryService.GetCategories().Select(c => c.CategoryId).ToList();
                        // var CatIds = Categories.Select(c => c.CategoryId);
                        List <string> Ids       = CatIds.ConvertAll <string>(x => x.ToString());
                        bool          isMatched = true;
                        foreach (var item in categoryIds)
                        {
                            if (!Ids.Contains(item))
                            {
                                isMatched = false;
                            }
                        }
                        IEnumerable <string> difference = Ids.Except(categoryIds);
                        if (isMatched)
                        {
                            location.CategoryIds = LocationModel.CategoryIds;
                        }
                        else
                        {
                            return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Category id is wrong."), Configuration.Formatters.JsonFormatter));
                        }
                    }
                    //location.CategoryIds = ((LocationModel.CategoryIds != null && LocationModel.CategoryIds != "") ? LocationModel.CategoryIds : location.CategoryIds);

                    _LocationService.UpdateLocation(location);
                    string tags        = "";
                    var    LocationTag = _LocationTagService.GetLocationTags().Where(t => t.LocationId == location.LocationId).ToList();
                    if (LocationModel.Tags != null || LocationModel.Tags != "")
                    {
                        string[] tagList = LocationModel.Tags.Split(',');


                        if (LocationTag.Count() > 0)
                        {
                            foreach (var tag in LocationTag)
                            {
                                _LocationTagService.DeleteLocationTag(tag);
                            }
                        }
                        foreach (var tag in tagList)
                        {
                            LocationTag locationTag = new LocationTag();
                            locationTag.LocationId = location.LocationId;
                            locationTag.Tag        = tag;
                            _LocationTagService.InsertLocationTag(locationTag);
                            tags = tags + "," + tag;
                        }
                    }

                    Mapper.CreateMap <Location, LocationResponseModel>();
                    LocationResponseModel model = Mapper.Map <Location, LocationResponseModel>(location);
                    string[] categoryId         = model.CategoryIds.Split(',');
                    string   categoryNames      = "";
                    foreach (var item in categoryId)
                    {
                        var categoryName = _CategoryService.GetCategories().Where(c => c.CategoryId == Convert.ToInt32(item)).Select(c => c.Name).FirstOrDefault();
                        categoryNames = categoryNames + ',' + categoryName;
                    }
                    model.CategoryNames = categoryNames.TrimStart(',').TrimEnd(',');
                    List <string> LocationImages = new List <string>();
                    var           images         = _LocationImagesService.GetLocationImages().Where(l => l.LocationId == location.LocationId).ToList();
                    if (images.Count() > 0)
                    {
                        foreach (var image in images)
                        {
                            LocationImages.Add(image.ImagePath);
                        }
                    }
                    model.LocationImages = LocationImages;

                    model.Tags = tags.TrimStart(',').TrimEnd(',');
                    // model.ContactInfo = location.MobileNo + "|" + location.EmailId;
                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("success", model), Configuration.Formatters.JsonFormatter));
                }
            }
            catch (Exception ex)
            {
                string ErrorMsg = ex.Message.ToString();
                ErrorLogging.LogError(ex);
                return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Please try again."), Configuration.Formatters.JsonFormatter));
            }
        }
        protected override IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            try
            {
                switch (msg)
                {
                case NativeMethods.WM_MOUSEWHEEL:
                    if (mouseInWindow)
                    {
                        int delta = 0;

                        try { delta = wParam.ToInt32(); }
                        catch (Exception) { /*supress error*/ }

                        if (delta == 0)
                        {
                            try { delta = (int)wParam.ToInt64(); }
                            catch (Exception) { /*supress error*/ }
                        }

                        if (HwndMouseWheel != null)
                        {
                            HwndMouseWheel(this, new HwndMouseEventArgs(mouseState, delta, 0));
                        }
                    }
                    break;

                case NativeMethods.WM_LBUTTONDOWN:
                    mouseState.LeftButton = MouseButtonState.Pressed;
                    if (HwndLButtonDown != null)
                    {
                        HwndLButtonDown(this, new HwndMouseEventArgs(mouseState));
                    }
                    break;

                case NativeMethods.WM_LBUTTONUP:
                    mouseState.LeftButton = MouseButtonState.Released;
                    if (HwndLButtonUp != null)
                    {
                        HwndLButtonUp(this, new HwndMouseEventArgs(mouseState));
                    }
                    break;

                case NativeMethods.WM_LBUTTONDBLCLK:
                    if (HwndLButtonDblClick != null)
                    {
                        HwndLButtonDblClick(this, new HwndMouseEventArgs(mouseState, MouseButton.Left));
                    }
                    break;

                case NativeMethods.WM_RBUTTONDOWN:
                    mouseState.RightButton = MouseButtonState.Pressed;
                    if (HwndRButtonDown != null)
                    {
                        HwndRButtonDown(this, new HwndMouseEventArgs(mouseState));
                    }
                    break;

                case NativeMethods.WM_RBUTTONUP:
                    mouseState.RightButton = MouseButtonState.Released;
                    if (HwndRButtonUp != null)
                    {
                        HwndRButtonUp(this, new HwndMouseEventArgs(mouseState));
                    }
                    break;

                case NativeMethods.WM_RBUTTONDBLCLK:
                    if (HwndRButtonDblClick != null)
                    {
                        HwndRButtonDblClick(this, new HwndMouseEventArgs(mouseState, MouseButton.Right));
                    }
                    break;

                case NativeMethods.WM_MBUTTONDOWN:
                    mouseState.MiddleButton = MouseButtonState.Pressed;
                    if (HwndMButtonDown != null)
                    {
                        HwndMButtonDown(this, new HwndMouseEventArgs(mouseState));
                    }
                    break;

                case NativeMethods.WM_MBUTTONUP:
                    mouseState.MiddleButton = MouseButtonState.Released;
                    if (HwndMButtonUp != null)
                    {
                        HwndMButtonUp(this, new HwndMouseEventArgs(mouseState));
                    }
                    break;

                case NativeMethods.WM_MBUTTONDBLCLK:
                    if (HwndMButtonDblClick != null)
                    {
                        HwndMButtonDblClick(this, new HwndMouseEventArgs(mouseState, MouseButton.Middle));
                    }
                    break;

                case NativeMethods.WM_XBUTTONDOWN:
                    if (((int)wParam & NativeMethods.MK_XBUTTON1) != 0)
                    {
                        mouseState.X1Button = MouseButtonState.Pressed;
                        if (HwndX1ButtonDown != null)
                        {
                            HwndX1ButtonDown(this, new HwndMouseEventArgs(mouseState));
                        }
                    }
                    else if (((int)wParam & NativeMethods.MK_XBUTTON2) != 0)
                    {
                        mouseState.X2Button = MouseButtonState.Pressed;
                        if (HwndX2ButtonDown != null)
                        {
                            HwndX2ButtonDown(this, new HwndMouseEventArgs(mouseState));
                        }
                    }
                    break;

                case NativeMethods.WM_XBUTTONUP:
                    if (((int)wParam & NativeMethods.MK_XBUTTON1) != 0)
                    {
                        mouseState.X1Button = MouseButtonState.Released;
                        if (HwndX1ButtonUp != null)
                        {
                            HwndX1ButtonUp(this, new HwndMouseEventArgs(mouseState));
                        }
                    }
                    else if (((int)wParam & NativeMethods.MK_XBUTTON2) != 0)
                    {
                        mouseState.X2Button = MouseButtonState.Released;
                        if (HwndX2ButtonUp != null)
                        {
                            HwndX2ButtonUp(this, new HwndMouseEventArgs(mouseState));
                        }
                    }
                    break;

                case NativeMethods.WM_XBUTTONDBLCLK:
                    if (((int)wParam & NativeMethods.MK_XBUTTON1) != 0)
                    {
                        if (HwndX1ButtonDblClick != null)
                        {
                            HwndX1ButtonDblClick(this, new HwndMouseEventArgs(mouseState, MouseButton.XButton1));
                        }
                    }
                    else if (((int)wParam & NativeMethods.MK_XBUTTON2) != 0)
                    {
                        if (HwndX2ButtonDblClick != null)
                        {
                            HwndX2ButtonDblClick(this, new HwndMouseEventArgs(mouseState, MouseButton.XButton2));
                        }
                    }
                    break;

                case NativeMethods.WM_MOUSEMOVE:
                    // If the application isn't in focus, we don't handle this message
                    if (!applicationHasFocus)
                    {
                        break;
                    }

                    // record the prevous and new position of the mouse
                    mouseState.PreviousPosition = mouseState.Position;
                    mouseState.Position         = new Point(
                        NativeMethods.GetXLParam((int)lParam),
                        NativeMethods.GetYLParam((int)lParam));

                    if (!mouseInWindow)
                    {
                        mouseInWindow = true;

                        // if the mouse is just entering, use the same position for the previous state
                        // so we don't get weird deltas happening when the move event fires
                        mouseState.PreviousPosition = mouseState.Position;

                        if (HwndMouseEnter != null)
                        {
                            HwndMouseEnter(this, new HwndMouseEventArgs(mouseState));
                        }
                        hWndprev = NativeMethods.GetFocus();
                        NativeMethods.SetFocus(hWnd);
                        // send the track mouse event so that we get the WM_MOUSELEAVE message
                        NativeMethods.TRACKMOUSEEVENT tme = new NativeMethods.TRACKMOUSEEVENT();
                        tme.cbSize  = Marshal.SizeOf(typeof(NativeMethods.TRACKMOUSEEVENT));
                        tme.dwFlags = NativeMethods.TME_LEAVE;
                        tme.hWnd    = hwnd;
                        NativeMethods.TrackMouseEvent(ref tme);
                    }

                    // Only fire the mouse move if the position actually changed
                    if (mouseState.Position != mouseState.PreviousPosition)
                    {
                        if (HwndMouseMove != null)
                        {
                            HwndMouseMove(this, new HwndMouseEventArgs(mouseState));
                        }
                    }

                    break;

                case NativeMethods.WM_MOUSELEAVE:

                    // If we have capture, we ignore this message because we're just
                    // going to reset the cursor position back into the window
                    if (isMouseCaptured)
                    {
                        break;
                    }

                    // Reset the state which releases all buttons and
                    // marks the mouse as not being in the window.
                    ResetMouseState();

                    if (HwndMouseLeave != null)
                    {
                        HwndMouseLeave(this, new HwndMouseEventArgs(mouseState));
                    }

                    NativeMethods.SetFocus(hWndprev);
                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                // log this
                ErrorLogging.LogException(ex);
            }

            return(base.WndProc(hwnd, msg, wParam, lParam, ref handled));
        }
        public HttpResponseMessage GetAllLocations(LocationModel LocationModel)
        {
            try
            {
                if (LocationModel.City == "" || LocationModel.City == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "City is blank."), Configuration.Formatters.JsonFormatter));
                }
                if (LocationModel.Country == "" || LocationModel.City == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Country is blank."), Configuration.Formatters.JsonFormatter));
                }
                if (LocationModel.State == "" || LocationModel.City == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "State is blank."), Configuration.Formatters.JsonFormatter));
                }
                List <Location> entity4 = new List <Location>();
                var             entity1 = _LocationService.GetLocations().Where(l => l.City.ToLower().Contains(LocationModel.City.ToLower()) && l.IsApproved == true).Distinct().ToList();
                if (entity1.Count() > 0)
                {
                    var entity2 = entity1.Where(l => l.State.ToLower().Contains(LocationModel.State.ToLower())).Distinct().ToList();
                    if (entity2.Count() > 0)
                    {
                        var entity3 = entity2.Where(l => l.Country.ToLower().Contains(LocationModel.Country.ToLower())).Distinct().ToList();
                        if (entity3.Count() > 0)
                        {
                            entity4 = entity3;
                        }
                        else
                        {
                            entity4 = entity2;
                        }
                    }
                    else
                    {
                        entity4 = entity1;
                    }
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "No locations found."), Configuration.Formatters.JsonFormatter));
                }

                //var entity1 = _LocationService.GetLocations().Where(l => l.IsApproved == true);
                var entity5 = _CustomerService.GetCustomers().Where(c => c.IsActive == true);

                var Locations = (from x in entity4
                                 join y in entity5
                                 on x.CustomerId equals y.CustomerId
                                 select x).ToList();
                //var Locations = _LocationService.GetLocations().Where(l=>l.IsApproved==true);

                var models = new List <LocationResponseModel>();
                Mapper.CreateMap <Friendlier.Entity.Location, Friendlier.Models.LocationResponseModel>();
                foreach (var Location in Locations)
                {
                    List <string> LocationImages = new List <string>();
                    var           LocationModl   = Mapper.Map <Friendlier.Entity.Location, Friendlier.Models.LocationResponseModel>(Location);
                    //LocationModel.ContactInfo = Location.MobileNo + "|" + Location.EmailId;
                    var images = _LocationImagesService.GetLocationImages().Where(l => l.LocationId == Location.LocationId).ToList();
                    if (images.Count() > 0)
                    {
                        foreach (var image in images)
                        {
                            LocationImages.Add(image.ImagePath);
                        }
                    }
                    // LocationResponseModel.ContactInfo = Location.MobileNo + "|" + Location.EmailId;
                    LocationModl.LocationImages = LocationImages;
                    LocationModl.CategoryNames  = "";
                    models.Add(LocationModl);
                }

                return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("success", models), Configuration.Formatters.JsonFormatter));
            }
            catch (Exception ex)
            {
                string ErrorMsg = ex.Message.ToString();
                ErrorLogging.LogError(ex);
                return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Please try again."), Configuration.Formatters.JsonFormatter));
            }
        }
Ejemplo n.º 22
0
 public void Remove(ErrorLogging item)
 {
     _context.ErrorLogging.Remove(item);
 }
        public HttpResponseMessage GetLocationByCustomerId([FromUri] int CustomerId)
        {
            try
            {
                var models   = new List <LocationResponseModel>();
                var customer = _CustomerService.GetCustomers().Where(c => c.CustomerId == CustomerId && c.IsActive == true).FirstOrDefault();
                if (customer == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Customer not found."), Configuration.Formatters.JsonFormatter));
                }
                var Locations = _LocationService.GetLocations().Where(l => l.CustomerId == CustomerId && l.IsApproved == true).ToList();
                if (Locations.Count() > 0)
                {
                    foreach (var Location in Locations)
                    {
                        List <string> LocationImages = new List <string>();
                        Mapper.CreateMap <Friendlier.Entity.Location, Friendlier.Models.LocationResponseModel>();
                        LocationResponseModel LocationResponseModel = Mapper.Map <Friendlier.Entity.Location, Friendlier.Models.LocationResponseModel>(Location);
                        var images = _LocationImagesService.GetLocationImages().Where(l => l.LocationId == Location.LocationId).ToList();
                        if (images.Count() > 0)
                        {
                            foreach (var image in images)
                            {
                                LocationImages.Add(image.ImagePath);
                            }
                        }
                        //LocationResponseModel.ContactInfo = Location.MobileNo + "|" + Location.EmailId;
                        LocationResponseModel.LocationImages = LocationImages;
                        var isFavourite = _FavoriteService.GetFavorites().Where(f => f.LocationId == Location.LocationId && f.CustomerId == CustomerId).FirstOrDefault();
                        if (isFavourite == null)
                        {
                            LocationResponseModel.IsFavourite = false;
                        }
                        else
                        {
                            LocationResponseModel.IsFavourite = true;
                        }

                        var tags = _LocationTagService.GetLocationTags().Where(t => t.LocationId == Location.LocationId).Select(t => t.Tag).ToList();
                        if (tags.Count() > 0)
                        {
                            string tagList = "";
                            foreach (var tag in tags)
                            {
                                tagList = tagList + "," + tag;
                            }
                            LocationResponseModel.Tags = tagList.TrimEnd(',').TrimStart(',');
                        }
                        models.Add(LocationResponseModel);
                    }
                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("success", models), Configuration.Formatters.JsonFormatter));
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Location not found."), Configuration.Formatters.JsonFormatter));
                }
            }
            catch (Exception ex)
            {
                string ErrorMsg = ex.Message.ToString();
                ErrorLogging.LogError(ex);
                return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "User not found."), Configuration.Formatters.JsonFormatter));
            }
        }
Ejemplo n.º 24
0
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            DocumentDetails    docObj   = new DocumentDetails();
            ELibraryDocumentBL docBLObj = new ELibraryDocumentBL();

            try
            {
                InitializeCombo();
                if (cbnDocumentID.SelectedIndex == -1)
                {
                    throw new ELibraryException("Select Document ID");
                }

                if (cboDocumentType.SelectedIndex == -1)
                {
                    throw new ELibraryException("Select Discipline");
                }
                if (cboDiscipline.SelectedIndex == -1)
                {
                    throw new ELibraryException("Select Document Type");
                }

                docObj.DocumentID = Convert.ToInt32(cbnDocumentID.SelectedValue);
                //Session["DocumentId"] = cbnDocumentID.SelectedValue;
                string folderPath = Server.MapPath("~/Files/");
                if (!Directory.Exists(folderPath))
                {
                    //If Directory (Folder) does not exists. Create it.
                    Directory.CreateDirectory(folderPath);
                }

                string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
                if (fileName == "")
                {
                    throw new ELibraryException("Select File");
                }
                FileUpload1.SaveAs(folderPath + Path.GetFileName(FileUpload1.FileName));
                docObj.DocumentPath = folderPath + Path.GetFileName(FileUpload1.FileName);

                docObj.DocumentName        = txtDocumentName.Text;
                docObj.DocumentDescription = txtDescription.Text;

                docObj.DocumentTypeID = docBLObj.GetDocumentTypeIDBL(cboDocumentType.SelectedItem.ToString());
                docObj.DisciplineID   = docBLObj.GetDisciplineIDBL(cboDiscipline.SelectedItem.ToString());
                docObj.Title          = txtTitle.Text;
                docObj.Author         = txtAuthor.Text;
                double price;
                bool   isValidPrice = double.TryParse(txtPrice.Text, out price);
                if (!isValidPrice)
                {
                    throw new ELibraryException("Invalid price");
                }
                docObj.Price      = price;
                docObj.UploadDate = DateTime.Today;

                if (docBLObj.UpdateDocumentBL(docObj))
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Successfully Updated')", true);
                    //string str = "<script>alert(\"Updated Successfully\");</script>";
                }
                else
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Updation Failed')", true);
                }
            }
            catch (ELibraryException ex)
            {
                ErrorLogging erLog = new ErrorLogging();
                erLog.LogError(ex.Message);
                ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + ex.Message + "')", true);
            }
        }
        public HttpResponseMessage SearchLocation([FromUri] string searchTerm)
        {
            var models = new List <LocationResponseModel>();

            try
            {
                if (searchTerm == null || searchTerm == "")
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "searchTerm is blank"), Configuration.Formatters.JsonFormatter));
                }
                string[]   searchList     = searchTerm.ToLower().Split(' ');
                List <int> locationIdList = _LocationTagService.GetLocationTags().Where(x => x.Tag.ToLower().Contains(searchTerm.ToLower())).Select(x => x.LocationId).Distinct().ToList();

                //  var locationsList = _LocationService.GetLocations().Where(l => l.Title.ToLower().Contains(searchTerm.ToLower()) || l.Address.ToLower().Contains(searchTerm.ToLower()) || locationIdList.Contains(l.LocationId) && l.IsApproved==true).ToList();
                var locationsList = _LocationService.GetLocations().Where(l => l.Title.ToLower().Contains(searchTerm.ToLower()) || searchList.Contains(l.City.ToLower()) || searchList.Contains(l.Street.ToLower()) || searchList.Contains(l.Country.ToLower()) || searchList.Contains(l.State.ToLower()) || locationIdList.Contains(l.LocationId) && l.IsApproved == true).ToList();
                var entity1       = locationsList;
                var entity2       = _CustomerService.GetCustomers().Where(c => c.IsActive == true);

                var locations = (from x in entity1
                                 join y in entity2
                                 on x.CustomerId equals y.CustomerId
                                 select x).ToList();


                if (locations.Count > 0)
                {
                    Mapper.CreateMap <Location, LocationResponseModel>();
                    //var tags = _LocationTagService.GetLocationTags();
                    //if (tags != null)
                    //{
                    //    tags = tags.Where(t => t.Tag.ToLower().Contains(searchTerm.ToLower())).ToList();

                    //    foreach (var tag in tags)
                    //    {
                    //        var locationList = _LocationService.GetLocations().Where(l => l.LocationId == tag.LocationId).FirstOrDefault();
                    //        LocationResponseModel loc = Mapper.Map<Location, LocationResponseModel>(locationList);
                    //        models.Add(loc);
                    //    }

                    //}
                    //locations = locations.Where(l => l.Title.ToLower().Contains(searchTerm.ToLower())).ToList();
                    foreach (var location in locations)
                    {
                        LocationResponseModel loc = Mapper.Map <Location, LocationResponseModel>(location);
                        var tags = _LocationTagService.GetLocationTags().Where(t => t.LocationId == loc.LocationId).Select(t => t.Tag).ToList();
                        if (tags.Count() > 0)
                        {
                            string tagList = "";
                            foreach (var tag in tags)
                            {
                                tagList = tagList + "," + tag;
                            }
                            loc.Tags = tagList.TrimEnd(',').TrimStart(',');
                        }
                        models.Add(loc);
                    }

                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("success", models), Configuration.Formatters.JsonFormatter));
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "No location found."), Configuration.Formatters.JsonFormatter));
                }
            }
            catch (Exception ex)
            {
                string ErrorMsg = ex.Message.ToString();
                ErrorLogging.LogError(ex);
                return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Please try again."), Configuration.Formatters.JsonFormatter));
            }
        }
 private void ViewLog()
 {
     ErrorLogging.ViewLog();
 }
        public HttpResponseMessage SaveLocation([FromBody] LocationModel LocationModel)
        {
            int locationId = 0;

            try
            {
                if (LocationModel.CustomerId == 0)
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Customer Id is blank"), Configuration.Formatters.JsonFormatter));
                }
                if (LocationModel.Title == null || LocationModel.Title == "")
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Title is blank"), Configuration.Formatters.JsonFormatter));
                }
                if (LocationModel.Description == null || LocationModel.Description == "")
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Description is blank"), Configuration.Formatters.JsonFormatter));
                }
                //if (LocationModel.ContactInfo == null && LocationModel.ContactInfo == "")
                //{
                //    return Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "ContactInfo is blank"), Configuration.Formatters.JsonFormatter);
                //}
                if (LocationModel.Street == null || LocationModel.Street == "")
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Street is blank"), Configuration.Formatters.JsonFormatter));
                }
                if (LocationModel.City == null || LocationModel.City == "")
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "City is blank"), Configuration.Formatters.JsonFormatter));
                }
                if (LocationModel.State == null || LocationModel.State == "")
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "State is blank"), Configuration.Formatters.JsonFormatter));
                }
                if (LocationModel.Country == null || LocationModel.Country == "")
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Country is blank"), Configuration.Formatters.JsonFormatter));
                }
                if (LocationModel.CategoryIds == null || LocationModel.CategoryIds == "")
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "CategoryIds is blank"), Configuration.Formatters.JsonFormatter));
                }
                if (LocationModel.Ratings == 0)
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Ratings is blank"), Configuration.Formatters.JsonFormatter));
                }

                var customer = _CustomerService.GetCustomers().Where(c => c.CustomerId == LocationModel.CustomerId && c.IsActive == true).FirstOrDefault();
                if (customer != null)
                {
                    var street = _LocationService.GetLocations().Where(l => l.Street.ToLower() == LocationModel.Street.ToLower()).Distinct().ToList();
                    if (street.Count() > 0)
                    {
                        var entity1 = street.Where(l => l.City.ToLower() == LocationModel.City.ToLower()).Distinct().ToList();
                        if (entity1.Count() > 0)
                        {
                            var entity2 = street.Where(l => l.State.ToLower() == LocationModel.State.ToLower()).Distinct().ToList();
                            if (entity2.Count() > 0)
                            {
                                var entity3 = street.Where(l => l.Country.ToLower() == LocationModel.Country.ToLower()).Distinct().ToList();
                                if (entity3.Count() > 0)
                                {
                                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "this location already exists."), Configuration.Formatters.JsonFormatter));
                                }
                            }
                        }
                    }


                    string[] categoryIds = LocationModel.CategoryIds.Split(',');

                    List <int> CatIds = _CategoryService.GetCategories().Select(c => c.CategoryId).ToList();
                    // var CatIds = Categories.Select(c => c.CategoryId);
                    List <string> Ids       = CatIds.ConvertAll <string>(x => x.ToString());
                    bool          isMatched = true;
                    foreach (var item in categoryIds)
                    {
                        if (!Ids.Contains(item))
                        {
                            isMatched = false;
                        }
                    }
                    IEnumerable <string> difference = Ids.Except(categoryIds);
                    if (isMatched)
                    {
                        Mapper.CreateMap <Friendlier.Models.LocationModel, Friendlier.Entity.Location>();
                        Friendlier.Entity.Location location = Mapper.Map <Friendlier.Models.LocationModel, Friendlier.Entity.Location>(LocationModel);
                        //string[] contactDetails = LocationModel.ContactInfo.Split('|');
                        //location.EmailId = contactDetails[1];
                        //location.MobileNo = contactDetails[0];
                        location.EmailId     = LocationModel.EmailId;
                        location.MobileNo    = LocationModel.MobileNo;
                        location.CategoryIds = LocationModel.CategoryIds;
                        location.IsApproved  = false;
                        location.Status      = EnumValue.GetEnumDescription(EnumValue.LocationStatus.New);
                        _LocationService.InsertLocation(location);
                        locationId = location.LocationId;
                        if (LocationModel.Tags != null && LocationModel.Tags != "")
                        {
                            string[] tagList = LocationModel.Tags.Split(',');
                            foreach (var tag in tagList)
                            {
                                LocationTag locationTag = new LocationTag();
                                locationTag.LocationId = locationId;
                                locationTag.Tag        = tag;
                                _LocationTagService.InsertLocationTag(locationTag);
                            }
                        }


                        Mapper.CreateMap <Location, LocationResponseModel>();
                        LocationResponseModel model = Mapper.Map <Location, LocationResponseModel>(location);
                        model.Tags = LocationModel.Tags;
                        SendMailToAdmin(customer.FirstName, model.Title, model.Street + " " + model.City + " " + model.State + " " + model.Country);
                        //model.ContactInfo = location.MobileNo + "|" + location.EmailId;
                        return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("success", model), Configuration.Formatters.JsonFormatter));
                    }

                    else
                    {
                        return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Category id is wrong."), Configuration.Formatters.JsonFormatter));
                    }
                }

                else
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Customer id is wrong."), Configuration.Formatters.JsonFormatter));
                }
            }
            catch (Exception ex)
            {
                string ErrorMsg = ex.Message.ToString();
                ErrorLogging.LogError(ex);
                return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Please try again."), Configuration.Formatters.JsonFormatter));
            }
        }
Ejemplo n.º 28
0
        public ActionResult Create([Bind(Include = "TipId,CustomerId,TipUrl,Title,CreatedOn,LastUpdatedOn,IsActive")] TipModel tipModel, HttpPostedFileBase file)
        {
            UserPermissionAction("Tip", RoleAction.create.ToString());
            CheckPermission();
            try
            {
                //TempData["ShowMessage"] = "error";
                //TempData["MessageBody"] = "Please fill the required field with valid data.";
                if (file != null)
                {
                    var fileExt = Path.GetExtension(file.FileName);
                    if (fileExt != ".pdf")
                    {
                        TempData["ShowMessage"] = "error";
                        TempData["MessageBody"] = "Please upload only .pdf file.";
                        return(RedirectToAction("Create"));
                    }

                    //if (tipModel.Title == "" || tipModel.Title == null )
                    //{
                    //    TempData["ShowMessage"] = "error";
                    //    TempData["MessageBody"] = "Please fill the title field.";
                    //    return RedirectToAction("Create");
                    //}


                    if (ModelState.IsValid)
                    {
                        Mapper.CreateMap <CommunicationApp.Models.TipModel, CommunicationApp.Entity.Tip>();
                        CommunicationApp.Entity.Tip tipEntity = Mapper.Map <CommunicationApp.Models.TipModel, CommunicationApp.Entity.Tip>(tipModel);

                        //Save the Logo in Folder

                        string fileName = Guid.NewGuid() + fileExt;

                        var subPath = Server.MapPath("~/TipData");
                        //Check SubPath Exist or Not
                        if (!Directory.Exists(subPath))
                        {
                            Directory.CreateDirectory(subPath);
                        }
                        //End : Check SubPath Exist or Not

                        var path = Path.Combine(subPath, fileName);
                        file.SaveAs(path);

                        string URL = CommonCls.GetURL() + "/TipData/" + fileName;
                        tipEntity.CustomerId = Convert.ToInt32(Session["CustomerId"]);
                        tipEntity.TipUrl     = URL;
                        tipEntity.IsActive   = true;
                        tipEntity.CreatedOn  = DateTime.Now;
                        _TipService.InsertTip(tipEntity);

                        var Flag    = 13;//status for Tip of the day.
                        var Message = "New Tip of the day.";
                        ////send notification
                        //var CustomerList = _CustomerService.GetCustomers().Where(c => c.CustomerId != tipModel.CustomerId && c.IsActive == true).ToList();
                        //foreach (var Customer in CustomerList)
                        //{
                        //    if (Customer != null)
                        //    {
                        //        if (Customer.ApplicationId != null && Customer.ApplicationId != "")
                        //        {
                        //            string PropertyDetail = "{\"Flag\":\"" + Flag + "\",\"Message\":\"" + Message + "\"}";
                        //            Common.SendGCM_Notifications(Customer.ApplicationId, PropertyDetail, true);
                        //        }

                        //    }
                        //}
                        TempData["ShowMessage"] = "success";
                        TempData["MessageBody"] = "Tip is saved successfully.";
                        return(RedirectToAction("Index"));
                    }
                }
                else
                {
                    TempData["ShowMessage"] = "error";
                    TempData["MessageBody"] = "Please upload a valid file.";
                    return(RedirectToAction("Create"));
                }
            }


            catch (Exception ex)
            {
                ErrorLogging.LogError(ex);

                TempData["ShowMessage"] = "error";
                TempData["MessageBody"] = "Some unknown problem occured while proccessing save operation on Tip.";
            }
            //  return RedirectToAction("Create", "Tip", new { id = tipModel.TipId });
            return(View(tipModel));
        }
        public ActionResult Create([Bind(Include = "CategoryId,Name,Colour,CurrentPageNo")] CategoryModel CategoryModel, HttpPostedFileBase file)
        {
            UserPermissionAction("Category", RoleAction.view.ToString());
            CheckPermission();
            try
            {
                string URL = "";

                if (string.IsNullOrWhiteSpace(CategoryModel.Name))
                {
                    ModelState.AddModelError("Name", "Please enter category name.");
                }
                if (string.IsNullOrWhiteSpace(CategoryModel.Colour))
                {
                    ModelState.AddModelError("Description", "Please enter category name.");
                }
                if (ModelState.IsValid)
                {
                    var IsCateGoryDuplicate = _CategoryService.GetCategories().Where(c => c.Name == CategoryModel.Name.Trim()).FirstOrDefault();
                    if (IsCateGoryDuplicate != null)
                    {
                        TempData["ShowMessage"] = "error";
                        TempData["MessageBody"] = " Category name is already exist.";
                        return(RedirectToAction("Create"));
                    }

                    if (file != null && file.ContentLength > 0)
                    {
                        try
                        {
                            if (file != null && file.ContentLength > 0)
                            {
                                string path = Path.Combine(Server.MapPath("~/CategoryImage"), Path.GetFileName(file.FileName));
                                file.SaveAs(path);
                                URL = CommonCls.GetURL() + "/CategoryImage/" + file.FileName;
                            }
                        }
                        catch (Exception ex)
                        {
                            ViewBag.Message = "ERROR:" + ex.Message.ToString();
                        }
                    }


                    Mapper.CreateMap <CategoryModel, Category>();
                    var category = Mapper.Map <CategoryModel, Category>(CategoryModel);

                    category.PhotoPath = URL;
                    category.IsActive  = true;
                    _CategoryService.InsertCategory(category);
                    //new CategoryModel
                    //{
                    //    CategoryId = Convert.ToInt32(CategoryModel.CategoryId),
                    //    Name = CategoryModel.Name,
                    //    Description=CategoryModel.Description// CategoryModel.ParentId == -1?null:Convert.ToInt32(CategoryModel.ParentId)
                    //}.InsertUpdate();

                    TempData["ShowMessage"] = "success";
                    TempData["MessageBody"] = " Category save  successfully.";
                    return(RedirectToAction("Index"));
                }
                else
                {
                    ViewBag.CategoryList = Colors.ToList();
                    return(View(CategoryModel));
                }
            }


            catch (Exception ex)
            {
                string ErrorMsg = ex.Message.ToString();//
                ErrorLogging.LogError(ex);
            }
            var errors           = ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => new { x.Key, x.Value.Errors }).ToArray();
            var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);

            return(View(CategoryModel));
        }
        public ActionResult Edit(EventModel EventModel, HttpPostedFileBase file)
        {
            UserPermissionAction("event", RoleAction.view.ToString());
            CheckPermission();
            TempData["ShowMessage"] = "";
            TempData["MessageBody"] = "";
            try
            {
                if (ModelState.IsValid)
                {
                    if (string.IsNullOrEmpty(EventModel.EventDate.ToString()))
                    {
                        TempData["ShowMessage"] = "error";
                        TempData["MessageBody"] = "Please select a valid Event Date.";
                        return(View("Create", EventModel));
                    }

                    if (string.IsNullOrEmpty(EventModel.EventName))
                    {
                        TempData["ShowMessage"] = "error";
                        TempData["MessageBody"] = "Please Fill Event Name.";
                        return(View("Create", EventModel));
                    }
                    if (string.IsNullOrEmpty(EventModel.EventDescription))
                    {
                        TempData["ShowMessage"] = "error";
                        TempData["MessageBody"] = "Please Fill  EventDescription.";
                        return(View("Create", EventModel));
                    }
                    Mapper.CreateMap <CommunicationApp.Models.EventModel, CommunicationApp.Entity.Event>();
                    CommunicationApp.Entity.Event Event = Mapper.Map <CommunicationApp.Models.EventModel, CommunicationApp.Entity.Event>(EventModel);
                    var EventImage = "";
                    if (file != null)
                    {
                        if (Event.EventImage != "")
                        {   //Delete Old Image
                            string pathDel = Server.MapPath("~/EventPhoto");

                            FileInfo objfile = new FileInfo(pathDel);
                            if (objfile.Exists) //check file exsit or not
                            {
                                objfile.Delete();
                            }
                            //End :Delete Old Image
                        }

                        //Save the photo in Folder
                        var    fileExt  = Path.GetExtension(file.FileName);
                        string fileName = Guid.NewGuid() + fileExt;
                        var    subPath  = Server.MapPath("~/EventPhoto");

                        //Check SubPath Exist or Not
                        if (!Directory.Exists(subPath))
                        {
                            Directory.CreateDirectory(subPath);
                        }
                        //End : Check SubPath Exist or Not

                        var path = Path.Combine(subPath, fileName);
                        file.SaveAs(path);

                        EventImage = CommonCls.GetURL() + "/EventPhoto/" + fileName;
                    }
                    Event.LastUpdatedon = DateTime.Now;
                    Event.EventImage    = EventImage;
                    _EventService.UpdateEvent(Event);
                    TempData["ShowMessage"] = "success";
                    TempData["MessageBody"] = "Event successfully updated.";
                    return(RedirectToAction("Index"));
                }
                return(View(EventModel));
            }
            catch (Exception ex)
            {
                ErrorLogging.LogError(ex);

                return(View(EventModel));
            }
        }
        public ActionResult Edit([Bind(Include = "CategoryId,Name,Colour,CurrentPageNo")] CategoryModel CategoryModel, HttpPostedFileBase file)
        {
            UserPermissionAction("Category", RoleAction.view.ToString());
            CheckPermission();
            try
            {
                if (string.IsNullOrWhiteSpace(CategoryModel.Name))
                {
                    ModelState.AddModelError("Name", "Please enter category name.");
                }
                if (string.IsNullOrWhiteSpace(CategoryModel.Colour))
                {
                    ModelState.AddModelError("Colour", "Please select colour.");
                }
                if (ModelState.IsValid)
                {
                    var IsParentAllReadyContainCategoryName = _CategoryService.GetCategories().Where(c => c.CategoryId != CategoryModel.CategoryId).Select(c => c.Name);
                    if (IsParentAllReadyContainCategoryName.Contains(CategoryModel.Name.Trim()))
                    {
                        TempData["ShowMessage"] = "error";
                        TempData["MessageBody"] = " Category name is already exist.";
                        return(RedirectToAction("Edit"));
                    }
                    Category CategoryFound    = _CategoryService.GetCategories().Where(x => x.Name == CategoryModel.Name && x.CategoryId != CategoryModel.CategoryId).FirstOrDefault();
                    var      existingCategory = _CategoryService.GetCategories().Where(c => c.CategoryId == CategoryModel.CategoryId).FirstOrDefault();
                    Mapper.CreateMap <HomeHelp.Models.CategoryModel, HomeHelp.Entity.Category>();
                    HomeHelp.Entity.Category Categorys = Mapper.Map <HomeHelp.Models.CategoryModel, HomeHelp.Entity.Category>(CategoryModel);
                    if (CategoryFound == null)
                    {
                        if (file != null && file.ContentLength > 0)
                        {
                            try
                            {
                                if (Categorys.PhotoPath != "")
                                {
                                    DeleteImage(Categorys.PhotoPath);
                                }

                                string path = Path.Combine(Server.MapPath("~/CategoryImage"), Path.GetFileName(file.FileName));
                                file.SaveAs(path);

                                string URL = CommonCls.GetURL() + "/CategoryImage/" + file.FileName;
                                Categorys.PhotoPath = URL;
                            }
                            catch (Exception ex)
                            {
                                ViewBag.Message = "ERROR:" + ex.Message.ToString();
                            }
                        }
                        else
                        {
                            Categorys.PhotoPath = existingCategory.PhotoPath;
                        }
                        Categorys.IsActive = true;
                        _CategoryService.UpdateCategory(Categorys);

                        TempData["ShowMessage"] = "success";
                        TempData["MessageBody"] = " Category update  successfully.";
                        return(RedirectToAction("Index", new { CurrentPageNo = CategoryModel.CurrentPageNo }));
                        // end  Update CompanyEquipments
                    }

                    else
                    {
                        TempData["ShowMessage"] = "error";
                        if (CategoryFound.Name.Trim().ToLower() == CategoryModel.Name.Trim().ToLower()) //Check User Name
                        {
                            TempData["MessageBody"] = CategoryFound.Name + " already exist.";
                        }

                        else
                        {
                            TempData["MessageBody"] = "Some unknown problem occured while proccessing save operation on ";
                        }
                    }
                }
                else
                {
                    ViewBag.CategoryList = Colors.ToList();
                    return(View(CategoryModel));
                }
            }
            catch (Exception ex)
            {
                string ErrorMsg = ex.Message.ToString();//
                ErrorLogging.LogError(ex);
            }
            ViewBag.Category = new SelectList(_CategoryService.GetCategories(), "CategoryId", "Name", CategoryModel.CategoryId);
            var errors           = ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => new { x.Key, x.Value.Errors }).ToArray();
            var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);

            return(View(CategoryModel));
        }
Ejemplo n.º 32
0
        private void ParseServerData(string data, bool Handled)
        {
        // page = engine.LoadFromString(cBot.MS_Script)
        if (data == "Dragonroar") {
        BotConnecting();
        //  Login Sucessful
        if (smProxy.IsClientConnected)
            smProxy.SendClient(data + Constants.vbLf);
        return;
        } else if (data == "&&&&&&&&&&&&&") {
        loggingIn = 2;
        TS_Status_Client.Image = My.Resources.images3;
        ReLogCounter = 0;
        //(0:1) When the bot logs into furcadia,
        MainMSEngine.PageExecute(1);
        if ((ReconnectTimeOutTimer != null))
            ReconnectTimeOutTimer.Dispose();
        if (smProxy.IsClientConnected)
            smProxy.SendClient(data + Constants.vbLf);
        return;
        // Species Tags
        } else if (data.StartsWith("]-")) {
        if (data.StartsWith("]-#A")) {
            SpeciesTag.Enqueue(data.Substring(4));
        } else if (data.StartsWith("]-#B")) {
            BadgeTag.Enqueue(data.Substring(2));
        }

        if (smProxy.IsClientConnected)
            smProxy.SendClient(data + Constants.vbLf);
        return;
        //DS Variables

        //Popup Dialogs!
        } else if (data.StartsWith("]#")) {
        //]#<idstring> <style 0-17> <message that might have spaces in>
        Regex repqq = new Regex("^\\]#(.*?) (\\d+) (.*?)$");
        System.Text.RegularExpressions.Match m = repqq.Match(data);
        Rep r = default(Rep);
        r.ID = m.Groups(1).Value;
        r.type = m.Groups(2).Value.ToInteger;
        Repq.Enqueue(r);
        MainMSEngine.PageSetVariable("MESSAGE", m.Groups(3).Value, true);
        Player.Message = m.Groups(3).Value;
        MainMSEngine.PageExecute(95, 96);
        if (smProxy.IsClientConnected)
            smProxy.SendClient(data + Constants.vbLf);
        return;
        } else if (data.StartsWith("0")) {
        InDream = true;
        //Phoenix Speak event
        if (smProxy.IsClientConnected)
            smProxy.SendClient(data + Constants.vbLf);
        return;
        } else if (data.StartsWith("3")) {
        if (smProxy.IsClientConnected)
            smProxy.SendClient(data + Constants.vbLf);
        return;
        //self Induced Dragon Speak Event
        } else if (data.StartsWith("6")) {
        if (smProxy.IsClientConnected)
            smProxy.SendClient(data + Constants.vbLf);
        return;
        //Dragon Speak event
        } else if (data.StartsWith("7")) {
        if (smProxy.IsClientConnected)
            smProxy.SendClient(data + Constants.vbLf);
        return;
        //Dragon Speak Addon (Follows Instructions 6 and 7
        } else if (data.StartsWith("8")) {
        if (smProxy.IsClientConnected)
            smProxy.SendClient(data + Constants.vbLf);
        return;
        //]s(.+)1 (.*?) (.*?) 0
        } else if (data.StartsWith("]s")) {
        Regex t = new Regex("\\]s(.+)1 (.*?) (.*?) 0", RegexOptions.IgnoreCase);
        System.Text.RegularExpressions.Match m = t.Match(data);

        if (BotName.ToFurcShortName == m.Groups(2).Value.ToFurcShortName) {
            MainMSEngine.PageExecute();
        }
        if (smProxy.IsClientConnected)
            smProxy.SendClient(data + Constants.vbLf);
        return;
        //Look response
        } else if (data.StartsWith("]f") & bConnected() & InDream == true) {
        short length = 14;
        if (Look) {
            LookQue.Enqueue(data.Substring(2));
        } else {
            if (data.Substring(2, 1) != "t") {
                length = 30;
            } else {
                length = 14;
            }
            try {
                Player = NametoFurre(data.Remove(0, length + 2), true);
                // If Player.ID = 0 Then Exit Sub
                Player.Color = data.Substring(2, length);
                if (IsBot(Player))
                    Look = false;
                if (DREAM.List.ContainsKey(Player.ID))
                    DREAM.List.Item(Player.ID) = Player;
            } catch (Exception eX) {
                ErrorLogging logError = new ErrorLogging(eX, this);
            }

        }
        if (smProxy.IsClientConnected)
            smProxy.SendClient(data + Constants.vbLf);
        return;
        //Spawn Avatar
        } else if (data.StartsWith("<") & bConnected()) {
        try {
            if (data.Length < 29)
                return;
            // Debug.Print(data)
            Player.ID = ConvertFromBase220(data.Substring(1, 4));

            if (DREAM.List.ContainsKey(Player.ID)) {
                Player = DREAM.List.Item(Player.ID);
            }

            Player.X = Convert.ToUInt32(ConvertFromBase220(data.Substring(5, 2)) * 2);
            Player.Y = ConvertFromBase220(data.Substring(7, 2));
            Player.Shape = ConvertFromBase220(data.Substring(9, 2));

            uint NameLength = ConvertFromBase220(data.Substring(11, 1));
            Player.Name = data.Substring(12, Convert.ToInt32(NameLength)).Replace("|", " ");

            uint ColTypePos = Convert.ToUInt32(12 + NameLength);
            Player.ColorType = Convert.ToChar(data.Substring(Convert.ToInt32(ColTypePos), 1));
            uint ColorSize = 10;
            if (Player.ColorType != "t") {
                ColorSize = 30;
            }
            int sColorPos = Convert.ToInt32(ColTypePos + 1);

            Player.Color = data.Substring(sColorPos, Convert.ToInt32(ColorSize));

            int FlagPos = data.Length - 6;
            Player.Flag = Convert.ToInt32(ConvertFromBase220(data.Substring(FlagPos, 1)));
            int AFK_Pos = data.Length - 5;
            string AFKStr = data.Substring(AFK_Pos, 4);
            Player.AFK = ConvertFromBase220(data.Substring(AFK_Pos, 4));
            int FlagCheck = Convert.ToInt32(Flags.CHAR_FLAG_NEW_AVATAR) - Player.Flag;

            // Add New Arrivals to Dream List
            // One or the other will trigger it
            IsBot(Player);
            MainMSEngine.PageSetVariable(MS_Name, Player.ShortName);

            if (Player.Flag == 4 | !DREAM.List.ContainsKey(Player.ID)) {
                DREAM.List.Add(Player.ID, Player);
                if (InDream)
                    UpDateDreamList(Player.Name);
                if (Player.Flag == 2) {
                    FURRE Bot = fIDtoFurre(Convert.ToUInt32(BotUID));
                    ViewArea VisableRectangle = getTargetRectFromCenterCoord(Convert.ToInt32(Bot.X), Convert.ToInt32(Bot.Y));
                    if (VisableRectangle.X <= Player.X & VisableRectangle.Y <= Player.Y & VisableRectangle.height >= Player.Y & VisableRectangle.length >= Player.X) {
                        Player.Visible = true;
                    } else {
                        Player.Visible = false;
                    }
                    MainMSEngine.PageExecute(28, 29, 24, 25);
                } else {
                    MainMSEngine.PageExecute(24, 25);
                }
            } else if (Player.Flag == 2) {
                FURRE Bot = fIDtoFurre(Convert.ToUInt32(BotUID));
                ViewArea VisableRectangle = getTargetRectFromCenterCoord(Convert.ToInt32(Bot.X), Convert.ToInt32(Bot.Y));
                if (VisableRectangle.X <= Player.X & VisableRectangle.Y <= Player.Y & VisableRectangle.height >= Player.Y & VisableRectangle.length >= Player.X) {
                    Player.Visible = true;
                } else {
                    Player.Visible = false;
                }
                MainMSEngine.PageExecute(28, 29);

            } else if (Player.Flag == 1) {

            } else if (Player.Flag == 0) {
            }
            if (DREAM.List.ContainsKey(Player.ID)) {
                DREAM.List.Item(Player.ID) = Player;
            }

        } catch (Exception eX) {
            ErrorLogging logError = new ErrorLogging(eX, this);
            return;
        }
        if (smProxy.IsClientConnected)
            smProxy.SendClient(data + Constants.vbLf);
        return;
        //Remove Furre
        //And loggingIn = False
        } else if (data.StartsWith(")") & bConnected()) {
        try {
            uint remID = ConvertFromBase220(data.Substring(1, 4));
            // remove departure from List
            if (DREAM.List.ContainsKey(remID) == true) {
                Player = DREAM.List.Item(remID);
                MainMSEngine.PageSetVariable(MS_Name, Player.Name);
                MainMSEngine.PageExecute(26, 27, 30, 31);
                DREAM.List.Remove(remID);
                UpDateDreamList("");
            }
        } catch (Exception eX) {
            ErrorLogging logError = new ErrorLogging(eX, this);
        }
        if (smProxy.IsClientConnected)
            smProxy.SendClient(data + Constants.vbLf);
        return;
        //Animated Move
        //And loggingIn = False
        } else if (data.StartsWith("/") & bConnected()) {
        try {
            Player = fIDtoFurre(ConvertFromBase220(data.Substring(1, 4)));
            Player.X = Convert.ToUInt32(ConvertFromBase220(data.Substring(5, 2)) * 2);
            Player.Y = ConvertFromBase220(data.Substring(7, 2));
            Player.Shape = ConvertFromBase220(data.Substring(9, 2));
            FURRE Bot = fIDtoFurre(Convert.ToUInt32(BotUID));
            ViewArea VisableRectangle = getTargetRectFromCenterCoord(Convert.ToInt32(Bot.X), Convert.ToInt32(Bot.Y));
            if (VisableRectangle.X <= Player.X & VisableRectangle.Y <= Player.Y & VisableRectangle.height >= Player.Y & VisableRectangle.length >= Player.X) {
                Player.Visible = true;
            } else {
                Player.Visible = false;
            }
            if (DREAM.List.ContainsKey(Player.ID))
                DREAM.List.Item(Player.ID) = Player;
            IsBot(Player);
            MainMSEngine.PageSetVariable(MS_Name, Player.ShortName);
            MainMSEngine.PageExecute(28, 29, 30, 31, 601, 602);
        } catch (Exception eX) {
            ErrorLogging logError = new ErrorLogging(eX, this);
        }
        if (smProxy.IsClientConnected)
            smProxy.SendClient(data + Constants.vbLf);
        return;
        // Move Avatar
        //And loggingIn = False
        } else if (data.StartsWith("A") & bConnected()) {
        try {
            Player = fIDtoFurre(ConvertFromBase220(data.Substring(1, 4)));
            Player.X = Convert.ToUInt32(ConvertFromBase220(data.Substring(5, 2)) * 2);
            Player.Y = ConvertFromBase220(data.Substring(7, 2));
            Player.Shape = ConvertFromBase220(data.Substring(9, 2));

            FURRE Bot = fIDtoFurre(Convert.ToUInt32(BotUID));
            ViewArea VisableRectangle = getTargetRectFromCenterCoord(Convert.ToInt32(Bot.X), Convert.ToInt32(Bot.Y));

            if (VisableRectangle.X <= Player.X & VisableRectangle.Y <= Player.Y & VisableRectangle.height >= Player.Y & VisableRectangle.length >= Player.X) {
                Player.Visible = true;
            } else {
                Player.Visible = false;
            }
            if (DREAM.List.ContainsKey(Player.ID))
                DREAM.List.Item(Player.ID) = Player;

            IsBot(Player);
            MainMSEngine.PageSetVariable(MS_Name, Player.ShortName);
            MainMSEngine.PageExecute(28, 29, 30, 31, 601, 602);
        } catch (Exception eX) {
            ErrorLogging logError = new ErrorLogging(eX, this);
        }
        if (smProxy.IsClientConnected)
            smProxy.SendClient(data + Constants.vbLf);
        return;
        // Update Color Code
        //And loggingIn = False
        } else if (data.StartsWith("B") != false & bConnected() & InDream) {
        try {
            Player = fIDtoFurre(ConvertFromBase220(data.Substring(1, 4)));
            Player.Shape = ConvertFromBase220(data.Substring(5, 2));
            uint ColTypePos = 7;
            Player.ColorType = Convert.ToChar(data.Substring(Convert.ToInt32(ColTypePos), 1));
            uint ColorSize = 10;
            if (Player.ColorType != "t") {
                ColorSize = 30;
            }
            uint sColorPos = Convert.ToUInt32(ColTypePos + 1);
            Player.Color = data.Substring(Convert.ToInt32(sColorPos), Convert.ToInt32(ColorSize));
            if (DREAM.List.ContainsKey(Player.ID))
                DREAM.List.Item(Player.ID) = Player;
            IsBot(Player);
        } catch (Exception eX) {
            ErrorLogging logError = new ErrorLogging(eX, this);
        }
        if (smProxy.IsClientConnected)
            smProxy.SendClient(data + Constants.vbLf);
        return;
        //Hide Avatar
        //And loggingIn = False
        } else if (data.StartsWith("C") != false & bConnected()) {
        try {
            Player = fIDtoFurre(ConvertFromBase220(data.Substring(1, 4)));
            Player.X = Convert.ToUInt32(ConvertFromBase220(data.Substring(5, 2)) * 2);
            Player.Y = ConvertFromBase220(data.Substring(7, 2));
            Player.Visible = false;
            if (DREAM.List.ContainsKey(Player.ID))
                DREAM.List.Item(Player.ID) = Player;
            IsBot(Player);
            MainMSEngine.PageSetVariable(MS_Name, Player.Name);
            MainMSEngine.PageExecute(30, 31);
        } catch (Exception eX) {
            ErrorLogging logError = new ErrorLogging(eX, this);
        }
        if (smProxy.IsClientConnected)
            smProxy.SendClient(data + Constants.vbLf);
        return;
        //Display Disconnection Dialog
        #if DEBUG
        } else if (data.StartsWith("[")) {
        Console.WriteLine("Disconnection Dialog:" + data);
        #endif
        InDream = false;
        DREAM.List.Clear();
        UpDateDreamList("");

        if (smProxy.IsClientConnected)
            smProxy.SendClient(data + Constants.vbLf);
        Interaction.MsgBox(data, MsgBoxStyle.Critical, "Disconnection Error");

        return;

        //;{mapfile}	Load a local map (one in the furcadia folder)
        //]q {name} {id}	Request to download a specific patch
        } else if (data.StartsWith(";") || data.StartsWith("]q") || data.StartsWith("]r")) {
        #if DEBUG
        try {
            Debug.Print("Entering new Dream" + data);
            #endif
            MainMSEngine.PageSetVariable("DREAMOWNER", "");
            MainMSEngine.PageSetVariable("DREAMNAME", "");
            HasShare = false;
            NoEndurance = false;

            DREAM.List.Clear();
            UpDateDreamList("");
            InDream = false;
        } catch (Exception eX) {
            ErrorLogging logError = new ErrorLogging(eX, this);
        }
        if (smProxy.IsClientConnected)
            smProxy.SendClient(data + Constants.vbLf);
        return;
        } else if (data.StartsWith("]z")) {
        BotUID = uint.Parse(data.Remove(0, 2));
        //Snag out UID
        } else if (data.StartsWith("]B")) {
        try {
            BotUID = uint.Parse(data.Remove(0, 2));
        } catch (Exception eX) {
            ErrorLogging logError = new ErrorLogging(eX, this);
        }
        if (smProxy.IsClientConnected)
            smProxy.SendClient(data + Constants.vbLf);
        return;
        } else if (data.StartsWith("~")) {
        if (smProxy.IsClientConnected)
            smProxy.SendClient(data + Constants.vbLf);
        return;
        } else if (data.StartsWith("=")) {
        if (smProxy.IsClientConnected)
            smProxy.SendClient(data + Constants.vbLf);
        return;
        #if DEBUG
        } else if (data.StartsWith("]c")) {
        Console.WriteLine(data);
        #endif
        if (smProxy.IsClientConnected)
            smProxy.SendClient(data + Constants.vbLf);
        return;
        } else if (data.StartsWith("]C")) {
        if (data.StartsWith("]C0")) {
            string dname = data.Substring(10);
            if (dname.Contains(":")) {
                string NameStr = dname.Substring(0, dname.IndexOf(":"));
                if (NameStr.ToFurcShortName == BotName.ToFurcShortName) {
                    HasShare = true;
                }
                MainMSEngine.PageSetVariable(Main.VarPrefix + "DREAMOWNER", NameStr);
            } else if (dname.EndsWith("/") && !dname.Contains(":")) {
                string NameStr = dname.Substring(0, dname.IndexOf("/"));
                if (NameStr.ToFurcShortName == BotName.ToFurcShortName) {
                    HasShare = true;
                }
                MainMSEngine.PageSetVariable("DREAMOWNER", NameStr);
            }

            MainMSEngine.PageSetVariable("DREAMNAME", dname);
            MainMSEngine.PageExecute(90, 91);
        }
        #if DEBUG
        Console.WriteLine(data);
        #endif
        if (smProxy.IsClientConnected)
            smProxy.SendClient(data + Constants.vbLf);
        return;
        //Process Channels Seperatly
        } else if (data.StartsWith("(")) {
        if (ThroatTired == false & data.StartsWith("(<font color='warning'>Your throat is tired. Try again in a few seconds.</font>")) {
            ThroatTired = true;

            //Throat Tired Syndrome, Halt all out going data for a few seconds
            TimeSpan Ts = TimeSpan.FromSeconds(cMain.TT_TimeOut);
            TroatTiredDelay = new Threading.Timer(TroatTiredDelayTick, null, Ts, Ts);
            //(0:92) When the bot detects the "Your throat is tired. Please wait a few seconds" message,
            MainMSEngine.PageExecute(92);
            //Exit Sub
            if (smProxy.IsClientConnected)
                smProxy.SendClient(data + Constants.vbLf);
            return;
        }

        ChannelProcess(ref data, Handled);
        return;
        }

        if (smProxy.IsClientConnected)
        smProxy.SendClient(data + Constants.vbLf);

        }
Ejemplo n.º 33
0
        private string GetWR(string game, bool isCurrent, string category, string level, Dictionary <string, string> subcategories, Dictionary <string, string> variables)
        {
            try
            {
                SetParameters(ref isCurrent, ref category, ref level, ref subcategories, ref variables);

                if (game == "")
                {
                    return("No game provided");
                }

                var srSearch = new SpeedrunComClient();
                var srGame   = srSearch.Games.SearchGame(game);
                if (srGame == null)
                {
                    return("No game was found");
                }
                else
                {
                    //Levels generally have different category, so they need a seperate look up
                    if (level != "")
                    {
                        Category srCategory;
                        if (category == "")
                        {
                            srCategory = srGame.LevelCategories.ElementAt(0);
                        }
                        else
                        {
                            srCategory = srGame.LevelCategories.FirstOrDefault(cat => cat.Name.ToLower().StartsWith(category.ToLower()));
                        }

                        if (srCategory == null)
                        {
                            return("No category was found");
                        }

                        var srLevel = srGame.Levels.FirstOrDefault(lvl => lvl.Name.ToLower().StartsWith(level.ToLower()));
                        if (srLevel == null)
                        {
                            return("No level was found");
                        }

                        //Haven't tested this for levels
                        List <VariableValue> lookVariable = GetVariablesForLevel(ref subcategories, ref variables, ref srCategory, ref srLevel);

                        var leaderboard = srSearch.Leaderboards.GetLeaderboardForLevel(srGame.ID, srLevel.ID, srCategory.ID, variableFilters: lookVariable);

                        if (leaderboard.Records.Count > 0)
                        {
                            var    record  = leaderboard.Records[0];
                            string runners = "";
                            if (record.Players.Count > 1)
                            {
                                for (int i = 0; i < record.Players.Count - 1; i++)
                                {
                                    runners += record.Players[i].Name + ", ";
                                }
                                runners += record.Players[record.Players.Count - 1].Name;
                            }
                            else
                            {
                                runners = record.Player.Name;
                            }

                            return(string.Format("{0} - Level: {1} WR ({2}) is {3} by {4} - {5}",
                                                 srGame.Name, srLevel.Name,
                                                 srCategory.Name,
                                                 record.Times.Primary.ToString(),
                                                 runners,
                                                 record.WebLink.ToString()
                                                 ));
                        }
                        else
                        {
                            return(string.Format("No records were found! - {0}", leaderboard.WebLink));
                        }
                    }
                    //Full-game run
                    else
                    {
                        Category srCategory;
                        if (category == "")
                        {
                            srCategory = srGame.FullGameCategories.ElementAt(0);
                        }
                        else
                        {
                            srCategory = srGame.FullGameCategories.FirstOrDefault(cat => cat.Name.ToLower().StartsWith(category.ToLower()));
                        }

                        if (srCategory == null)
                        {
                            return("No category was found");
                        }

                        List <VariableValue> lookVariable = GetVariablesForFullGameCategory(ref subcategories, ref variables, ref srCategory);

                        var leaderboard = srSearch.Leaderboards.GetLeaderboardForFullGameCategory(srGame.ID, srCategory.ID, variableFilters: lookVariable);

                        if (leaderboard.Records.Count > 0)
                        {
                            var    record  = leaderboard.Records[0];
                            string runners = "";
                            if (record.Players.Count > 1)
                            {
                                for (int i = 0; i < record.Players.Count - 1; i++)
                                {
                                    runners += record.Players[i].Name + ", ";
                                }
                                runners += record.Players[record.Players.Count - 1].Name;
                            }
                            else
                            {
                                runners = record.Player.Name;
                            }

                            return(string.Format("{0} ({1}) record is {2} by {3} - {4}",
                                                 srGame.Name,
                                                 srCategory.Name,
                                                 record.Times.Primary.ToString(),
                                                 runners,
                                                 record.WebLink
                                                 ));
                        }
                        else
                        {
                            return("Leaderboard doesn't have any records! " + leaderboard.WebLink);
                        };
                    }
                }
            }
            catch (Exception e)
            {
                ErrorLogging.WriteLine(e.ToString());
                return("Error looking for a game on speedrun.com.");
            }
        }