public void ShouldGetItem_Correctly()
        {
            var cachingService = new HttpRuntimeCacheService();
            const string key = "TEST_CACHEKEY_3";
            ClearCache(key);
            var cacheObject = new CacheObject(key);

            HttpRuntime.Cache.Add(key, cacheObject, null, DateTime.Now.Add(TimeSpan.FromMinutes(1)), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null);

            var cachedItem = cachingService.Get<CacheObject>(key);
            Assert.AreEqual(cachedItem, cacheObject);
        }
        public void ShouldRemoveItem_Successfully()
        {
            const string key = "TEST_CACHEKEY_6";
            var cacheObject = new CacheObject(key);

            HttpRuntime.Cache.Add(key, cacheObject, null, DateTime.Now.Add(TimeSpan.FromMinutes(1)), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null);
            Assert.AreEqual(HttpRuntime.Cache[key], cacheObject);

            var cachingService = new HttpRuntimeCacheService();
            cachingService.Remove(key);
            Assert.IsNull(HttpRuntime.Cache[key]);
        }
        public void ShouldSetItem_WithTimeSpan_Correctly()
        {
            var cachingService = new HttpRuntimeCacheService();
            var timespan = TimeSpan.FromSeconds(1);
            const string key = "TEST_CACHEKEY_2";
            ClearCache(key);
            var cacheObject = new CacheObject(key);

            cachingService.Set(key, cacheObject, timespan);
            Assert.AreEqual(HttpRuntime.Cache[key], cacheObject);

            System.Threading.Thread.Sleep(timespan);
            Assert.IsNull(HttpRuntime.Cache[key]);
        }
        public void ShouldGetItem_WithDelegate_WithExpiration_Correctly()
        {
            var timespan = TimeSpan.FromSeconds(3);
            var cachingService = new HttpRuntimeCacheService();
            const string key = "TEST_CACHEKEY_5";
            ClearCache(key);
            var cacheObject = new CacheObject(key);

            Assert.IsNull(HttpRuntime.Cache[key]);
            var cachedItem = cachingService.Get(key, timespan, () => cacheObject);
            Assert.AreEqual(cachedItem, cacheObject);
            Assert.AreEqual(HttpRuntime.Cache[key], cacheObject);

            System.Threading.Thread.Sleep(timespan);
            Assert.IsNull(HttpRuntime.Cache[key]);
        }
Пример #5
0
        public object Invoke(object instance, object[] inputs, out object[] outputs)
        {
            var cacheKey = CreateCacheKey(operationName, inputs);

            if (MemoryCache.Default.Contains(cacheKey, regionName))
            {
                var cachedValue = (CacheObject) MemoryCache.Default.Get(cacheKey);
                outputs = cachedValue.Outputs;
                return cachedValue.ReturnValue;
            }

            var returnValue = previousInvoker.Invoke(instance, inputs, out outputs);
            var cacheValue = new CacheObject
                {
                    Outputs = outputs,
                    ReturnValue = returnValue
                };
            AddToCache(cacheKey, cacheValue);
            return returnValue;
        }
Пример #6
0
#pragma warning restore 465

        #region Load Cache

        private static void LoadCache(BinaryReader rdr)
        {
            if (rdr.ReadUInt32() != CacheHeader)
            {
                ErrorManager.Warning(89, Processor.file, Processor.file.Filename + ".cache");
                return;
            }
            uint version = rdr.ReadUInt32();
            if (version > OMCFVersion)
            {
                ErrorManager.Error(90, Processor.file, OMCFVersion, version);
                return;
            }

            ulong objectCount = rdr.ReadUInt64();
            for (ulong i = 0; i < objectCount; i++)
            {
                CacheObject c = new CacheObject();
                c.Type = (CacheObjectType)rdr.ReadByte();

                #region Read Actual Data
                switch (c.Type)
                {
                    case CacheObjectType.String:
                        c.Size = rdr.ReadUInt32();
                        byte[] buf = rdr.ReadBytes((int)c.Size);
                        c.Value = Encoding.GetString(buf);
                        break;
                    case CacheObjectType.Byte:
                        c.Value = rdr.ReadByte();
                        c.Size = 1;
                        break;
                    case CacheObjectType.SByte:
                        c.Value = rdr.ReadSByte();
                        c.Size = 1;
                        break;
                    case CacheObjectType.Bool:
                        c.Value = (bool)(rdr.ReadByte() == 0 ? false : true);
                        c.Size = 1;
                        break;
                    case CacheObjectType.UShort:
                        c.Value = rdr.ReadUInt16();
                        c.Size = 2;
                        break;
                    case CacheObjectType.Short:
                        c.Value = rdr.ReadInt16();
                        c.Size = 2;
                        break;
                    case CacheObjectType.UInt:
                        c.Value = rdr.ReadUInt32();
                        c.Size = 4;
                        break;
                    case CacheObjectType.Int:
                        c.Value = rdr.ReadInt32();
                        c.Size = 4;
                        break;
                    case CacheObjectType.ULong:
                        c.Value = rdr.ReadUInt64();
                        c.Size = 8;
                        break;
                    case CacheObjectType.Long:
                        c.Value = rdr.ReadInt64();
                        c.Size = 8;
                        break;
                    case CacheObjectType.Float:
                        c.Value = rdr.ReadSingle();
                        c.Size = 4;
                        break;
                    case CacheObjectType.Double:
                        c.Value = rdr.ReadDouble();
                        c.Size = 8;
                        break;
                    case CacheObjectType.Decimal:
                        c.Value = rdr.ReadDecimal();
                        c.Size = 16;
                        break;
                    case CacheObjectType.Data:
                        c.Size = rdr.ReadUInt32();
                        c.Value = rdr.ReadBytes((int)c.Size);
                        break;
                    default:
                        throw new Exception("Unknown cache object type!");
                }
                #endregion

                uint strSize = rdr.ReadUInt32();
                byte[] buf2 = rdr.ReadBytes((int)strSize);
                c.Name = Encoding.GetString(buf2);
                if (objects.ContainsKey(c.Name))
                {
                    ErrorManager.Warning(91, Processor.file, c.Name);
                    objects[c.Name] = c;
                }
                else
                {
                    objects.Add(c.Name, c);
                }
            }
        }
 private bool SettingsCached(int queryDirectionsId, CacheObject cacheObjectType, out object cacheValue)
 {
     int? queryDirectionsIdCached = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.SettingsQueryDirectionsId, queryDirectionsId)] as int?;
     cacheValue = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(cacheObjectType, queryDirectionsId)];
     return queryDirectionsIdCached.HasValue && (cacheValue != null);
 }
 private bool SettingsCached(int multipleChoiceId, CacheObject cacheObjectType, out object cacheValue)
 {
     int? multipleChoiceIdCached = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.SettingsMultipleChoiceOptionsId, multipleChoiceId)] as int?;
     cacheValue = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(cacheObjectType, multipleChoiceId)];
     return multipleChoiceIdCached.HasValue && (cacheValue != null);
 }
Пример #9
0
        protected override bool DoDownload()
        {
            var strImgURL = this.ImageLinkURL;

            if (this.EventTable.ContainsKey(strImgURL))
            {
                return(true);
            }

            var strIVPage = this.GetImageHostPage(ref strImgURL);

            if (strIVPage.Length < 10)
            {
                return(false);
            }

            var strNewURL = strImgURL.Substring(0, strImgURL.IndexOf("/", 8) + 1);

            var iStartSRC = 0;
            var iEndSRC   = 0;

            iStartSRC = strIVPage.IndexOf("toggleResize();'><img src='");

            if (iStartSRC < 0)
            {
                return(false);
            }

            iStartSRC += 27;

            iEndSRC = strIVPage.IndexOf("' id='mainImage'", iStartSRC);

            if (iEndSRC < 0)
            {
                return(false);
            }

            strNewURL = "http://suprfile.com/" + strIVPage.Substring(iStartSRC, iEndSRC - iStartSRC);

            var strFilePath = strNewURL.Substring(strNewURL.LastIndexOf("/") + 1);

            try
            {
                if (!Directory.Exists(this.SavePath))
                {
                    Directory.CreateDirectory(this.SavePath);
                }
            }
            catch (IOException ex)
            {
                // MainForm.DeleteMessage = ex.Message;
                // MainForm.Delete = true;
                return(false);
            }

            strFilePath = Path.Combine(this.SavePath, Utility.RemoveIllegalCharecters(strFilePath));

            var CCObj = new CacheObject();

            CCObj.IsDownloaded = false;
            CCObj.FilePath     = strFilePath;
            CCObj.Url          = strImgURL;
            try
            {
                this.EventTable.Add(strImgURL, CCObj);
            }
            catch (ThreadAbortException)
            {
                return(true);
            }
            catch (Exception)
            {
                if (this.EventTable.ContainsKey(strImgURL))
                {
                    return(false);
                }
                else
                {
                    this.EventTable.Add(strImgURL, CCObj);
                }
            }

            //////////////////////////////////////////////////////////////////////////
            var NewAlteredPath = Utility.GetSuitableName(strFilePath);

            if (strFilePath != NewAlteredPath)
            {
                strFilePath = NewAlteredPath;
                ((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath;
            }

            try
            {
                var client = new WebClient();
                client.Headers.Add("Accept-Language: en-us,en;q=0.5");
                client.Headers.Add("Accept-Encoding: gzip,deflate");
                client.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7");
                client.Headers.Add("Referer: " + strImgURL);
                client.Headers.Add(
                    "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6");
                client.DownloadFile(strNewURL, strFilePath);
            }
            catch (ThreadAbortException)
            {
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(true);
            }
            catch (IOException ex)
            {
                // MainForm.DeleteMessage = ex.Message;
                // MainForm.Delete = true;
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(true);
            }
            catch (WebException)
            {
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(false);
            }

            ((CacheObject)this.EventTable[this.ImageLinkURL]).IsDownloaded = true;

            // CacheController.GetInstance().u_s_LastPic = ((CacheObject)eventTable[mstrURL]).FilePath;
            CacheController.Instance().LastPic =
                ((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath;

            return(true);
        }
Пример #10
0
        private void GetSettingsValue(int snoozeOptionsId, CacheObject cacheObjectType, out object cacheValue)
        {
            using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
            {
                using (NpgsqlCommand cmd = con.CreateCommand())
                {
                    cmd.CommandText = "SELECT * FROM \"SnoozeOptions\" WHERE id=:id";
                    cmd.Parameters.Add("id", snoozeOptionsId);

                    NpgsqlDataReader reader = PostgreSQLConn.ExecuteReader(cmd, Parent.CurrentUser);
                    reader.Read();

                    int?        sid           = DbValueConverter.Convert <int>(reader["id"]);
                    bool?       cardsEnabled  = DbValueConverter.Convert <bool>(reader["cards_enabled"]);
                    bool?       rightsEnabled = DbValueConverter.Convert <bool>(reader["rights_enabled"]);
                    bool?       timeEnabled   = DbValueConverter.Convert <bool>(reader["time_enabled"]);
                    int?        snoozeCards   = DbValueConverter.Convert <int>(reader["snooze_cards"]);
                    int?        snoozeHigh    = DbValueConverter.Convert <int>(reader["snooze_high"]);
                    int?        snoozeLow     = DbValueConverter.Convert <int>(reader["snooze_low"]);
                    ESnoozeMode?snoozeMode    = DbValueConverter.Convert <ESnoozeMode>(reader["snooze_mode"]);
                    int?        snoozeRights  = DbValueConverter.Convert <int>(reader["snooze_rights"]);
                    int?        snoozeTime    = DbValueConverter.Convert <int>(reader["snooze_time"]);

                    //cache values
                    DateTime expires = DateTime.Now.Add(Cache.DefaultSettingsValidationTime);
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeCardsEnabled, snoozeOptionsId, expires)]  = cardsEnabled;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeRightsEnabled, snoozeOptionsId, expires)] = rightsEnabled;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeTimeEnabled, snoozeOptionsId, expires)]   = timeEnabled;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeCards, snoozeOptionsId, expires)]         = snoozeCards;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeHigh, snoozeOptionsId, expires)]          = snoozeHigh;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeLow, snoozeOptionsId, expires)]           = snoozeLow;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeMode, snoozeOptionsId, expires)]          = snoozeMode;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeRights, snoozeOptionsId, expires)]        = snoozeRights;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeTime, snoozeOptionsId, expires)]          = snoozeTime;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeOptionsId, snoozeOptionsId, expires)]     = sid;

                    //set output value
                    switch (cacheObjectType)
                    {
                    case CacheObject.SettingsSnoozeCardsEnabled: cacheValue = cardsEnabled; break;

                    case CacheObject.SettingsSnoozeRightsEnabled: cacheValue = rightsEnabled; break;

                    case CacheObject.SettingsSnoozeTimeEnabled: cacheValue = timeEnabled; break;

                    case CacheObject.SettingsSnoozeCards: cacheValue = snoozeCards; break;

                    case CacheObject.SettingsSnoozeHigh: cacheValue = snoozeHigh; break;

                    case CacheObject.SettingsSnoozeLow: cacheValue = snoozeLow; break;

                    case CacheObject.SettingsSnoozeMode: cacheValue = snoozeMode; break;

                    case CacheObject.SettingsSnoozeRights: cacheValue = snoozeRights; break;

                    case CacheObject.SettingsSnoozeTime: cacheValue = snoozeTime; break;

                    case CacheObject.SettingsSnoozeOptionsId: cacheValue = sid; break;

                    default: cacheValue = null; break;
                    }
                }
            }
        }
Пример #11
0
 /// <summary>
 /// 更新对象,并将对象同步持久化的磁盘,同时更新索引
 /// </summary>
 /// <param name="obj"></param>
 /// <returns></returns>
 public static Result update(CacheObject obj)
 {
     return(MemoryDB.Update(obj));
 }
Пример #12
0
        /// <summary>
        /// Do the Download
        /// </summary>
        /// <returns>
        /// Returns if the Image was downloaded
        /// </returns>
        protected override bool DoDownload()
        {
            var imageURL = ImageLinkURL;
            var filePath = string.Empty;

            if (EventTable.ContainsKey(imageURL))
            {
                return(true);
            }

            try
            {
                if (!Directory.Exists(this.SavePath))
                {
                    Directory.CreateDirectory(this.SavePath);
                }
            }
            catch (IOException ex)
            {
                //MainForm.DeleteMessage = ex.Message;
                //MainForm.Delete = true;

                return(false);
            }

            var cacheObject = new CacheObject {
                IsDownloaded = false, FilePath = filePath, Url = imageURL
            };

            try
            {
                EventTable.Add(imageURL, cacheObject);
            }
            catch (ThreadAbortException)
            {
                return(true);
            }
            catch (Exception)
            {
                if (EventTable.ContainsKey(imageURL))
                {
                    return(false);
                }

                EventTable.Add(imageURL, cacheObject);
            }

            var page = GetImageHostPage(ref imageURL);

            if (page.Length < 10)
            {
                return(false);
            }

            string imageDownloadURL;

            var m = Regex.Match(page, @"<img class=\""pic\"" src=\""(?<inner>[^\""]*)\"".*?alt=\""(?<title>[^\""]*)\""", RegexOptions.Compiled);

            if (m.Success)
            {
                imageDownloadURL = m.Groups["inner"].Value;
                filePath         = m.Groups["title"].Value;
            }
            else
            {
                return(false);
            }

            filePath = Path.Combine(this.SavePath, Utility.RemoveIllegalCharecters(filePath));

            if (!Directory.Exists(this.SavePath))
            {
                Directory.CreateDirectory(this.SavePath);
            }

            //////////////////////////////////////////////////////////////////////////

            string newAlteredPath = Utility.GetSuitableName(filePath);

            if (filePath != newAlteredPath)
            {
                filePath = newAlteredPath;
                ((CacheObject)EventTable[this.ImageLinkURL]).FilePath = filePath;
            }

            try
            {
                var webClient = new WebClient();
                webClient.Headers.Add(string.Format("Referer: {0}", imageURL));
                webClient.DownloadFile(imageDownloadURL, filePath);
                webClient.Dispose();
            }
            catch (ThreadAbortException)
            {
                ((CacheObject)EventTable[imageURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(true);
            }
            catch (IOException ex)
            {
                //MainForm.DeleteMessage = ex.Message;
                //MainForm.Delete = true;

                ((CacheObject)EventTable[imageURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(true);
            }
            catch (WebException)
            {
                ((CacheObject)EventTable[imageURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(false);
            }

            ((CacheObject)EventTable[this.ImageLinkURL]).IsDownloaded = true;
            CacheController.Instance().LastPic = ((CacheObject)EventTable[this.ImageLinkURL]).FilePath = filePath;

            return(true);
        }
Пример #13
0
        /// <summary>
        /// Do the Download
        /// </summary>
        /// <returns>
        /// Return if Downloaded or not
        /// </returns>
        protected override bool DoDownload()
        {
            string strImgURL = ImageLinkURL;

            if (EventTable.ContainsKey(strImgURL))
            {
                return(true);
            }

            string strFilePath = string.Empty;

            try
            {
                if (!Directory.Exists(SavePath))
                {
                    Directory.CreateDirectory(SavePath);
                }
            }
            catch (IOException ex)
            {
                //MainForm.DeleteMessage = ex.Message;
                //MainForm.Delete = true;

                return(false);
            }

            CacheObject ccObj = new CacheObject {
                IsDownloaded = false, FilePath = strFilePath, Url = strImgURL
            };

            try
            {
                EventTable.Add(strImgURL, ccObj);
            }
            catch (ThreadAbortException)
            {
                return(true);
            }
            catch (Exception)
            {
                if (EventTable.ContainsKey(strImgURL))
                {
                    return(false);
                }

                EventTable.Add(strImgURL, ccObj);
            }

            const string StartSrc = "<script type=\"text/javascript\" src=\"imgiga/showimg";

            string sPage = GetImageHostPage(ref strImgURL);

            if (sPage.Length < 10)
            {
                return(false);
            }

            int iStartSrc = sPage.IndexOf(StartSrc);

            if (iStartSrc < 0)
            {
                return(false);
            }

            iStartSrc += StartSrc.Length;

            int iEndSrc = sPage.IndexOf("\"", iStartSrc);

            if (iEndSrc < 0)
            {
                return(false);
            }

            string sScriptUrl = strImgURL;

            sScriptUrl = sScriptUrl.Remove(sScriptUrl.IndexOf(@"img.php"));

            sScriptUrl += string.Format("imgiga/showimg{0}", sPage.Substring(iStartSrc, iEndSrc - iStartSrc));

            string sPage2 = GetImageHostPage(ref sScriptUrl);

            const string StartSrc2 = "href=\"";

            int iStartSrc2 = sPage2.IndexOf(StartSrc2);

            if (iStartSrc2 < 0)
            {
                return(false);
            }

            iStartSrc2 += StartSrc2.Length;

            int iEndSrc2 = sPage2.IndexOf("\"", iStartSrc2);

            string strNewURL = sPage2.Substring(iStartSrc2, iEndSrc2 - iStartSrc2);

            strFilePath = strNewURL;

            if (strFilePath.Contains(".jpg"))
            {
                strFilePath = strFilePath.Remove(strFilePath.IndexOf(".jpg") + 4);
            }
            else if (strFilePath.Contains(".jpeg"))
            {
                strFilePath = strFilePath.Remove(strFilePath.IndexOf(".jpeg") + 5);
            }

            strFilePath = strFilePath.Substring(strFilePath.LastIndexOf("/") + 1);

            strFilePath = Path.Combine(SavePath, Utility.RemoveIllegalCharecters(strFilePath));

            //////////////////////////////////////////////////////////////////////////

            string newAlteredPath = Utility.GetSuitableName(strFilePath);

            if (strFilePath != newAlteredPath)
            {
                strFilePath = newAlteredPath;
                ((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath;
            }

            strFilePath = Utility.CheckPathLength(strFilePath);
            ((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath;

            try
            {
                WebClient client = new WebClient();
                client.Headers.Add("Referer: " + strImgURL);
                client.Headers.Add("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6");
                client.DownloadFile(strNewURL, strFilePath);
                client.Dispose();
            }
            catch (ThreadAbortException)
            {
                ((CacheObject)EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL);

                return(true);
            }
            catch (IOException ex)
            {
                //MainForm.DeleteMessage = ex.Message;
                //MainForm.Delete = true;

                ((CacheObject)EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL);

                return(true);
            }
            catch (WebException)
            {
                ((CacheObject)EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL);

                return(false);
            }

            ((CacheObject)EventTable[ImageLinkURL]).IsDownloaded = true;
            CacheController.Instance().LastPic = ((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath;

            return(true);
        }
Пример #14
0
 public static void SetValue(string name, decimal value)
 {
     if (objects.ContainsKey(name))
     {
         objects[name] = new CacheObject(name, CacheObjectType.Decimal, value);
     }
     else
     {
         objects.Add(name, new CacheObject(name, CacheObjectType.Decimal, value));
     }
 }
Пример #15
0
 public static void SetValue(string name, ushort value)
 {
     if (objects.ContainsKey(name))
     {
         objects[name] = new CacheObject(name, CacheObjectType.UShort, value);
     }
     else
     {
         objects.Add(name, new CacheObject(name, CacheObjectType.UShort, value));
     }
 }
Пример #16
0
        /// <summary>
        /// Do the Download
        /// </summary>
        /// <returns>
        /// Returns if the Image was downloaded
        /// </returns>
        protected override bool DoDownload()
        {
            var strImgURL = this.ImageLinkURL;

            if (this.EventTable.ContainsKey(strImgURL))
            {
                return(true);
            }

            var strFilePath = string.Empty;

            try
            {
                if (!Directory.Exists(this.SavePath))
                {
                    Directory.CreateDirectory(this.SavePath);
                }
            }
            catch (IOException ex)
            {
                // MainForm.DeleteMessage = ex.Message;
                // MainForm.Delete = true;
                return(false);
            }

            var ccObj = new CacheObject
            {
                IsDownloaded = false,
                FilePath     = strFilePath,
                Url          = strImgURL
            };

            try
            {
                this.EventTable.Add(strImgURL, ccObj);
            }
            catch (ThreadAbortException)
            {
                return(true);
            }
            catch (Exception)
            {
                if (this.EventTable.ContainsKey(strImgURL))
                {
                    return(false);
                }

                this.EventTable.Add(strImgURL, ccObj);
            }

            var sLargeUrl = $"{strImgURL}&pjk=l".Replace("view/?id", "view/index.php?id");

            var sPage = this.GetImageHostsPage(ref sLargeUrl, strImgURL);

            if (sPage.Length < 10)
            {
                return(false);
            }

            string strNewURL;

            var m = Regex.Match(sPage, @"src=\""(?<inner>[^\""]*)\"" id=img1", RegexOptions.Singleline);

            if (m.Success)
            {
                strNewURL = m.Groups["inner"].Value;
            }
            else
            {
                return(false);
            }

            strFilePath = strNewURL.Substring(strNewURL.LastIndexOf("/") + 1);

            strFilePath = Path.Combine(this.SavePath, Utility.RemoveIllegalCharecters(strFilePath));

            //////////////////////////////////////////////////////////////////////////
            try
            {
                var sNewAlteredPath = Utility.GetSuitableName(strFilePath);
                if (strFilePath != sNewAlteredPath)
                {
                    strFilePath = sNewAlteredPath;
                    ((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath;
                }

                var client = new WebClient();
                client.Headers.Add($"Referer: {sLargeUrl}");
                client.Headers.Add("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6");
                client.DownloadFile(strNewURL, strFilePath);

                client.Dispose();
            }
            catch (ThreadAbortException)
            {
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(true);
            }
            catch (IOException ex)
            {
                // MainForm.DeleteMessage = ex.Message;
                // MainForm.Delete = true;
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(true);
            }
            catch (WebException)
            {
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(false);
            }

            ((CacheObject)this.EventTable[this.ImageLinkURL]).IsDownloaded = true;
            CacheController.Instance().LastPic = ((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath;

            return(true);
        }
        private void GetSettingsValue(int synonymsGradingId, CacheObject cacheObjectType, out object cacheValue)
        {
            using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
            {
                using (NpgsqlCommand cmd = con.CreateCommand())
                {
                    cmd.CommandText = "SELECT * FROM \"SynonymGradings\" WHERE id=:id";
                    cmd.Parameters.Add("id", synonymsGradingId);

                    NpgsqlDataReader reader = PostgreSQLConn.ExecuteReader(cmd, Parent.CurrentUser);
                    reader.Read();

                    int? sid = DbValueConverter.Convert<int>(reader["id"]);
                    bool? allKnown = DbValueConverter.Convert<bool>(reader["all_known"]);
                    bool? halfKnown = DbValueConverter.Convert<bool>(reader["half_known"]);
                    bool? oneKnown = DbValueConverter.Convert<bool>(reader["one_known"]);
                    bool? firstKnown = DbValueConverter.Convert<bool>(reader["first_known"]);
                    bool? prompt = DbValueConverter.Convert<bool>(reader["prompt"]);

                    //cache values
                    DateTime expires = DateTime.Now.Add(Cache.DefaultSettingsValidationTime);
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSynonymGradingsAllKnown, synonymsGradingId, expires)] = allKnown;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSynonymGradingsHalfKnown, synonymsGradingId, expires)] = halfKnown;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSynonymGradingsOneKnown, synonymsGradingId, expires)] = oneKnown;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSynonymGradingsFirstKnown, synonymsGradingId, expires)] = firstKnown;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSynonymGradingsPrompt, synonymsGradingId, expires)] = prompt;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSynonymGradingsId, synonymsGradingId, expires)] = sid;

                    //set output value
                    switch (cacheObjectType)
                    {
                        case CacheObject.SettingsSynonymGradingsAllKnown: cacheValue = allKnown; break;
                        case CacheObject.SettingsSynonymGradingsHalfKnown: cacheValue = halfKnown; break;
                        case CacheObject.SettingsSynonymGradingsOneKnown: cacheValue = oneKnown; break;
                        case CacheObject.SettingsSynonymGradingsFirstKnown: cacheValue = firstKnown; break;
                        case CacheObject.SettingsSynonymGradingsPrompt: cacheValue = prompt; break;
                        case CacheObject.SettingsSynonymGradingsId: cacheValue = sid; break;
                        default: cacheValue = null; break;
                    }
                }
            }
        }
        /// <summary>
        /// Gets the settings value.
        /// </summary>
        /// <param name="snoozeOptionsId">The snooze options id.</param>
        /// <param name="cacheObjectType">Type of the cache object.</param>
        /// <param name="cacheValue">The cache value.</param>
        /// <remarks>Documented by Dev08, 2009-01-13</remarks>
        private void GetSettingsValue(int snoozeOptionsId, CacheObject cacheObjectType, out object cacheValue)
        {
            SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser);
            cmd.CommandText = "SELECT * FROM \"SnoozeOptions\" WHERE id=@id";
            cmd.Parameters.Add("@id", snoozeOptionsId);

            SqlCeDataReader reader = MSSQLCEConn.ExecuteReader(cmd);
            reader.Read();

            int? sid = DbValueConverter.Convert<int>(reader["id"]);
            bool? cardsEnabled = DbValueConverter.Convert<bool>(reader["cards_enabled"]);
            bool? rightsEnabled = DbValueConverter.Convert<bool>(reader["rights_enabled"]);
            bool? timeEnabled = DbValueConverter.Convert<bool>(reader["time_enabled"]);
            int? snoozeCards = DbValueConverter.Convert<int>(reader["snooze_cards"]);
            int? snoozeHigh = DbValueConverter.Convert<int>(reader["snooze_high"]);
            int? snoozeLow = DbValueConverter.Convert<int>(reader["snooze_low"]);
            ESnoozeMode? snoozeMode = DbValueConverter.Convert<ESnoozeMode>(reader["snooze_mode"]);
            int? snoozeRights = DbValueConverter.Convert<int>(reader["snooze_rights"]);
            int? snoozeTime = DbValueConverter.Convert<int>(reader["snooze_time"]);
            reader.Close();

            //cache values
            DateTime expires = DateTime.Now.Add(Cache.DefaultSettingsValidationTime);
            Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeCardsEnabled, snoozeOptionsId, expires)] = cardsEnabled;
            Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeRightsEnabled, snoozeOptionsId, expires)] = rightsEnabled;
            Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeTimeEnabled, snoozeOptionsId, expires)] = timeEnabled;
            Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeCards, snoozeOptionsId, expires)] = snoozeCards;
            Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeHigh, snoozeOptionsId, expires)] = snoozeHigh;
            Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeLow, snoozeOptionsId, expires)] = snoozeLow;
            Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeMode, snoozeOptionsId, expires)] = snoozeMode;
            Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeRights, snoozeOptionsId, expires)] = snoozeRights;
            Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeTime, snoozeOptionsId, expires)] = snoozeTime;
            Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeOptionsId, snoozeOptionsId, expires)] = sid;

            //set output value
            switch (cacheObjectType)
            {
                case CacheObject.SettingsSnoozeCardsEnabled: cacheValue = cardsEnabled; break;
                case CacheObject.SettingsSnoozeRightsEnabled: cacheValue = rightsEnabled; break;
                case CacheObject.SettingsSnoozeTimeEnabled: cacheValue = timeEnabled; break;
                case CacheObject.SettingsSnoozeCards: cacheValue = snoozeCards; break;
                case CacheObject.SettingsSnoozeHigh: cacheValue = snoozeHigh; break;
                case CacheObject.SettingsSnoozeLow: cacheValue = snoozeLow; break;
                case CacheObject.SettingsSnoozeMode: cacheValue = snoozeMode; break;
                case CacheObject.SettingsSnoozeRights: cacheValue = snoozeRights; break;
                case CacheObject.SettingsSnoozeTime: cacheValue = snoozeTime; break;
                case CacheObject.SettingsSnoozeOptionsId: cacheValue = sid; break;
                default: cacheValue = null; break;
            }
        }
Пример #19
0
 /// <summary>
 /// 插入数据,并对所有属性做索引,速度较慢。新插入的数据会被同步持久化到磁盘。
 /// </summary>
 public static void insert(CacheObject obj)
 {
     MemoryDB.Insert(obj);
 }
 /// <summary>
 /// Settingses the cached.
 /// </summary>
 /// <param name="snoozeOptionsId">The snooze options id.</param>
 /// <param name="cacheObjectType">Type of the cache object.</param>
 /// <param name="cacheValue">The cache value.</param>
 /// <returns></returns>
 /// <remarks>Documented by Dev08, 2009-01-13</remarks>
 private bool SettingsCached(int snoozeOptionsId, CacheObject cacheObjectType, out object cacheValue)
 {
     int? snoozeOptionsIdCached = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.SettingsSnoozeOptionsId, snoozeOptionsId)] as int?;
     cacheValue = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(cacheObjectType, snoozeOptionsId)];
     //return snoozeOptionsIdCached.HasValue && (cacheValue != null);
     return snoozeOptionsIdCached.HasValue;
 }
Пример #21
0
 /// <summary>
 /// 从内存中删除数据,并同步磁盘中内容。
 /// </summary>
 /// <param name="obj"></param>
 public static void delete(CacheObject obj)
 {
     MemoryDB.Delete(obj);
 }
Пример #22
0
        /// <summary>
        /// Do the Download
        /// </summary>
        /// <returns>
        /// Return if Downloaded or not
        /// </returns>
        protected override bool DoDownload()
        {
            string strImgURL = ImageLinkURL;

            if (EventTable.ContainsKey(strImgURL))
            {
                return(true);
            }

            try
            {
                if (!Directory.Exists(SavePath))
                {
                    Directory.CreateDirectory(SavePath);
                }
            }
            catch (IOException ex)
            {
                //MainForm.DeleteMessage = ex.Message;
                //MainForm.Delete = true;

                return(false);
            }

            string filePath = string.Empty;

            CacheObject cCObj = new CacheObject {
                IsDownloaded = false, FilePath = filePath, Url = strImgURL
            };

            try
            {
                EventTable.Add(strImgURL, cCObj);
            }
            catch (ThreadAbortException)
            {
                return(true);
            }
            catch (Exception)
            {
                if (EventTable.ContainsKey(strImgURL))
                {
                    return(false);
                }

                this.EventTable.Add(strImgURL, cCObj);
            }

            string newURL;

            var m = Regex.Match(strImgURL, @"img=(?<img>[^&]*)&y=(?<year>[0-9]*)&m=(?<month>[0-9]*)&t=(?<type>[^&]*)&rand=(?<rand>([0-9]*))", RegexOptions.Singleline);

            if (m.Success)
            {
                var img = m.Groups["img"].Value.Remove(m.Groups["img"].Value.Length - 1);
                filePath = string.Format(
                    "{0}{1}L.{2}", img, m.Groups["rand"].Value, m.Groups["type"].Value);

                if (strImgURL.Contains("&srv="))
                {
                    newURL = string.Format(
                        "http://{5}.glowfoto.com/images/{0}/{1}/{2}{3}L.{4}",
                        m.Groups["year"].Value,
                        m.Groups["month"].Value,
                        img,
                        m.Groups["rand"].Value,
                        m.Groups["type"].Value,
                        strImgURL.Substring(strImgURL.IndexOf("&srv=") + 5));
                }
                else
                {
                    newURL = string.Format(
                        "http://www.glowfoto.com/images/{0}/{1}/{2}{3}L.{4}",
                        m.Groups["year"].Value,
                        m.Groups["month"].Value,
                        img,
                        m.Groups["rand"].Value,
                        m.Groups["type"].Value);
                }
            }
            else
            {
                return(false);
            }

            filePath = Path.Combine(SavePath, Utility.RemoveIllegalCharecters(filePath));

            //////////////////////////////////////////////////////////////////////////
            string newAlteredPath = Utility.GetSuitableName(filePath);

            if (filePath != newAlteredPath)
            {
                filePath = newAlteredPath;
                ((CacheObject)EventTable[ImageLinkURL]).FilePath = filePath;
            }

            try
            {
                WebClient client = new WebClient();
                client.Headers.Add(string.Format("Referer: {0}", strImgURL));
                client.Headers.Add(
                    "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6");
                client.DownloadFile(newURL, filePath);
                client.Dispose();
            }
            catch (ThreadAbortException)
            {
                ((CacheObject)EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL);

                return(true);
            }
            catch (IOException ex)
            {
                //MainForm.DeleteMessage = ex.Message;
                //MainForm.Delete = true;

                ((CacheObject)EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL);

                return(true);
            }
            catch (WebException)
            {
                ((CacheObject)EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL);

                return(false);
            }

            ((CacheObject)EventTable[ImageLinkURL]).IsDownloaded = true;
            CacheController.Instance().LastPic = ((CacheObject)EventTable[ImageLinkURL]).FilePath = filePath;

            return(true);
        }
Пример #23
0
        /// <summary>
        /// Do the Download
        /// </summary>
        /// <returns>
        /// Return if Downloaded or not
        /// </returns>
        protected override bool DoDownload()
        {
            var strImgURL = this.ImageLinkURL;

            if (this.EventTable.ContainsKey(strImgURL))
            {
                return(true);
            }

            var strFilePath = string.Empty;

            try
            {
                if (!Directory.Exists(this.SavePath))
                {
                    Directory.CreateDirectory(this.SavePath);
                }
            }
            catch (IOException ex)
            {
                // MainForm.DeleteMessage = ex.Message;
                // MainForm.Delete = true;
                return(false);
            }

            var ccObj = new CacheObject {
                IsDownloaded = false, FilePath = strFilePath, Url = strImgURL
            };

            try
            {
                this.EventTable.Add(strImgURL, ccObj);
            }
            catch (ThreadAbortException)
            {
                return(true);
            }
            catch (Exception)
            {
                if (this.EventTable.ContainsKey(strImgURL))
                {
                    return(false);
                }

                this.EventTable.Add(strImgURL, ccObj);
            }

            var cookieValue = this.GetCookieValue(strImgURL, @"writeCookie\('ads_pixhub', '(?<inner>[^']*)', '1'\)");

            if (string.IsNullOrEmpty(cookieValue))
            {
                return(false);
            }

            var sPage = this.GetImageHostPage(ref strImgURL, $"ads_pixhub={cookieValue};");

            if (sPage.Length < 10)
            {
                return(false);
            }

            string strNewURL;

            var match = Regex.Match(
                sPage,
                @"<div class=\""image-show resize\"">\s+.+?<img.+?src=\""(?<inner>[^\""]*)\"" alt=\""(?<filename>[^\""]*)\""",
                RegexOptions.Multiline);

            if (match.Success)
            {
                strNewURL = match.Groups["inner"].Value;

                if (strNewURL.Contains("thumbnail"))
                {
                    strNewURL = strNewURL.Replace("thumbnail/", string.Empty);
                }

                strFilePath = match.Groups["filename"].Value;
            }
            else
            {
                return(false);
            }

            strFilePath = Path.Combine(this.SavePath, Utility.RemoveIllegalCharecters(strFilePath));

            //////////////////////////////////////////////////////////////////////////
            var newAlteredPath = Utility.GetSuitableName(strFilePath);

            if (strFilePath != newAlteredPath)
            {
                strFilePath = newAlteredPath;
                ((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath;
            }

            try
            {
                var client = new WebClient();
                client.Headers.Add($"Referer: {strImgURL}");
                client.Headers.Add("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6");
                client.DownloadFile(strNewURL, strFilePath);
                client.Dispose();
            }
            catch (ThreadAbortException)
            {
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(true);
            }
            catch (IOException ex)
            {
                // MainForm.DeleteMessage = ex.Message;
                // MainForm.Delete = true;
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(true);
            }
            catch (WebException)
            {
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(false);
            }

            ((CacheObject)this.EventTable[this.ImageLinkURL]).IsDownloaded = true;
            CacheController.Instance().LastPic = ((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath;

            return(true);
        }
Пример #24
0
        public override void Initialize()
        {
            base.Test = (ref CacheObject obj) =>
            {
                if (obj == null)
                {
                    // See if we should wait for milliseconds for possible loot drops before continuing run
                    if (DateTime.Now.Subtract(Bot.Targeting.Cache.lastHadUnitInSights).TotalMilliseconds <= Bot.Settings.AfterCombatDelay && DateTime.Now.Subtract(Bot.Targeting.Cache.lastHadEliteUnitInSights).TotalMilliseconds <= 10000 ||
                        //Cut the delay time in half for non-elite monsters!
                        DateTime.Now.Subtract(Bot.Targeting.Cache.lastHadUnitInSights).TotalMilliseconds <= Bot.Settings.AfterCombatDelay)
                    {
                        obj = new CacheObject(Bot.Character.Data.Position, TargetType.NoMovement, 20000, "WaitForLootDrops", 2f, -1);
                        return(true);
                    }
                    //Herbfunks wait after loot containers are opened. 3s for rare chests, half the settings delay for everything else.
                    if ((DateTime.Now.Subtract(Bot.Targeting.Cache.lastHadRareChestAsTarget).TotalMilliseconds <= 3750) ||
                        (DateTime.Now.Subtract(Bot.Targeting.Cache.lastHadContainerAsTarget).TotalMilliseconds <= (Bot.Settings.AfterCombatDelay * 1.25)) ||
                        (DateTime.Now.Subtract(Bot.Targeting.Cache.lastSeenCursedShrine).TotalMilliseconds <= (1000)))
                    {
                        obj = new CacheObject(Bot.Character.Data.Position, TargetType.NoMovement, 20000, "ContainerLootDropsWait", 2f, -1);
                        return(true);
                    }
                    if (DateTime.Now.Subtract(Bot.Targeting.Cache.lastSeenCursedShrine).TotalMilliseconds <= (1000))
                    {
                        Bot.Targeting.Cache.UpdateQuestMonsterProperty = true;
                        obj = new CacheObject(Bot.Character.Data.Position, TargetType.NoMovement, 20000, "CursedShrineWait", 2f, -1);
                        return(true);
                    }
                    else
                    {
                        Bot.Targeting.Cache.UpdateQuestMonsterProperty = false;
                    }

                    // Finally, a special check for waiting for wrath of the berserker cooldown before engaging Azmodan
                    if (Bot.Character.Class.HotBar.HotbarPowers.Contains(SNOPower.Barbarian_WrathOfTheBerserker) && Bot.Settings.Class.bWaitForWrath && !Bot.Character.Class.Abilities[SNOPower.Barbarian_WrathOfTheBerserker].AbilityUseTimer() &&
                        Bot.Character.Data.iCurrentWorldID == 121214 &&
                        (Vector3.Distance(Bot.Character.Data.Position, new Vector3(711.25f, 716.25f, 80.13903f)) <= 40f || Vector3.Distance(Bot.Character.Data.Position, new Vector3(546.8467f, 551.7733f, 1.576313f)) <= 40f))
                    {
                        Logger.DBLog.InfoFormat("[Funky] Waiting for Wrath Of The Berserker cooldown before continuing to Azmodan.");
                        obj = new CacheObject(Bot.Character.Data.Position, TargetType.NoMovement, 20000, "GilesWaitForWrath", 0f, -1);
                        InactivityDetector.Reset();
                        return(true);
                    }
                    // And a special check for wizard archon
                    if (Bot.Character.Class.HotBar.HotbarPowers.Contains(SNOPower.Wizard_Archon) && !Bot.Character.Class.Abilities[SNOPower.Wizard_Archon].AbilityUseTimer() && Bot.Settings.Class.bWaitForArchon && ZetaDia.CurrentWorldId == 121214 &&
                        (Vector3.Distance(Bot.Character.Data.Position, new Vector3(711.25f, 716.25f, 80.13903f)) <= 40f || Vector3.Distance(Bot.Character.Data.Position, new Vector3(546.8467f, 551.7733f, 1.576313f)) <= 40f))
                    {
                        Logger.DBLog.InfoFormat("[Funky] Waiting for Wizard Archon cooldown before continuing to Azmodan.");
                        obj = new CacheObject(Bot.Character.Data.Position, TargetType.NoMovement, 20000, "GilesWaitForArchon", 0f, -1);
                        InactivityDetector.Reset();
                        return(true);
                    }
                    // And a very sexy special check for WD BigBadVoodoo
                    if (Bot.Character.Class.HotBar.HotbarPowers.Contains(SNOPower.Witchdoctor_BigBadVoodoo) && !PowerManager.CanCast(SNOPower.Witchdoctor_BigBadVoodoo) && ZetaDia.CurrentWorldId == 121214 &&
                        (Vector3.Distance(Bot.Character.Data.Position, new Vector3(711.25f, 716.25f, 80.13903f)) <= 40f || Vector3.Distance(Bot.Character.Data.Position, new Vector3(546.8467f, 551.7733f, 1.576313f)) <= 40f))
                    {
                        Logger.DBLog.InfoFormat("[Funky] Waiting for WD BigBadVoodoo cooldown before continuing to Azmodan.");
                        obj = new CacheObject(Bot.Character.Data.Position, TargetType.NoMovement, 20000, "GilesWaitForVoodooo", 0f, -1);
                        InactivityDetector.Reset();
                        return(true);
                    }

                    //Currently preforming an interactive profile behavior (check if in town and not vendoring)
                    if (Bot.Game.Profile.PreformingInteractiveBehavior && (!Bot.Character.Data.bIsInTown || !BrainBehavior.IsVendoring))
                    {
                        if (Bot.Game.Profile.InteractableCachedObject.Position.Distance(Bot.Character.Data.Position) > 50f)
                        {
                            if (Bot.Targeting.Cache.LastCachedTarget.Position != Bot.Game.Profile.InteractableCachedObject.Position)
                            {
                                Navigator.Clear();
                            }

                            //Generate the path here so we can start moving..
                            Navigation.NP.MoveTo(Bot.Game.Profile.InteractableCachedObject.Position, "ReturnToOOCLoc", true);

                            //Setup a temp target that the handler will use
                            obj = new CacheObject(Bot.Game.Profile.InteractableCachedObject.Position, TargetType.LineOfSight, 1d, "ReturnToOOCLoc", 10f, Bot.Game.Profile.InteractableCachedObject.RAGUID);
                            return(true);
                        }
                    }

                    //Check if we engaged in combat..
                    bool  EngagedInCombat   = false;
                    float distanceFromStart = 0f;
                    if (Bot.Targeting.Cache.LastCachedTarget != ObjectCache.FakeCacheObject && !Bot.Targeting.Cache.Backtracking && Bot.Targeting.Cache.StartingLocation != Vector3.Zero)
                    {
                        EngagedInCombat   = true;
                        distanceFromStart = Bot.Character.Data.Position.Distance(Bot.Targeting.Cache.StartingLocation);
                        //lets see how far we are from our starting location.
                        if (distanceFromStart > 20f &&
                            !Navigation.CanRayCast(Bot.Character.Data.Position, Funky.PlayerMover.vLastMoveTo, UseSearchGridProvider: true))
                        {
                            Logger.Write(LogLevel.Movement, "Updating Navigator in Target Refresh");

                            SkipAheadCache.ClearCache();
                            Navigator.Clear();
                            //Navigator.MoveTo(Funky.PlayerMover.vLastMoveTo, "original destination", true);
                        }
                    }

                    //Check if our current path intersects avoidances. (When not in town, and not currently inside avoidance)
                    if (!Bot.Character.Data.bIsInTown && (Bot.Settings.Avoidance.AttemptAvoidanceMovements || Bot.Character.Data.CriticalAvoidance) &&
                        Navigation.NP.CurrentPath.Count > 0 &&
                        Bot.Targeting.Cache.Environment.TriggeringAvoidances.Count == 0)
                    {
                        if (ObjectCache.Obstacles.TestVectorAgainstAvoidanceZones(Bot.Character.Data.Position, Navigation.NP.CurrentPath.Current))
                        {
                            obj = new CacheObject(Bot.Character.Data.Position, TargetType.NoMovement, 20000, "AvoidanceIntersection", 2.5f, -1);
                            return(true);
                        }
                    }

                    //Backtracking Check..
                    if (EngagedInCombat && Bot.Settings.Backtracking.EnableBacktracking && distanceFromStart >= Bot.Settings.Backtracking.MinimumDistanceFromStart)
                    {
                        Bot.Targeting.Cache.Backtracking = true;
                        obj = new CacheObject(Bot.Targeting.Cache.StartingLocation, TargetType.Backtrack, 20000, "Backtracking", 2.5f);
                        return(true);
                    }
                }

                return(obj != null);
            };
        }
Пример #25
0
        public void ProcessRequest(HttpContext context)
        {
            Timingutil.init();

            HttpResponse resp = context.Response;
            HttpRequest req = context.Request;
            HttpSessionState session = context.Session;

            /*
            {
            int loop1, loop2;
            NameValueCollection coll;

            coll=req.Params;//ServerVariables;
            String[] arr1 = coll.AllKeys;
            for (loop1 = 0; loop1 < arr1.Length; loop1++)
            {
               Console.Error.WriteLine("Key: " + arr1[loop1] + "<br>");
              String[] arr2=coll.GetValues(arr1[loop1]);
             for (loop2 = 0; loop2 < arr2.Length; loop2++) {
                   Console.Error.WriteLine("Value " + loop2 + ": " + arr2[loop2] + "<br>");
              }
              }
            }
            */

            string rootpath = Path.GetFullPath(req.PhysicalApplicationPath);
            string basepath = Path.GetFullPath(Directory.GetParent(req.PhysicalPath).ToString());

            Timingutil.start("getXsltParameters");
            // eleminate this ".." try to find the docroot
            Hashtable xsltParameters = Xsltparameters.getXsltParameters(req.PhysicalApplicationPath+"/bin/xsltparameters.xslt",rootpath+"/xsltParameters.xml",req.ServerVariables["HTTP_HOST"]);
            Timingutil.stop();

            resp.ContentType = "text/html";

            string filename = Path.GetFullPath(basepath+"/"+Path.GetFileName(req.PhysicalPath).ToString());

            DateTime filemtime = File.GetLastWriteTime(filename);

            //Console.Error.WriteLine("basepath:"+basepath);
            //Console.Error.WriteLine("filename:"+filename);

            XmlDocument inputDoc;

            try
            {
                object loObject;

                lock(codefileCacheLock)
                {
                    try
                    {
                        Timingutil.start("getPageObject");
                        if (codefileCache.Contains(filename))
                        {
                            if(((CacheObject)codefileCache[filename]).mtime != filemtime)
                            {
                                codefileCache.Remove(filename);
                                CacheFile(filename,req);
                            }
                        }
                        else
                        {
                            CacheFile(filename,req);
                        }
                        loObject = ((CacheObject)codefileCache[filename]).content;
                    }
                    catch(CompileException e)
                    {
                        throw;
                    }
                    finally
                    {
                        Timingutil.stop();
                    }
                }

                object[] loCodeParms = new object[3];
                loCodeParms[0] = req;
                loCodeParms[1] = session;
                loCodeParms[2] = xsltParameters;

                object loResult;
            //		try
            //		{
                    Timingutil.start("executePage");
                    loResult = loObject.GetType().InvokeMember("Query",BindingFlags.InvokeMethod,null,loObject,loCodeParms);
            //		}
            //		catch (Exception e)
            //		{
            //			throw;
            //		}
            //		finally
            //		{
                    Timingutil.stop();
            //		}

                if(loResult.GetType().ToString() == "System.String")
                {
                    resp.ContentType = "application/vnd.ms-excel";
            //					resp.ContentType = "text/plain";
                    resp.Write((string)loResult);
                    return;
                }
                if(loResult.GetType().ToString() == "System.Byte[]")
                {
                    resp.ContentType = "image/png";
                    resp.BinaryWrite((byte[])loResult);
                    resp.Flush();
                    return;
                }
                else
                {
                    inputDoc = (XmlDocument)loResult;
                }

            }
            catch(CompileException e)
            {
                Console.Error.WriteLine("compile Exception:"+e.s);
                inputDoc = Commonutil.GetErrorDocument(e.s);
            }
            catch(Exception e)
            {
                //Console.Error.WriteLine("Runtime Exception:"+e.ToString());
                inputDoc = Commonutil.GetErrorDocument("Runtime Exception:"+e.ToString());
            }

            string redirectContent="";
            if (inputDoc.HasChildNodes)
            {
                for (int i=0; i<inputDoc.ChildNodes.Count; i++)
                {
                    if (inputDoc.ChildNodes[i].NodeType == XmlNodeType.ProcessingInstruction)
                    {
                        if ( "http-redirect" == ((XmlProcessingInstruction)inputDoc.ChildNodes[i]).Target)
                        {
                            redirectContent = ((XmlProcessingInstruction)inputDoc.ChildNodes[i]).Data;
                        }
                    }
                }
            }

            if (redirectContent != "")
            {
                Timingutil.stop();
                resp.Redirect(redirectContent,false);
                // if reguest logging is activated log redirect here
            }
            else
            {

                Timingutil.start("transform");

                XsltUtilReturnObject result = null;
                try
                {
                    result = Xsltutil.doTransform(inputDoc,xsltParameters,basepath,rootpath);
                }
                catch(XsltutilException e)
                {
                    //Console.Error.WriteLine("xsltutil Exception:"+e.s);
                    inputDoc = Commonutil.GetErrorDocument(e.s);

                    try
                    {
                        result = Xsltutil.doTransform(inputDoc,xsltParameters,basepath,rootpath);
                    }
                    catch(XsltutilException e2)
                    {
                        throw;
                    }
                }
                if(result == null)
                {
                    //Console.Error.WriteLine("result Doc is Null");
                    inputDoc = Commonutil.GetErrorDocument("result Doc is Null");
                    result = Xsltutil.doTransform(inputDoc,xsltParameters,basepath,rootpath);
                }

                XmlDocument resultDoc = result.document;

                Timingutil.stop();

                Timingutil.start("output");

                string docType = "text/html" ; // the default;

                {
                    Timingutil.start("regex_1");

                    XmlNode piNode = (XmlProcessingInstruction)resultDoc.SelectSingleNode("/processing-instruction(\"output-format\")");

                    if (piNode != null)
                    {
                        string pi = piNode.Value;
                        Regex regex = new Regex("type=\"(?'g1'[^\"]*)\"");
                        foreach(Match match in regex.Matches(pi) )
                        {
                            docType=match.Groups["g1"].Captures[0].Value;
                        }
                        ((XmlNode)resultDoc).RemoveChild(piNode);
                        Timingutil.info("doctype "+docType);
                    }else{
                        Timingutil.info("default doctype (text/html)");
                    }
                    Timingutil.stop();
                }

                resp.ContentType = docType;

                if (docType == "text/html")
                {
                    Timingutil.start("tostring");
                    string string1 = Commonutil.XmlDocumentToString(resultDoc);
                    //Console.Error.WriteLine('a'+string1);
                    string1 = string1.Remove(0,string1.IndexOf("<"));
                    Timingutil.stop();
                    {

                /*		Timingutil.start("regex");
                        Regex regex;
                        //string1=string1.Replace("&lt;","<");
                        //string1=string1.Replace("&gt;",">");
                        regex = new Regex(@"&amp;");
                        string1=regex.Replace(string1,"&");
                        Timingutil.stop();
                */
                    }
                    string1 = string1.Insert(string1.IndexOf("<html>"),"\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/2002/REC-xhtml1-20020801/DTD/xhtml1-transitional.dtd\">\n");
                    string1 = string1.Replace("<html>","<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">");
                    //string1 = string1.Replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>","");
                    resp.Write(string1);
                    Timingutil.stop();
                    //resp.Write("\n<!--\n100 = 1ms\n\n"+Timingutil.dump()+"\n\n-->");
                    if(session["lasttiming"] != null)
                    {
                        //resp.Write("<pre>LAST:"+session["lasttiming"]+"</pre>");
                        session["lasttiming"] = null;
                    }

                    //resp.Write("<pre align=\"left\" text-align=\"left\">"+Timingutil.dump()+"</pre>");
                    //resp.Write("<!-- debug:"+result.debugcontent+"-->");
                }

                if (docType == "text/css")
                {
                    if (inputDoc.HasChildNodes)
                    {
                        for (int i=0; i<inputDoc.ChildNodes.Count; i++)
                        {
                            if (inputDoc.ChildNodes[i].NodeType == XmlNodeType.ProcessingInstruction)
                            {
                                if ( "output-header" == ((XmlProcessingInstruction)inputDoc.ChildNodes[i]).Target)
                                {
                                    string headerstr = ((XmlProcessingInstruction)inputDoc.ChildNodes[i]).Data;
                                    string headercontent = headerstr.Remove(0,headerstr.IndexOf(":")+2);
                                    string headername = headerstr.Remove(headerstr.IndexOf(":"),headerstr.Length-(headerstr.IndexOf(":")));

                                    resp.AddHeader(headername,headercontent);

                                }
                            }
                        }
                    }

                //	XmlTextWriter writer = new XmlTextWriter (Console.Error);
                 //   writer.Formatting = Formatting.Indented;
            //		writer.WriteNode(resultDoc.DocumentElement, false);
            //		writer.Close();
                    string string1 = resultDoc.DocumentElement.InnerXml;
                    resp.Write(string1);
                    Timingutil.stop();
                }

                if (docType == "text/xml")
                {
                    string string1 = resultDoc.InnerXml;
                    resp.Write(string1);
            //					Timingutil.stop();
                    session["lasttiming"]=Timingutil.dump();
                }

                if (docType == "text/plain")
                {
                    string string1 = resultDoc.InnerXml;
                    resp.Write(string1);
                    Timingutil.stop();
                }

                if ((docType == "image/png")||(docType == "image/jpeg"))
                {

                    string string1 = resultDoc.InnerXml;

                    byte[] hashdata = System.Text.Encoding.ASCII.GetBytes(string1);
                    hashdata = Md5Provider.ComputeHash(hashdata);
                    string hashvalue = "";
                    for (int i=0; i < hashdata.Length; i++) hashvalue += hashdata[i].ToString("x2").ToLower();

                    /*
                        TODO: remove that tmeporary files
                    */

                    string fileext;
                    if(docType == "image/png")
                    {
                        fileext = "png";
                    }
                    else
                    {
                        fileext = "jpeg";
                    }

                    lock(imageCacheLock)
                    {
                        if (imageCache.Contains(hashvalue))
                        {
                            resp.BinaryWrite((byte[])((CacheObject)imageCache[hashvalue]).content);
                        }
                        else
                        {
                            lock(rsvgProcessLock)
                            {
                                TextWriter tw = new StreamWriter("/tmp/_image.svg");
                                tw.Write(string1);
                                tw.Close();

                                Process compiler = new Process();
                                compiler.StartInfo.FileName = "/usr/bin/rsvg";
                                compiler.StartInfo.Arguments = "/tmp/_image.svg /tmp/_image.png";
                                compiler.StartInfo.UseShellExecute = false;
                                compiler.Start();
                                compiler.WaitForExit();

                                if(fileext == "jpeg")
                                {
                                    Process converter = new Process();
                                    converter.StartInfo.FileName = "/usr/bin/convert";
                                    converter.StartInfo.Arguments = "/tmp/_image.png /tmp/_image.jpeg";
                                    converter.StartInfo.UseShellExecute = false;
                                    converter.Start();
                                    converter.WaitForExit();
                                }

                                FileStream fs = new FileStream("/tmp/_image."+fileext, FileMode.OpenOrCreate,FileAccess.Read);
                                byte[] MyData= new byte[fs.Length];
                                fs.Read(MyData, 0, System.Convert.ToInt32(fs.Length));
                                fs.Close();

                                CacheObject cacheObject = new CacheObject(MyData);
                                imageCache.Add(hashvalue,cacheObject);

                                resp.BinaryWrite(MyData);
                            }
                        }
                    }

                    Timingutil.stop();
                }

            }
        }
Пример #26
0
        protected override bool DoDownload()
        {
            string strImgURL = ImageLinkURL;

            if (EventTable.ContainsKey(strImgURL))
            {
                return(true);
            }

            string strNewURL = strImgURL;

            strNewURL = strNewURL.Replace("i.cc/i/", "i.cc/im/");

            string strFilePath = string.Empty;

            try
            {
                if (!Directory.Exists(SavePath))
                {
                    Directory.CreateDirectory(SavePath);
                }
            }
            catch (IOException ex)
            {
                //MainForm.DeleteMessage = ex.Message;
                //MainForm.Delete = true;

                return(false);
            }

            strFilePath = Path.Combine(SavePath, Utility.RemoveIllegalCharecters(strFilePath));

            CacheObject CCObj = new CacheObject();

            CCObj.IsDownloaded = false;
            CCObj.FilePath     = strFilePath;
            CCObj.Url          = strImgURL;
            try
            {
                EventTable.Add(strImgURL, CCObj);
            }
            catch (ThreadAbortException)
            {
                return(true);
            }
            catch (Exception)
            {
                if (EventTable.ContainsKey(strImgURL))
                {
                    return(false);
                }
                else
                {
                    EventTable.Add(strImgURL, CCObj);
                }
            }



            //////////////////////////////////////////////////////////////////////////

            try
            {
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(strNewURL);

                req.UserAgent = "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1";
                req.Referer   = strNewURL;

                HttpWebResponse res = (HttpWebResponse)req.GetResponse();

                string sRes = res.Headers.ToString().Substring(res.Headers.ToString().IndexOf("filename") + 10);

                sRes = sRes.Remove(sRes.IndexOf("\""));

                strFilePath += sRes;

                string NewAlteredPath = Utility.GetSuitableName(strFilePath);
                if (strFilePath != NewAlteredPath)
                {
                    strFilePath = NewAlteredPath;
                    ((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath;
                }

                Stream resStream = res.GetResponseStream();

                Image ImageDozerImage = Image.FromStream(resStream);

                ImageDozerImage.Save(strFilePath);
            }
            catch (ThreadAbortException)
            {
                ((CacheObject)EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL);

                return(true);
            }
            catch (IOException ex)
            {
                //MainForm.DeleteMessage = ex.Message;
                //MainForm.Delete = true;

                ((CacheObject)EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL);

                return(true);
            }
            catch (WebException)
            {
                ((CacheObject)EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL);

                return(false);
            }

            ((CacheObject)EventTable[ImageLinkURL]).IsDownloaded = true;
            //CacheController.GetInstance().u_s_LastPic = ((CacheObject)eventTable[mstrURL]).FilePath;
            CacheController.Instance().LastPic = ((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath;

            return(true);
        }
        /// <summary>
        /// Gets the settings value.
        /// </summary>
        /// <param name="queryTypeId">The query type id.</param>
        /// <param name="cacheObjectType">Type of the cache object.</param>
        /// <param name="cacheValue">The cache value.</param>
        /// <remarks>Documented by Dev08, 2009-01-13</remarks>
        private void GetSettingsValue(int queryTypeId, CacheObject cacheObjectType, out object cacheValue)
        {
            SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser);
            cmd.CommandText = "SELECT * FROM \"QueryTypes\" WHERE id=@id";
            cmd.Parameters.Add("@id", queryTypeId);

            SqlCeDataReader reader = MSSQLCEConn.ExecuteReader(cmd);
            reader.Read();

            int? qid = DbValueConverter.Convert<int>(reader["id"]);
            bool? imageRecognition = DbValueConverter.Convert<bool>(reader["image_recognition"]);
            bool? listeningComprehension = DbValueConverter.Convert<bool>(reader["listening_comprehension"]);
            bool? multipleChoice = DbValueConverter.Convert<bool>(reader["multiple_choice"]);
            bool? sentenceMode = DbValueConverter.Convert<bool>(reader["sentence"]);
            bool? wordMode = DbValueConverter.Convert<bool>(reader["word"]);
            reader.Close();

            //cache values
            DateTime expires = DateTime.Now.Add(Cache.DefaultSettingsValidationTime);
            Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsQueryTypesImageRecognition, queryTypeId, expires)] = imageRecognition;
            Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsQueryTypesListeningComprehension, queryTypeId, expires)] = listeningComprehension;
            Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsQueryTypesMultipleChoice, queryTypeId, expires)] = multipleChoice;
            Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsQueryTypesSentence, queryTypeId, expires)] = sentenceMode;
            Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsQueryTypesWord, queryTypeId, expires)] = wordMode;
            Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsQueryTypesId, queryTypeId, expires)] = qid;

            //set output value
            switch (cacheObjectType)
            {
                case CacheObject.SettingsQueryTypesImageRecognition: cacheValue = imageRecognition; break;
                case CacheObject.SettingsQueryTypesListeningComprehension: cacheValue = listeningComprehension; break;
                case CacheObject.SettingsQueryTypesMultipleChoice: cacheValue = multipleChoice; break;
                case CacheObject.SettingsQueryTypesSentence: cacheValue = sentenceMode; break;
                case CacheObject.SettingsQueryTypesWord: cacheValue = wordMode; break;
                case CacheObject.SettingsQueryTypesId: cacheValue = qid; break;
                default: cacheValue = null; break;
            }
        }
Пример #28
0
        private static void CacheStyleSheet(string filepath,Hashtable xsltParameters)
        {
            try
            {
                XslCompiledTransform transformer2 = new XslCompiledTransform();

                XmlTextReader reader = new XmlTextReader(filepath);
                reader.WhitespaceHandling = WhitespaceHandling.All;

                XmlDocument doc = new XmlDocument();
                doc.PreserveWhitespace=true;
                doc.Load(reader);

                /*XmlNode node = doc.FirstChild.NextSibling.NextSibling;

                IDictionaryEnumerator xsltParameterEnum = xsltParameters.GetEnumerator();
                while ( xsltParameterEnum.MoveNext() )
                {
                    XmlNode paramNode = doc.CreateNode(XmlNodeType.Element, "xsl:param", "http://www.w3.org/1999/XSL/Transform");

                    XmlAttribute newAttr1 = doc.CreateAttribute("name");
                    newAttr1.Value = (string)xsltParameterEnum.Key;
                    paramNode.Attributes.Append(newAttr1);

                    XmlAttribute newAttr2 = doc.CreateAttribute("select");
                    newAttr2.Value = "'__undefined__'";
                    paramNode.Attributes.Append(newAttr2);

                    node.InsertBefore(paramNode, node.FirstChild);
                }

                Console.Error.Write(Commonutil.XmlDocumentToString(doc));*/
                transformer2.Load(doc.CreateNavigator(),null,null);

                DateTime filemtime = File.GetLastWriteTime(filepath);
                CacheObject cacheObject = new CacheObject(transformer2,filemtime);
                stylesheetCache.Add(filepath,cacheObject);
            }
            catch (System.Xml.XmlException e)
            {
                throw new XsltutilException("Parse Stylesheet unsuccessful:"+e.Message);
            }
            catch (System.Xml.Xsl.XsltCompileException e)
            {
                throw new XsltutilException("Compile Stylesheet unsuccessful:"+e.Message);
            }
        }
Пример #29
0
        /******************************************************************************************/
        //Global caching functions
        /******************************************************************************************/
        private void GetSettingsValue(int settingsId, CacheObject cacheObjectType, out object cacheValue)
        {
            using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
            {
                using (NpgsqlCommand cmd = con.CreateCommand())
                {
                    cmd.CommandText = "SELECT * FROM \"GetAllSettings\"(:id)";
                    cmd.Parameters.Add("id", settingsId);

                    NpgsqlDataReader reader = PostgreSQLConn.ExecuteReader(cmd, Parent.CurrentUser);
                    reader.Read();
                    //read the values
                    bool? autoplayAudio = DbValueConverter.Convert<bool>(reader["autoplay_audio"]);
                    bool? caseSensitive = DbValueConverter.Convert<bool>(reader["case_sensitive"]);
                    bool? confirmDemote = DbValueConverter.Convert<bool>(reader["confirm_demote"]);
                    bool? enableCommentary = DbValueConverter.Convert<bool>(reader["enable_commentary"]);
                    bool? correctOnTheFly = DbValueConverter.Convert<bool>(reader["correct_on_the_fly"]);
                    bool? enableTimer = DbValueConverter.Convert<bool>(reader["enable_timer"]);
                    int? synonymGradingsId = DbValueConverter.Convert<int>(reader["synonymGradingsId"]);    //FK
                    int? typeGradingsId = DbValueConverter.Convert<int>(reader["typeGradingsId"]);    //FK
                    int? multipleChoiceOptionsId = DbValueConverter.Convert<int>(reader["multipleChoiceOptionsId"]);    //FK
                    int? queryDirectionsId = DbValueConverter.Convert<int>(reader["queryDirectionsId"]);    //FK
                    int? queryTypesId = DbValueConverter.Convert<int>(reader["queryTypesId"]);    //FK
                    bool? randomPool = DbValueConverter.Convert<bool>(reader["random_pool"]);
                    bool? selfAssessment = DbValueConverter.Convert<bool>(reader["self_assessment"]);
                    bool? showImages = DbValueConverter.Convert<bool>(reader["show_images"]);
                    string stripChars = DbValueConverter.Convert(reader["stripchars"]);
                    string questionCulture = DbValueConverter.Convert(reader["question_culture"]);
                    string answerCulture = DbValueConverter.Convert(reader["answer_culture"]);
                    string questionCaption = DbValueConverter.Convert(reader["question_caption"]);
                    string answerCaption = DbValueConverter.Convert(reader["answer_caption"]);
                    int? logoId = DbValueConverter.Convert<int>(reader["logo"]);    //FK
                    bool? autoBoxsize = DbValueConverter.Convert<bool>(reader["auto_boxsize"]);
                    bool? poolEmptyMessageShown = DbValueConverter.Convert<bool>(reader["pool_empty_message_shown"]);
                    bool? showStatistics = DbValueConverter.Convert<bool>(reader["show_statistics"]);
                    bool? skipCorrectAnswers = DbValueConverter.Convert<bool>(reader["skip_correct_answers"]);
                    int? snoozeOptionsId = DbValueConverter.Convert<int>(reader["snoozeOptionsId"]);    //FK
                    bool? useLmStylesheets = DbValueConverter.Convert<bool>(reader["use_lm_stylesheets"]);
                    int? cardStyleId = DbValueConverter.Convert<int>(reader["cardStyleId"]);    //FK
                    int? boxesId = DbValueConverter.Convert<int>(reader["boxesId"]);    //FK
                    bool? isCached = DbValueConverter.Convert<bool>(reader["isCached"]);
                    //StyleSheets
                    string questionStylesheet = DbValueConverter.Convert(reader["question_stylesheet"]);
                    string answerStylesheet = DbValueConverter.Convert(reader["answer_stylesheet"]);
                    string cardStyle = DbValueConverter.Convert(reader["cardstyle"]);

                    //cache values
                    DateTime expires = DateTime.Now.Add(Cache.DefaultSettingsValidationTime);
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsAutoPlayAudio, settingsId, expires)] = autoplayAudio;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsCaseSensetive, settingsId, expires)] = caseSensitive;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsConfirmDemote, settingsId, expires)] = confirmDemote;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsEnableCommentary, settingsId, expires)] = enableCommentary;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsCorrectOnTheFly, settingsId, expires)] = correctOnTheFly;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsEnableTimer, settingsId, expires)] = enableTimer;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSynonymGradingsFk, settingsId, expires)] = synonymGradingsId;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsTypeGradingsFk, settingsId, expires)] = typeGradingsId;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsMultipleChoiceOptionsFk, settingsId, expires)] = multipleChoiceOptionsId;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsQueryDirectionsFk, settingsId, expires)] = queryDirectionsId;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsQueryTypesFk, settingsId, expires)] = queryTypesId;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsRandomPool, settingsId, expires)] = randomPool;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSelfAssessment, settingsId, expires)] = selfAssessment;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsShowImages, settingsId, expires)] = showImages;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsStripchars, settingsId, expires)] = stripChars;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsQuestionCulture, settingsId, expires)] = questionCulture;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsAnswerCulture, settingsId, expires)] = answerCulture;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsQuestionCaption, settingsId, expires)] = questionCaption;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsAnswerCaption, settingsId, expires)] = answerCaption;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsLogoFk, settingsId, expires)] = logoId;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsAutoBoxsize, settingsId, expires)] = autoBoxsize;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsPoolEmptyMessageShown, settingsId, expires)] = poolEmptyMessageShown;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsShowStatistics, settingsId, expires)] = showStatistics;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSkipCorrectAnswers, settingsId, expires)] = skipCorrectAnswers;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeOptionsFk, settingsId, expires)] = snoozeOptionsId;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsUseLearningModuleStylesheet, settingsId, expires)] = useLmStylesheets;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsCardStyleFk, settingsId, expires)] = cardStyleId;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsBoxesFk, settingsId, expires)] = boxesId;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsStyleSheetsQuestionValue, settingsId, expires)] = questionStylesheet;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsStyleSheetsAnswerValue, settingsId, expires)] = answerStylesheet;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsCardStyleValue, settingsId, expires)] = cardStyle;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsIsCached, settingsId, expires)] = isCached;

                    //set output value
                    switch (cacheObjectType)
                    {
                        case CacheObject.SettingsAutoPlayAudio: cacheValue = autoplayAudio; break;
                        case CacheObject.SettingsCaseSensetive: cacheValue = caseSensitive; break;
                        case CacheObject.SettingsConfirmDemote: cacheValue = confirmDemote; break;
                        case CacheObject.SettingsEnableCommentary: cacheValue = enableCommentary; break;
                        case CacheObject.SettingsCorrectOnTheFly: cacheValue = correctOnTheFly; break;
                        case CacheObject.SettingsEnableTimer: cacheValue = enableTimer; break;
                        case CacheObject.SettingsSynonymGradingsFk: cacheValue = synonymGradingsId; break;
                        case CacheObject.SettingsTypeGradingsFk: cacheValue = typeGradingsId; break;
                        case CacheObject.SettingsMultipleChoiceOptionsFk: cacheValue = multipleChoiceOptionsId; break;
                        case CacheObject.SettingsQueryDirectionsFk: cacheValue = queryDirectionsId; break;
                        case CacheObject.SettingsQueryTypesFk: cacheValue = queryTypesId; break;
                        case CacheObject.SettingsRandomPool: cacheValue = randomPool; break;
                        case CacheObject.SettingsSelfAssessment: cacheValue = selfAssessment; break;
                        case CacheObject.SettingsShowImages: cacheValue = showImages; break;
                        case CacheObject.SettingsStripchars: cacheValue = stripChars; break;
                        case CacheObject.SettingsQuestionCulture: cacheValue = questionCulture; break;
                        case CacheObject.SettingsAnswerCulture: cacheValue = answerCulture; break;
                        case CacheObject.SettingsQuestionCaption: cacheValue = questionCaption; break;
                        case CacheObject.SettingsAnswerCaption: cacheValue = answerCaption; break;
                        case CacheObject.SettingsLogoFk: cacheValue = logoId; break;
                        case CacheObject.SettingsAutoBoxsize: cacheValue = autoBoxsize; break;
                        case CacheObject.SettingsPoolEmptyMessageShown: cacheValue = poolEmptyMessageShown; break;
                        case CacheObject.SettingsShowStatistics: cacheValue = showStatistics; break;
                        case CacheObject.SettingsSkipCorrectAnswers: cacheValue = skipCorrectAnswers; break;
                        case CacheObject.SettingsSnoozeOptionsFk: cacheValue = snoozeOptionsId; break;
                        case CacheObject.SettingsUseLearningModuleStylesheet: cacheValue = useLmStylesheets; break;
                        case CacheObject.SettingsCardStyleFk: cacheValue = cardStyleId; break;
                        case CacheObject.SettingsBoxesFk: cacheValue = boxesId; break;
                        case CacheObject.SettingsIsCached: cacheValue = isCached; break;
                        case CacheObject.SettingsStyleSheetsQuestionValue: cacheValue = questionStylesheet; break;
                        case CacheObject.SettingsStyleSheetsAnswerValue: cacheValue = answerStylesheet; break;
                        case CacheObject.SettingsCardStyleValue: cacheValue = cardStyle; break;
                        default: cacheValue = null; break;
                    }
                    //System.Diagnostics.Trace.Assert(cacheValue == null);
                }
            }
        }
Пример #30
0
 /// <summary>
 /// Private constructure.  Creates the instance of EmojiRetriever
 /// </summary>
 /// <param name="_Method">IRetrieval Method of getting the data.</param>
 /// <param name="CO">Cache Object Parameters on how the cache should react.</param>
 private EmojiDataRetriever(IRetrievalBase _Method, CacheObject CO)
 {
     RetrievingMethod = _Method;
     CacheParameters  = CO;
     cache            = new MemoryCache(new MemoryCacheOptions());
 }
Пример #31
0
        protected override bool DoDownload()
        {
            var strImgURL = this.ImageLinkURL;

            if (this.EventTable.ContainsKey(strImgURL))
            {
                return(true);
            }

            try
            {
                if (!Directory.Exists(this.SavePath))
                {
                    Directory.CreateDirectory(this.SavePath);
                }
            }
            catch (IOException ex)
            {
                // MainForm.DeleteMessage = ex.Message;
                // MainForm.Delete = true;
                return(false);
            }

            var CCObj = new CacheObject();

            CCObj.IsDownloaded = false;

            // CCObj.FilePath = strFilePath;
            CCObj.Url = strImgURL;
            try
            {
                this.EventTable.Add(strImgURL, CCObj);
            }
            catch (ThreadAbortException)
            {
                return(true);
            }
            catch (Exception)
            {
                if (this.EventTable.ContainsKey(strImgURL))
                {
                    return(false);
                }
                else
                {
                    this.EventTable.Add(strImgURL, CCObj);
                }
            }

            var strIVPage = this.GetImageHostPage(ref strImgURL);

            if (strIVPage.Length < 10)
            {
                return(false);
            }

            var strNewURL = strImgURL.Substring(0, strImgURL.IndexOf("/", 8) + 1);

            var iStartSRC = 0;
            var iEndSRC   = 0;

            iStartSRC = strIVPage.IndexOf("Note: Large images are scaled to fit.  <a href=\"");

            if (iStartSRC < 0)
            {
                return(false);
            }

            iStartSRC += 48;

            iEndSRC = strIVPage.IndexOf("\" class=\"small\">Click Here to view full size.</a> </p>", iStartSRC);

            if (iEndSRC < 0)
            {
                return(false);
            }

            strNewURL = strIVPage.Substring(iStartSRC, iEndSRC - iStartSRC);

            var strFilePath = strNewURL.Substring(strNewURL.LastIndexOf("/") + 1);

            strFilePath = Path.Combine(this.SavePath, Utility.RemoveIllegalCharecters(strFilePath));

            CCObj.FilePath = strFilePath;

            //////////////////////////////////////////////////////////////////////////
            var NewAlteredPath = Utility.GetSuitableName(strFilePath);

            if (strFilePath != NewAlteredPath)
            {
                strFilePath = NewAlteredPath;
                ((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath;
            }

            try
            {
                var client = new WebClient();
                client.Headers.Add("Referer: " + strImgURL);
                client.Headers.Add(
                    "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6");
                client.DownloadFile(strNewURL, strFilePath);
                client.Dispose();
            }
            catch (ThreadAbortException)
            {
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(true);
            }
            catch (IOException ex)
            {
                // MainForm.DeleteMessage = ex.Message;
                // MainForm.Delete = true;
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(true);
            }
            catch (WebException)
            {
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(false);
            }

            ((CacheObject)this.EventTable[this.ImageLinkURL]).IsDownloaded = true;

            // CacheController.GetInstance().u_s_LastPic = ((CacheObject)eventTable[mstrURL]).FilePath;
            CacheController.Instance().LastPic =
                ((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath;

            return(true);
        }
Пример #32
0
 public void SetValue(string name, ulong value)
 {
     if (objects.ContainsKey(name))
     {
         objects[name] = new CacheObject(name, CacheObjectType.ULong, value);
     }
     else
     {
         objects.Add(name, new CacheObject(name, CacheObjectType.ULong, value));
     }
 }
Пример #33
0
        protected override bool DoDownload()
        {
            var strImgURL = this.ImageLinkURL;

            if (this.EventTable.ContainsKey(strImgURL))
            {
                return(true);
            }

            var strFilePath = string.Empty;

            try
            {
                if (!Directory.Exists(this.SavePath))
                {
                    Directory.CreateDirectory(this.SavePath);
                }
            }
            catch (IOException ex)
            {
                // MainForm.DeleteMessage = ex.Message;
                // MainForm.Delete = true;
                return(false);
            }

            var ccObj = new CacheObject {
                IsDownloaded = false, FilePath = strFilePath, Url = strImgURL
            };

            try
            {
                this.EventTable.Add(strImgURL, ccObj);
            }
            catch (ThreadAbortException)
            {
                return(true);
            }
            catch (Exception)
            {
                if (this.EventTable.ContainsKey(strImgURL))
                {
                    return(false);
                }

                this.EventTable.Add(strImgURL, ccObj);
            }

            const string sStartSrc = "<img style='width:{szer}px;' src='";

            var sPage = this.GetImageHostPage(ref strImgURL);

            if (sPage.Length < 10)
            {
                return(false);
            }

            var iStartSrc = sPage.IndexOf(sStartSrc);

            if (iStartSrc < 0)
            {
                return(false);
            }

            iStartSrc += sStartSrc.Length;

            var iEndSrc = sPage.IndexOf("\" /></a>", iStartSrc);

            if (iEndSrc < 0)
            {
                return(false);
            }

            var sFullUrl = sPage.Substring(iStartSrc, iEndSrc - iStartSrc);

            strFilePath = sFullUrl.Substring(sFullUrl.IndexOf("\"") + 1);

            var strNewURL = sFullUrl.Remove(sFullUrl.IndexOf("'"));

            strFilePath = Path.Combine(this.SavePath, Utility.RemoveIllegalCharecters(strFilePath));

            //////////////////////////////////////////////////////////////////////////
            var newAlteredPath = Utility.GetSuitableName(strFilePath);

            if (strFilePath != newAlteredPath)
            {
                strFilePath = newAlteredPath;
                ((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath;
            }

            strFilePath = Utility.CheckPathLength(strFilePath);
            ((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath;


            try
            {
                var client = new WebClient();
                client.Headers.Add("Referer: " + strImgURL);
                client.Headers.Add("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6");
                client.DownloadFile(strNewURL, strFilePath);
                client.Dispose();
            }
            catch (ThreadAbortException)
            {
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(true);
            }
            catch (IOException ex)
            {
                // MainForm.DeleteMessage = ex.Message;
                // MainForm.Delete = true;
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(true);
            }
            catch (WebException)
            {
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(false);
            }

            ((CacheObject)this.EventTable[this.ImageLinkURL]).IsDownloaded = true;
            CacheController.Instance().LastPic = ((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath;

            return(true);
        }
Пример #34
0
 public void SetValue(string name, byte[] value)
 {
     if (objects.ContainsKey(name))
     {
         objects[name] = new CacheObject(name, CacheObjectType.Data, value);
     }
     else
     {
         objects.Add(name, new CacheObject(name, CacheObjectType.Data, value));
     }
 }
 /// <summary>
 /// Checks if a given synonym grading value is cached and outputs the value.
 /// </summary>
 /// <param name="synonymsGradingId">The synonyms grading id.</param>
 /// <param name="cacheObjectType">Type of the cache object.</param>
 /// <param name="cacheValue">The cache value.</param>
 /// <returns>[true] if cached.</returns>
 /// <remarks>Documented by Dev03, 2008-11-26</remarks>
 private bool SettingsCached(int synonymsGradingId, CacheObject cacheObjectType, out object cacheValue)
 {
     int? synonymsGradingIdCached = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.SettingsSynonymGradingsId, synonymsGradingId)] as int?;
     cacheValue = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(cacheObjectType, synonymsGradingId)];
     return synonymsGradingIdCached.HasValue && (cacheValue != null);
 }
Пример #36
0
        private void LoadCache(BinaryReader rdr)
        {
            if (rdr.ReadUInt32() != CacheHeader)
            {
                throw new Exception("Invalid cache header!");
            }
            uint version = rdr.ReadUInt32();
            if (version > OMCFVersion)
            {
                throw new Exception("OMCF Version is to high!");
            }

            ulong objectCount = rdr.ReadUInt64();
            for (ulong i = 0; i < objectCount; i++)
            {
                CacheObject c = new CacheObject();
                c.Type = (CacheObjectType)rdr.ReadByte();

                #region Read Actual Data
                switch (c.Type)
                {
                    case CacheObjectType.String:
                        c.Size = rdr.ReadUInt32();
                        byte[] buf = rdr.ReadBytes((int)c.Size);
                        c.Value = Encoding.GetString(buf);
                        break;
                    case CacheObjectType.Byte:
                        c.Value = rdr.ReadByte();
                        c.Size = 1;
                        break;
                    case CacheObjectType.SByte:
                        c.Value = rdr.ReadSByte();
                        c.Size = 1;
                        break;
                    case CacheObjectType.Bool:
                        c.Value = (bool)(rdr.ReadByte() == 0 ? false : true);
                        c.Size = 1;
                        break;
                    case CacheObjectType.UShort:
                        c.Value = rdr.ReadUInt16();
                        c.Size = 2;
                        break;
                    case CacheObjectType.Short:
                        c.Value = rdr.ReadInt16();
                        c.Size = 2;
                        break;
                    case CacheObjectType.UInt:
                        c.Value = rdr.ReadUInt32();
                        c.Size = 4;
                        break;
                    case CacheObjectType.Int:
                        c.Value = rdr.ReadInt32();
                        c.Size = 4;
                        break;
                    case CacheObjectType.ULong:
                        c.Value = rdr.ReadUInt64();
                        c.Size = 8;
                        break;
                    case CacheObjectType.Long:
                        c.Value = rdr.ReadInt64();
                        c.Size = 8;
                        break;
                    case CacheObjectType.Float:
                        c.Value = rdr.ReadSingle();
                        c.Size = 4;
                        break;
                    case CacheObjectType.Double:
                        c.Value = rdr.ReadDouble();
                        c.Size = 8;
                        break;
                    case CacheObjectType.Decimal:
                        c.Value = rdr.ReadDecimal();
                        c.Size = 16;
                        break;
                    case CacheObjectType.Data:
                        c.Size = rdr.ReadUInt32();
                        c.Value = rdr.ReadBytes((int)c.Size);
                        break;
                    default:
                        throw new Exception("Unknown cache object type!");
                }
                #endregion

                uint strSize = rdr.ReadUInt32();
                byte[] buf2 = rdr.ReadBytes((int)strSize);
                c.Name = Encoding.GetString(buf2);
                if (objects.ContainsKey(c.Name))
                {
                    throw new Exception("Duplicate entry in cache file!");
                    objects[c.Name] = c;
                }
                else
                {
                    objects.Add(c.Name, c);
                }
            }
        }
Пример #37
0
        /// <summary>
        /// Do the Download
        /// </summary>
        /// <returns>
        /// Return if Downloaded or not
        /// </returns>
        protected override bool DoDownload()
        {
            var imageURL = ImageLinkURL;
            var thumbURL = ThumbImageURL;

            if (EventTable.ContainsKey(imageURL))
            {
                return(true);
            }

            var filePath = string.Empty;

            try
            {
                if (!Directory.Exists(this.SavePath))
                {
                    Directory.CreateDirectory(this.SavePath);
                }
            }
            catch (IOException ex)
            {
                //MainForm.DeleteMessage = ex.Message;
                //MainForm.Delete = true;

                return(false);
            }

            var cacheObject = new CacheObject {
                IsDownloaded = false, FilePath = filePath, Url = imageURL
            };

            try
            {
                EventTable.Add(imageURL, cacheObject);
            }
            catch (ThreadAbortException)
            {
                return(true);
            }
            catch (Exception)
            {
                if (EventTable.ContainsKey(imageURL))
                {
                    return(false);
                }

                EventTable.Add(imageURL, cacheObject);
            }

            // Set the download Path
            var imageDownloadURL = thumbURL.Replace(@"_t", string.Empty);

            // Set Image Name instead of using random name
            filePath = this.GetImageName(this.PostTitle, imageDownloadURL, this.ImageNumber);

            filePath = Path.Combine(this.SavePath, Utility.RemoveIllegalCharecters(filePath));

            //////////////////////////////////////////////////////////////////////////

            filePath = Utility.GetSuitableName(filePath, true);

            ((CacheObject)EventTable[imageURL]).FilePath = filePath;

            try
            {
                var client = new WebClient();
                client.Headers.Add(string.Format("Referer: {0}", imageURL));
                client.Headers.Add("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6");
                client.DownloadFile(imageDownloadURL, filePath);
                client.Dispose();
            }
            catch (ThreadAbortException)
            {
                ((CacheObject)EventTable[imageURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(imageURL);

                return(true);
            }
            catch (IOException ex)
            {
                //MainForm.DeleteMessage = ex.Message;
                //MainForm.Delete = true;

                ((CacheObject)EventTable[imageURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(imageURL);

                return(true);
            }
            catch (WebException)
            {
                ((CacheObject)EventTable[imageURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(imageURL);

                return(false);
            }

            ((CacheObject)EventTable[imageURL]).IsDownloaded = true;
            CacheController.Instance().LastPic = ((CacheObject)EventTable[imageURL]).FilePath = filePath;

            return(true);
        }
Пример #38
0
        //

        ///<summary>
        ///Adds/Updates CacheObjects inside collection by Iteration of RactorList
        ///This is the method that caches all live data about an object!
        ///</summary>
        internal static bool UpdateCacheObjectCollection()
        {
            //Update Character (just incase it wasnt called before..)
            FunkyGame.Hero.Update(false, true);

            Obstacles.AttemptToClearEntries();

            HashSet <int> hashDoneThisRactor = new HashSet <int>();

            using (ZetaDia.Memory.AcquireFrame(true))
            {
                if (!ZetaDia.IsInGame || ZetaDia.IsLoadingWorld || !ZetaDia.Me.IsValid)
                {
                    return(false);
                }

                foreach (Actor thisActor in ZetaDia.Actors.RActorList)
                {
                    int       tmp_raGUID;
                    DiaObject thisObj;

                    if (!thisActor.IsValid)
                    {
                        continue;
                    }
                    //Convert to DiaObject
                    thisObj    = (DiaObject)thisActor;
                    tmp_raGUID = thisObj.RActorGuid;

                    // See if we've already checked this ractor, this loop
                    if (hashDoneThisRactor.Contains(tmp_raGUID))
                    {
                        continue;
                    }
                    hashDoneThisRactor.Add(tmp_raGUID);

                    //Update RactorGUID and check blacklisting..
                    if (BlacklistCache.IsRAGUIDBlacklisted(tmp_raGUID))
                    {
                        continue;
                    }
                    CacheObject tmp_CachedObj;

                    if (!Objects.TryGetValue(tmp_raGUID, out tmp_CachedObj))
                    {
                        ActorType Actortype;
                        Vector3   tmp_position;
                        int       tmp_acdguid;
                        int       tmp_SNOID;



                        #region SNO
                        //Lookup SNO
                        try
                        {
                            tmp_SNOID = thisObj.ActorSNO;
                        }
                        catch (Exception ex)
                        {
                            Logger.Write(LogLevel.Cache, "Safely handled getting SNO for {0}", tmp_raGUID);
                            //Logger.DBLog.InfoFormat("Failure to get SNO from object! RaGUID: {0}", tmp_raGUID);
                            continue;
                        }
                        #endregion

                        //check our SNO blacklist (exclude pets?)
                        if (BlacklistCache.IsSNOIDBlacklisted(tmp_SNOID))
                        {
                            continue;
                        }


                        #region Position
                        try
                        {
                            tmp_position = thisObj.Position;
                        }
                        catch (Exception ex)
                        {
                            Logger.Write(LogLevel.Cache, "Safely handled getting Position for {0}", tmp_SNOID);
                            continue;
                        }

                        #endregion

                        #region AcdGUID
                        try
                        {
                            tmp_acdguid = thisObj.ACDGuid;
                        }
                        catch (Exception ex)
                        {
                            Logger.Write(LogLevel.Cache, "Safely handled getting ACDGuid for {0}", tmp_SNOID);
                            continue;
                        }

                        #endregion


                        tmp_CachedObj = new CacheObject(tmp_SNOID, tmp_raGUID, tmp_acdguid, tmp_position);
                    }
                    else
                    {
                        //Reset unseen var
                        tmp_CachedObj.LoopsUnseen = 0;
                    }


                    ////Validate (ignore special object SNO Ids)
                    //if (!CacheIDLookup.hashSNOSkipCommonDataCheck.Contains(tmp_CachedObj.SNOID))
                    //{
                    //    try
                    //    {
                    //        if (thisObj.CommonData == null)
                    //        {
                    //            Logger.Write(LogLevel.Cache, "CommonData is no longer valid! {0}", tmp_CachedObj.DebugStringSimple);
                    //            //BlacklistCache.AddObjectToBlacklist(tmp_CachedObj.RAGUID, BlacklistType.Temporary);
                    //            continue;
                    //        }
                    //        if (thisObj.CommonData.ACDGuid != thisObj.ACDGuid)
                    //        {
                    //            Logger.Write(LogLevel.Cache, "ACDGuid Mismatched! {0}", tmp_CachedObj.DebugStringSimple);
                    //            //BlacklistCache.AddObjectToBlacklist(tmp_CachedObj.RAGUID, BlacklistType.Temporary);
                    //            continue;
                    //        }
                    //    }
                    //    catch (Exception ex)
                    //    {
                    //        //Logger.Write(LogLevel.Cache, "Object is no longer valid! (Exception) SNOID {0}", tmp_CachedObj.DebugStringSimple);
                    //        //BlacklistCache.AddObjectToBlacklist(tmp_CachedObj.RAGUID, BlacklistType.Temporary);
                    //        continue;
                    //    }
                    //}

                    //Update any SNO Data.
                    #region SNO_Cache_Update
                    if (tmp_CachedObj.ref_DiaObject == null || tmp_CachedObj.ContainsNullValues())
                    {
                        if (!tmp_CachedObj.UpdateData(thisObj, tmp_CachedObj.RAGUID))
                        {
                            continue;
                        }
                    }
                    else if (!tmp_CachedObj.IsFinalized)
                    {                    //Finalize this data by recreating it and updating the Sno cache with a new finalized entry, this also clears our all Sno cache dictionaries since we no longer need them!
                        cacheSnoCollection.FinalizeEntry(tmp_CachedObj.SNOID);
                    }
                    #endregion

                    //Check if this object is a summoned unit by a player...
                    #region SummonedUnits
                    if (tmp_CachedObj.IsSummonedPet && CacheIDLookup.hashSNOSkipCommonDataCheck.Contains(tmp_CachedObj.SNOID))
                    {
                        PetTypes PetType = (PetTypes)TheCache.ObjectIDCache.UnitPetEntries[tmp_CachedObj.SNOID].ObjectType;
                        if (PetType == PetTypes.WIZARD_ArcaneOrbs)
                        {
                            FunkyGame.Targeting.Cache.Environment.HeroPets.WizardArcaneOrbs++;
                            tmp_CachedObj.NeedsRemoved = true;
                            continue;
                        }
                    }
                    #endregion

                    //Special Cache for Interactable Server Objects
                    if (CheckFlag(tmp_CachedObj.targetType.Value, TargetType.ServerInteractable))
                    {
                        if (!InteractableObjectCache.ContainsKey(tmp_CachedObj.RAGUID))
                        {
                            InteractableObjectCache.Add(tmp_CachedObj.RAGUID, tmp_CachedObj);

                            //Adventure Mode -- Rifting we add Exit to LOS movement!
                            //if (FunkyGame.AdventureMode && FunkyGame.Bounty.IsInRiftWorld && FunkyBaseExtension.Settings.AdventureMode.EnableAdventuringMode)
                            //{
                            //	if (tmp_CachedObj.InternalName.Contains("Exit"))
                            //	{
                            //		int index = FunkyGame.Bounty.CurrentBountyMapMarkers.Count;
                            //		FunkyGame.Bounty.CurrentBountyMapMarkers.Add(index, new BountyCache.BountyMapMarker(tmp_CachedObj.Position, FunkyGame.Hero.CurrentWorldDynamicID, index));
                            //	}
                            //}
                        }

                        //Whymsdal Portal!
                        if (tmp_CachedObj.SNOID == 405590)
                        {
                            GoblinBehavior.Portal = tmp_CachedObj;
                        }
                        else if (tmp_CachedObj.SNOID == 393030)
                        {
                            GoblinBehavior.Portal = tmp_CachedObj;
                        }

                        //Do not add to main cache!
                        continue;
                    }

                    //Objects with static positions already cached don't need to be updated here.
                    if (!tmp_CachedObj.NeedsUpdate)
                    {
                        continue;
                    }

                    //Obstacles -- (Not an actual object we add to targeting.)
                    if (CheckFlag(tmp_CachedObj.targetType.Value, TargetType.Avoidance) || tmp_CachedObj.IsObstacle || tmp_CachedObj.HandleAsAvoidanceObject)
                    {
                        #region Obstacles

                        CacheObstacle thisObstacle;
                        //Do we have this cached?
                        if (!Obstacles.TryGetValue(tmp_CachedObj.RAGUID, out thisObstacle))
                        {
                            AvoidanceType AvoidanceType = AvoidanceType.None;
                            if (tmp_CachedObj.IsAvoidance)
                            {
                                AvoidanceType = AvoidanceCache.FindAvoidanceUsingSNOID(tmp_CachedObj.SNOID);
                                if (AvoidanceType == AvoidanceType.None)
                                {
                                    AvoidanceType = AvoidanceCache.FindAvoidanceUsingName(tmp_CachedObj.InternalName);
                                    if (AvoidanceType == AvoidanceType.None)
                                    {
                                        continue;
                                    }
                                }
                            }

                            if (tmp_CachedObj.IsAvoidance && tmp_CachedObj.IsProjectileAvoidance)
                            {                            //Ranged Projectiles require more than simple bounding points.. so we create it as avoidance zone to cache it with properties.
                                //Check for intersection..
                                try
                                {
                                    ActorMovement thisMovement = thisObj.Movement;
                                    Vector2       Direction    = thisMovement.DirectionVector;
                                    Ray           R            = new Ray(tmp_CachedObj.Position, Direction.ToVector3());
                                    double        Speed;
                                    //Lookup Cached Speed, or add new entry.
                                    if (!dictProjectileSpeed.TryGetValue(tmp_CachedObj.SNOID, out Speed))
                                    {
                                        Speed = thisMovement.DesiredSpeed;
                                        dictProjectileSpeed.Add(tmp_CachedObj.SNOID, Speed);
                                    }

                                    thisObstacle = new CacheAvoidance(tmp_CachedObj, AvoidanceType, R, Speed);
                                    Obstacles.Add(thisObstacle);
                                }
                                catch
                                {
                                    Logger.Write(LogLevel.Cache, "Failed to create projectile avoidance with rotation and speed. {0}", tmp_CachedObj.InternalName);
                                }
                            }
                            else if (tmp_CachedObj.IsAvoidance)
                            {
                                //Poison Gas Can Be Friendly...
                                if (AvoidanceType == AvoidanceType.PoisonGas)
                                {
                                    int TeamID = 0;
                                    try
                                    {
                                        TeamID = thisObj.CommonData.GetAttribute <int>(ActorAttributeType.TeamID);
                                    }
                                    catch
                                    {
                                        Logger.Write(LogLevel.Cache, "Failed to retrieve TeamID attribute for object {0}", tmp_CachedObj.InternalName);
                                    }

                                    //ID of 1 means its non-hostile! (-1?) 2??
                                    //if (TeamID==1||TeamID==-1)
                                    if (TeamID != 10)
                                    {
                                        //Logger.Write(LogLevel.None, "Ignoring Avoidance {0} due to Friendly TeamID match!", tmp_CachedObj.InternalName);
                                        BlacklistCache.AddObjectToBlacklist(tmp_CachedObj.RAGUID, BlacklistType.Permanent);
                                        continue;
                                    }
                                }


                                thisObstacle = new CacheAvoidance(tmp_CachedObj, AvoidanceType);
                                Obstacles.Add(thisObstacle);
                            }
                            else
                            {
                                //Obstacles.
                                thisObstacle = new CacheServerObject(tmp_CachedObj);
                                Obstacles.Add(thisObstacle);
                            }
                        }

                        continue;
                        #endregion
                    }

                    if (tmp_CachedObj.ObjectShouldBeRecreated)
                    {                    //This is where we create the real object after its done with SNO Update.
                        //Specific updates
                        if (tmp_CachedObj.Actortype.Value == ActorType.Item)
                        {
                            tmp_CachedObj = new CacheItem(tmp_CachedObj);
                        }
                        else if (tmp_CachedObj.Actortype.Value == ActorType.Monster)
                        {
                            if (!tmp_CachedObj.IsSummonedPet)
                            {
                                tmp_CachedObj = new CacheUnit(tmp_CachedObj);
                            }
                            else
                            {
                                PetTypes PetType = (PetTypes)TheCache.ObjectIDCache.UnitPetEntries[tmp_CachedObj.SNOID].ObjectType;

                                #region Summoner ID Check

                                // Get the summoned-by info, cached if possible
                                if (!tmp_CachedObj.SummonerID.HasValue)
                                {
                                    try
                                    {
                                        tmp_CachedObj.SummonerID = thisObj.CommonData.GetAttribute <int>(ActorAttributeType.SummonedByACDID);
                                    }
                                    catch (Exception ex)
                                    {
                                        //Logger.DBLog.InfoFormat("[Funky] Safely handled exception getting summoned-by info [" + tmp_CachedObj.SNOID.ToString(CultureInfo.InvariantCulture) + "]");
                                        //Logger.DBLog.DebugFormat(ex.ToString());
                                        continue;
                                    }
                                }

                                if (FunkyGame.Hero.iMyDynamicID != tmp_CachedObj.SummonerID.Value)
                                {
                                    BlacklistCache.IgnoreThisObject(tmp_CachedObj, false, false);
                                    tmp_CachedObj.NeedsRemoved = true;
                                    continue;
                                }

                                #endregion

                                tmp_CachedObj = new CachePet(tmp_CachedObj, PetType);
                            }
                        }
                        else if (tmp_CachedObj.Actortype.Value == ActorType.Gizmo)
                        {
                            if (CheckFlag(tmp_CachedObj.targetType.Value, TargetType.Interactables))
                            {
                                tmp_CachedObj = new CacheInteractable(tmp_CachedObj);
                            }
                            else
                            {
                                tmp_CachedObj = new CacheDestructable(tmp_CachedObj);
                            }
                        }


                        //Update Properties (currently only for units)

                        try
                        {
                            tmp_CachedObj.UpdateProperties();
                        }
                        catch
                        {
                            Logger.Write(LogLevel.Cache, "Failed to update properties for {0}", tmp_CachedObj.DebugStringSimple);
                        }
                    }

                    if (!tmp_CachedObj.UpdateData())
                    {
                        //Logger.Write(LogLevel.Cache, "Update Failed for {0}", tmp_CachedObj.DebugStringSimple);

                        if (!tmp_CachedObj.IsStillValid())
                        {
                            tmp_CachedObj.NeedsRemoved = true;
                        }

                        continue;
                    }

                    //Obstacle cache
                    if (tmp_CachedObj.Obstacletype.Value != ObstacleType.None &&
                        (CheckFlag(tmp_CachedObj.targetType.Value, TargetType.ServerObjects)))
                    {
                        CacheObstacle thisObstacleObj;

                        if (!Obstacles.TryGetValue(tmp_CachedObj.RAGUID, out thisObstacleObj))
                        {
                            CacheServerObject newobj = new CacheServerObject(tmp_CachedObj);
                            Obstacles.Add(tmp_CachedObj.RAGUID, newobj);

                            //Add nearby objects to our collection (used in navblock/obstaclecheck methods to reduce queries)
                            if (CacheIDLookup.hashSNONavigationObstacles.Contains(newobj.SNOID))
                            {
                                Navigation.Navigation.MGP.AddCellWeightingObstacle(newobj.SNOID, newobj.Radius);
                            }
                        }
                        else
                        {
                            if (thisObstacleObj.targetType.Value == TargetType.Unit)
                            {
                                //Since units position requires updating, we update using the CacheObject
                                thisObstacleObj.Position        = tmp_CachedObj.Position;
                                Obstacles[tmp_CachedObj.RAGUID] = thisObstacleObj;
                            }
                        }
                    }


                    //cache it
                    if (Objects.ContainsKey(tmp_CachedObj.RAGUID))
                    {
                        Objects[tmp_CachedObj.RAGUID] = tmp_CachedObj;
                    }
                    else
                    {
                        Objects.Add(tmp_CachedObj.RAGUID, tmp_CachedObj);
                    }
                }        //End of Loop
            }            // End of Framelock

            //Tally up unseen objects.
            var UnseenObjects = Objects.Keys.Where(O => !hashDoneThisRactor.Contains(O)).ToList();
            if (UnseenObjects.Any())
            {
                for (int i = 0; i < UnseenObjects.Count(); i++)
                {
                    Objects[UnseenObjects[i]].LoopsUnseen++;
                }
            }

            //Trim our collection every 5th refresh.
            UpdateLoopCounter++;
            if (UpdateLoopCounter > 4)
            {
                UpdateLoopCounter = 0;
                //Now flag any objects not seen for 5 loops. Gold/Globe only 1 loop.
                foreach (var item in Objects.Values.Where(CO =>
                                                          (CO.LoopsUnseen >= 5 ||                                                                                                    //5 loops max..
                                                           (CO.targetType.HasValue && (CheckFlag(CO.targetType.Value, TargetType.Gold | TargetType.Globe)) && CO.LoopsUnseen > 0)))) //gold/globe only 1 loop!
                {
                    item.NeedsRemoved = true;
                }
            }

            CheckForCacheRemoval();

            _lastUpdatedCacheCollection = DateTime.Now;
            return(true);
        }
Пример #39
0
 /// <summary>
 /// 插入时,只针对特定属性做索引,提高速度
 /// </summary>
 /// <param name="propertyName">需要做索引的属性</param>
 /// <param name="pValue">属性的值</param>
 public static void insertByIndex(CacheObject obj, String propertyName, Object pValue)
 {
     MemoryDB.InsertByIndex(obj, propertyName, pValue);
 }
Пример #40
0
        protected override bool DoDownload()
        {
            string strImgURL = ImageLinkURL;

            if (EventTable.ContainsKey(strImgURL))
            {
                return(true);
            }

            string strFilePath = strImgURL.Substring(strImgURL.IndexOf("picture-hosting/") + 16);

            strFilePath = strFilePath.Remove(strFilePath.Length - 4, 4);

            try
            {
                if (!Directory.Exists(SavePath))
                {
                    Directory.CreateDirectory(SavePath);
                }
            }
            catch (IOException ex)
            {
                //MainForm.DeleteMessage = ex.Message;
                //MainForm.Delete = true;

                return(false);
            }

            strFilePath = Path.Combine(SavePath, Utility.RemoveIllegalCharecters(strFilePath));

            CacheObject CCObj = new CacheObject();

            CCObj.IsDownloaded = false;
            CCObj.FilePath     = strFilePath;
            CCObj.Url          = strImgURL;
            try
            {
                EventTable.Add(strImgURL, CCObj);
            }
            catch (ThreadAbortException)
            {
                return(true);
            }
            catch (Exception)
            {
                if (EventTable.ContainsKey(strImgURL))
                {
                    return(false);
                }
                else
                {
                    EventTable.Add(strImgURL, CCObj);
                }
            }

            string strIVPage = GetImageHostPage(ref strImgURL);

            if (strIVPage.Length < 10)
            {
                return(false);
            }

            string strNewURL = string.Empty;

            strNewURL = strImgURL.Substring(0, strImgURL.IndexOf("/", 8) + 1);

            int iStartSRC = 0;
            int iEndSRC   = 0;

            iStartSRC = strIVPage.IndexOf("<img id=\"mainImg\" src='");

            if (iStartSRC < 0)
            {
                return(false);
            }

            iStartSRC += 23;

            iEndSRC = strIVPage.IndexOf("' alt='", iStartSRC);

            if (iEndSRC < 0)
            {
                return(false);
            }

            strNewURL = strIVPage.Substring(iStartSRC, iEndSRC - iStartSRC);

            //////////////////////////////////////////////////////////////////////////

            HttpWebRequest  lHttpWebRequest;
            HttpWebResponse lHttpWebResponse;
            Stream          lHttpWebResponseStream;

            try
            {
                lHttpWebRequest = (HttpWebRequest)WebRequest.Create(strNewURL);

                lHttpWebRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6";
                lHttpWebRequest.Headers.Add("Accept-Language: en-us,en;q=0.5");
                lHttpWebRequest.Headers.Add("Accept-Encoding: gzip,deflate");
                lHttpWebRequest.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7");
                lHttpWebRequest.Referer   = strImgURL;
                lHttpWebRequest.Accept    = "image/png,*/*;q=0.5";
                lHttpWebRequest.KeepAlive = true;

                lHttpWebResponse       = (HttpWebResponse)lHttpWebRequest.GetResponse();
                lHttpWebResponseStream = lHttpWebRequest.GetResponse().GetResponseStream();

                if (lHttpWebResponse.ContentType.IndexOf("image") < 0)
                {
                    //if (lFileStream != null)
                    //	lFileStream.Close();
                    return(false);
                }
                if (lHttpWebResponse.ContentType.ToLower() == "image/jpeg")
                {
                    strFilePath += ".jpg";
                }
                else if (lHttpWebResponse.ContentType.ToLower() == "image/gif")
                {
                    strFilePath += ".gif";
                }
                else if (lHttpWebResponse.ContentType.ToLower() == "image/png")
                {
                    strFilePath += ".png";
                }

                lHttpWebResponseStream.Close();

                string NewAlteredPath = Utility.GetSuitableName(strFilePath);
                if (strFilePath != NewAlteredPath)
                {
                    strFilePath = NewAlteredPath;
                    ((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath;
                }

                WebClient client = new WebClient();
                client.Headers.Add("Accept-Language: en-us,en;q=0.5");
                client.Headers.Add("Accept-Encoding: gzip,deflate");
                client.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7");
                client.Headers.Add("Referer: " + strImgURL);
                client.Headers.Add("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6");
                client.DownloadFile(strNewURL, strFilePath);
            }
            catch (ThreadAbortException)
            {
                ((CacheObject)EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL);

                return(true);
            }
            catch (IOException ex)
            {
                //MainForm.DeleteMessage = ex.Message;
                //MainForm.Delete = true;

                ((CacheObject)EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL);

                return(true);
            }
            catch (WebException)
            {
                ((CacheObject)EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL);

                return(false);
            }

            ((CacheObject)EventTable[ImageLinkURL]).IsDownloaded = true;
            //CacheController.GetInstance().u_s_LastPic = ((CacheObject)eventTable[mstrURL]).FilePath;
            CacheController.Instance().LastPic = ((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath;

            return(true);
        }
Пример #41
0
 /// <summary>
 ///  更新数据(不持久化,也不做索引)
 /// </summary>
 /// <returns></returns>
 public static Result updateNoIndex(CacheObject obj)
 {
     return(new Result());
 }
Пример #42
0
        /// <summary>
        /// Do the Download
        /// </summary>
        /// <returns>
        /// Return if Downloaded or not
        /// </returns>
        protected override bool DoDownload()
        {
            string strImgURL = ImageLinkURL;

            if (EventTable.ContainsKey(strImgURL))
            {
                return(true);
            }

            string strFilePath = string.Empty;

            try
            {
                if (!Directory.Exists(this.SavePath))
                {
                    Directory.CreateDirectory(this.SavePath);
                }
            }
            catch (IOException ex)
            {
                //MainForm.DeleteMessage = ex.Message;
                //MainForm.Delete = true;

                return(false);
            }

            var cacheObject = new CacheObject {
                IsDownloaded = false, FilePath = strFilePath, Url = strImgURL
            };

            try
            {
                EventTable.Add(strImgURL, cacheObject);
            }
            catch (ThreadAbortException)
            {
                return(true);
            }
            catch (Exception)
            {
                if (EventTable.ContainsKey(strImgURL))
                {
                    return(false);
                }

                EventTable.Add(strImgURL, cacheObject);
            }

            var page = GetImageHostPage(ref strImgURL, "hoosterads=1;");

            if (page.Length < 10)
            {
                return(false);
            }

            string strNewURL;

            var m = Regex.Match(page, @"img src=\""(?<inner>[^\""]*)\"" alt=\""", RegexOptions.Singleline);

            if (m.Success)
            {
                strNewURL = m.Groups["inner"].Value;
            }
            else
            {
                return(false);
            }

            if (strNewURL.StartsWith(" "))
            {
                strNewURL = strNewURL.Replace(" ", string.Empty);
            }

            strFilePath = strImgURL.Substring(strImgURL.LastIndexOf("/", StringComparison.Ordinal) + 1);

            strFilePath = Path.Combine(this.SavePath, Utility.RemoveIllegalCharecters(strFilePath));

            //////////////////////////////////////////////////////////////////////////

            string newAlteredPath = Utility.GetSuitableName(strFilePath);

            if (strFilePath != newAlteredPath)
            {
                strFilePath = newAlteredPath;
                ((CacheObject)EventTable[this.ImageLinkURL]).FilePath = strFilePath;
            }

            try
            {
                WebClient client = new WebClient();
                client.Headers.Add(string.Format("Referer: {0}", strImgURL));
                client.Headers.Add("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6");
                client.DownloadFile(strNewURL, strFilePath);
                client.Dispose();
            }
            catch (ThreadAbortException)
            {
                ((CacheObject)EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(true);
            }
            catch (IOException ex)
            {
                //MainForm.DeleteMessage = ex.Message;
                //MainForm.Delete = true;

                ((CacheObject)EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(true);
            }
            catch (WebException)
            {
                ((CacheObject)EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(false);
            }

            ((CacheObject)EventTable[ImageLinkURL]).IsDownloaded = true;
            CacheController.Instance().LastPic = ((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath;

            return(true);
        }
Пример #43
0
 /// <summary>
 /// Creates an Instance of Stored User Data Manager.
 /// </summary>
 /// <param name="iconf">Config File.</param>
 public StoredUserDataManager(IConfiguration iconf) : base(SectionName, iconf)
 {
     CO = new CacheObject(SectionName, int.Parse(WCSM.GetSectionConfigValue("CacheLength")));
 }
Пример #44
0
        /// <summary>
        /// Do the Download
        /// </summary>
        /// <returns>
        /// Return if Downloaded or not
        /// </returns>
        protected override bool DoDownload()
        {
            var strImgURL = this.ImageLinkURL;

            if (this.EventTable.ContainsKey(strImgURL))
            {
                return(true);
            }

            var strFilePath = string.Empty;

            try
            {
                if (!Directory.Exists(this.SavePath))
                {
                    Directory.CreateDirectory(this.SavePath);
                }
            }
            catch (IOException ex)
            {
                // MainForm.DeleteMessage = ex.Message;
                // MainForm.Delete = true;
                return(false);
            }

            var ccObj = new CacheObject {
                IsDownloaded = false, FilePath = strFilePath, Url = strImgURL
            };

            try
            {
                this.EventTable.Add(strImgURL, ccObj);
            }
            catch (ThreadAbortException)
            {
                return(true);
            }
            catch (Exception)
            {
                if (this.EventTable.ContainsKey(strImgURL))
                {
                    return(false);
                }

                this.EventTable.Add(strImgURL, ccObj);
            }

            var strNewURL = strImgURL.Replace(".php", ".jpg");

            strFilePath = strNewURL.Substring(strNewURL.LastIndexOf("/") + 1);

            strFilePath = Path.Combine(this.SavePath, Utility.RemoveIllegalCharecters(strFilePath));

            //////////////////////////////////////////////////////////////////////////
            var newAlteredPath = Utility.GetSuitableName(strFilePath);

            if (strFilePath != newAlteredPath)
            {
                strFilePath = newAlteredPath;
                ((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath;
            }

            try
            {
                var client = new WebClient();
                client.Headers.Add("Referer: " + strImgURL);
                client.Headers.Add("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6");
                client.DownloadFile(strNewURL, strFilePath);
                client.Dispose();
            }
            catch (ThreadAbortException)
            {
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(true);
            }
            catch (IOException ex)
            {
                // MainForm.DeleteMessage = ex.Message;
                // MainForm.Delete = true;
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(true);
            }
            catch (WebException)
            {
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(false);
            }

            ((CacheObject)this.EventTable[this.ImageLinkURL]).IsDownloaded = true;
            CacheController.Instance().LastPic = ((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath;

            return(true);
        }
Пример #45
0
        public static void Set(EffectVariable variable, object o, int len) {
            if (o == null) {
                // TODO (?)
            } else {
                CacheObject cobj;
                if (!Cache.TryGetValue(len, out cobj)) {
                    cobj = new CacheObject(len);
                    Cache[len] = cobj;
                    Debug.WriteLine("CACHED MEMORY AREA CREATED: " + len);
                }

                Marshal.StructureToPtr(o, cobj.Pointer, true);
                Marshal.Copy(cobj.Pointer, CacheObject.Array, 0, len);
                variable.SetRawValue(cobj.Data, len);
            }
        }
Пример #46
0
        protected override bool DoDownload()
        {
            var strImgURL = this.ImageLinkURL;

            if (this.EventTable.ContainsKey(strImgURL))
            {
                return(true);
            }

            var strFilePath = string.Empty;

            strFilePath = strImgURL.Substring(strImgURL.IndexOf("html/") + 5);

            try
            {
                if (!Directory.Exists(this.SavePath))
                {
                    Directory.CreateDirectory(this.SavePath);
                }
            }
            catch (IOException ex)
            {
                // MainForm.DeleteMessage = ex.Message;
                // MainForm.Delete = true;
                return(false);
            }

            strFilePath = Path.Combine(this.SavePath, Utility.RemoveIllegalCharecters(strFilePath));

            var CCObj = new CacheObject();

            CCObj.IsDownloaded = false;
            CCObj.FilePath     = strFilePath;
            CCObj.Url          = strImgURL;
            try
            {
                this.EventTable.Add(strImgURL, CCObj);
            }
            catch (ThreadAbortException)
            {
                return(true);
            }
            catch (Exception)
            {
                if (this.EventTable.ContainsKey(strImgURL))
                {
                    return(false);
                }
                else
                {
                    this.EventTable.Add(strImgURL, CCObj);
                }
            }

            var strNewURL = "http://www.moast.com/free_image_hosting/"
                            + strImgURL.Substring(strImgURL.IndexOf("html/") + 5);

            //////////////////////////////////////////////////////////////////////////
            HttpWebRequest  lHttpWebRequest;
            HttpWebResponse lHttpWebResponse;
            Stream          lHttpWebResponseStream;

            try
            {
                lHttpWebRequest = (HttpWebRequest)WebRequest.Create(strNewURL);

                lHttpWebRequest.UserAgent =
                    "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6";
                lHttpWebRequest.Headers.Add("Accept-Language: en-us,en;q=0.5");
                lHttpWebRequest.Headers.Add("Accept-Encoding: gzip,deflate");
                lHttpWebRequest.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7");
                lHttpWebRequest.Referer   = strImgURL;
                lHttpWebRequest.Accept    = "image/png,*/*;q=0.5";
                lHttpWebRequest.KeepAlive = true;

                lHttpWebResponse       = (HttpWebResponse)lHttpWebRequest.GetResponse();
                lHttpWebResponseStream = lHttpWebRequest.GetResponse().GetResponseStream();

                if (lHttpWebResponse.ContentType.IndexOf("image") < 0)
                {
                    // if (lFileStream != null)
                    //  lFileStream.Close();
                    return(false);
                }

                if (lHttpWebResponse.ContentType.ToLower() == "image/jpeg")
                {
                    strFilePath += ".jpg";
                }
                else if (lHttpWebResponse.ContentType.ToLower() == "image/gif")
                {
                    strFilePath += ".gif";
                }
                else if (lHttpWebResponse.ContentType.ToLower() == "image/png")
                {
                    strFilePath += ".png";
                }

                lHttpWebResponseStream.Close();

                var NewAlteredPath = Utility.GetSuitableName(strFilePath);
                if (strFilePath != NewAlteredPath)
                {
                    strFilePath = NewAlteredPath;
                    ((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath;
                }

                var client = new WebClient();
                client.Headers.Add("Accept-Language: en-us,en;q=0.5");
                client.Headers.Add("Accept-Encoding: gzip,deflate");
                client.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7");
                client.Headers.Add("Referer: " + strImgURL);
                client.Headers.Add(
                    "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6");
                client.DownloadFile(strNewURL, strFilePath);

                client.Dispose();
            }
            catch (ThreadAbortException)
            {
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(true);
            }
            catch (IOException ex)
            {
                // MainForm.DeleteMessage = ex.Message;
                // MainForm.Delete = true;
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(true);
            }
            catch (WebException)
            {
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(false);
            }

            ((CacheObject)this.EventTable[this.ImageLinkURL]).IsDownloaded = true;

            // CacheController.GetInstance().u_s_LastPic = ((CacheObject)eventTable[mstrURL]).FilePath;
            CacheController.Instance().LastPic =
                ((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath;

            return(true);
        }
Пример #47
0
        protected override bool DoDownload()
        {
            string strImgURL = ImageLinkURL;

            if (EventTable.ContainsKey(strImgURL))
            {
                return(true);
            }

            string strFilePath = string.Empty;

            strFilePath = strImgURL.Substring(strImgURL.LastIndexOf("/") + 8);

            try
            {
                if (!Directory.Exists(SavePath))
                {
                    Directory.CreateDirectory(SavePath);
                }
            }
            catch (IOException ex)
            {
                //MainForm.DeleteMessage = ex.Message;
                //MainForm.Delete = true;

                return(false);
            }

            strFilePath = Path.Combine(SavePath, Utility.RemoveIllegalCharecters(strFilePath));

            CacheObject CCObj = new CacheObject();

            CCObj.IsDownloaded = false;
            CCObj.FilePath     = strFilePath;
            CCObj.Url          = strImgURL;
            try
            {
                EventTable.Add(strImgURL, CCObj);
            }
            catch (ThreadAbortException)
            {
                return(true);
            }
            catch (Exception)
            {
                if (EventTable.ContainsKey(strImgURL))
                {
                    return(false);
                }
                else
                {
                    EventTable.Add(strImgURL, CCObj);
                }
            }

            string strNewURL = strImgURL;

            //////////////////////////////////////////////////////////////////////////
            try
            {
                string NewAlteredPath = Utility.GetSuitableName(strFilePath);
                if (strFilePath != NewAlteredPath)
                {
                    strFilePath = NewAlteredPath;
                    ((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath;
                }

                WebClient client = new WebClient();
                client.Headers.Add("Referer: " + strImgURL);
                client.Headers.Add("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6");
                client.DownloadFile(strNewURL, strFilePath);
                client.Dispose();
            }
            catch (ThreadAbortException)
            {
                ((CacheObject)EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL);

                return(true);
            }
            catch (IOException ex)
            {
                //MainForm.DeleteMessage = ex.Message;
                //MainForm.Delete = true;

                ((CacheObject)EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL);

                return(true);
            }
            catch (WebException)
            {
                ((CacheObject)EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL);

                return(false);
            }

            ((CacheObject)EventTable[ImageLinkURL]).IsDownloaded = true;
            //CacheController.GetInstance().u_s_LastPic = ((CacheObject)eventTable[mstrURL]).FilePath;
            CacheController.Instance().LastPic = ((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath;

            return(true);
        }
Пример #48
0
        protected override bool DoDownload()
        {
            var strImgURL = this.ImageLinkURL;

            if (this.EventTable.ContainsKey(strImgURL))
            {
                return(true);
            }

            var strFilePath = string.Empty;

            strFilePath = strImgURL.Substring(strImgURL.IndexOf("images/") + 7);

            strFilePath = strFilePath.Remove(strFilePath.Length - 37, 37);

            strFilePath += ".jpg";

            try
            {
                if (!Directory.Exists(this.SavePath))
                {
                    Directory.CreateDirectory(this.SavePath);
                }
            }
            catch (IOException ex)
            {
                // MainForm.DeleteMessage = ex.Message;
                // MainForm.Delete = true;
                return(false);
            }

            strFilePath = Path.Combine(this.SavePath, Utility.RemoveIllegalCharecters(strFilePath));

            var CCObj = new CacheObject();

            CCObj.IsDownloaded = false;
            CCObj.FilePath     = strFilePath;
            CCObj.Url          = strImgURL;
            try
            {
                this.EventTable.Add(strImgURL, CCObj);
            }
            catch (ThreadAbortException)
            {
                return(true);
            }
            catch (Exception)
            {
                if (this.EventTable.ContainsKey(strImgURL))
                {
                    return(false);
                }
                else
                {
                    this.EventTable.Add(strImgURL, CCObj);
                }
            }

            //////////////////////////////////////////////////////////////////////////
            try
            {
                var NewAlteredPath = Utility.GetSuitableName(strFilePath);
                if (strFilePath != NewAlteredPath)
                {
                    strFilePath = NewAlteredPath;
                    ((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath;
                }

                var client = new WebClient();
                client.DownloadFile(strImgURL, strFilePath);
                client.Dispose();
            }
            catch (ThreadAbortException)
            {
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(true);
            }
            catch (IOException ex)
            {
                // MainForm.DeleteMessage = ex.Message;
                // MainForm.Delete = true;
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(true);
            }
            catch (WebException)
            {
                ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL);

                return(false);
            }

            ((CacheObject)this.EventTable[this.ImageLinkURL]).IsDownloaded = true;

            // CacheController.GetInstance().u_s_LastPic = ((CacheObject)eventTable[mstrURL]).FilePath;
            CacheController.Instance().LastPic =
                ((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath;

            return(true);
        }
Пример #49
0
        private void CacheFile(String filename,HttpRequest req)
        {
            //				string lcCode = Commonutil.ReadTextFile(filename);

                DateTime filemtime = File.GetLastWriteTime(filename);

                Assembly loAssembly = null;

                string directory = "/tmp/www-data-temp-aspnet-0/";
                string [] fileEntries_tmp = Directory.GetFiles(directory);
                foreach(string fileEntry in fileEntries_tmp)
                {
                    if (fileEntry.EndsWith(".mdb")) continue;

                    if ((fileEntry.Length > (33+directory.Length))&&((fileEntry.Substring(directory.Length,32) == GetMD5(filename))))
                    {
                        string moduleName = directory+GetMD5(filename)+"_"+Commonutil.ConvertToUnixTimestamp(filemtime).ToString();

                        if(moduleName+".dll" == fileEntry)
                        {
                            FileStream fs1 = new FileStream(moduleName+".dll", FileMode.Open,FileAccess.Read);
                            FileStream fs2 = new FileStream(moduleName+".dll.mdb", FileMode.Open,FileAccess.Read);
                            byte[] data1 = new byte[fs1.Length];
                            byte[] data2 = new byte[fs2.Length];
                            fs1.Read(data1,0,System.Convert.ToInt32(fs1.Length));
                            fs2.Read(data2,0,System.Convert.ToInt32(fs2.Length));
                            fs1.Close();
                            fs2.Close();

                            Console.Error.WriteLine("use assembly for(2) "+filename);
                            Timingutil.info("reuse : "+filename);
            //							loAssembly = Assembly.LoadFile(moduleName);
                            //load all modules in lib

                            loAssembly = Assembly.Load(data1,data2);

                            string [] fileEntries = Directory.GetFiles(Directory.GetParent(filename).ToString()+"/libs/");
                            foreach(string fileName2 in fileEntries)
                            {
                                DateTime filemtime2 = File.GetLastWriteTime(fileName2);
                                string moduleName2 = directory+GetMD5(fileName2)+"_"+Commonutil.ConvertToUnixTimestamp(filemtime2).ToString();
                                    FileStream fs21 = new FileStream(moduleName2+".dll", FileMode.Open,FileAccess.Read);
                                    FileStream fs22 = new FileStream(moduleName2+".dll.mdb", FileMode.Open,FileAccess.Read);
                                    byte[] data21 = new byte[fs21.Length];
                                    byte[] data22 = new byte[fs22.Length];
                                    fs21.Read(data21,0,System.Convert.ToInt32(fs21.Length));
                                    fs22.Read(data22,0,System.Convert.ToInt32(fs22.Length));
                                    fs21.Close();
                                    fs22.Close();

                                    Console.Error.WriteLine("load sub assembly "+fileName2);
                                    Assembly loAssembly2 = Assembly.Load(data21,data22);
                            }
            //							loAssembly = Assembly.Load(data1);
                            //http://msdn.microsoft.com/en-us/library/system.reflection.moduleresolveeventhandler(VS.71).aspx
                        }
                        else
                        {
                            Timingutil.info("deleting old");
                            File.Delete(fileEntry);
                            File.Delete(fileEntry+".mdb");
                        }
                    }
                }

                if(loAssembly == null)
                {
                    if(codefileCache.Contains(filename))
                        codefileCache.Remove(filename);

                    string moduleName = "/tmp/www-data-temp-aspnet-0/"+GetMD5(filename)+"_"+Commonutil.ConvertToUnixTimestamp(filemtime).ToString()+".dll";

                    Console.Error.WriteLine("compile "+filename);

                    CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
                    //ICodeCompiler loCompiler = new CSharpCodeProvider().CreateCompiler();
                    CompilerParameters loParameters = new CompilerParameters();

                    string [] fileEntries = Directory.GetFiles(Directory.GetParent(filename).ToString()+"/libs/");
                    foreach(string fileName in fileEntries)
                    {
                        string pathtolib = CompileLib(fileName);
                        loParameters.ReferencedAssemblies.Add(pathtolib);
                    }
                    string [] fileEntries2 = Directory.GetFiles("/var/www_mono/bin/");
                    foreach(string fileName in fileEntries2)
                    {
                        if(fileName.EndsWith(".dll"))
                            loParameters.ReferencedAssemblies.Add(fileName);
                    }

                    foreach (Assembly assem in AppDomain.CurrentDomain.GetAssemblies())
                    {
                        //Console.Error.WriteLine(assem.Location);
                        Match m = Regex.Match(assem.Location,@"^(/tmp/www-data-temp-aspnet-0/[0-9a-f]+/App_Code\.[0-9a-f]+\.dll)$");
                        loParameters.ReferencedAssemblies.Add(m.Groups[1].Value);
                        //Console.Error.WriteLine("Ma"+m.Groups[1].Value);
                    }
                    loParameters.ReferencedAssemblies.Add("System.dll");
                    loParameters.ReferencedAssemblies.Add("Npgsql.dll");
                    loParameters.ReferencedAssemblies.Add("System.Web.dll");
                    loParameters.ReferencedAssemblies.Add("System.Drawing.dll");
                    loParameters.ReferencedAssemblies.Add("System.Web.Services.dll");
                    loParameters.ReferencedAssemblies.Add("System.Data.dll");
                    loParameters.GenerateInMemory = false;
                    loParameters.IncludeDebugInformation = true;
                    loParameters.CompilerOptions = "-debug";
                    //cp.TempFiles = new TempFileCollection(".", true);

                    loParameters.OutputAssembly = moduleName;

                    Timingutil.start("compile "+filename);
            //					CompilerResults loCompiled = loCompiler.CompileAssemblyFromFile(loParameters,filename);
                    CompilerResults loCompiled = provider.CompileAssemblyFromFile(loParameters,filename);
                    Timingutil.stop();

                    if (loCompiled.Errors.HasErrors)
                    {
                        string lcErrorMsg = "";
                        lcErrorMsg = loCompiled.Errors.Count.ToString() + " Errors:";
                        for (int x=0;x<loCompiled.Errors.Count;x++)
                            lcErrorMsg = lcErrorMsg  + "\r\nLine: " +
                            loCompiled.Errors[x].Line.ToString() + " - " +
                            loCompiled.Errors[x].ErrorText;

                        throw new CompileException("Errors compiling '"+filename+"':\n\n"+lcErrorMsg);
                    }
                    loAssembly = loCompiled.CompiledAssembly;
                }

                Timingutil.start("createInstance");

                object loObject  = loAssembly.CreateInstance("Page");

                CacheObject cacheObject = new CacheObject(loObject,filemtime);

                codefileCache.Add(filename,cacheObject);
                Timingutil.stop();
        }
Пример #50
0
        protected override bool DoDownload()
        {
            string strImgURL = ImageLinkURL;

            if (EventTable.ContainsKey(strImgURL))
            {
                return(true);
            }

            string strFilePath = string.Empty;

            strFilePath = strImgURL.Substring(strImgURL.IndexOf("_") + 1).Replace(".html", "");

            try
            {
                if (!Directory.Exists(SavePath))
                {
                    Directory.CreateDirectory(SavePath);
                }
            }
            catch (IOException ex)
            {
                //MainForm.DeleteMessage = ex.Message;
                //MainForm.Delete = true;

                return(false);
            }

            strFilePath = Path.Combine(SavePath, Utility.RemoveIllegalCharecters(strFilePath));


            CacheObject CCObj = new CacheObject();

            CCObj.IsDownloaded = false;
            CCObj.FilePath     = strFilePath;
            CCObj.Url          = strImgURL;
            try
            {
                EventTable.Add(strImgURL, CCObj);
            }
            catch (ThreadAbortException)
            {
                return(true);
            }
            catch (Exception)
            {
                if (EventTable.ContainsKey(strImgURL))
                {
                    return(false);
                }
                else
                {
                    EventTable.Add(strImgURL, CCObj);
                }
            }

            string strNewURL = string.Empty;

            string sPage = GetImageHostPage(ref strImgURL);



            int iStartSRC = 0;
            int iEndSRC   = 0;

            iStartSRC = sPage.IndexOf("<span id=imagecode style=\"visibility:visible\"><img src=\"");

            if (iStartSRC < 0)
            {
                return(false);
            }

            iStartSRC += 56;

            iEndSRC = sPage.IndexOf("\"", iStartSRC);

            if (iEndSRC < 0)
            {
                return(false);
            }

            strNewURL = sPage.Substring(iStartSRC, iEndSRC - iStartSRC);


            //////////////////////////////////////////////////////////////////////////

            string NewAlteredPath = Utility.GetSuitableName(strFilePath);

            if (strFilePath != NewAlteredPath)
            {
                strFilePath = NewAlteredPath;
                ((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath;
            }

            try
            {
                WebClient client = new WebClient();
                client.Headers.Add("Referer: " + strImgURL);
                client.Headers.Add("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6");
                client.DownloadFile(strNewURL, strFilePath);

                client.Dispose();
            }
            catch (ThreadAbortException)
            {
                ((CacheObject)EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL);

                return(true);
            }
            catch (IOException ex)
            {
                //MainForm.DeleteMessage = ex.Message;
                //MainForm.Delete = true;

                ((CacheObject)EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL);

                return(true);
            }
            catch (WebException)
            {
                ((CacheObject)EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL);

                return(false);
            }

            ((CacheObject)EventTable[ImageLinkURL]).IsDownloaded = true;
            //CacheController.GetInstance().u_s_LastPic = ((CacheObject)eventTable[mstrURL]).FilePath;
            CacheController.Instance().LastPic = ((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath;

            return(true);
        }
        private void GetSettingsValue(int multipleChoiceId, CacheObject cacheObjectType, out object cacheValue)
        {
            using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
            {
                using (NpgsqlCommand cmd = con.CreateCommand())
                {
                    cmd.CommandText = "SELECT * FROM \"MultipleChoiceOptions\" WHERE id=:id";
                    cmd.Parameters.Add("id", multipleChoiceId);

                    NpgsqlDataReader reader = PostgreSQLConn.ExecuteReader(cmd, Parent.CurrentUser);
                    reader.Read();

                    int? mid = DbValueConverter.Convert<int>(reader["id"]);
                    bool? allowMultipleCorrectAnswers = DbValueConverter.Convert<bool>(reader["allow_multiple_correct_answers"]);
                    bool? allowRandomDistractors = DbValueConverter.Convert<bool>(reader["allow_random_distractors"]);
                    int? maxCorrectAnswers = DbValueConverter.Convert<int>(reader["max_correct_answers"]);
                    int? numberOfChoices = DbValueConverter.Convert<int>(reader["number_of_choices"]);

                    //cache values
                    DateTime expires = DateTime.Now.Add(Cache.DefaultSettingsValidationTime);
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsMultipleChoiceOptionsAllowMultipleCorrectAnswers, multipleChoiceId, expires)] = allowMultipleCorrectAnswers;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsMultipleChoiceOptionsAllowRandomDistractors, multipleChoiceId, expires)] = allowRandomDistractors;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsMultipleChoiceOptionsMaxCorrectAnswers, multipleChoiceId, expires)] = maxCorrectAnswers;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsMultipleChoiceOptionsNumberOfChoices, multipleChoiceId, expires)] = numberOfChoices;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsMultipleChoiceOptionsId, multipleChoiceId, expires)] = mid;

                    //set output value
                    switch (cacheObjectType)
                    {
                        case CacheObject.SettingsMultipleChoiceOptionsAllowMultipleCorrectAnswers: cacheValue = allowMultipleCorrectAnswers; break;
                        case CacheObject.SettingsMultipleChoiceOptionsAllowRandomDistractors: cacheValue = allowRandomDistractors; break;
                        case CacheObject.SettingsMultipleChoiceOptionsMaxCorrectAnswers: cacheValue = maxCorrectAnswers; break;
                        case CacheObject.SettingsMultipleChoiceOptionsNumberOfChoices: cacheValue = numberOfChoices; break;
                        case CacheObject.SettingsMultipleChoiceOptionsId: cacheValue = mid; break;
                        default: cacheValue = null; break;
                    }
                }
            }
        }
Пример #52
0
        ///<summary>
        ///Resets/Updates cache and misc vars
        ///</summary>
        private void InitObjectRefresh()
        {
            //Cache last target only if current target is not avoidance (Movement).
            LastCachedTarget = CurrentTarget != null ? CurrentTarget : ObjectCache.FakeCacheObject;

            if (CurrentTarget != null && CurrentTarget.targetType.HasValue && ObjectCache.CheckTargetTypeFlag(CurrentTarget.targetType.Value, TargetType.AvoidanceMovements))
            {
                if (CurrentTarget.targetType.Value == TargetType.Fleeing)
                {
                    LastFleeAction    = DateTime.Now;
                    FleeingLastTarget = true;
                }
                else
                {
                    LastAvoidanceMovement = DateTime.Now;
                    AvoidanceLastTarget   = true;
                }
            }
            else
            {
                FleeingLastTarget   = false;
                AvoidanceLastTarget = false;
            }

            //Traveling Flag Reset
            TravellingAvoidance = false;

            //Reset target
            CurrentTarget     = null;
            CurrentUnitTarget = null;



            //Kill Loot Radius Update
            UpdateKillLootRadiusValues();

            // Refresh buffs (so we can check for wrath being up to ignore ice balls and anything else like that)
            Bot.Character.Class.HotBar.RefreshHotbarBuffs();


            // Bunch of variables used throughout
            Bot.Character.Data.PetData.Reset();
            // Reset the counters for monsters at various ranges
            Environment.Reset();



            //Check if we should trim our SNO cache..
            if (DateTime.Now.Subtract(ObjectCache.cacheSnoCollection.lastTrimming).TotalMilliseconds > Bot.Settings.Plugin.UnusedSNORemovalRate)
            {
                ObjectCache.cacheSnoCollection.TrimOldUnusedEntries();
            }


            //Check Cached Object Removal flag
            if (RemovalCheck)
            {
                //Remove flagged objects
                var RemovalObjs = (from objs in ObjectCache.Objects.Values
                                   where objs.NeedsRemoved
                                   select objs.RAGUID).ToList();

                foreach (var item in RemovalObjs)
                {
                    CacheObject thisObj = ObjectCache.Objects[item];

                    //remove prioritized raguid
                    if (Bot.NavigationCache.PrioritizedRAGUIDs.Contains(item))
                    {
                        Bot.NavigationCache.PrioritizedRAGUIDs.Remove(item);
                    }

                    //Blacklist flag check
                    if (thisObj.BlacklistFlag != BlacklistType.None)
                    {
                        BlacklistCache.AddObjectToBlacklist(thisObj.RAGUID, thisObj.BlacklistFlag);
                    }

                    ObjectCache.Objects.Remove(thisObj.RAGUID);
                }

                RemovalCheck = false;
            }


            //Increase counter, clear entries if overdue.
            ObjectCache.Obstacles.AttemptToClearEntries();

            //Non-Combat behavior we reset temp blacklist so we don't get killed by "ignored" units..
            if (Bot.IsInNonCombatBehavior)
            {
                BlacklistCache.CheckRefreshBlacklists(10);
            }

            //Check Gold Inactivity
            Bot.Game.GoldTimeoutChecker.CheckTimeoutTripped();
        }
Пример #53
0
        public static Hashtable getXsltParameters(string filepath1,string filepath2,string httphost)
        {
            DateTime filemtime = File.GetLastWriteTime(filepath2);

            // the lock synchronizes the access to the static members of this class,
            // cause it may happen that multiple threads want to access this at the same time
            // which may cause to load the file more than one

            lock(lock1)
            {
                if (
                    parameterCache.Contains(httphost) && ((CacheObject)parameterCache[httphost]).mtime == filemtime
                )
                {
                    return (Hashtable)((Hashtable)((CacheObject)parameterCache[httphost]).content).Clone();
                }
                else
                {
                    Timingutil.start("read parameter file");
                    XmlDocument doc = new XmlDocument();

                    {

                        XslTransform transformer = new XslTransform();
                        XmlDocument doc1 = new XmlDocument();
                        doc1.Load(filepath1);
                        transformer.Load(doc1.CreateNavigator(),null,null);

                        XmlDocument inputDoc = new XmlDocument();
                        inputDoc.Load(filepath2);

                        XmlReader reader = null;
                        reader = transformer.Transform(inputDoc, new XsltArgumentList(),(XmlResolver)null);

                        XmlDocument doc2 = new XmlDocument();
                        doc2.Load(reader);

                        //Console.Error.WriteLine(doc2.InnerXml);

                        transformer.Load(doc2.CreateNavigator(),null,null);

                        XmlDocument tmpDoc = new XmlDocument();
                        tmpDoc.AppendChild(tmpDoc.CreateNode(XmlNodeType.Element, "root", null));
                        reader = transformer.Transform(tmpDoc, new XsltArgumentList(),(XmlResolver)null);

                        doc.Load(reader);
                        //Console.Error.WriteLine(doc.InnerXml);
                    }

                    Hashtable xsltParameters = new Hashtable();

                    IEnumerator paramEnum = doc.GetElementsByTagName("parameters")[0].SelectSingleNode("global").SelectNodes("param").GetEnumerator();

                    while (paramEnum.MoveNext())
                    {
                        //Console.Error.WriteLine("loop param");
                        xsltParameters.Add(((XmlNode)paramEnum.Current).Attributes["key"].InnerText,((XmlNode)paramEnum.Current).Attributes["value"].InnerText);
                    }
                    //XmlElement nodeList = (XmlElement)doc.GetElementsByTagName("parameters")[0];
                    //Console.Error.WriteLine(nodeList.InnerXml);

                    Console.Error.WriteLine(httphost);

                    //Console.Error.WriteLine("scan2");

                    IEnumerator paramEnum5 = doc.GetElementsByTagName("parameters")[0].SelectNodes("domaingroup").GetEnumerator();
                    while (paramEnum5.MoveNext())
                    {
                        //Console.Error.WriteLine("loop domaingroup");

                        IEnumerator paramEnum2 = ((XmlNode)paramEnum5.Current).SelectNodes("domain").GetEnumerator();
                        while (paramEnum2.MoveNext())
                        {
                            //Console.Error.WriteLine("loop domains");
                            if ( ((XmlNode)paramEnum2.Current).Attributes["name"].InnerText == httphost )
                            {
                                //Console.Error.WriteLine("hostmatch");

                                IEnumerator paramEnum4 = ((XmlNode)paramEnum5.Current).SelectNodes("param").GetEnumerator();

                                while (paramEnum4.MoveNext())
                                {
                                    //Console.Error.WriteLine("loop params in group");
                                    if(xsltParameters.Contains(((XmlNode)paramEnum4.Current).Attributes["key"].InnerText))
                                    {
                                        xsltParameters.Remove(((XmlNode)paramEnum4.Current).Attributes["key"].InnerText);
                                    }
                                    xsltParameters.Add(((XmlNode)paramEnum4.Current).Attributes["key"].InnerText,((XmlNode)paramEnum4.Current).Attributes["value"].InnerText);
                                }

                                IEnumerator paramEnum3 = ((XmlNode)paramEnum2.Current).SelectNodes("param").GetEnumerator();

                                while (paramEnum3.MoveNext())
                                {
                                    //Console.Error.WriteLine("loop params in domain");

                                    if(xsltParameters.Contains(((XmlNode)paramEnum3.Current).Attributes["key"].InnerText))
                                    {
                                        xsltParameters.Remove(((XmlNode)paramEnum3.Current).Attributes["key"].InnerText);
                                    }

                                    xsltParameters.Add(((XmlNode)paramEnum3.Current).Attributes["key"].InnerText,((XmlNode)paramEnum3.Current).Attributes["value"].InnerText);
                                }

                            }
                        }

                    }

                    if(parameterCache.Contains(httphost))
                    {
                        parameterCache.Remove(httphost);
                    }
                    CacheObject cacheObject = new CacheObject(xsltParameters,filemtime);
                    parameterCache.Add(httphost,cacheObject);

                    Timingutil.stop();

                    return (Hashtable)xsltParameters.Clone();
                }
            }
        }
Пример #54
0
 public TargetChangedArgs(CacheObject newobj, TargetBehavioralTypes sendingtype)
 {
     newObject          = newobj;
     targetBehaviorUsed = sendingtype;
 }
        private void GetSettingsValue(int queryDirectionsId, CacheObject cacheObjectType, out object cacheValue)
        {
            using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
            {
                using (NpgsqlCommand cmd = con.CreateCommand())
                {
                    cmd.CommandText = "SELECT * FROM \"QueryDirections\" WHERE id=:id";
                    cmd.Parameters.Add("id", queryDirectionsId);

                    NpgsqlDataReader reader = PostgreSQLConn.ExecuteReader(cmd, Parent.CurrentUser);
                    reader.Read();

                    int? did = DbValueConverter.Convert<int>(reader["id"]);
                    bool? questionToAnswer = DbValueConverter.Convert<bool>(reader["question2answer"]);
                    bool? answerToQuestion = DbValueConverter.Convert<bool>(reader["answer2question"]);
                    bool? mixed = DbValueConverter.Convert<bool>(reader["mixed"]);

                    //cache values
                    DateTime expires = DateTime.Now.Add(Cache.DefaultSettingsValidationTime);
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsQueryDirectionsQuestion2Answer, queryDirectionsId, expires)] = questionToAnswer;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsQueryDirectionsAnswer2Question, queryDirectionsId, expires)] = answerToQuestion;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsQueryDirectionsMixed, queryDirectionsId, expires)] = mixed;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsQueryDirectionsId, queryDirectionsId, expires)] = did;

                    //set output value
                    switch (cacheObjectType)
                    {
                        case CacheObject.SettingsQueryDirectionsQuestion2Answer: cacheValue = questionToAnswer; break;
                        case CacheObject.SettingsQueryDirectionsAnswer2Question: cacheValue = answerToQuestion; break;
                        case CacheObject.SettingsQueryDirectionsMixed: cacheValue = mixed; break;
                        case CacheObject.SettingsQueryDirectionsId: cacheValue = did; break;
                        default: cacheValue = null; break;
                    }
                }
            }
        }
Пример #56
0
        /// <summary>
        /// Gets the settings value.
        /// </summary>
        /// <param name="typeGradingsId">The type gradings id.</param>
        /// <param name="cacheObjectType">Type of the cache object.</param>
        /// <param name="cacheValue">The cache value.</param>
        /// <remarks>Documented by Dev08, 2009-01-13</remarks>
        private void GetSettingsValue(int typeGradingsId, CacheObject cacheObjectType, out object cacheValue)
        {
            using (SqlCeCommand cmd = MSSQLCEConn.CreateCommand(parent.CurrentUser))
            {
                cmd.CommandText = "SELECT * FROM \"TypeGradings\" WHERE id=@id";
                cmd.Parameters.Add("@id", typeGradingsId);

                SqlCeDataReader reader = MSSQLCEConn.ExecuteReader(cmd);
                reader.Read();

                int? gid = DbValueConverter.Convert<int>(reader["id"]);
                bool? allCorrect = DbValueConverter.Convert<bool>(reader["all_correct"]);
                bool? halfCorrect = DbValueConverter.Convert<bool>(reader["half_correct"]);
                bool? noneCorrect = DbValueConverter.Convert<bool>(reader["none_correct"]);
                bool? prompt = DbValueConverter.Convert<bool>(reader["prompt"]);
                reader.Close();

                //cache values
                DateTime expires = DateTime.Now.Add(Cache.DefaultSettingsValidationTime);
                parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsTypeGradingsAllCorrect, typeGradingsId, expires)] = allCorrect;
                parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsTypeGradingsHalfCorrect, typeGradingsId, expires)] = halfCorrect;
                parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsTypeGradingsNoneCorrect, typeGradingsId, expires)] = noneCorrect;
                parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsTypeGradingsPrompt, typeGradingsId, expires)] = prompt;
                parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsTypeGradingsId, typeGradingsId, expires)] = gid;

                //set output value
                switch (cacheObjectType)
                {
                    case CacheObject.SettingsTypeGradingsAllCorrect: cacheValue = allCorrect; break;
                    case CacheObject.SettingsTypeGradingsHalfCorrect: cacheValue = halfCorrect; break;
                    case CacheObject.SettingsTypeGradingsNoneCorrect: cacheValue = noneCorrect; break;
                    case CacheObject.SettingsTypeGradingsPrompt: cacheValue = prompt; break;
                    case CacheObject.SettingsTypeGradingsId: cacheValue = gid; break;
                    default: cacheValue = null; break;
                }
            }
        }
Пример #57
0
 /// <summary>
 /// Settingses the cached.
 /// </summary>
 /// <param name="typeGradingsId">The type gradings id.</param>
 /// <param name="cacheObjectType">Type of the cache object.</param>
 /// <param name="cacheValue">The cache value.</param>
 /// <returns></returns>
 /// <remarks>Documented by Dev08, 2009-01-13</remarks>
 private bool SettingsCached(int typeGradingsId, CacheObject cacheObjectType, out object cacheValue)
 {
     int? typeGradingsIdCached = parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.SettingsTypeGradingsId, typeGradingsId)] as int?;
     cacheValue = parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(cacheObjectType, typeGradingsId)];
     return typeGradingsIdCached.HasValue && (cacheValue != null);
 }
Пример #58
0
        protected override bool DoDownload()
        {
            string strImgURL = ImageLinkURL;

            if (EventTable.ContainsKey(strImgURL))
            {
                return(true);
            }

            string strFilePath = string.Empty;

            try
            {
                if (!Directory.Exists(SavePath))
                {
                    Directory.CreateDirectory(SavePath);
                }
            }
            catch (IOException ex)
            {
                //MainForm.DeleteMessage = ex.Message;
                //MainForm.Delete = true;

                return(false);
            }

            CacheObject ccObj = new CacheObject
            {
                IsDownloaded = false,
                FilePath     = strFilePath,
                Url          = strImgURL
            };

            try
            {
                EventTable.Add(strImgURL, ccObj);
            }
            catch (ThreadAbortException)
            {
                return(true);
            }
            catch (Exception)
            {
                if (EventTable.ContainsKey(strImgURL))
                {
                    return(false);
                }

                EventTable.Add(strImgURL, ccObj);
            }

            const string sStartTitle = "<title>Kemipic - Earn money by sharing pictures, images - ";

            string sPage = GetImageHostPage(ref strImgURL);

            if (sPage.Length < 10)
            {
                return(false);
            }

            int iStartSrc = sPage.IndexOf(sStartTitle);

            if (iStartSrc < 0)
            {
                return(false);
            }

            iStartSrc += sStartTitle.Length;

            int iEndSrc = sPage.IndexOf(" - </title>", iStartSrc);

            if (iEndSrc < 0)
            {
                return(false);
            }

            strFilePath = sPage.Substring(iStartSrc, iEndSrc - iStartSrc);

            string strNewURL = strImgURL.Replace("share", "image").Replace(".html", strFilePath.Substring(strFilePath.LastIndexOf(".")));

            strFilePath = Path.Combine(SavePath, Utility.RemoveIllegalCharecters(strFilePath));

            //////////////////////////////////////////////////////////////////////////

            try
            {
                string sNewAlteredPath = Utility.GetSuitableName(strFilePath);
                if (strFilePath != sNewAlteredPath)
                {
                    strFilePath = sNewAlteredPath;
                    ((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath;
                }

                WebClient client = new WebClient();
                client.Headers.Add("Referer: " + strImgURL);
                client.Headers.Add("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6");
                client.DownloadFile(strNewURL, strFilePath);

                client.Dispose();
            }
            catch (ThreadAbortException)
            {
                ((CacheObject)EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL);

                return(true);
            }
            catch (IOException ex)
            {
                //MainForm.DeleteMessage = ex.Message;
                //MainForm.Delete = true;

                ((CacheObject)EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL);

                return(true);
            }
            catch (WebException)
            {
                ((CacheObject)EventTable[strImgURL]).IsDownloaded = false;
                ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL);

                return(false);
            }

            ((CacheObject)EventTable[ImageLinkURL]).IsDownloaded = true;
            //CacheController.GetInstance().u_s_LastPic = ((CacheObject)eventTable[mstrURL]).FilePath;
            CacheController.Instance().LastPic = ((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath;

            return(true);
        }
Пример #59
0
 /// <summary>
 /// Checks if a given setting value is cached and outputs the value.
 /// </summary>
 /// <param name="settingsId">The settings Id.</param>
 /// <param name="cacheObjectType">Type of the cache object.</param>
 /// <param name="cacheValue">The cache value.</param>
 /// <returns>[true] if cached.</returns>
 /// <remarks>Documented by Dev03, 2008-11-26</remarks>
 private bool SettingsCached(int settingsId, CacheObject cacheObjectType, out object cacheValue)
 {
     bool? isCached = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.SettingsIsCached, settingsId)] as bool?;
     cacheValue = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(cacheObjectType, settingsId)];
     return isCached.HasValue && (cacheValue != null);
 }
        /// <summary>
        /// Gets the settings value.
        /// </summary>
        /// <param name="synonymsGradingId">The synonyms grading id.</param>
        /// <param name="cacheObjectType">Type of the cache object.</param>
        /// <param name="cacheValue">The cache value.</param>
        /// <remarks>Documented by Dev08, 2009-01-13</remarks>
        private void GetSettingsValue(int synonymsGradingId, CacheObject cacheObjectType, out object cacheValue)
        {
            using (SqlCeCommand cmd = MSSQLCEConn.CreateCommand(parent.CurrentUser))
            {
                cmd.CommandText = "SELECT * FROM \"SynonymGradings\" WHERE id=@id";
                cmd.Parameters.Add("@id", synonymsGradingId);

                SqlCeDataReader reader = MSSQLCEConn.ExecuteReader(cmd);
                reader.Read();

                int? sid = DbValueConverter.Convert<int>(reader["id"]);
                bool? allKnown = DbValueConverter.Convert<bool>(reader["all_known"]);
                bool? halfKnown = DbValueConverter.Convert<bool>(reader["half_known"]);
                bool? oneKnown = DbValueConverter.Convert<bool>(reader["one_known"]);
                bool? firstKnown = DbValueConverter.Convert<bool>(reader["first_known"]);
                bool? prompt = DbValueConverter.Convert<bool>(reader["prompt"]);
                reader.Close();

                //save all values to cache
                DateTime expires = DateTime.Now.Add(Cache.DefaultSettingsValidationTime);
                parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSynonymGradingsAllKnown, synonymsGradingId, expires)] = allKnown;
                parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSynonymGradingsHalfKnown, synonymsGradingId, expires)] = halfKnown;
                parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSynonymGradingsOneKnown, synonymsGradingId, expires)] = oneKnown;
                parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSynonymGradingsFirstKnown, synonymsGradingId, expires)] = firstKnown;
                parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSynonymGradingsPrompt, synonymsGradingId, expires)] = prompt;
                parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSynonymGradingsId, synonymsGradingId, expires)] = sid;

                //set output value (the call by reference parameter)
                switch (cacheObjectType)
                {
                    case CacheObject.SettingsSynonymGradingsAllKnown: cacheValue = allKnown; break;
                    case CacheObject.SettingsSynonymGradingsHalfKnown: cacheValue = halfKnown; break;
                    case CacheObject.SettingsSynonymGradingsOneKnown: cacheValue = oneKnown; break;
                    case CacheObject.SettingsSynonymGradingsFirstKnown: cacheValue = firstKnown; break;
                    case CacheObject.SettingsSynonymGradingsPrompt: cacheValue = prompt; break;
                    case CacheObject.SettingsSynonymGradingsId: cacheValue = sid; break;
                    default: cacheValue = null; break;
                }
            }
        }