示例#1
0
        /// <summary>
        /// AES256解密
        /// </summary>
        /// <param name="toDecrypt"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string AES256Decrypt(string toDecrypt, string key)
        {
            if (string.IsNullOrEmpty(toDecrypt) || string.IsNullOrEmpty(key))
            {
                return(null);
            }
            string toDecryptRaw = string.Empty;

            try
            {
                var             toDecryptArray = Convert.FromBase64String(toDecrypt);
                RijndaelManaged rm             = new RijndaelManaged
                {
                    Key     = Encoding.UTF8.GetBytes(key),
                    Mode    = CipherMode.ECB,
                    Padding = PaddingMode.PKCS7
                };
                var cryptoTransform = rm.CreateDecryptor();
                var resultArray     = cryptoTransform.TransformFinalBlock(toDecryptArray, 0, toDecryptArray.Length);
                toDecryptRaw = Encoding.UTF8.GetString(resultArray);
            }
            catch (Exception ex)
            {
                LOG.Error(LOG.ST.Day, "AES256", ex.StackTrace);
            }

            return(toDecryptRaw);
        }
 protected void SavePolicies(object sender, EventArgs e)
 {
     try
     {
         if (_dataItem != null)
         {
             IList <UserAccessPolicy> oldPolicies = _dataItem.Policies;
             try
             {
                 _dataItem.Policies = GetPolicies();
                 _dataItem          = _dataItemService.Save(_dataItem, VisitHelper.GetVisit());
             }
             catch
             {
                 _dataItem.Policies = oldPolicies;
                 throw;
             }
         }
         ResponseRedirect("../Secure/SecurityPolicy.aspx");
     }
     catch (Exception ex)
     {
         LOG.Error(ex.Message, ex);
         divPageError.Visible   = true;
         divPageError.InnerText = UIUtility.ParseException(ex);
     }
 }
        protected void OnSaveUser(object sender, EventArgs e)
        {
            if (!this.IsValid)
            {
                // Error on page, get out of here
                return;
            }
            try
            {
                AssignEditUserAccount(true);

                ICollection <FlowNameAndRole> permissionedFlows = GetPermissionedFlows();
                SystemRoleType role     = EnumUtils.FromDescription <SystemRoleType>(roleCtrl.SelectedValue);
                bool           isActive = activeCtrl.Checked;
                _accountService.BulkAddUser(_editUserAccount.NaasAccount, false, string.Empty, role,
                                            permissionedFlows, isActive, VisitHelper.GetVisit());

                ResponseRedirect("../Secure/SecurityUser.aspx");
            }
            catch (Exception ex)
            {
                LOG.Error(ex.Message, ex);
                SetDivPageError(ex);
            }
        }
示例#4
0
        public void StaticLogTest()
        {
            try
            {
                LOG.Error("this should not work");
            }
            catch (Exception e)
            {
                Assert.AreEqual(typeof(NotInitializedException), e.GetType());
            }
            using (new AsyncLOGInstance(true, SyncType.EventWaitHandle, true, new[] { new TestOutputter() }))
            {
                _testingSeverity = LogSeverity.Error;
                _testingMessage  = "test Message";
                _testingTag      = "TTag";
                LOG.Error(_testingMessage, _testingTag);
            }

            _testingSeverity = LogSeverity.Debug;
            _testingMessage  = null;
            _testingTag      = null;
            try
            {
                LOG.Error("this should not work");
            }
            catch (Exception e)
            {
                Assert.AreEqual(typeof(NotInitializedException), e.GetType());
            }
        }
示例#5
0
        private void ParsePresenceContent(SubscriptionEventArgs e)
        {
            try
            {
                if (ContentType.MULTIPART_RELATED.Equals(e.ContentType) && (e.GetExtra(SubscriptionEventArgs.EXTRA_CONTENTYPE_TYPE) as String).Contains(ContentType.RLMI))
                {
                    String boundary = e.GetExtra(SubscriptionEventArgs.EXTRA_CONTENTYPE_BOUNDARY) as String;
                    // to support both \r\n and \n\n
                    String[] contents = Encoding.UTF8.GetString(e.Content).Split(new String[] { ("\n--" + boundary), ("\r--" + boundary) }, StringSplitOptions.RemoveEmptyEntries);
                    int      indexStart, indexEnd, contentStart;
                    String   contentType;
                    foreach (String content in contents)
                    {
                        String _content = content.Trim();
                        if (_content == String.Empty)
                        {
                            continue;
                        }
                        indexStart = _content.IndexOf("Content-Type:", StringComparison.InvariantCultureIgnoreCase);
                        if (indexStart == -1)
                        {
                            continue;
                        }
                        indexEnd = _content.IndexOf("\n", indexStart);
                        if (indexEnd == -1)
                        {
                            continue;
                        }
                        contentType = _content.Substring(indexStart + 13, (indexEnd - indexStart - 13)).Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[0].Trim();

                        if ((contentStart = _content.IndexOf("\r\n\r\n")) == -1 && (contentStart = _content.IndexOf("\n\n\r\n")) == -1)
                        {
                            continue;
                        }
                        _content = _content.Substring(contentStart).Trim();

                        if (ContentType.RLMI.Equals(contentType, StringComparison.InvariantCultureIgnoreCase))
                        {
                            this.ParseRLMI(Encoding.UTF8.GetBytes(_content));
                        }
                        else if (ContentType.PIDF.Equals(contentType, StringComparison.InvariantCultureIgnoreCase))
                        {
                            this.ParsePidf(Encoding.UTF8.GetBytes(_content));
                        }
                    }
                }
                else if (ContentType.RLMI.Equals(e.ContentType))
                {
                    this.ParseRLMI(e.Content);
                }
                else if (ContentType.PIDF.Equals(e.ContentType))
                {
                    this.ParsePidf(e.Content);
                }
            }
            catch (Exception ex)
            {
                LOG.Error(ex);
            }
        }
示例#6
0
 private void SendComplete(IAsyncResult ar)
 {
     try
     {
         int len = _socket.EndSend(ar);
         if (len == 0)
         {
             return;
         }
         lock (this)
         {
             sendStreams.Clear();
             if (waitStreams.Count > 0)
             {
                 IList <ArraySegment <byte> > temp = sendStreams;
                 sendStreams = waitStreams;
                 waitStreams = temp;
                 _socket.BeginSend(sendStreams, SocketFlags.None, SendComplete, null);
             }
         }
     }
     catch (Exception e)
     {
         LOG.Error("tcp SendComplete exception :{0}", e.ToString());
     }
 }
示例#7
0
        protected override void OnInitializeControls(EventArgs e)
        {
            base.OnInitializeControls(e);

            if (!this.IsPostBack)
            {
                try
                {
                    ChartTop.Display(_chartConfig);
                }
                catch (Exception ex)
                {
                    LOG.Error("Failed to load ChartTop.Display()", ex);
                }
                try
                {
                    NewsSideBar.Display(_rssFeedUrl + "?q=" + GetUsageStatsParamString());
                }
                catch (Exception ex)
                {
                    LOG.Error("Failed to load NewsSideBar.Display()", ex);
                }
            }
            if (!CollectionUtils.IsNullOrEmpty(_dataModel.SearchResults))
            {
                BindSearchResults();
            }
        }
示例#8
0
 private void RefreshListBox()
 {
     try
     {
         string        filter   = textNaasUserFilter.Text;
         List <string> userList = new List <string>(50);
         if (!string.IsNullOrEmpty(filter) && (_dataModel != null) && (_dataModel._userList != null))
         {
             foreach (string userName in _dataModel._userList)
             {
                 if (userName.StartsWith(filter, StringComparison.InvariantCultureIgnoreCase))
                 {
                     userList.Add(userName);
                 }
             }
         }
         listNaasUsers.DataSource = userList;
         listNaasUsers.DataBind();
     }
     catch (Exception ex)
     {
         LOG.Error(ex.Message, ex);
         divPageError.Visible   = true;
         divPageError.InnerText = UIUtility.ParseException(ex);
     }
 }
 protected void DoSearch()
 {
     if (divPageError.Visible || !Page.IsValid)
     {
         // Error on page, get out of here
         return;
     }
     try
     {
         FillSearchParams();
         _dataModel.SearchResults =
             _dataService.Search(DataItem, VisitHelper.GetVisit(), false);
         if (CollectionUtils.IsNullOrEmpty(_dataModel.SearchResults))
         {
             noItemsDiv.Visible = true;
         }
         else
         {
             noItemsDiv.Visible = false;
             foreach (Activity activity in _dataModel.SearchResults)
             {
                 activity.ModifiedById = GetUsernameById(activity.ModifiedById);
             }
             _dataModel.SearchResults.Sort(_dataModel.SortProperty, _dataModel.SortAscending);
         }
         _dataModel.PageIndex     = 0;
         _dataModel.RebindResults = true;
     }
     catch (Exception ex)
     {
         LOG.Error(ex.Message, ex);
         divPageError.Visible   = true;
         divPageError.InnerText = ExceptionUtils.GetDeepExceptionMessage(ex);
     }
 }
示例#10
0
        private String GetAvatarBase64FromFilePath(String filePath, out String mimeType)
        {
            mimeType = null;

            if (String.IsNullOrEmpty(filePath) || !File.Exists(filePath))
            {
                return(String.Empty);
            }

            String b64 = String.Empty;

            try
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    System.Drawing.Imaging.ImageFormat rawFormat;
                    System.Drawing.Image avatar;
                    if ((avatar = this.GetAvatarFromFilePath(filePath, out rawFormat)) != null)
                    {
                        avatar.Save(stream, rawFormat);
                        b64      = Convert.ToBase64String(stream.GetBuffer());
                        mimeType = this.GetAvatarMimeType(rawFormat);
                    }
                }
            }
            catch (Exception ex)
            {
                LOG.Error("Failed to resize avatar", ex);
            }

            return(b64);
        }
示例#11
0
 /// <summary>
 /// Sends schedule notifications
 /// </summary>
 /// <param name="tran"></param>
 public void DoScheduleNotifications(TransactionStatus status, string emailAddresses,
                                     string subjectLine, string scheduleName, string attachmentFile,
                                     string attachmentName, string additionalMessage)
 {
     try
     {
         if (string.IsNullOrEmpty(subjectLine))
         {
             subjectLine = GetDoScheduleSubjectLine(status, scheduleName);
         }
         if (!string.IsNullOrEmpty(attachmentFile))
         {
             using (Stream stream = File.OpenRead(attachmentFile))
             {
                 SendNotificationsPriv(null, status.Id, emailAddresses, NotificationType.OnSchedule, subjectLine,
                                       stream, attachmentName,
                                       new string[] { _serverName, FromEmailAddress, DateTime.Now.ToString(), scheduleName,
                                                      AdminInterfaceUrl, status.Id.ToString(), additionalMessage ?? string.Empty });
             }
         }
         else
         {
             SendNotificationsPriv(null, status.Id, emailAddresses, NotificationType.OnSchedule, subjectLine,
                                   null, null,
                                   new string[] { _serverName, FromEmailAddress, DateTime.Now.ToString(), scheduleName,
                                                  AdminInterfaceUrl, status.Id.ToString(), additionalMessage ?? string.Empty });
         }
     }
     catch (Exception ex)
     {
         LOG.Error(ex);
     }
 }
        private Object Deserialize(byte[] content, Type type)
        {
            Object result = null;

            if (content != null)
            {
                XmlReaderSettings settings = new XmlReaderSettings();

                using (MemoryStream stream = new MemoryStream(content))
                {
                    using (XmlReader reader = XmlReader.Create(stream, settings))
                    {
                        XmlSerializer xmlSerializer = new XmlSerializer(type);
                        try
                        {
                            result = xmlSerializer.Deserialize(reader);
                        }
                        catch (Exception e)
                        {
                            LOG.Error("Failed to deserialize xml content", e);
                        }
                    }
                }
            }
            else
            {
                LOG.Error("Null content");
            }

            return(result);
        }
示例#13
0
 /// <summary>
 /// Get icon for executable
 /// </summary>
 /// <param name="path">path to the exe or dll</param>
 /// <param name="index">index of the icon</param>
 /// <returns>Bitmap with the icon or null if something happended</returns>
 private static Bitmap GetExeIcon(string path, int index)
 {
     if (!File.Exists(path))
     {
         return(null);
     }
     try
     {
         using (Icon appIcon = ImageHelper.ExtractAssociatedIcon(path, index, conf.UseLargeIcons))
         {
             if (appIcon != null)
             {
                 return(appIcon.ToBitmap());
             }
         }
         using (Icon appIcon = Shell32.GetFileIcon(path, conf.UseLargeIcons ? Shell32.IconSize.Large : Shell32.IconSize.Small, false))
         {
             if (appIcon != null)
             {
                 return(appIcon.ToBitmap());
             }
         }
     }
     catch (Exception exIcon)
     {
         LOG.Error("error retrieving icon: ", exIcon);
     }
     return(null);
 }
示例#14
0
        static public void Update()
        {
            int count = OnDisconnectCallbacks.Count;

            Tcp.AsyncDisconnectCallback disconnectCallback;
            for (int i = 0; i < count; i++)
            {
                if (OnDisconnectCallbacks.TryDequeue(out disconnectCallback))
                {
                    if (disconnectCallback == null)
                    {
                        return;
                    }
                    else
                    {
                        try
                        {
                            disconnectCallback();
                        }
                        catch (Exception e)
                        {
                            LOG.Error(e.ToString());
                        }
                    }
                }
            }
        }
示例#15
0
 public bool Write(MemoryStream stream)
 {
     if (stream.Length == 0)
     {
         return(true);
     }
     stream.Seek(0, SeekOrigin.Begin);
     lock (this)
     {
         if (_state != (int)State.RUN)
         {
             return(false);
         }
         ArraySegment <byte> segment = new ArraySegment <byte>(stream.GetBuffer(), 0, (int)stream.Length);
         if (sendStreams.Count == 0)
         {
             sendStreams.Add(segment);
             try
             {
                 _socket.BeginSend(sendStreams, SocketFlags.None, SendComplete, null);
             }
             catch (Exception e)
             {
                 LOG.Error("tcp  Write exception :{0}", e.ToString());
                 return(false);
             }
         }
         else
         {
             waitStreams.Add(segment);
             _waitStreamsCount = waitStreams.Count;
         }
     }
     return(true);
 }
 protected void OnClickReset(object sender, EventArgs e)
 {
     try
     {
         exchangeDropDownList.SelectedValue  = NOT_SELECTED_TEXT;
         operationDropDownList.SelectedValue = NOT_SELECTED_TEXT;
         noItemsDiv.Visible       = false;
         fromDateImageButton.Text = string.Empty;
         toDateImageButton.Text   = string.Empty;
         fromDateCalendarExtender.SelectedDate = null;
         toDateCalendarExtender.SelectedDate   = null;
         activityTypeCtrl.SelectedValue        = NOT_SELECTED_TEXT;
         nodeMethodTypeDropdown.SelectedValue  = NOT_SELECTED_TEXT;
         transactionIdCtrl.Text   = string.Empty;
         fromIpCtrl.SelectedValue = NOT_SELECTED_TEXT;
         byUserCtrl.SelectedValue = NOT_SELECTED_TEXT;
         contentCtrl.Text         = string.Empty;
         _dataModel = new DataModel();
         _dataModel.SearchParams    = new ActivitySearchParams();
         _dataModel.UserIdToNameMap = DataService.GetUserIdToNameMap();
         _dataModel.RebindResults   = true;
     }
     catch (Exception ex)
     {
         LOG.Error(ex.Message, ex);
         divPageError.Visible   = true;
         divPageError.InnerText = ExceptionUtils.GetDeepExceptionMessage(ex);
     }
 }
示例#17
0
 /// <summary>
 /// 发送字节数组
 /// </summary>
 /// <param name="first">报头</param>
 /// <param name="second">报文</param>
 /// <returns></returns>
 public bool Write(ArraySegment <byte> first, ArraySegment <byte> second)
 {
     lock (this)
     {
         if (_state != (int)State.RUN)
         {
             return(false);
         }
         if (sendStreams.Count == 0)
         {
             sendStreams.Add(first);
             sendStreams.Add(second);
             try
             {
                 _socket.BeginSend(sendStreams, SocketFlags.None, SendComplete, null);
             }
             catch (Exception e)
             {
                 LOG.Error("tcp Write exception :{0}", e.ToString());
                 return(false);
             }
         }
         else
         {
             waitStreams.Add(first);
             waitStreams.Add(second);
             _waitStreamsCount = waitStreams.Count;
         }
     }
     return(true);
 }
示例#18
0
 protected void DownloadAllTempFiles(string url, string downloadDirectoryPath,
                                     NetworkUtils.DownloadProgressHandler progressCallback,
                                     object callbackParam)
 {
     try
     {
         LOG.Debug("DownloadAllTempFiles: Attempting to download files from url: {0}", url);
         string tempZipFile = MakeTempFilePath();
         NetworkUtils.DownloadFile(url, tempZipFile);
         try
         {
             _zipHelper.UncompressDirectory(tempZipFile, downloadDirectoryPath, _downloadedContentPassword);
         }
         finally
         {
             FileUtils.SafeDeleteFile(tempZipFile);
         }
         LOG.Debug("DownloadAllTempFiles: Downloaded files from url: {0}", url);
     }
     catch (Exception e)
     {
         LOG.Error("DownloadAllTempFiles: Failed to download data from url: {0}", e, url);
         throw;
     }
 }
示例#19
0
        /// <summary>
        /// Download the FavIcon as a Bitmap
        /// </summary>
        /// <param name="baseUri"></param>
        /// <returns>Bitmap with the FavIcon</returns>
        public static Bitmap DownloadFavIcon(Uri baseUri)
        {
            Uri url = new Uri(baseUri, new Uri("favicon.ico"));

            try
            {
                HttpWebRequest request = CreateWebRequest(url);
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    if (request.HaveResponse)
                    {
                        using (Stream responseStream = response.GetResponseStream())
                        {
                            if (responseStream != null)
                            {
                                using (Image image = Image.FromStream(responseStream))
                                {
                                    return((image.Height > 16 && image.Width > 16) ? new Bitmap(image, 16, 16) : new Bitmap(image));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                LOG.Error("Problem downloading the FavIcon from: " + baseUri, e);
            }
            return(null);
        }
        protected void SaveDataItem(object sender, EventArgs e)
        {
            if (divPageError.Visible || !Page.IsValid)
            {
                // Error on page, get out of here
                return;
            }
            try
            {
                _modelState.DataItem =
                    _dataItemService.Save(_modelState.DataItem, passwordCtrl.Text, VisitHelper.GetVisit());

                Button btn = sender as Button;

                if (btn != null && btn.ID == savePolicyBtn.ID)
                {
                    ResponseRedirect("../Secure/SecurityPolicyEdit.aspx?id=" + _modelState.DataItem.NaasAccount);
                }
                else
                {
                    ResponseRedirect("../Secure/SecurityUser.aspx");
                }
            }
            catch (Exception ex)
            {
                LOG.Error(ex.Message, ex);
                divPageError.Visible   = true;
                divPageError.InnerText = UIUtility.ParseException(ex);
            }
        }
示例#21
0
 /// <summary>
 /// Retrieves the cursor location safely, accounting for DPI settings in Vista/Windows 7.
 /// </summary>
 /// <returns>Point with cursor location, relative to the origin of the monitor setup
 /// (i.e. negative coordinates arepossible in multiscreen setups)</returns>
 public static Point GetCursorLocation()
 {
     if (Environment.OSVersion.Version.Major >= 6 && _CanCallGetPhysicalCursorPos)
     {
         POINT cursorLocation;
         try
         {
             if (GetPhysicalCursorPos(out cursorLocation))
             {
                 return(new Point(cursorLocation.X, cursorLocation.Y));
             }
             else
             {
                 Win32Error error = Win32.GetLastErrorCode();
                 LOG.ErrorFormat("Error retrieving PhysicalCursorPos : {0}", Win32.GetMessage(error));
             }
         }
         catch (Exception ex)
         {
             LOG.Error("Exception retrieving PhysicalCursorPos, no longer calling this. Cause :", ex);
             _CanCallGetPhysicalCursorPos = false;
         }
     }
     return(new Point(Cursor.Position.X, Cursor.Position.Y));
 }
示例#22
0
        public GameObject GetRes(string sPath)
        {
            UnityEngine.Object obj;
            if (m_mResList.ContainsKey(sPath))
            {
                obj = m_mResList[sPath];
            }
            else
            {
                obj = Resources.Load(sPath, typeof(GameObject));
                if (obj != null)
                {
                    m_mResList.Add(sPath, obj);
                }
            }

            if (obj == null)
            {
                LOG.Error("No Resource In Path=" + sPath);
                return(null);
            }

            var gameObject = (GameObject)GameObject.Instantiate(obj);

            return(gameObject);
        }
示例#23
0
        static void Main(string[] args)
        {
            Api api = new Api();

            try
            {
                api.ServerName = "BattleServer";
                api.Init(args);
            }
            catch (Exception e)
            {
                LOG.Error("{0} init failed:{1}", api.ServerName, e.ToString());
                api.Exit();
                return;
            }

            Thread thread = new Thread(api.Run);

            thread.Start();

            LOG.Info("{0} OnReady..", api.ServerName);

            while (thread.IsAlive)
            {
                api.ProcessInput();
                Thread.Sleep(1000);
            }

            api.Exit();
            LOG.Info("{0} Exit..", api.ServerName);
        }
示例#24
0
 public T GetRes <T>(string sPath) where T : UnityEngine.Object
 {
     UnityEngine.Object obj;
     if (m_mResList.ContainsKey(sPath))
     {
         obj = m_mResList[sPath];
     }
     else
     {
         obj = Resources.Load(sPath);
         if (obj != null)
         {
             m_mResList.Add(sPath, obj);
         }
     }
     if (obj != null)
     {
         return((T)obj);
     }
     else
     {
         LOG.Error(sPath + " resources  is  null");
         return(null);
     }
 }
示例#25
0
 protected virtual void UpdateScheduleRunInfo(ScheduledItem scheduledItem, Activity activity)
 {
     if (scheduledItem != null)
     {
         int count = 3;
         do
         {
             try
             {
                 if (scheduledItem.FrequencyType == ScheduledFrequencyType.OnceThenDelete)
                 {
                     ScheduleManager.Delete(scheduledItem.Id);
                 }
                 else
                 {
                     scheduledItem.LastExecutedOn        = DateTime.Now;
                     scheduledItem.LastExecuteActivityId = activity.Id;
                     scheduledItem.NextRunOn             =
                         ScheduledItem.CalcNextRunTime(scheduledItem.NextRunOn, scheduledItem.FrequencyType,
                                                       scheduledItem.Frequency, true, scheduledItem.StartOn,
                                                       scheduledItem.EndOn, scheduledItem.IsActive);
                     scheduledItem = ScheduleManager.Update(scheduledItem, false);
                 }
                 count = 0;
             }
             catch (Exception e)
             {
                 LOG.Error("Error in UpdateScheduleRunInfo().", e);
             }
         }while (--count > 0);
     }
 }
示例#26
0
        public bool Accept(ushort port)
        {
            this._port = port;
            if (_socket != null)
            {
                return(false);
            }
            if (!TcpMng.IsAvailable)
            {
                return(false);
            }
            if (Interlocked.CompareExchange(ref _state, (int)State.WAIT, (int)State.IDLE) != (int)State.IDLE)
            {
                return(false);
            }
            Socket listenSocket = TcpMng.Accept(port);

            if (listenSocket == null)
            {
                return(false);
            }
            try
            {
                listenSocket.BeginAccept(new AsyncCallback(ListenComplete), listenSocket);
                return(true);
            }
            catch (Exception e)
            {
                LOG.Error("tcp Accept exception :{0}", e.ToString());
            }
            return(false);
        }
示例#27
0
        private void ParseWatcherInfo(byte[] Content)
        {
            try
            {
                watcherinfo winfo = null;
                using (Stream stream = new MemoryStream(Content))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(watcherinfo));
                    winfo = serializer.Deserialize(stream) as watcherinfo;
                    if (winfo.watcherlist != null)
                    {
                        if (String.Equals("full", winfo.state.ToString(), StringComparison.CurrentCultureIgnoreCase))
                        {
                            this.watchers.Clear();
                        }

                        foreach (watcherlist wlist in winfo.watcherlist)
                        {
                            if (wlist.watcher == null || wlist.watcher.Length == 0)
                            {
                                continue;
                            }
                            foreach (watcher w in wlist.watcher)
                            {
                                WatcherInfo watcherInfo = this.watchers.FirstOrDefault(x =>
                                                                                       String.Equals(x.Resource, wlist.resource) && String.Equals(x.WatcherId, w.id));
                                bool isNew = (watcherInfo == null);
                                if (isNew)
                                {
                                    watcherInfo                  = new WatcherInfo();
                                    watcherInfo.Resource         = wlist.resource;
                                    watcherInfo.Package          = wlist.package;
                                    watcherInfo.WatcherId        = w.id;
                                    watcherInfo.WatcherUriString = w.Value;
                                }

                                watcherInfo.WatcherDisplayName        = w.displayname;
                                watcherInfo.WatcherDurationSubscribed = (int)((w.durationsubscribedSpecified) ? w.durationsubscribed : 0);
                                watcherInfo.WatcherEvent      = w.@event;
                                watcherInfo.WatcherExpiration = (int)((w.expirationSpecified) ? w.expiration : 0);
                                watcherInfo.WatcherStatus     = w.status;

                                if (isNew)
                                {
                                    this.watchers.Add(watcherInfo);
                                }
                            }
                        }
                    }
                }

                // Remove terminated registration
                this.watchers.RemoveAll(x =>
                                        x.WatcherStatus == watcherStatus.terminated);
            }
            catch (Exception ex)
            {
                LOG.Error(ex);
            }
        }
示例#28
0
 private void ConnectComplete(IAsyncResult ar)
 {
     if (_socket == null)
     {
         OnConnect(false);
         return;
     }
     try
     {
         _socket.EndConnect(ar);
         if (Interlocked.CompareExchange(ref _state, (int)State.RUN, (int)State.WAIT) != (int)State.WAIT)
         {
             _socket.Close();
             _socket = null;
             OnConnect(false);
             return;
         }
         _state = (int)State.RUN;
         _socket.BeginReceive(recvStream, 0, 2048, SocketFlags.None, new AsyncCallback(RecvComplete), null);
         OnConnect(true);
         return;
     }
     catch (Exception e)
     {
         LOG.Error("tcp ConnectComplete exception :{0}", e.ToString());
     }
     _socket = null;
     _state  = (int)State.IDLE;
     OnConnect(false);
 }
示例#29
0
        /// <summary>
        /// Helper method to try to get an image in the specified format from the dataObject
        /// </summary>
        /// <param name="format">string with the format</param>
        /// <param name="dataObject">IDataObject</param>
        /// <returns>Image or null</returns>
        private static Image GetImageFormat(string format, IDataObject dataObject)
        {
            MemoryStream imageStream = GetFromDataObject(dataObject, format) as MemoryStream;

            if (isValidStream(imageStream))
            {
                try
                {
                    using (FileStream fs = new FileStream(@"C:\Localdata\test.png", FileMode.OpenOrCreate))
                    {
                        imageStream.WriteTo(fs);
                    }
                    imageStream.Seek(0, SeekOrigin.Begin);
                    using (Image tmpImage = Image.FromStream(imageStream, true, true))
                    {
                        if (tmpImage != null)
                        {
                            LOG.InfoFormat("Got image with clipboard format {0} from the clipboard.", format);
                            return(ImageHelper.Clone(tmpImage));
                        }
                    }
                }
                catch (Exception streamImageEx)
                {
                    LOG.Error(string.Format("Problem retrieving {0} from clipboard.", format), streamImageEx);
                }
            }
            return(null);
        }
示例#30
0
        public bool Init(string ip, string database, string username, string password, string port)
        {
            m_cReconnectInfo = new ReconnectRecord();
            m_cReconnectInfo.Init(60 * 1000);
            _saveQueue       = new Queue <AbstractDBQuery>();
            _postUpdateQueue = new Queue <AbstractDBQuery>();

            this._strIp       = ip;
            this._strDatabase = database;
            this._strUsername = username;
            this._strPassword = password;
            this._strPort     = port;

            string strConn = string.Format("data source={0}; database={1}; user id={2}; password={3}; port={4}", _strIp, _strDatabase, _strUsername, _strPassword, _strPort);

            try
            {
                _conn = new MySqlConnection(strConn);
                _conn.Open();
                m_bOpened = true;
                return(true);
            }
            catch (MySqlException e)
            {
                LOG.Error(e.ToString());
                return(false);
            }
        }