Support logging activity to files.
コード例 #1
0
ファイル: Login.aspx.cs プロジェクト: sancsoft/FileZilla.NET
	void LoginButton_Click(object sender, EventArgs e)
	{
		string user = AccAccountTextBox.Text.Trim().ToLower();
		string password = AccPasswordTextBox.Text;

		ActivityLog log = new ActivityLog();

		// create a filezilla object using the active configuration
		Filezilla fz = new Filezilla(settings.Lookup("ConfigurationFile"));
		if (!fz.Authenticate(user, password))
		{
			log.LogActivity(LogAction.Login, user, "authentication failed");

			LoginValidator.IsValid = false;
			return;
		}

		log.LogActivity(LogAction.Login, user);

		// Set the session vars
		Session["FZNET_USER"] = user;
		Session["FZNET_SILVERLIGHT"] = IsSilverlightHidden.Value;

		// Redirect to the home page
		Response.Redirect("Default.aspx");
	}
コード例 #2
0
ファイル: IActivitiyLogService.cs プロジェクト: aderman/Doco
 public void Message(ActivityLog.ActivityType type,params object [] p )
 {
     var log = new ActivityLog()
                   {
                       LogContent = ActivityLogHelper.ApplyMessage(type, p),
                       AType = type,
                       LogTime = DateTime.Now,
                       UserName = "******"
                   };
     AddNewLogRecord(log);
 }
コード例 #3
0
ファイル: ActivityLog.cs プロジェクト: JtheSpaceC/Space-Game
	void Awake () 
	{
		if (instance == null) 
		{
			instance = this;
		}
		else 
		{
			Debug.LogError("Duplicate instances " + gameObject.name);
			Destroy (gameObject);
		}
		CreateRandomLogEntries (40);
	}
コード例 #4
0
ファイル: Logout.aspx.cs プロジェクト: sancsoft/FileZilla.NET
    protected void Page_Load(object sender, EventArgs e)
    {
		ActivityLog log = new ActivityLog();
		log.LogActivity(LogAction.Logout, Master.UserName);

		// clear the user out of the session
		Session.Remove("FZNET_USER");
		// clear the silverlight flag
		Session.Remove("FZNET_SILVERLIGHT");
		// clear the administration flag
		Session.Remove("FZNET_ADMIN");

		Response.Redirect("~/Login.aspx");
    }
コード例 #5
0
        private async Task RequestFeeds(string feedSource)
        {
            try
            {
                await Task.Run(() => GetFeeds(feedSource));
            }
            catch (Exception ex) when(!ExceptionExtensions.IsCriticalException(ex))
            {
                MessageBox.Show(SR.GetString(SR.WebPiFeedError, feedSource, ex.Message));

                var fullMessage = SR.GetString(SR.WebPiFeedError, feedSource, ex);

                Trace.WriteLine(fullMessage);
                try
                {
                    ActivityLog.LogError("WebPiComponentPickerControl", fullMessage);
                }
                catch (InvalidOperationException)
                {
                }
            }
        }
コード例 #6
0
        public static void WriteActivity(string Action)
        {
            using (var db = new DBContext())
            {
                try
                {
                    var         UserId = (new AdminService()).GetCurrentUser().UserId;
                    ActivityLog log    = new ActivityLog();
                    log.Action     = Action;
                    log.UserId     = UserId;
                    log.IP         = CoreApp.getUserIP();
                    log.UserAgent  = CoreApp.getUserAgent();
                    log.ActionTime = DateTime.Now;

                    db.ActivityLogs.Add(log);
                    db.SaveChanges();
                }
                catch (Exception e)
                {
                }
            }
        }
コード例 #7
0
        public static void LogSend(string s, HttpRequestMessage request)
        {
            string[]   endpoint = { Program.SqsUSwestEndpoint, Program.SqsUSwest2Endpoint, Program.SqsUSeastEndpoint };
            Sqsservice sqs      = new Sqsservice();

            HttpRequestHeaders res = request.Headers;
            string             r   = res.Accept + "//" + res.AcceptCharset + "//" + res.Connection + "//" + res.Referrer + "//";

            /*  Task<DateTime> task = sqs.AsyncProessor(SqsUSeastEndpoint, Queuename);
             * for (int i = 0; i < 50; i++)
             * { task = sqs.AsyncProessor(SqsUSeastEndpoint, Queuename); }*/

            ActivityLog mess = new ActivityLog(s, DateTime.Now.ToString(CultureInfo.CurrentCulture),
                                               r);

            for (int i = 0; i < 10; i++)
            {
                Task <DateTime> task = sqs.AsyncSendtoQueue(Program.SqsUSwest2Endpoint, "api", mess);
            }

            //sqs.SendtoQueue(Program.SqsUSeastEndpoint, "api", mess);
        }
コード例 #8
0
        public static void LogofPost(Contact contact, HttpRequestMessage request)
        {
            string[]   endpoint = { Program.SqsUSwestEndpoint, Program.SqsUSwest2Endpoint, Program.SqsUSeastEndpoint };
            Sqsservice sqs      = new Sqsservice();

            HttpRequestHeaders res = request.Headers;
            string             r   = res.Accept + "//" + res.AcceptCharset + "//" + res.Connection + "//" + res.Referrer + "//";

            /*  Task<DateTime> task = sqs.AsyncProessor(SqsUSeastEndpoint, Queuename);
             * for (int i = 0; i < 50; i++)
             * { task = sqs.AsyncProessor(SqsUSeastEndpoint, Queuename); }*/

            ActivityLog mess = new ActivityLog(((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress, DateTime.Now.ToString(CultureInfo.CurrentCulture),
                                               r);

            for (int i = 0; i < 50; i++)
            {
                Task <DateTime> task = sqs.AsyncSendtoQueue(Program.SqsUSwest2Endpoint, "test", mess);
            }

            //sqs.SendtoQueue(Program.SqsUSeastEndpoint, "api", mess);
        }
コード例 #9
0
        public int SetRoleRights(List <VMRoleAccess> vMRoles, int RoleID, int UserID)
        {
            foreach (var item in vMRoles)
            {
                RoleAccessMaster roleAccess = _context.RoleAccessMasters.Where(x => x.RoleId == item.RoleId && x.RoleAccessId == item.RoleAccessId).FirstOrDefault();
                roleAccess.ViewAccess   = item.ViewAccess;
                roleAccess.CreateAccess = item.CreateAccess;
                roleAccess.UpdateAccess = item.UpdateAccess;
                roleAccess.DeleteAccess = item.DeleteAccess;
                roleAccess.UpdatedBy    = UserID;
                roleAccess.UpdatedTime  = DateTime.Now;
                _context.RoleAccessMasters.Update(roleAccess);
                _context.SaveChanges();
            }

            ActivityLog activity = new ActivityLog();

            activity.ActivityType = "access changed";
            activity.ActivityFor  = "Role";
            _logRepository.SetActivityLog(activity, RoleID, UserID);
            return(0);
        }
コード例 #10
0
        //ProcessMessage is called every time a message is received from the Websocket, here the message is interpreted and directed to the correct function
        public void ProcessMessage(object source, string message)
        {
            //The Websocket message contains an update regarding the QUOTE subscription
            //We get rid of the unnecessary part of the string and deserialise the remaining to obtain an object of BitMexWebsocketQuote type
            //We then pass the call another event to update the object through a Delegate
            //Note that the websocket message can contain several quotes at the same time so what we do is deserialize to a list and only keep the last
            //because the last is the most recent
            if (message.Contains("\"table\":\"quote\""))
            {
                try
                {
                    string search = "\"data\":";
                    int    i      = message.IndexOf(search);
                    string json   = message.Substring(i + search.Length);
                    json = json.Remove(json.Length - 1);
                    BitMexWebsocketQuote quote = JsonConvert.DeserializeObject <List <BitMexWebsocketQuote> >(json).Last();
                    OnInterpreterProcessedQuote(quote);
                    return;
                }
                catch (Exception e)
                {
                    ActivityLog.Error("WEBSOCKET INTERPRETER", e.Message);
                }
            }

            //We add this check so that we do not log API Keys in plain text in the log file
            if (message.Contains("error") && !message.Contains("authKey"))
            {
                ActivityLog.Error("WEBSOCKET INTERPRETER", message);
                return;
            }

            //We add this check so that we do not log API Keys in plain text in the log file
            if (message.Contains("error") && message.Contains("authKey"))
            {
                ActivityLog.Error("WEBSOCKET INTERPRETER", "Authentication Failed, Please Check API Keys");
                return;
            }
        }
コード例 #11
0
        public TV Create(TV param)
        {
            var entity = ViewToEntity(param);

            entity = Repository.Create(entity);
            Catalog.SaveChanges();

            var log = new ActivityLog
            {
                Active    = true,
                Operation = Operation.Create,
                Table     = nameof(TV),
                EntityId  = entity.Id,
                OnTime    = DateTime.Now.ToShortDateTime(),
                NewValue  = entity.JsonSerialize(),
            };

            Catalog.ActivityLogRepository.Create(log);
            Catalog.SaveChanges();

            return(EntityToView(entity));
        }
コード例 #12
0
 private async void SaveButton_Click(Object sender, RoutedEventArgs e)
 {
     DiscordRPforVSPackage.Settings.enabled          = (Boolean)this.IsPresenceEnabled.IsChecked;
     DiscordRPforVSPackage.Settings.showFileName     = (Boolean)this.IsFileNameShown.IsChecked;
     DiscordRPforVSPackage.Settings.showSolutionName = (Boolean)this.IsSolutionNameShown.IsChecked;
     DiscordRPforVSPackage.Settings.showTimestamp    = (Boolean)this.IsTimestampShown.IsChecked;
     DiscordRPforVSPackage.Settings.resetTimestamp   = (Boolean)this.IsTimestampResetEnabled.IsChecked;
     DiscordRPforVSPackage.Settings.largeLanguage    = (Boolean)this.IsLanguageImageLarge.IsChecked;
     DiscordRPforVSPackage.Settings.secretMode       = (Boolean)this.SecretMode.IsChecked;
     DiscordRPforVSPackage.Settings.loadOnStartup    = (Boolean)this.LoadOnStartup.IsChecked;
     DiscordRPforVSPackage.Settings.Save();
     try
     {
         await SettingsCommand.Instance.package.JoinableTaskFactory.SwitchToMainThreadAsync();
     }
     catch (OperationCanceledException exc)
     {
         ActivityLog.LogError(exc.Source, exc.Message);
     }
     await((DiscordRPforVSPackage)SettingsCommand.Instance.package).UpdatePresenceAsync(DiscordRPforVSPackage.ide.ActiveDocument, true).ConfigureAwait(true);
     this.Close();
 }
コード例 #13
0
        public static Guid add(Guid userAccountID, string name, string notes)
        {
            Guid id = Guid.NewGuid();

            using (SqlConnection sqlConnection = new SqlConnection(DBConnection.ConnectionString))
            {
                SqlQueryResult result = DBConnection.query(
                    sqlConnection,
                    QueryTypes.ExecuteNonQuery,
                    "WorkshiftCategories_add",
                    new SqlQueryParameter(COL_DB_Id, SqlDbType.UniqueIdentifier, id),
                    new SqlQueryParameter(COL_DB_Name, SqlDbType.NVarChar, name),
                    new SqlQueryParameter(COL_DB_Notes, SqlDbType.NVarChar, notes)
                    );

                if (result.IsSuccessful)
                {
                    ActivityLog.add(sqlConnection, userAccountID, id, "Added");
                }
            }
            return(id);
        }
コード例 #14
0
        public void AddRamlReference(RamlChooserActionParams parameters)
        {
            try
            {
                ActivityLog.LogInformation(VisualStudioAutomationHelper.RamlVsToolsActivityLogSource, "Add RAML Reference process started");
                var dte  = serviceProvider.GetService(typeof(SDTE)) as DTE;
                var proj = VisualStudioAutomationHelper.GetActiveProject(dte);

                InstallNugetDependencies(proj);
                ActivityLog.LogInformation(VisualStudioAutomationHelper.RamlVsToolsActivityLogSource, "Nuget Dependencies installed");

                AddFilesToProject(parameters.RamlFilePath, proj, parameters.TargetNamespace, parameters.RamlSource, parameters.TargetFileName, parameters.ClientRootClassName);
                ActivityLog.LogInformation(VisualStudioAutomationHelper.RamlVsToolsActivityLogSource, "Files added to project");
            }
            catch (Exception ex)
            {
                ActivityLog.LogError(VisualStudioAutomationHelper.RamlVsToolsActivityLogSource,
                                     VisualStudioAutomationHelper.GetExceptionInfo(ex));
                MessageBox.Show("Error when trying to add the RAML reference. " + ex.Message);
                throw;
            }
        }
コード例 #15
0
        public bool ConfirmIncomingOrder(int orderId)
        {
            using (var context = new WareMasterContext())
            {
                var orderToConfirm = context.Orders.Include(order => order.Supplier).SingleOrDefault(order => order.Id == orderId);
                if (orderToConfirm == null || orderToConfirm.Status != Status.Created)
                {
                    return(false);
                }
                orderToConfirm.Status = Status.InProgress;
                context.SaveChanges();
                var activityLog = new ActivityLog()
                {
                    CompanyId = orderToConfirm.CompanyId,
                    Text      = "Dobavljač " + orderToConfirm.Supplier.Name + " je potvrdio ulaznu narudžbu."
                };
                var activityLogRepository = new ActivityLogRepository();
                activityLogRepository.AddActivityLog(activityLog);

                return(true);
            }
        }
コード例 #16
0
        public static bool SetBrowserEmulationVersion(BrowserEmulationVersion browserEmulationVersion)
        {
            bool result;

            result = false;

            try
            {
                RegistryKey key;

                key = Registry.CurrentUser.OpenSubKey(BrowserEmulationKey, true);

                if (key != null)
                {
                    string programName;

                    programName = Path.GetFileName(Environment.GetCommandLineArgs()[0]);

                    if (browserEmulationVersion != BrowserEmulationVersion.Default)
                    {
                        // if it's a valid value, update or create the value
                        key.SetValue(programName, (int)browserEmulationVersion, RegistryValueKind.DWord);
                    }
                    else
                    {
                        // otherwise, remove the existing value
                        key.DeleteValue(programName, false);
                    }

                    result = true;
                }
            }
            catch (Exception)
            {
                ActivityLog.LogWarning(ExtensionName, "Failed to set the registry key for FEATURE_BROWSER_EMULATION");
            }

            return(result);
        }
コード例 #17
0
        public void AddReverseEngineering()
        {
            try
            {
                ActivityLog.LogInformation(VisualStudioAutomationHelper.RamlVsToolsActivityLogSource, "Enable RAML metadata output process started");
                var dte  = serviceProvider.GetService(typeof(SDTE)) as DTE;
                var proj = VisualStudioAutomationHelper.GetActiveProject(dte);

                InstallNugetAndDependencies(proj);
                ActivityLog.LogInformation(VisualStudioAutomationHelper.RamlVsToolsActivityLogSource, "Nuget package and dependencies installed");

                AddXmlCommentsDocumentation(proj);
                ActivityLog.LogInformation(VisualStudioAutomationHelper.RamlVsToolsActivityLogSource, "XML comments documentation added");
            }
            catch (Exception ex)
            {
                ActivityLog.LogError(VisualStudioAutomationHelper.RamlVsToolsActivityLogSource,
                                     VisualStudioAutomationHelper.GetExceptionInfo(ex));
                MessageBox.Show("Error when trying to enable RAML metadata output. " + ex.Message);
                throw;
            }
        }
コード例 #18
0
ファイル: PythonToolsPackage.cs プロジェクト: valsun2016/PTVS
        /// <summary>
        /// Default constructor of the package.
        /// Inside this method you can place any initialization code that does not require
        /// any Visual Studio service because at this point the package object is created but
        /// not sited yet inside Visual Studio environment. The place to do all the other
        /// initialization is the Initialize method.
        /// </summary>
        public PythonToolsPackage()
        {
            Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering constructor for: {0}", this.ToString()));

#if DEBUG
            System.Threading.Tasks.TaskScheduler.UnobservedTaskException += (sender, e) => {
                if (!e.Observed)
                {
                    var str = e.Exception.ToString();
                    if (str.Contains("Python"))
                    {
                        try {
                            ActivityLog.LogError(
                                "UnobservedTaskException",
                                string.Format("An exception in a task was not observed: {0}", e.Exception.ToString())
                                );
                        } catch (InvalidOperationException) {
                        }
                        Debug.Fail("An exception in a task was not observed. See ActivityLog.xml for more details.", e.Exception.ToString());
                    }
                    e.SetObserved();
                }
            };
#endif

            if (IsIpyToolsInstalled())
            {
                MessageBox.Show(
                    @"WARNING: Both Python Tools for Visual Studio and IronPython Tools are installed.

Only one extension can handle Python source files and having both installed will usually cause both to be broken.

You should uninstall IronPython 2.7 and re-install it with the ""Tools for Visual Studio"" option unchecked.",
                    "Python Tools for Visual Studio",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Warning
                    );
            }
        }
コード例 #19
0
ファイル: BaseAdminController.cs プロジェクト: ankn85/apex2.0
        protected ActivityLog GetActivityLog(Type objectType, object oldValue = null, object newValue = null)
        {
            var activityLog = new ActivityLog
            {
                CreatedOn         = DateTime.UtcNow,
                ObjectFullName    = objectType.FullName,
                IP                = Request.HttpContext.Connection.RemoteIpAddress.ToString(),
                ApplicationUserId = 1
            };

            if (oldValue != null)
            {
                activityLog.OldValue = ObjectToJson(oldValue);
            }

            if (newValue != null)
            {
                activityLog.NewValue = ObjectToJson(newValue);
            }

            return(activityLog);
        }
コード例 #20
0
        public static async Task PostFaultAsync(Exception e, string callerClassName, [CallerMemberName] string callerMemberName = null)
        {
            if (e == null)
            {
                throw new ArgumentNullException(nameof(e));
            }

            var caller      = $"{callerClassName}.{callerMemberName}";
            var description = $"{e.GetType().Name} - {e.Message}";

            await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            var fault = new FaultEvent($"{VSTelemetrySession.VSEventNamePrefix}Fault", description, FaultSeverity.General, e, gatherEventDetails: null);

            fault.Properties[$"{VSTelemetrySession.VSPropertyNamePrefix}Fault.Caller"] = caller;
            TelemetryService.DefaultSession.PostEvent(fault);

            if (await IsShellAvailable.GetValueAsync())
            {
                ActivityLog.TryLogError(caller, description);
            }
        }
コード例 #21
0
    public ActionResult Update(Learning oldLearning, Learning newLearning, int[] newAssistants, int userId, int companyId)
    {
        var    res       = ActionResult.NoAction;
        string extradata = Learning.Differences(oldLearning, newLearning);

        if (!string.IsNullOrEmpty(extradata))
        {
            res = newLearning.Update(userId);
            if (res.Success)
            {
                ActivityLog.Learning(newLearning.Id, userId, companyId, LearningLogActions.Modified, extradata);
                res.SetSuccess(newLearning.Id.ToString());
            }
        }

        foreach (int assistantId in newAssistants)
        {
            var newAssistant = new Assistant
            {
                CompanyId = companyId,
                Completed = null,
                Success   = null,
                Learning  = new Learning {
                    Id = newLearning.Id
                },
                Employee = new Employee(assistantId, true)
            };

            newAssistant.JobPosition = newAssistant.Employee.JobPosition;
            newAssistant.Insert(userId);
        }

        if (res.MessageError == ActionResult.NoAction.MessageError)
        {
            res.SetSuccess();
        }

        return(res);
    }
コード例 #22
0
        public void RemoveReverseEngineering()
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            try
            {
                ActivityLog.LogInformation(VisualStudioAutomationHelper.RamlVsToolsActivityLogSource, "Disable RAML metadata output process started");
                var dte  = serviceProvider.GetService(typeof(SDTE)) as DTE;
                var proj = VisualStudioAutomationHelper.GetActiveProject(dte);

                UninstallNugetAndDependencies(proj);
                ActivityLog.LogInformation(VisualStudioAutomationHelper.RamlVsToolsActivityLogSource, "Nuget package uninstalled");

                RemoveConfiguration(proj);
            }
            catch (Exception ex)
            {
                ActivityLog.LogError(VisualStudioAutomationHelper.RamlVsToolsActivityLogSource,
                                     VisualStudioAutomationHelper.GetExceptionInfo(ex));
                MessageBox.Show("Error when trying to disable RAML metadata output. " + ex.Message);
                throw;
            }
        }
コード例 #23
0
        public ActionResult Login(string returnUrl)
        {
            string loginuserType = Request.QueryString["loginUserType"];

            ViewBag.hdLoginUserType = loginuserType;
            LoginViewModel model = new LoginViewModel();

            ViewBag.ReturnUrl = returnUrl;

            if (Request.Cookies["usercode"] != null && Request.Cookies["userpassword"] != null)
            {
                model.UserName = Request.Cookies["usercode"].Value.ToString().Trim();
                //model.UserName.ToString().Attributes.Add("value", Request.Cookies["userpassword"].Value.ToString().Trim());
                model.RememberMe = true;
            }
            else
            {
                model.RememberMe = false;
            }
            ActivityLog.SetLog("LogIn Page Opened Successfully : ", LogLoc.DEBUG);
            return(View());
        }
コード例 #24
0
        public async Task FromFile()
        {
            //TODO: check
            try
            {
                txtFileName.Text = Path.GetFileName(RamlTempFilePath);

                SetDefaultClientRootClassName();

                var result   = includesManager.Manage(RamlTempFilePath, Path.GetTempPath(), Path.GetTempPath());
                var parser   = new RamlParser();
                var document = await parser.LoadRamlAsync(result.ModifiedContents, Path.GetTempPath());

                SetPreview(document);
            }
            catch (Exception ex)
            {
                ShowErrorStopProgressAndDisableOk("Error while parsing raml file. " + ex.Message);
                ActivityLog.LogError(VisualStudioAutomationHelper.RamlVsToolsActivityLogSource,
                                     VisualStudioAutomationHelper.GetExceptionInfo(ex));
            }
        }
コード例 #25
0
        private async Task RunSolutionRestoreAsync()
        {
            var cancellationTokenSource = new CancellationTokenSource();

            _cancelBuildToken = cancellationTokenSource;

            try
            {
                await GetAndActivatePackageManagerOutputWindowAsync();

                await TaskScheduler.Default;
                SB.IBrokeredServiceContainer serviceContainer = await _asyncServiceProvider.GetServiceAsync <SB.SVsBrokeredServiceContainer, SB.IBrokeredServiceContainer>();

                IServiceBroker serviceBroker = serviceContainer.GetFullAccessServiceBroker();

                INuGetSolutionService nugetSolutionService = await serviceBroker.GetProxyAsync <INuGetSolutionService>(NuGetServices.SolutionService);

                try
                {
                    await nugetSolutionService.RestoreSolutionAsync(cancellationTokenSource.Token);
                }
                finally
                {
                    (nugetSolutionService as IDisposable)?.Dispose();
                }
            }
            catch (Exception e)
            {
                // Only log to the activity log for now
                // TODO: https://github.com/NuGet/Home/issues/9352
                ActivityLog.LogError("NuGet Package Manager", e.Message);
            }
            finally
            {
                cancellationTokenSource.Dispose();
                _cancelBuildToken = null;
            }
        }
コード例 #26
0
        public ActionResult DeleteConfirmed(ReasonViewModel vm)
        {
            if (ModelState.IsValid)
            {
                var         temp = _ProductUidService.Find(vm.id);
                ActivityLog al   = new ActivityLog()
                {
                    ActivityType = (int)ActivityTypeContants.Deleted,
                    CreatedBy    = User.Identity.Name,
                    CreatedDate  = DateTime.Now,
                    DocId        = vm.id,
                    UserRemark   = vm.Reason,
                    Narration    = "Delivery terms is deleted with Name:" + temp.ProductUidName,
                    DocTypeId    = new DocumentTypeService(_unitOfWork).FindByName(TransactionDocCategoryConstants.SaleOrder).DocumentTypeId,
                    UploadDate   = DateTime.Now,
                };
                new ActivityLogService(_unitOfWork).Create(al);


                _ProductUidService.Delete(vm.id);

                try
                {
                    _unitOfWork.Save();
                }

                catch (Exception ex)
                {
                    string message = _exception.HandleException(ex);
                    ModelState.AddModelError("", message);
                    return(PartialView("_Reason", vm));
                }


                return(Json(new { success = true }));
            }
            return(PartialView("_Reason", vm));
        }
コード例 #27
0
        private void getData()
        {
            ActivityLog    log       = new ActivityLog();
            ActivityLogBll logBll    = new ActivityLogBll();
            string         host      = Request.UserHostName;
            string         ipaddress = Request.UserHostAddress;
            string         userName  = Session["user"].ToString();

            if (String.IsNullOrEmpty(ipaddress))
            {
                ipaddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            log.HostName  = host;
            log.IPAddress = ipaddress;
            log.Action    = "get data jadwal supplier";
            log.UserName  = userName;



            try
            {
                var       branchCode = ((wcf_auth.GeneralUserProfile)SessionCheck.Check(Response, Session["userprofile"])).mAuthObjectValueList.FirstOrDefault(t => t.mAuthObjectName == "REGION").Value1;
                DataTable dt         = bll.getData(branchCode.ToString());
                gvJadwalPembayaran.DataSource = dt;
                gvJadwalPembayaran.DataBind();

                log.Type        = "S";
                log.Description = "get data jadwal pembayaran sukses";
            }
            catch (Exception ex)
            {
                log.Type        = "E";
                log.Description = "get data jadwal pembayaran error :" + ex.Message;
            }
            finally {
                logBll.InsertActivity(log);
            }
        }
コード例 #28
0
        public int SubmitUserOrder(OrderMaster order)
        {
            ActivityLog.SetLog("WeddingDataImpl > SubmitUserOrder initiated for User: "******"WeddingDataImpl > Main Order is Saved. ", LogLoc.INFO);
                    foreach (var item in order.OrderDetails)
                    {
                        for (int i = 1; i <= item.Quantity; i++)
                        {
                            AddUserWeddingSubscription(order.UserID, item);
                        }
                    }
                    scope.Complete();
                }
                else
                {
                    OrderMaster myOrder = AccuitAdminDbContext.OrderMasters.Where(x => x.OrderID == order.OrderID).FirstOrDefault();
                    AccuitAdminDbContext.Entry <OrderMaster>(myOrder).State = EntityState.Modified;
                    AccuitAdminDbContext.SaveChanges();
                    scope.Complete();
                }
            }

            return(order.OrderID);
        }
コード例 #29
0
        public async void EditActivityPostSucceedsOnUpdate()
        {
            var mailer = new Mock <IEmailSender>();
            // Setup repo mock that accepts one Id but not another
            var good = new ActivityLog();

            good.Id = new Guid();
            var bad = new ActivityLog();

            bad.Id = new Guid();
            var repo = new Mock <ILogRepository>();

            repo.Setup(r => r.UpdateAsync(good)).Returns(Task.FromResult(true));
            repo.Setup(r => r.UpdateAsync(bad)).Returns(Task.FromResult(false));

            // Good guid test
            var ctrl   = new LogListsController(repo.Object, mailer.Object);
            var result = await ctrl.EditActivity(good.Id, good);

            Assert.IsType <JsonResult>(result);
            dynamic model = result.Value;

            Assert.True(model.success);

            // Bad guid test
            result = await ctrl.EditActivity(bad.Id, bad);

            Assert.IsType <JsonResult>(result);
            model = result.Value;
            Assert.False(model.success);

            // No guid test
            result = await ctrl.EditActivity(Guid.Empty, bad);

            Assert.IsType <JsonResult>(result);
            model = result.Value;
            Assert.False(model.success);
        }
コード例 #30
0
        protected override async System.Threading.Tasks.Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress)
        {
            try
            {
                await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

                ide = GetGlobalService(typeof(SDTE)) as DTE;
                ide.Events.WindowEvents.WindowActivated += this.WindowActivated;
                ide.Events.SolutionEvents.BeforeClosing += this.SolutionBeforeClosing;

                String ideVersion = ide.Version.Split(new Char[1] {
                    '.'
                })[0];
                this.versionString   = $"Visual Studio {Constants.IdeVersions[Int32.Parse(ideVersion, CultureInfo.InvariantCulture)]}";
                this.versionImageKey = $"dev{ideVersion}";

                await SettingsCommand.InitializeAsync(this).ConfigureAwait(true);

                if (!this.Discord.IsInitialized && !this.Discord.IsDisposed)
                {
                    if (!this.Discord.Initialize())
                    {
                        ActivityLog.LogError("DiscordRPforVS", "Could not start RP");
                    }
                }

                if (Settings.loadOnStartup)
                {
                    await this.UpdatePresenceAsync(ide.ActiveDocument).ConfigureAwait(true);
                }

                await base.InitializeAsync(cancellationToken, progress).ConfigureAwait(true);
            }
            catch (OperationCanceledException exc)
            {
                ActivityLog.LogError(exc.Source, exc.Message);
            }
        }
コード例 #31
0
        private void PackageRestore(ProjectPackageReferenceFile projectPackageReferenceFile)
        {
            if (HasCanceled())
            {
                return;
            }

            var repoSettings = ServiceLocator.GetInstance <IRepositorySettings>();
            var fileSystem   = new PhysicalFileSystem(repoSettings.RepositoryPath);
            var projectName  = projectPackageReferenceFile.Project.GetName();

            try
            {
                WriteLine(VerbosityLevel.Normal, Resources.RestoringPackagesForProject, projectName);
                WriteLine(VerbosityLevel.Detailed, Resources.RestoringPackagesListedInFile,
                          projectPackageReferenceFile.FullPath);
                RestorePackages(projectPackageReferenceFile.FullPath, fileSystem);
            }
            catch (Exception ex)
            {
                var exceptionMessage = _msBuildOutputVerbosity >= (int)VerbosityLevel.Detailed ?
                                       ex.ToString() :
                                       ex.Message;
                var message = String.Format(
                    CultureInfo.CurrentCulture,
                    Resources.PackageRestoreFailedForProject, projectName,
                    exceptionMessage);
                WriteLine(VerbosityLevel.Quiet, message);
                ActivityLog.LogError(LogEntrySource, message);
                VsUtility.ShowError(_errorListProvider, TaskErrorCategory.Error,
                                    TaskPriority.High, message, hierarchyItem: null);
                _hasError = true;
            }
            finally
            {
                WriteLine(VerbosityLevel.Normal, Resources.PackageRestoreFinishedForProject, projectName);
            }
        }
コード例 #32
0
        public HttpResponseMessage Update([FromBody] ActivityLogUpdateRequest activityLogUpdateRequest)
        {
            // Get the UserId of the logged in user.
            int userId = int.Parse(User.Identity.GetUserId());

            // Get the ActivityLog from the database.
            ActivityLog activityLog = (ActivityLog)_Database.ActivityLogs.SingleOrDefault(actLog => actLog.ActivityLogId == activityLogUpdateRequest.ActivityLogId);

            // Verify that the current user is the same one associated with this activityLog.
            if (activityLog.User.UserId != userId)
            {
                return(Request.CreateResponse(HttpStatusCode.Forbidden, "This log doesn't belong to the current user."));
            }

            // Update the start and end times.
            activityLog.StartTime = activityLogUpdateRequest.StartTime;
            activityLog.EndTime   = activityLogUpdateRequest.EndTime;

            // Commit the changes to the database.
            _Database.SaveChanges();

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
コード例 #33
0
        public List <ActivityLog> ActivityLog(string ActionUser)
        {
            List <ActivityLog> activityLogs = new List <ActivityLog>();
            string             sql          = "sproc_activity_log @flag = 's', @action_user= '******'";
            var dbres = DAO.ExecuteDataTable(sql);

            if (dbres != null)
            {
                foreach (DataRow dr in dbres.Rows)
                {
                    ActivityLog ActivityLog = new ActivityLog();
                    ActivityLog.page_name        = dr["page_name"].ToString();
                    ActivityLog.page_url         = dr["Page_url"].ToString();
                    ActivityLog.ipaddress        = dr["from_ip_address"].ToString();
                    ActivityLog.browser_detail   = dr["from_browser"].ToString();
                    ActivityLog.CreatedBy        = dr["created_by"].ToString();
                    ActivityLog.CreatedLocalDate = dr["created_local_Date"].ToString();

                    activityLogs.Add(ActivityLog);
                }
            }
            return(activityLogs);
        }
コード例 #34
0
        private void set(ActivityLog log, Activity act)
        {
            if (log != null)
            {
                this.LogId       = log.Id;
                this.Quantity    = log.Quantity;
                this.unitid      = log.Unit.Id;
                this.UnitList    = new SelectList(log.Unit.UnitType.Units, "Id", "Description", this.sUnitId);
                this.Hyperlink   = log.Hyperlink;
                this.Notes       = log.Notes;
                this.Description = log.Activity.Description;
                this.JourId      = log.Journal.Id;
                //               this.TotalPoints = (int)(act.Points * log.Quantity);
            }
            else
            {
                this.unitid   = act.Unit.Id;
                this.UnitList = new SelectList(act.Unit.UnitType.Units, "Id", "Description", this.sUnitId);
            }
            this.ActId       = act.Id;
            this.Description = act.Description;
//            this.Points = act.Points;
        }
コード例 #35
0
	void LoginButton_Click(object sender, EventArgs e)
	{
		string password = AccPasswordTextBox.Text;

		ActivityLog log = new ActivityLog();

		// create a filezilla object using the active configuration
		Filezilla fz = new Filezilla(settings.Lookup("ConfigurationFile"));
		if (!fz.AuthenticateAdministration(password))
		{
			log.LogActivity(LogAction.Login, "REMOTEADMIN", "authentication failed");

			LoginValidator.IsValid = false;
			return;
		}

		log.LogActivity(LogAction.Login, "REMOTEADMIN");

		// Set the session vars
		Session["FZNET_ADMIN"] = true;

		// Redirect to the administration home page
		Response.Redirect("Admin.aspx");
	}
コード例 #36
0
	/// <summary>
	/// A file is being downloaded, check to see if the user has read access
	/// Also overrides the download function to cut the file into 64k blocks to preserve memory
	/// </summary>
	/// <param name="source">event source</param>
	/// <param name="e">event args - used to identify target for read</param>
	void FileManager_FileDownloading(object source, FileManagerFileDownloadingEventArgs e)
	{
		if (!fz.AllowFileRead(Master.UserName, rootFolder))
		{
			e.Cancel = true;
			// track the download action
			ActivityLog log = new ActivityLog();
			log.LogActivity(LogAction.Download, Master.UserName, e.File.FullName, (e.Cancel) ? "Access denied" : "");
		}
		else
		{
			// download the file a block at a time to preserve memory
			byte[] buffer = new byte[1024*1024];
			HttpResponse response = Response;
			response.Clear();
			response.AddHeader("ContentType", string.Format("application/{0}", Path.GetExtension(e.File.Name).TrimStart('.')));
			response.AddHeader("Content-Transfer-Encoding", "binary");
			response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}",Server.UrlEncode(e.File.Name)));
			long dataToRead = e.InputStream.Length;
			response.AddHeader("Content-Length", string.Format("{0}",dataToRead));
			while (dataToRead > 0)
			{
				if ( response.IsClientConnected)
				{
					int length = e.InputStream.Read(buffer, 0, 1024 * 1024);
					response.OutputStream.Write(buffer, 0, length);
					response.Flush();
					dataToRead -= length;
				}
				else
				{
					dataToRead = -1;
				}
			}
			// clean up at end of response
			response.Flush();
			// track the download action
			ActivityLog log = new ActivityLog();
			log.LogActivity(LogAction.Download, Master.UserName, e.File.FullName, (e.Cancel) ? "Access denied" : "");
			// terminate the response - we passed back the file
			response.End();
		}
		e.Cancel = true;
	}
コード例 #37
0
    protected void Page_Load(object sender, EventArgs e)
    {
		// this page requires an authenticated user
		Master.ForceAuthentication();

		// wire the file manager events
		FileManager.CustomThumbnail += new FileManagerThumbnailCreateEventHandler(FileManager_CustomThumbnail);
		FileManager.FileDownloading += new FileManagerFileDownloadingEventHandler(FileManager_FileDownloading);
		FileManager.FileUploading += new FileManagerFileUploadEventHandler(FileManager_FileUploading);
		FileManager.FolderCreating += new FileManagerFolderCreateEventHandler(FileManager_FolderCreating);
		FileManager.ItemDeleting += new FileManagerItemDeleteEventHandler(FileManager_ItemDeleting);
		FileManager.ItemMoving += new FileManagerItemMoveEventHandler(FileManager_ItemMoving);
		FileManager.ItemRenaming += new FileManagerItemRenameEventHandler(FileManager_ItemRenaming);

		// create the configuration related objects
		webSettings = new WebSettings();
		fz = new Filezilla(webSettings.Lookup("ConfigurationFile"));

		// create the activity related objects
		log = new ActivityLog();

		// get the root folder based on the authenticated user
		rootFolder = fz.HomeDirectory(Master.UserName);

		if (!Page.IsPostBack)
		{
			// configure the general settings of the file manager 
			FileManager.SettingsEditing.AllowCreate = WebConvert.ToBoolean(webSettings.Lookup("AllowCreate", "0"), false);
			FileManager.SettingsEditing.AllowDelete = WebConvert.ToBoolean(webSettings.Lookup("AllowDelete", "0"), false);
			FileManager.SettingsEditing.AllowMove = WebConvert.ToBoolean(webSettings.Lookup("AllowMove", "0"), false);
			FileManager.SettingsEditing.AllowRename = WebConvert.ToBoolean(webSettings.Lookup("AllowRename", "0"), false);
			FileManager.SettingsFolders.ShowFolderIcons = WebConvert.ToBoolean(webSettings.Lookup("ShowFolderIcons", "0"), false);
			FileManager.SettingsToolbar.ShowDownloadButton = WebConvert.ToBoolean(webSettings.Lookup("ShowDownloadButton", "0"), false);
			FileManager.Settings.ThumbnailFolder = webSettings.Lookup("ThumbnailFolder");
			// advanced upload mode requires Microsoft Silverlight ... really?
			if (Master.IsSilverlightAvailable)
			{
				// silverlight is available - check the system configuration to see if we want to utilize it
				FileManager.SettingsUpload.UseAdvancedUploadMode = WebConvert.ToBoolean(webSettings.Lookup("UseAdvancedUploadMode", "0"), false);
				FileManager.SettingsUpload.AdvancedModeSettings.EnableMultiSelect = WebConvert.ToBoolean(webSettings.Lookup("EnableMultiSelect", "0"), false);
			}
			else
			{
				// no silverlight - no advanced upload mode
				FileManager.SettingsUpload.UseAdvancedUploadMode = false;
				FileManager.SettingsUpload.AdvancedModeSettings.EnableMultiSelect = false;

				// if the user could be utilizing silverlight, let them know
				if (WebConvert.ToBoolean(webSettings.Lookup("UseAdvancedUploadMode", "0"), false))
				{
					SilverlightPanel.Visible = true;
				}
			}
			// set the max file size from the settings, default to 1MB
			FileManager.SettingsUpload.ValidationSettings.MaxFileSize = WebConvert.ToInt32(webSettings.Lookup("MaxFileSize","1000000"),1000000);
 
			// limit permissions based on the settings for the ftp share

			// disable creating folders if its not enabled in the configuration
			if (!fz.AllowDirCreate(Master.UserName, rootFolder))
			{
				FileManager.SettingsEditing.AllowCreate = false;
			}

			// disable deleting, moving items if its not enabled in the configuration
			if (!fz.AllowFileDelete(Master.UserName, rootFolder))
			{
				FileManager.SettingsEditing.AllowDelete = false;
				FileManager.SettingsEditing.AllowMove = false;
			}
			
			// disable upload, move, rename, delete if write is not enabled
			if (!fz.AllowFileWrite(Master.UserName, rootFolder))
			{
				FileManager.SettingsUpload.Enabled = false;
				FileManager.SettingsEditing.AllowMove = false;
				FileManager.SettingsEditing.AllowRename = false;
				FileManager.SettingsEditing.AllowDelete = false;
			}

			// assign the root folder to the user's normalized home directory
			FileManager.Settings.RootFolder = fz.NormalizeFolderName(rootFolder);


			// log the browse action
			log.LogActivity(LogAction.Browse, Master.UserName, FileManager.Settings.RootFolder, "Silverlight=" + WebConvert.ToString( Session["FZNET_SILVERLIGHT"], "false") );
		}
    }
コード例 #38
0
        /// <summary>
        /// Inserts an activity log item
        /// </summary>
        /// <param name="systemKeyword">The system keyword</param>
        /// <param name="comment">The activity comment</param>
        /// <param name="account">The account</param>
        /// <param name="commentParams">The activity comment parameters for string.Format() function.</param>
        /// <returns>Activity log item</returns>
        public virtual ActivityLog InsertActivity(string systemKeyword, 
            string comment, Account account, params object[] commentParams)
        {
            if (account == null)
                return null;

            var activityTypes = GetAllActivityTypes();
            var activityType = activityTypes.ToList().Find(at => at.SystemKeyword == systemKeyword);
            if (activityType == null || !activityType.Enabled)
                return null;

            comment = CommonHelper.EnsureNotNull(comment);
            comment = string.Format(comment, commentParams);
            comment = CommonHelper.EnsureMaximumLength(comment, 4000);

            var activity = new ActivityLog();
            activity.ActivityLogType = activityType;
            activity.Account = account;
            activity.Comment = comment;
            activity.CreatedOnUtc = DateTime.UtcNow;

            _activityLogRepository.Insert(activity);

            return activity;
        }
コード例 #39
0
        /// <summary>
        /// Deletes an activity log item
        /// </summary>
        /// <param name="activityLog">Activity log type</param>
        public virtual void DeleteActivity(ActivityLog activityLog)
        {
            if (activityLog == null)
                throw new ArgumentNullException("activityLog");

            _activityLogRepository.Delete(activityLog);
        }
コード例 #40
0
ファイル: MongoService.cs プロジェクト: aderman/Doco
 public static string ApplyMessage(ActivityLog.ActivityType act, params object []  p )
 {
     return String.Format(Messages[act], p);
 }
コード例 #41
0
	/// <summary>
	/// Check to see if an item can be deleted; this is used to differentiate between deleting
	/// files and deleting folders, which are separate permissions in FileZilla
	/// </summary>
	/// <param name="source">event source</param>
	/// <param name="e">event args - used to identify target for deletion</param>
	void FileManager_ItemDeleting(object source, FileManagerItemDeleteEventArgs e)
	{
		// if the item is a folder, check for permission to delete folders
		if (e.Item is FileManagerFolder)
		{
			if (!fz.AllowDirDelete(Master.UserName, rootFolder))
			{
				e.Cancel = true;
				e.ErrorText = "Folders may not be deleted.";
			}
		}
		ActivityLog log = new ActivityLog();
		log.LogActivity(LogAction.Delete, Master.UserName, e.Item.FullName, e.ErrorText);
	}
コード例 #42
0
    /// <summary>
    ///To Get all the Log activities From the Device to Admin (database)
    /// </summary>
    /// <param name="Ar"></param>
    /// <returns></returns>
    public HttpResponseMessage logActivities(logActivities LA)
    {
        ar = new WebApiResponse();        
        try
        {
            string qry = "select * from MDM_DeviceMaster where DeviceID='" + LA.uuid + "'";
            //linfo.LogFile(enLogType.QUERY, "Query = " + qry + "Device ID = " + LA.uuid, "Rizwan");
            dr = databaseHelper.getDataReader(qry);

            if (dr.Read())
            {
                ActivityLog la = new ActivityLog();
                DeviceTrackingDetail dt = new DeviceTrackingDetail();
                var list = LA.activity;

                string id = LA.uuid;
                if (!dr.IsClosed)
                    dr.Close();

                foreach (var c in list)
                {
                    la.DeviceID = id;
                    la.ActivityCode = c.activityCode;
                    la.LogText = c.actitivyDetail;
                    la.CreatedBy = 1;
                    la.UpdatedBy = 1;
                    la.LogDateTime = c.activityOn;
                    la.activityType = c.activityType;
                    if (c.activityCode == 2)
                    {
                        la.LogText = c.actitivyDetail + " Latitude : " + c.latitude + " Longitude : " + c.longitude;
                    }
                    qry = "insert into MDM_ActivityLog(LogText,DeviceID,EmployeeID,LogDateTime,ActivityCode,ActivityType)values('" + la.LogText + "','" + la.DeviceID + "','1','" + DateTime.Now.ToString("dd-MMM-yyyy HH:mm:ss") + "','" + la.ActivityCode + "','" + la.activityType + "')";

                    //linfo.LogFile(enLogType.QUERY, "\n\n Query = " + qry , "Rizwan");

                    rcnt = databaseHelper.ExecuteQuery(qry);
                }
                ar.response = true;
                response = Request.CreateResponse(HttpStatusCode.Created, ar);

                return response;
            }
            else
            {
                ar.errorCode = "No Device Found";
                ar.response = false;
                response = Request.CreateResponse(HttpStatusCode.BadRequest, ar);
                return response;
            }
        }
        catch (Exception ex)
        {
            if (!dr.IsClosed)
                dr.Close();
            linfo.LogFile(enLogType.EXCEPTION, "Function = logActivities() Error Message = "+ex.Message+"  InnerException ="+ex.InnerException.ToString(),null);

            ar.errorCode = "Problem in logActivities() WS";
            ar.response = false;
            response = Request.CreateResponse(HttpStatusCode.BadRequest, ar);
            
        }
        finally
        {
            if (dr != null && !dr.IsClosed)
                dr.Close();            
        }
        return response;
    }
コード例 #43
0
ファイル: IActivitiyLogService.cs プロジェクト: aderman/Doco
 public void AddNewLogRecord(ActivityLog log)
 {
     ValidationResult = log.Validation();
     if ( ValidationResult.IsValid)
         _mongoDb.Insert(log);
 }
コード例 #44
0
            public SanitizedActivityLog(ActivityLog activityLog)
            {
                if (string.IsNullOrEmpty(activityLog.Name))
                    throw new SerializationException("An ActivityLog Name is required");
                if (activityLog.CompensateAddress == null)
                    throw new SerializationException("An ActivityLog CompensateAddress is required");

                Name = activityLog.Name;
                CompensateAddress = activityLog.CompensateAddress;
                Results = activityLog.Results ?? new Dictionary<string, string>();
            }