Пример #1
0
 public List<Sector> LoadSector()
 {
     try
     {
         using (MySqlConnection cn = new MySqlConnection((clsCon = new Connection(this.user)).Parameters()))
         {
             listSec = new List<Sector>();
             cn.Open();
             sql = "select * from asada.view_sectores";
             cmd = new MySqlCommand(sql, cn);
             reader = cmd.ExecuteReader();
             while (reader.Read())
             {
                 sec = new Sector();
                 sec.Code = reader.GetString(0);
                 sec.Consecutive = reader.GetInt32(1);
                 sec.Description = reader.GetString(2);
                 listSec.Add(sec);
             }
             reader.Close();
             return listSec;
         }
     }
     catch (Exception e)
     {
         Logs lg = new Logs();
         lg.Log(DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss") + ", " + e.Message.ToString());
         throw;
     }
 }
        public static void GetLogs()
        {
            var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
            var filename = Path.Combine (documents, "proscanmobile_logs.xml");

            if (File.Exists (filename)) {

                Logs s_tmp = new Logs ();

                XmlSerializer deserializer = new XmlSerializer (typeof(Logs));
                TextReader textReader = new StreamReader (filename, Encoding.UTF8);
                s_tmp = (Logs)deserializer.Deserialize (textReader);
                textReader.Close ();

                _log = new Logs ();
                _log.LogsList = new List<LogsDisplay> ();

                foreach (LogsDisplay sd_tmp in s_tmp.LogsList) {
                    _log.LogsList.Add (new LogsDisplay () {
                        sys = XmlConvert.DecodeName(sd_tmp.sys),
                        grp = XmlConvert.DecodeName(sd_tmp.grp),
                        alert = sd_tmp.alert,
                        lastalert = sd_tmp.lastalert
                    } );
                }

                s_tmp = null;
            }
        }
Пример #3
0
        public LoggingRequestDialog(Logs<Log> logs)
        {
            _viewModel = new LoggingRequestDialogViewModel(this, logs);

            InitializeComponent();

            DataContext = _viewModel;
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (State.ContainsKey("LogPageModel"))
            {
                Logs pageData = (Logs)State["LogPageModel"];
                this.Logs = pageData;
                State.Remove("LogPageModel");
            }

            base.OnNavigatedTo(e);
        }
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            LogsModel = new Logs();
            MainPageModel = new MainPageModel();

            _notifServerApi = App.NotifServerApi;

            SetNotificationEnabled(false);
            UiStateToStopped(true);

            // DataContexts
            this.ActivitySlider.DataContext = CameraViewfinder.CameraData;
            this.ActivitySlider.Style = Application.Current.Resources["CustomSliderStyle_Yellow"] as Style;
            this.CameraTresholdSlider.DataContext = CameraViewfinder.CameraData;

            // Custom screensaver
            _screensaverControl = new ScreenSaver(this.LayoutRoot, this.ApplicationBar);

            // Read Ovi accout id from isolated storage
            string usernameFromStore;
            if (ReadUsername(out usernameFromStore))
                MainPageModel.OviAccountId = usernameFromStore;

            // Load sounds
            StreamResourceInfo alarmStream = Application.GetResourceStream(
                new Uri("SoundFiles/26173__wim__sirene-06080401.wav", UriKind.RelativeOrAbsolute));
            _alarmSound = SoundEffect.FromStream(alarmStream.Stream);

            StreamResourceInfo waitAlarmSound = Application.GetResourceStream(
                new Uri("SoundFiles/31841__hardpcm__chip001.wav", UriKind.RelativeOrAbsolute));
            _waitAlarmSound = SoundEffect.FromStream(waitAlarmSound.Stream);

            StreamResourceInfo radioStream = Application.GetResourceStream(
                new Uri("SoundFiles/30335__erh__radio-noise-2.wav", UriKind.RelativeOrAbsolute));
            _radioSound = SoundEffect.FromStream(radioStream.Stream);

            StreamResourceInfo radioStream2 = Application.GetResourceStream(
                new Uri("SoundFiles/30623__erh__do-it-now-2.wav", UriKind.RelativeOrAbsolute));
            _radioSound2 = SoundEffect.FromStream(radioStream2.Stream);

            StreamResourceInfo radioStream3 = Application.GetResourceStream(
                new Uri("SoundFiles/27878__inequation__walkietalkie-eot.wav", UriKind.RelativeOrAbsolute));
            _radioSound3 = SoundEffect.FromStream(radioStream3.Stream);

            StreamResourceInfo radioStream4 = Application.GetResourceStream(
                new Uri("SoundFiles/34383__erh__walk-away.wav", UriKind.RelativeOrAbsolute));
            _radioSound4 = SoundEffect.FromStream(radioStream4.Stream);
        }
Пример #6
0
        public void AddLog(Logs.Log log)
        {
            logs.Add(log);

            listViewExLogs.Invoke(new MethodInvoker(delegate
            {
                ListViewItem lvi = new ListViewItem();
                lvi.Tag = log;
                lvi.Text = log.datetime.ToShortTimeString();
                lvi.SubItems.Add(log.logType.ToString());
                lvi.SubItems.Add(log.message);

                listViewExLogs.Items.Add(lvi);
                lvi.EnsureVisible();
            }));
        }
Пример #7
0
        public static void Run(ControllerConfiguration context, Guid instanceKey)
        {
            var logsController = new Logs(context);

            var searchEmpty = logsController.GetLogEntryPage(instanceKey);
            Debug.Assert(searchEmpty.LogEntries.Count() == 0);
            Debug.Assert(searchEmpty.InstanceKey == instanceKey);

            var logEntry1 = new LogEntry() { InstanceKey = instanceKey, LogContent = "Now this is the story all about how\r\nMy life got flipped, turned upside down\r\nAnd I'd like to take a minute just sit right there\r\nI'll tell you how I became the prince of a town called Bel-air" };
            logsController.AddLogEntry(logEntry1);

            var createdLogEntry1 = logsController.GetLogEntry(instanceKey, logEntry1.Timestamp, logEntry1.Status);
            Debug.Assert(createdLogEntry1.Timestamp == logEntry1.Timestamp);
            Debug.Assert(createdLogEntry1.InstanceKey == logEntry1.InstanceKey);
            Debug.Assert(createdLogEntry1.Status == logEntry1.Status);
            Debug.Assert(createdLogEntry1.LogContent == logEntry1.LogContent);

            var searchSingle = logsController.GetLogEntryPage(instanceKey);
            Debug.Assert(searchSingle.LogEntries.Count() == 1);
            Debug.Assert(searchSingle.LogEntries.ElementAt(0).Timestamp == logEntry1.Timestamp);
            Debug.Assert(searchSingle.LogEntries.ElementAt(0).Status == LogStatus.Ok);

            var logEntry2 = new LogEntry() { InstanceKey = instanceKey, Status = LogStatus.Warning, LogContent = "In west Philadelphia born and raised\r\nOn the playground where I spent most of my days\r\nChilling out, maxing, relaxing all cool\r\nAnd all shooting some b-ball outside of the school\r\nWhen a couple of guys, they were up to no good\r\nStarted making trouble in my neighbourhood\r\nI got in one little fight and my mom got scared\r\nAnd said \"You're moving with your auntie and uncle in Bel-air\"" };
            logsController.AddLogEntry(logEntry2);

            var createdLogEntry2 = logsController.GetLogEntry(instanceKey, logEntry2.Timestamp, logEntry2.Status);
            Debug.Assert(createdLogEntry2.Timestamp == logEntry2.Timestamp);
            Debug.Assert(createdLogEntry2.InstanceKey == logEntry2.InstanceKey);
            Debug.Assert(createdLogEntry2.Status == logEntry2.Status);
            Debug.Assert(createdLogEntry2.LogContent == logEntry2.LogContent);

            var search2 = logsController.GetLogEntryPage(instanceKey);
            Debug.Assert(search2.LogEntries.Count() == 2);
            Debug.Assert(search2.LogEntries.ElementAt(0).Timestamp == logEntry2.Timestamp);
            Debug.Assert(search2.LogEntries.ElementAt(0).Status == LogStatus.Warning);
            Debug.Assert(search2.LogEntries.ElementAt(1).Timestamp == logEntry1.Timestamp);

            var searchFirst = logsController.GetLogEntryPage(instanceKey, pageSize: 1);
            Debug.Assert(searchFirst.PageSize == 1);
            Debug.Assert(searchFirst.LogEntries.Count() == 1);
            Debug.Assert(searchFirst.LogEntries.ElementAt(0).Timestamp == logEntry2.Timestamp);

            var searchNext = logsController.GetLogEntryPage(instanceKey, searchFirst.NextMarker);
            Debug.Assert(searchNext.StartMarker == searchFirst.NextMarker);
            Debug.Assert(searchNext.LogEntries.Count() == 1);
            Debug.Assert(searchNext.LogEntries.ElementAt(0).Timestamp == logEntry1.Timestamp);
        }
Пример #8
0
        public Form1()
        {
            InitializeComponent();
            SendToAll.Enabled = false;
            Start.Enabled = false;
            LoadCommandScript.Enabled = false;

            previousCommands = new List<string>();
            commandListPos = 0;
            logs = new Logs(this.Logs);
            config = new Configuration(this.logs);
            Start.Enabled = true;

            if (confLoaded == false)
            {
                var path = @"Config/ManagerConfig.xml";
                config.loadConfiguration(path);
                afterConfiguration();
            }
        }
Пример #9
0
        public Form1()
        {
            InitializeComponent();
            SendToAll.Enabled = false;
            Start.Enabled = false;
            LoadCommandScript.Enabled = false;

            previousCommands = new List<string>();
            commandListPos = 0;
            logs = new Logs(this.Logs);
            config = new Configuration(this.logs);
            Start.Enabled = true;

            if (path.pathToFile != null)
            {
                config.loadConfiguration(path.pathToFile);
                afterConfiguration();
                startService();
            }
        }
Пример #10
0
        public ActionResult Details(Guid iid, long t, LogStatus s)
        {
            var logs = new Logs();
            var instances = new Instances();
            var targets = new Targets();
            var groups = new Groups();

            var log = logs.GetLogEntry(iid, new DateTime(t, DateTimeKind.Utc), s);
            var instance = instances.GetInstance(iid);
            var target = targets.GetTarget(instance.TargetKey);
            var group = groups.GetGroup(target.GroupKey);

            var model = new LogDetails()
            {
                LogEntry = log,
                Instance = instance,
                Target = target,
                Group = group,
            };

            return View(model);
        }
Пример #11
0
        //
        // GET: /Logs/
        public ActionResult Index(Guid iid, string m = null, int c = 50)
        {
            var logs = new Logs();
            var instances = new Instances();
            var targets = new Targets();
            var groups = new Groups();

            var logPage = logs.GetLogEntryPage(iid, m, c);
            var instance = instances.GetInstance(iid);
            var target = targets.GetTarget(instance.TargetKey);
            var group = groups.GetGroup(target.GroupKey);

            var model = new LogIndex()
            {
                LogEntryPage = logPage,
                Instance = instance,
                Target = target,
                Group = group,
            };

            return View(model);
        }
Пример #12
0
 /// <summary>
 /// Cria uma Fatura para um Cliente (Podendo ser um objeto cliente ou apenas um e-mail).
 /// </summary>
 /// <param name="email">E-Mail do cliente</param>
 /// <param name="due_date">Data de Expiração (DD/MM/AAAA)</param>
 /// <param name="items"> Itens da Fatura</param>
 /// <param name="return_url">(opcional)	Cliente é redirecionado para essa URL após efetuar o pagamento da Fatura pela página de Fatura da Iugu</param>
 /// <param name="expired_url">(opcional) Cliente é redirecionado para essa URL se a Fatura que estiver acessando estiver expirada</param>
 ///  <param name="notification_url">(opcional) URL chamada para todas as notificações de Fatura, assim como os webhooks (Gatilhos) são chamados</param>
 /// <param name="tax_cents">(opcional) Valor dos Impostos em centavos</param>
 /// <param name="discount_cents">(opcional)	Valor dos Descontos em centavos</param>
 /// <param name="customer_id">(opcional) ID do Cliente</param>
 /// <param name="ignore_due_email">(opcional) Booleano que ignora o envio do e-mail de cobrança</param>
 /// <param name="subscription_id">(opcional) Amarra essa Fatura numa Assinatura</param>
 /// <param name="credits">(opcional) Caso tenha o subscription_id, pode-se enviar o número de créditos a adicionar nessa Assinatura quando a Fatura for paga</param>
 /// <param name="logs">(opcional) Logs da Fatura</param>
 /// <param name="custom_variables">(opcional) Variáveis Personalizadas</param>
 /// <returns></returns>
 public InvoiceModel Create(string email, DateTime due_date, Item[] items, string return_url = "",
     string expired_url = "", string notification_url = "", int tax_cents = 0, int discount_cents = 0, string customer_id = "", bool ignore_due_email = false,
     string subscription_id = "", int credits = 0, Logs logs = null, CustomVariables custom_variables = null)
 {
     //TODO: implementar  custom_variables[]
     var invoice = new
     {
         email = email,
         due_date = due_date.ToString("dd/MM/yyyy"),
         items = items,
         return_url = return_url,
         expired_url = expired_url,
         tax_cents = tax_cents,
         discount_cents = discount_cents,
         customer_id = customer_id,
         ignore_due_email = ignore_due_email,
         subscription_id = subscription_id,
         credits = credits,
         logs = logs,
         custom_variables = custom_variables
     };
     var retorno = PostAsync<InvoiceModel>(invoice).Result;
     return retorno;
 }
Пример #13
0
        protected virtual void Page_Load(object sender, EventArgs e)
        {
            if (this.userid > 0)
            {
                if (CheckUserPopedoms("X") || CheckUserPopedoms("4-1"))
                {
                    ucode   = DES.Encode(this.userinfo.uName + "|" + UsersUtils.GetCookiePassword(config.Passwordkey), config.Passwordkey);
                    Act     = HTTPRequest.GetString("Act");
                    StaffID = Utils.StrToInt(HTTPRequest.GetString("sid"), 0);
                    format  = HTTPRequest.GetString("format");
                    if (Act == "Edit")
                    {
                        si = tbStaffInfo.GetStaffInfoModel(StaffID);

                        sd = tbStaffInfo.GetStaffDataInfoModelByStaffID(StaffID);

                        if (sd != null)
                        {
                            sd.sBirthDay     = sd.sBirthDay != null?sd.sBirthDay:"";
                            sd.sPolitical    = sd.sPolitical != null ? sd.sPolitical : "";
                            sd.sBirthplace   = sd.sBirthplace != null ? sd.sBirthplace : "";
                            sd.sHometown     = sd.sHometown != null ? sd.sHometown : "";
                            sd.sEducation    = sd.sEducation != null ? sd.sEducation : "";
                            sd.sProfessional = sd.sProfessional != null ? sd.sProfessional : "";
                            sd.sHealth       = sd.sHealth != null ? sd.sHealth : "";

                            sd.sSpecialty      = sd.sSpecialty != null ? sd.sSpecialty : "";
                            sd.sHobbies        = sd.sHobbies != null ? sd.sHobbies : "";
                            sd.sContactAddress = sd.sContactAddress != null ? sd.sContactAddress : "";
                            sd.sPhotos         = sd.sPhotos != null ? sd.sPhotos : "";

                            sd.sCanBeDate = sd.sCanBeDate != null ? sd.sCanBeDate : "";
                        }

                        sad = tbStaffInfo.GetStaffAnalysisDataInfoModelByStaffID(StaffID);
                        if (sad != null)
                        {
                            sad.aEvaluationMSG = sad.aEvaluationMSG != null ? sad.aEvaluationMSG : "";
                        }
                    }
                    //修改状体
                    if (Act == "State")
                    {
                        si    = tbStaffInfo.GetStaffInfoModel(StaffID);
                        tJson = ",\"StaffID\":" + StaffID + "";
                        if (si != null)
                        {
                            si.sState = (si.sState == 0 ? 1 : 0);
                            tbStaffInfo.UpdateStaffInfo(si);
                            Logs.AddEventLog(this.userid, "修改人员状态." + si.sName);
                            tJson += ",\"StaffState\":" + si.sState;
                            AddMsgLine("修改成功!");
                        }
                        else
                        {
                            AddErrLine("修改失败,对象不存在!");
                        }
                    }
                    if (ispost)
                    {
                        sName              = Utils.ChkSQL(HTTPRequest.GetString("sName"));
                        sSex               = Utils.ChkSQL(HTTPRequest.GetString("sSex"));
                        sTel               = Utils.ChkSQL(HTTPRequest.GetString("sTel"));
                        sCarID             = Utils.ChkSQL(HTTPRequest.GetString("sCarID"));
                        sType              = Utils.StrToInt(HTTPRequest.GetString("sType"), 0);
                        sEmail             = Utils.ChkSQL(HTTPRequest.GetString("sEmail"));
                        DepartmentsClassID = Utils.StrToInt(HTTPRequest.GetString("DepartmentsClassID"), 0);
                        sState             = HTTPRequest.GetString("sState").Trim() != "" ? Utils.StrToInt(HTTPRequest.GetString("sState"), 0) : 1;

                        si.sSex               = sSex;
                        si.sTel               = sTel;
                        si.sCarID             = sCarID;
                        si.sType              = sType;
                        si.sState             = sState;
                        si.sEmail             = sEmail;
                        si.DepartmentsClassID = DepartmentsClassID;

                        sd = sd != null ? sd : new StaffDataInfo();

                        sd.sBirthDay       = Utils.ChkSQL(HTTPRequest.GetString("sBirthDay"));
                        sd.sPolitical      = Utils.ChkSQL(HTTPRequest.GetString("sPolitical"));
                        sd.sBirthplace     = Utils.ChkSQL(HTTPRequest.GetString("sBirthplace"));
                        sd.sHometown       = Utils.ChkSQL(HTTPRequest.GetString("sHometown"));
                        sd.sEducation      = Utils.ChkSQL(HTTPRequest.GetString("sEducation"));
                        sd.sProfessional   = Utils.ChkSQL(HTTPRequest.GetString("sProfessional"));
                        sd.sHealth         = Utils.ChkSQL(HTTPRequest.GetString("sHealth"));
                        sd.sHeight         = HTTPRequest.GetInt("sHeight", 0);
                        sd.sWeight         = HTTPRequest.GetInt("sWeight", 0);
                        sd.sSpecialty      = Utils.ChkSQL(HTTPRequest.GetString("sSpecialty"));
                        sd.sHobbies        = Utils.ChkSQL(HTTPRequest.GetString("sHobbies"));
                        sd.sContactAddress = Utils.ChkSQL(HTTPRequest.GetString("sContactAddress"));
                        sd.sPhotos         = Utils.ChkSQL(HTTPRequest.GetString("sPhotos"));
                        sd.sEmployment     = HTTPRequest.GetInt("sEmployment", 0);
                        sd.sCanBeDate      = Utils.ChkSQL(HTTPRequest.GetString("sCanBeDate"));
                        sd.sTreatment      = HTTPRequest.GetInt("sTreatment", 0);

                        sad = sad != null ? sad : new StaffAnalysisDataInfo();

                        sad.aWearing       = HTTPRequest.GetInt("aWearing", 0);
                        sad.aEducation     = HTTPRequest.GetInt("aEducation", 0);
                        sad.aWork          = HTTPRequest.GetInt("aWork", 0);
                        sad.aCommunication = HTTPRequest.GetInt("aCommunication", 0);
                        sad.aConfidence    = HTTPRequest.GetInt("aConfidence", 0);
                        sad.aLeadership    = HTTPRequest.GetInt("aLeadership", 0);
                        sad.aJobstability  = HTTPRequest.GetInt("aJobstability", 0);
                        sad.aComputer      = HTTPRequest.GetInt("aComputer", 0);
                        sad.aEnglish       = HTTPRequest.GetInt("aEnglish", 0);
                        sad.aWritten       = HTTPRequest.GetInt("aWritten", 0);
                        sad.aEvaluation    = HTTPRequest.GetInt("aEvaluation", 0);
                        sad.aEvaluationMSG = Utils.ChkSQL(HTTPRequest.GetString("aEvaluationMSG"));
                        try
                        {
                            sad.aDateTime = Utils.IsDateString(HTTPRequest.GetString("aDateTime")) ? DateTime.Parse(HTTPRequest.GetString("aDateTime").Trim()) : DateTime.Now;
                        }
                        catch {
                            sad.aDateTime = DateTime.Now;
                        }

                        EduDataListJson    = HTTPRequest.GetString("EduDataListJson");
                        WorkDataListJson   = HTTPRequest.GetString("WorkDataListJson");
                        FamilyDataListJson = HTTPRequest.GetString("FamilyDataListJson");

                        if (Act == "Add")
                        {
                            if (!tbStaffInfo.ExistsStaffInfo(sName))
                            {
                                si.sName       = sName;
                                si.sAppendTime = sAppendTime;
                                StaffID        = tbStaffInfo.AddStaffInfo(si);
                                if (StaffID > 0)
                                {
                                    sd.StaffID = StaffID;

                                    tbStaffInfo.AddStaffDataInfo(sd);

                                    sad.StaffID     = StaffID;
                                    sad.aAppendTime = DateTime.Now;

                                    tbStaffInfo.AddStaffAnalysisDataInfo(sad);

                                    if (EduDataListJson.Trim() != "")
                                    {
                                        StaffEduDataJson EduDataJson = (StaffEduDataJson)JavaScriptConvert.DeserializeObject(EduDataListJson, typeof(StaffEduDataJson));

                                        tbStaffInfo.AddStaffEduDataInfoByJson(EduDataJson);
                                    }
                                    if (WorkDataListJson.Trim() != "")
                                    {
                                        StaffWorkDataJson WorkDataJson = (StaffWorkDataJson)JavaScriptConvert.DeserializeObject(WorkDataListJson, typeof(StaffWorkDataJson));

                                        tbStaffInfo.AddStaffWorkDataInfoByJson(WorkDataJson);
                                    }
                                    if (FamilyDataListJson.Trim() != "")
                                    {
                                        StaffFamilyDataJson FamilyDataJson = (StaffFamilyDataJson)JavaScriptConvert.DeserializeObject(FamilyDataListJson, typeof(StaffFamilyDataJson));

                                        tbStaffInfo.AddStaffFamilyDataInfoByJson(FamilyDataJson);
                                    }
                                    Logs.AddEventLog(this.userid, "新增人员." + si.sName);
                                    AddMsgLine("创建成功!");
                                    AddScript("window.setTimeout('window.parent.HidBox();',1000);");
                                }
                                else
                                {
                                    AddErrLine("创建失败!");
                                    AddScript("window.setTimeout('history.back(1);',1000);");
                                }
                            }
                            else
                            {
                                AddErrLine("人员:" + sName + ",已存在,请更换!");
                                AddScript("window.setTimeout('history.back(1);',3000);");
                            }
                        }
                        if (Act == "Edit")
                        {
                            bool nOK = false;
                            if (si.sName.Trim() != sName.Trim())
                            {
                                if (!tbStaffInfo.ExistsStaffInfo(sName.Trim()))
                                {
                                    nOK = true;
                                }
                                else
                                {
                                    nOK = false;
                                    AddErrLine("人员:" + sName + ",已存在,请更换!");
                                    AddScript("window.setTimeout('history.back(1);',3000);");
                                }
                            }
                            else
                            {
                                nOK = true;
                            }
                            if (nOK)
                            {
                                try
                                {
                                    si.sName = sName;

                                    tbStaffInfo.UpdateStaffInfo(si);

                                    if (sd.StaffID > 0)
                                    {
                                        tbStaffInfo.UpdateStaffDataInfo(sd);
                                    }
                                    else
                                    {
                                        sd.StaffID = StaffID;

                                        tbStaffInfo.AddStaffDataInfo(sd);
                                    }

                                    if (sad.StaffID > 0)
                                    {
                                        tbStaffInfo.UpdateStaffAnalysisDataInfo(sad);
                                    }
                                    else
                                    {
                                        sad.StaffID     = StaffID;
                                        sad.aAppendTime = DateTime.Now;

                                        tbStaffInfo.AddStaffAnalysisDataInfo(sad);
                                    }

                                    if (EduDataListJson.Trim() != "")
                                    {
                                        StaffEduDataJson EduDataJson = (StaffEduDataJson)JavaScriptConvert.DeserializeObject(EduDataListJson, typeof(StaffEduDataJson));

                                        tbStaffInfo.UpdateStaffEduDataInfoByJson(EduDataJson, StaffID);
                                    }
                                    if (WorkDataListJson.Trim() != "")
                                    {
                                        StaffWorkDataJson WorkDataJson = (StaffWorkDataJson)JavaScriptConvert.DeserializeObject(WorkDataListJson, typeof(StaffWorkDataJson));

                                        tbStaffInfo.UpdateStaffWorkDataInfoByJson(WorkDataJson, StaffID);
                                    }
                                    if (FamilyDataListJson.Trim() != "")
                                    {
                                        StaffFamilyDataJson FamilyDataJson = (StaffFamilyDataJson)JavaScriptConvert.DeserializeObject(FamilyDataListJson, typeof(StaffFamilyDataJson));

                                        tbStaffInfo.UpdateStaffFamilyDataInfoByJson(FamilyDataJson, StaffID);
                                    }

                                    Logs.AddEventLog(this.userid, "修改人员." + si.sName);
                                    AddMsgLine("修改成功!");
                                    AddScript("window.setTimeout('window.parent.HidBox();',1000);");
                                }
                                catch (Exception ex)
                                {
                                    AddErrLine("修改失败!<br/>" + ex);
                                    //AddScript("window.setTimeout('window.parent.HidBox();',1000);");
                                }
                            }
                        }
                        Caches.ReSet();
                    }
                    else
                    {
                        DepartmentsClass = Caches.GetDepartmentsClassInfoToHTML();
                        if (Act == "Add")
                        {
                            si.sName  = "";
                            si.sSex   = "男";
                            si.sState = 0;
                            si.sType  = 0;
                        }
                        if (Act == "Edit")
                        {
                            EduDataListJson    = "";
                            WorkDataListJson   = "";
                            FamilyDataListJson = "";

                            EduDataList         = tbStaffInfo.GetStaffEduDataInfoList(" StaffID=" + StaffID + " order by StaffEduDataID desc").Tables[0];
                            StaffWorkDataList   = tbStaffInfo.GetStaffWorkDataInfoList(" StaffID=" + StaffID + " order by StaffWorkDataID desc").Tables[0];
                            StaffFamilyDataList = tbStaffInfo.GetStaffFamilyDataInfoList(" StaffID=" + StaffID + " order by StaffFamilyDataID desc").Tables[0];
                            try {
                                foreach (DataRow dr in EduDataList.Rows)
                                {
                                    EduDataListJson += "{\"StaffEduDataID\":\"" + dr["StaffEduDataID"].ToString() + "\",\"StaffID\":\"" + dr["StaffID"].ToString() + "\",\"eDate\":\"" + dr["eDate"].ToString() + "\",\"eSchools\":\"" + dr["eSchools"].ToString().Replace("\"", "\\\"") + "\",\"eContent\":\"" + dr["eContent"].ToString().Replace("\"", "\\\"") + "\"},";
                                }
                                if (EduDataListJson.Trim() != "")
                                {
                                    EduDataListJson = EduDataListJson.Substring(0, EduDataListJson.Length - 1);
                                }
                                EduDataListJson = "{\"EduDataList\":[" + EduDataListJson + "]}";

                                foreach (DataRow dr in StaffWorkDataList.Rows)
                                {
                                    WorkDataListJson += "{\"StaffWorkDataID\":\"" + dr["StaffWorkDataID"].ToString() + "\",\"StaffID\":\"" + dr["StaffID"].ToString() + "\",\"wDate\":\"" + dr["wDate"].ToString() + "\",\"wEnterprise\":\"" + dr["wEnterprise"].ToString().Replace("\"", "\\\"") + "\",\"wTel\":\"" + dr["wTel"].ToString().Replace("\"", "\\\"") + "\",\"wJobs\":\"" + dr["wJobs"].ToString().Replace("\"", "\\\"") + "\",\"wIncome\":\"" + dr["wIncome"].ToString().Replace("\"", "\\\"") + "\"},";
                                }
                                if (WorkDataListJson.Trim() != "")
                                {
                                    WorkDataListJson = WorkDataListJson.Substring(0, WorkDataListJson.Length - 1);
                                }
                                WorkDataListJson = "{\"WorkDataList\":[" + WorkDataListJson + "]}";

                                foreach (DataRow dr in StaffFamilyDataList.Rows)
                                {
                                    FamilyDataListJson += "{\"StaffFamilyDataID\":\"" + dr["StaffFamilyDataID"].ToString() + "\",\"StaffID\":\"" + dr["StaffID"].ToString() + "\",\"fTitle\":\"" + dr["fTitle"].ToString() + "\",\"fName\":\"" + dr["fName"].ToString().Replace("\"", "\\\"") + "\",\"fAge\":\"" + dr["fAge"].ToString().Replace("\"", "\\\"") + "\",\"fEnterprise\":\"" + dr["fEnterprise"].ToString().Replace("\"", "\\\"") + "\",\"fWork\":\"" + dr["fWork"].ToString().Replace("\"", "\\\"") + "\",\"fAddress\":\"" + dr["fAddress"].ToString().Replace("\"", "\\\"") + "\",\"fTel\":\"" + dr["fTel"].ToString().Replace("\"", "\\\"") + "\"},";
                                }
                                if (FamilyDataListJson.Trim() != "")
                                {
                                    FamilyDataListJson = FamilyDataListJson.Substring(0, FamilyDataListJson.Length - 1);
                                }
                                FamilyDataListJson = "{\"FamilyDataList\":[" + FamilyDataListJson + "]}";
                            }
                            finally {
                                EduDataList         = null;
                                StaffWorkDataList   = null;
                                StaffFamilyDataList = null;
                            }
                        }

                        if (Act == "Del")
                        {
                            try
                            {
                                tbStaffInfo.DeleteStaffInfo(HTTPRequest.GetString("sid"));
                                Logs.AddEventLog(this.userid, "删除人员." + HTTPRequest.GetString("sid"));
                                AddMsgLine("删除成功!");
                                AddScript("window.setTimeout('window.parent.HidBox();',1000);");
                            }
                            catch (Exception ex)
                            {
                                AddErrLine("删除失败!<br/>" + ex);
                                AddScript("window.setTimeout('window.parent.HidBox();',1000);");
                            }
                        }
                    }
                }
                else
                {
                    AddErrLine("权限不足!");
                    AddScript("window.setTimeout('window.parent.HidBox();',1000);");
                }
            }
            else
            {
                AddErrLine("请先登录!");
                SetBackLink("login.aspx?referer=" + Utils.UrlEncode(Utils.GetUrlReferrer()));
                SetMetaRefresh(1, "login.aspx?referer=" + Utils.UrlEncode(Utils.GetUrlReferrer()));
            }
            if (format == "json")
            {
                Response.ClearContent();
                Response.Buffer          = true;
                Response.ExpiresAbsolute = System.DateTime.Now.AddYears(-1);
                Response.Expires         = 0;

                Response.Charset         = "utf-8";
                Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
                Response.ContentType     = "application/json";
                string Json_Str = "{\"results\": {\"msg\":\"" + this.msgbox_text + "\",\"state\":\"" + (!IsErr()).ToString() + "\"" + tJson + "}}";
                Response.Write(Json_Str);
                Response.End();
            }
        }
        public override void ExecuteCmdlet()
        {
            if (DataConnectorId == null)
            {
                DataConnectorId = Guid.NewGuid().ToString();
            }

            var name = DataConnectorId;

            var tenantId = AzureRmProfileProvider.Instance.Profile.DefaultContext.Tenant.Id;

            if (ShouldProcess(name, VerbsCommon.New))
            {
                switch (ParameterSetName)
                {
                case ParameterSetNames.AzureActiveDirectory:
                    DataConnectorDataTypeCommon aadcommon = new DataConnectorDataTypeCommon
                    {
                        State = Alerts.ToLower()
                    };
                    AlertsDataTypeOfDataConnector aadalerts = new AlertsDataTypeOfDataConnector
                    {
                        Alerts = aadcommon
                    };
                    AADDataConnector aadDataTypes = new AADDataConnector
                    {
                        DataTypes = aadalerts,
                        TenantId  = tenantId
                    };
                    DataConnector aadDataConnector   = aadDataTypes;
                    var           outputaadconnector = SecurityInsightsClient.DataConnectors.CreateOrUpdate(ResourceGroupName, WorkspaceName, name, aadDataConnector);
                    WriteObject(outputaadconnector.ConvertToPSType(), enumerateCollection: false);
                    break;

                case ParameterSetNames.AzureAdvancedThreatProtection:
                    DataConnectorDataTypeCommon aatpcommon = new DataConnectorDataTypeCommon
                    {
                        State = Alerts.ToLower()
                    };
                    AlertsDataTypeOfDataConnector aatpalerts = new AlertsDataTypeOfDataConnector
                    {
                        Alerts = aatpcommon
                    };
                    AATPDataConnector aatpDataTypes = new AATPDataConnector
                    {
                        DataTypes = aatpalerts,
                        TenantId  = tenantId
                    };
                    DataConnector aatpDataConnector   = aatpDataTypes;
                    var           outputaatpconnector = SecurityInsightsClient.DataConnectors.CreateOrUpdate(ResourceGroupName, WorkspaceName, name, aatpDataConnector);
                    WriteObject(outputaatpconnector.ConvertToPSType(), enumerateCollection: false);
                    break;

                case ParameterSetNames.AzureSecurityCenter:
                    DataConnectorDataTypeCommon asccommon = new DataConnectorDataTypeCommon
                    {
                        State = Alerts.ToLower()
                    };
                    AlertsDataTypeOfDataConnector ascalerts = new AlertsDataTypeOfDataConnector
                    {
                        Alerts = asccommon
                    };
                    ASCDataConnector ascDataTypes = new ASCDataConnector
                    {
                        DataTypes      = ascalerts,
                        SubscriptionId = SubscriptionId
                    };
                    DataConnector ascDataConnector   = ascDataTypes;
                    var           outputascconnector = SecurityInsightsClient.DataConnectors.CreateOrUpdate(ResourceGroupName, WorkspaceName, name, ascDataConnector);
                    WriteObject(outputascconnector.ConvertToPSType(), enumerateCollection: false);
                    break;

                case ParameterSetNames.AmazonWebServicesCloudTrail:
                    AwsCloudTrailDataConnectorDataTypesLogs awscommon = new AwsCloudTrailDataConnectorDataTypesLogs
                    {
                        State = Logs.ToLower()
                    };
                    AwsCloudTrailDataConnectorDataTypes awslogs = new AwsCloudTrailDataConnectorDataTypes
                    {
                        Logs = awscommon
                    };
                    AwsCloudTrailDataConnector awsDataTypes = new AwsCloudTrailDataConnector
                    {
                        DataTypes  = awslogs,
                        AwsRoleArn = AwsRoleArn
                    };
                    DataConnector awsDataConnector   = awsDataTypes;
                    var           outputawsconnector = SecurityInsightsClient.DataConnectors.CreateOrUpdate(ResourceGroupName, WorkspaceName, name, awsDataConnector);
                    WriteObject(outputawsconnector.ConvertToPSType(), enumerateCollection: false);
                    break;

                case ParameterSetNames.MicrosoftCloudAppSecurity:
                    DataConnectorDataTypeCommon mcascommon = new DataConnectorDataTypeCommon
                    {
                        State = Alerts.ToLower()
                    };
                    DataConnectorDataTypeCommon mcasdiscovery = new DataConnectorDataTypeCommon
                    {
                        State = DiscoveryLogs
                    };
                    MCASDataConnectorDataTypes mcasDataTypes = new MCASDataConnectorDataTypes
                    {
                        Alerts        = mcascommon,
                        DiscoveryLogs = mcasdiscovery
                    };
                    MCASDataConnector mcasConnector = new MCASDataConnector
                    {
                        DataTypes = mcasDataTypes,
                        TenantId  = tenantId
                    };
                    DataConnector mcasDataConnector   = mcasConnector;
                    var           outputmcasconnector = SecurityInsightsClient.DataConnectors.CreateOrUpdate(ResourceGroupName, WorkspaceName, name, mcasDataConnector);
                    WriteObject(outputmcasconnector.ConvertToPSType(), enumerateCollection: false);
                    break;

                case ParameterSetNames.MicrosoftDefenderAdvancedThreatProtection:
                    DataConnectorDataTypeCommon mdatpcommon = new DataConnectorDataTypeCommon
                    {
                        State = Alerts.ToLower()
                    };
                    AlertsDataTypeOfDataConnector mdatpalerts = new AlertsDataTypeOfDataConnector
                    {
                        Alerts = mdatpcommon
                    };
                    MDATPDataConnector mdatpDataTypes = new MDATPDataConnector
                    {
                        DataTypes = mdatpalerts,
                        TenantId  = tenantId
                    };
                    DataConnector mdatpDataConnector   = mdatpDataTypes;
                    var           outputmdatpconnector = SecurityInsightsClient.DataConnectors.CreateOrUpdate(ResourceGroupName, WorkspaceName, name, mdatpDataConnector);
                    WriteObject(outputmdatpconnector.ConvertToPSType(), enumerateCollection: false);
                    break;

                case ParameterSetNames.Office365:
                    OfficeDataConnectorDataTypesExchange officeExchange = new OfficeDataConnectorDataTypesExchange
                    {
                        State = Exchange.ToLower()
                    };
                    OfficeDataConnectorDataTypesSharePoint officeSharePoint = new OfficeDataConnectorDataTypesSharePoint
                    {
                        State = SharePoint.ToLower()
                    };
                    OfficeDataConnectorDataTypes officeDataTypes = new OfficeDataConnectorDataTypes
                    {
                        Exchange   = officeExchange,
                        SharePoint = officeSharePoint
                    };
                    OfficeDataConnector officeConnector = new OfficeDataConnector
                    {
                        DataTypes = officeDataTypes,
                        TenantId  = tenantId
                    };
                    DataConnector officeDataConnector   = officeConnector;
                    var           outputofficeconnector = SecurityInsightsClient.DataConnectors.CreateOrUpdate(ResourceGroupName, WorkspaceName, name, officeDataConnector);
                    WriteObject(outputofficeconnector.ConvertToPSType(), enumerateCollection: false);
                    break;

                case ParameterSetNames.ThreatIntelligence:
                    TIDataConnectorDataTypesIndicators tiIndicators = new TIDataConnectorDataTypesIndicators
                    {
                        State = Indicators.ToLower()
                    };
                    TIDataConnectorDataTypes tiDataTypes = new TIDataConnectorDataTypes
                    {
                        Indicators = tiIndicators
                    };
                    TIDataConnector tiConnector = new TIDataConnector
                    {
                        DataTypes = tiDataTypes,
                        TenantId  = tenantId
                    };
                    DataConnector tiDataConnector   = tiConnector;
                    var           outputticonnector = SecurityInsightsClient.DataConnectors.CreateOrUpdate(ResourceGroupName, WorkspaceName, name, tiDataConnector);
                    WriteObject(outputticonnector.ConvertToPSType(), enumerateCollection: false);
                    break;

                default:
                    throw new PSInvalidOperationException();
                }
            }
        }
Пример #15
0
        public void GenerateObjSet(string filePath, Model stgpv, ObjectDatabase objdb, TextureDatabase texturedb, StageDatabase staged, string acpath, divamodgen divamods, bool doProcess = true, bool debug = false)
        {
            /*
             * var stgpv = new Model();
             * var textures = new MikuMikuLibrary.Textures.TextureSet();
             * var texdb = new TextureDatabase();
             *
             * using (var farcArchive = BinaryFile.Load<FarcArchive>(filePath))
             * using (var entryStream = farcArchive.Open(farcArchive.Entries.Where(c => c.Contains("txi")).First(), EntryStreamMode.MemoryStream))
             *  texdb.Load(entryStream);
             *
             * if (debug)
             * {
             *  string farcpath = acpath + "\\rom\\objset\\" + Path.GetFileNameWithoutExtension(filePath).Replace("stgpv0", "stgpv8") + ".farc";
             *
             *  using (var farcArchive = BinaryFile.Load<FarcArchive>(farcpath))
             *  using (var entryStream = farcArchive.Open(farcArchive.Entries.Where(c => c.Contains("tex")).First(), EntryStreamMode.MemoryStream))
             *      textures.Load(entryStream);
             *
             * }
             * else
             * {
             *  using (var farcArchive = BinaryFile.Load<FarcArchive>(filePath))
             *  using (var entryStream = farcArchive.Open(farcArchive.Entries.Where(c => c.Contains("txd")).First(), EntryStreamMode.MemoryStream))
             *      textures.Load(entryStream);
             *
             *  using (var farcArchive = BinaryFile.Load<FarcArchive>(filePath))
             *  using (var entryStream = farcArchive.Open(farcArchive.Entries.First(), EntryStreamMode.MemoryStream))
             *      stgpv.Load(entryStream, textures, texdb);
             * }
             *
             */

            if (Path.GetFileNameWithoutExtension(filePath).Contains("effpv"))
            {
                filePath = Path.GetDirectoryName(filePath) + "\\" + Path.GetFileNameWithoutExtension(filePath).Replace("effpv", "stgpv") + "hrc2.farc";
            }

            var texdb = new TextureDatabase();

            //using (var farcArchive = BinaryFile.Load<FarcArchive>(filePath))
            //using (var entryStream = farcArchive.Open(farcArchive.Entries.Where(c => c.Contains("txi")).First(), EntryStreamMode.MemoryStream))
            //   texdb.Load(entryStream);

            var objentry = new ObjectEntry();

            objentry.ArchiveFileName = Path.GetFileName(filePath).Replace("stgpv0", "stgpv8");
            objentry.FileName        = Path.GetFileNameWithoutExtension(filePath).Replace("stgpv0", "stgpv8") + "_obj.bin";
            objentry.Id              = FindUnusedID(objdb);
            objentry.Name            = Path.GetFileNameWithoutExtension(filePath).Replace("stgpv0", "stgpv8").ToUpper();
            objentry.TextureFileName = Path.GetFileNameWithoutExtension(filePath).Replace("stgpv0", "stgpv8") + "_tex.bin";

            int ground_id = -1;

            ushort counter = 1;

            foreach (var meshes in stgpv.Meshes)
            {
                meshes.SubMeshes.RemoveAll(x => x.Vertices == null || x.Vertices.Length == 0);
                meshes.Name = meshes.Name.Replace("STGPV0", "STGPV8");
                meshes.Name = meshes.Name.Replace("EFFPV", "STGPV");

                if (Path.GetFileName(filePath).Contains("hrc"))
                {
                    int pvid = int.Parse(Path.GetFileName(filePath).Substring(5, 3));

                    if (pvid < 200)
                    {
                        pvid = pvid + 800;
                    }

                    {
                        var check2 = divamods.Divamods.Where(c => c.pvid == pvid).FirstOrDefault();
                        if (check2 == null)
                        {
                            divamods.Divamods.Add(new pdaconversion.divamods(pvid));
                            Logs.WriteLine("objset: Created new PV at id " + pvid);
                            check2 = divamods.Divamods.Where(c => c.pvid == pvid).First();
                        }
                        check2.item_pv.Add(meshes.Name);
                        Logs.WriteLine("objset: Added item_pv for PV at id " + pvid + "," + meshes.Name);
                    }

                    if (pvid >= 800)
                    {
                        var check2 = divamods.Divamods.Where(c => c.pvid == (pvid - 100)).FirstOrDefault();
                        if (check2 == null)
                        {
                            divamods.Divamods.Add(new pdaconversion.divamods(pvid - 100));
                            Logs.WriteLine("objset: Created new PV at id " + (pvid - 100));
                            check2 = divamods.Divamods.Where(c => c.pvid == (pvid - 100)).First();
                        }
                        check2.item_pv.Add(meshes.Name);
                        Logs.WriteLine("objset: Added item_pv for PV at id " + (pvid - 100) + "," + meshes.Name);
                    }
                }

                var meshentry = new MeshEntry();
                meshes.Id      = counter;
                meshentry.Id   = (ushort)meshes.Id;
                meshentry.Name = meshes.Name;

                if (meshes.Name.Contains("GND"))
                {
                    ground_id = meshes.Id;
                }

                objentry.Meshes.Add(meshentry);

                if (doProcess)
                {
                    if (!debug)
                    {
                        /*
                         * foreach (var submeshes in meshes.SubMeshes)
                         * {
                         *  foreach (var indexTable in submeshes.IndexTables)
                         *  {
                         *      ushort[] triangleStrip = Stripifier.Stripify(indexTable.Indices);
                         *      if (triangleStrip != null)
                         *      {
                         *          indexTable.PrimitiveType = PrimitiveType.TriangleStrip;
                         *          indexTable.Indices = triangleStrip;
                         *      }
                         *  }
                         * }
                         */
                    }

                    //foreach (var textures in M)

                    foreach (var material in meshes.Materials)
                    {
                        if ((Path.GetFileName(filePath).Contains("hrc2")) || (Path.GetFileName(filePath).Contains("hrc")))
                        {
                            material.Shader         = "ITEM";
                            material.IsAlphaEnabled = false;
                            //material.Field00 = 0x00000001;
                            //material.Field02 = 0x00000A80;

                            //material.Diffuse.Field00 = 0x00000000;
                            //material.Diffuse.Field01 = 0x016400E1;
                            //material.Diffuse.Field02 = 0x000000F1;

                            MikuMikuLibrary.Misc.Color asdf = new MikuMikuLibrary.Misc.Color(0, 0, 0, 0);

                            material.SpecularColor = asdf;

                            //material.AmbientColor = asdf;
                            //material.EmissionColor = asdf;
                            //material.SpecularColor = asdf;

                            //material.Shininess = 1;

                            //material.Diffuse.Field00 = 0x00000000;
                            //material.Diffuse.Field01 = 0x002400E0;
                            //material.Diffuse.Field02 = 0x000000F1;

                            if (material.Ambient.TextureId == 1509989155)
                            {
                                material.Ambient.TextureId = -1;
                            }
                            if (material.Normal.TextureId == 1509989155)
                            {
                                material.Normal.TextureId = -1;
                            }
                            if (material.Specular.TextureId == 1509989155)
                            {
                                material.Specular.TextureId = -1;
                                material.SpecularColor      = asdf;
                            }
                            //else { material.Field00 = 0x0000002D; }

                            /*
                             *
                             * // this blacken the screen on STAGE SHADER
                             * material.Specular.Field01 = 0x002418C3;
                             * material.Specular.Field02 = 0x000000F3;
                             * material.Specular.Field05 = 1;
                             * material.Specular.Field06 = 1;
                             * material.Specular.Field11 = 1;
                             * material.Specular.Field16 = 1;
                             * material.Specular.Field21 = 1;
                             *
                             *
                             * material.Specular.TextureId = -1;
                             * material.Specular.Field01 = 0x00000000;
                             * material.Specular.Field02 = 0x000000F0;
                             * material.Specular.Field05 = 1;
                             * material.Specular.Field06 = 0;
                             * material.Specular.Field11 = 0;
                             * material.Specular.Field16 = 0;
                             * material.Specular.Field21 = 0;
                             *
                             * material.Reflection.TextureId = -1;
                             * material.Reflection.Field01 = 0x00000000;
                             * material.Reflection.Field02 = 0x000000F0;
                             * material.Reflection.Field05 = 1;
                             * material.Reflection.Field06 = 0;
                             * material.Reflection.Field11 = 0;
                             * material.Reflection.Field16 = 0;
                             * material.Reflection.Field21 = 0;
                             */

                            if (material.Reflection.TextureId == 1509989155)
                            {
                                material.Reflection.TextureId = -1;
                            }
                            if (material.ToonCurve.TextureId == 1509989155)
                            {
                                material.ToonCurve.TextureId = -1;
                            }
                            if (material.SpecularPower.TextureId == 1509989155)
                            {
                                material.SpecularPower.TextureId = -1;
                            }
                            if (material.Texture08.TextureId == 1509989155)
                            {
                                material.Texture08.TextureId = -1;
                            }
                        }
                        else
                        {
                            material.Shader = "BLINN";
                            //material.Field00 = 0x0000000D;
                            //material.Field02 = 0x00000A80;

                            MikuMikuLibrary.Misc.Color asdf = new MikuMikuLibrary.Misc.Color(0, 0, 0, 0);

                            //material.AmbientColor = asdf;
                            //material.EmissionColor = asdf;
                            //material.Shininess = 1;
                            //material.Diffuse.Field00 = 0x00000230;
                            //material.Diffuse.Field02 = 0x002418C3;

                            if (material.Ambient.TextureId == 1509989155)
                            {
                                material.Ambient.TextureId = -1;
                            }
                            if (material.Normal.TextureId == 1509989155)
                            {
                                material.Normal.TextureId = -1;
                            }
                            if (material.Specular.TextureId == 1509989155)
                            {
                                material.Specular.TextureId = -1;
                                material.SpecularColor      = asdf;
                            }
                            //else { material.Field00 = 0x0000002D; }

                            /*
                             *
                             * // this blacken the screen on STAGE SHADER
                             * material.Specular.Field01 = 0x002418C3;
                             * material.Specular.Field02 = 0x000000F3;
                             * material.Specular.Field05 = 1;
                             * material.Specular.Field06 = 1;
                             * material.Specular.Field11 = 1;
                             * material.Specular.Field16 = 1;
                             * material.Specular.Field21 = 1;
                             *
                             */

                            /*
                             * material.Specular.TextureId = -1;
                             * material.Specular.Field01 = 0x00000000;
                             * material.Specular.Field02 = 0x000000F0;
                             * material.Specular.Field05 = 5;
                             * material.Specular.Field06 = 0;
                             * material.Specular.Field11 = 0;
                             * material.Specular.Field16 = 0;
                             * material.Specular.Field21 = 0;
                             *
                             *
                             * material.Normal.Field01 = 0x00000000;
                             * material.Normal.Field02 = 0x000000F0;
                             * material.Normal.Field05 = 5;
                             * material.Normal.Field06 = 0;
                             * material.Normal.Field11 = 0;
                             * material.Normal.Field16 = 0;
                             * material.Normal.Field21 = 0;
                             *
                             *
                             * material.ToonCurve.TextureId = -1;
                             * material.ToonCurve.Field01 = 0x00000000;
                             * material.ToonCurve.Field02 = 0x000000F0;
                             * material.ToonCurve.Field05 = 5;
                             * material.ToonCurve.Field06 = 0;
                             * material.ToonCurve.Field11 = 0;
                             * material.ToonCurve.Field16 = 0;
                             * material.ToonCurve.Field21 = 0;
                             */

                            if (material.Reflection.TextureId == 1509989155)
                            {
                                material.Reflection.TextureId = -1;
                            }
                            if (material.ToonCurve.TextureId == 1509989155)
                            {
                                material.ToonCurve.TextureId = -1;
                            }
                            if (material.SpecularPower.TextureId == 1509989155)
                            {
                                material.SpecularPower.TextureId = -1;
                            }
                            if (material.Texture08.TextureId == 1509989155)
                            {
                                material.Texture08.TextureId = -1;
                            }
                        }
                    }
                }
                counter++;
            }

            stgpv.TextureSet.Format = BinaryFormat.DT;
            stgpv.Format            = BinaryFormat.DT;



            if (doProcess)
            {
                stgpv.Save("temp\\" + Path.GetFileNameWithoutExtension(filePath) + "_obj.bin", null, texturedb, null);
            }
            objdb.Objects.Add(objentry);

            if (Path.GetFileNameWithoutExtension(filePath).Count() == 8)
            {
                StageEntry stage = new StageEntry();
                stage.Id                  = FindUnusedID(staged);
                stage.Name                = Path.GetFileNameWithoutExtension(filePath).Replace("stgpv0", "stgpv8").ToUpper();
                stage.ObjectGroundId      = (short)ground_id;
                stage.ObjectGroundIdFlag  = (short)objentry.Id;
                stage.ObjectId3           = -1;
                stage.ObjectIdFlag3       = -1;
                stage.ObjectId5           = -1;
                stage.ObjectIdFlag5       = -1;
                stage.ObjectId7           = -1;
                stage.ObjectIdFlag7       = -1;
                stage.RingRectangleX      = -8;
                stage.RingRectangleY      = -8;
                stage.RingRectangleWidth  = 16;
                stage.RingRectangleHeight = 16;
                stage.RingRingHeight      = 0;
                stage.RingOutHeight       = -1000;
                stage.Field00             = 1;
                stage.Field11             = -1;
                stage.Field02             = -1;

                stage.LensFlareScaleX = -1;
                stage.LensFlareScaleY = -1;
                stage.LensFlareScaleZ = -1;

                stage.ObjectSkyId         = -1;
                stage.ObjectSkyIdFlag     = -1;
                stage.ObjectReflectId     = -1;
                stage.ObjectReflectIdFlag = -1;

                stage.CollisionFilePath = @"rom/STGTST_COLI.000.bin";

                stage.ObjectId1    = (short)objentry.Id;
                stage.StageEffect1 = StageEntry.StageEffect.Empty;
                stage.Auth3dName   = "EFF" + stage.Name;
                staged.Stages.Add(stage);
            }

            if (doProcess)
            {
                var newfarc = new FarcArchive();
                newfarc.Add(Path.GetFileNameWithoutExtension(filePath).Replace("stgpv0", "stgpv8") + "_obj.bin", "temp\\" + Path.GetFileNameWithoutExtension(filePath) + "_obj.bin");
                newfarc.Add(Path.GetFileNameWithoutExtension(filePath).Replace("stgpv0", "stgpv8") + "_tex.bin", "temp\\" + Path.GetFileNameWithoutExtension(filePath) + "_tex.bin");
                newfarc.Alignment    = 16;
                newfarc.IsCompressed = false;
                newfarc.Save(acpath + "\\rom\\objset\\" + Path.GetFileNameWithoutExtension(filePath).Replace("stgpv0", "stgpv8") + ".farc");
            }
        }
Пример #16
0
        public async Task <(string DeviceName, int?exitCode)> RunApp(
            AppBundleInformation appInformation,
            TestTargetOs target,
            TimeSpan timeout,
            string?deviceName              = null,
            string?companionDeviceName     = null,
            bool ensureCleanSimulatorState = false,
            int verbosity = 1,
            CancellationToken cancellationToken = default)
        {
            bool isSimulator = target.Platform.IsSimulator();

            ISimulatorDevice?simulator          = null;
            ISimulatorDevice?companionSimulator = null;

            // Find devices
            if (isSimulator)
            {
                (simulator, companionSimulator) = await _simulatorLoader.FindSimulators(target, _mainLog, 3);

                deviceName = companionSimulator?.Name ?? simulator.Name;
            }
            else
            {
                deviceName ??= await FindDevice(target) ?? throw new NoDeviceFoundException();
            }

            var crashLogs = new Logs(_logs.Directory);

            ICrashSnapshotReporter crashReporter = _snapshotReporterFactory.Create(_mainLog, crashLogs, isDevice: !isSimulator, deviceName);

            _mainLog.WriteLine($"*** Executing '{appInformation.AppName}' on {target} '{deviceName}' ***");

            if (isSimulator)
            {
                if (simulator == null)
                {
                    _mainLog.WriteLine("Didn't find any suitable simulator");
                    throw new NoDeviceFoundException();
                }

                var mlaunchArguments = GetSimulatorArguments(appInformation, simulator, verbosity);

                await RunSimulatorApp(
                    mlaunchArguments,
                    appInformation,
                    crashReporter,
                    simulator,
                    companionSimulator,
                    ensureCleanSimulatorState,
                    timeout,
                    cancellationToken);
            }
            else
            {
                var mlaunchArguments = GetDeviceArguments(appInformation, deviceName, target.Platform.IsWatchOSTarget(), verbosity);

                await RunDeviceApp(
                    mlaunchArguments,
                    crashReporter,
                    deviceName,
                    timeout,
                    cancellationToken);
            }

            var systemLog = _logs.FirstOrDefault(log => log.Description == LogType.SystemLog.ToString());

            if (systemLog == null)
            {
                _mainLog.WriteLine("App run ended but failed to detect exit code (no system log found)");
                return(deviceName, null);
            }

            var exitCode = _exitCodeDetector.DetectExitCode(appInformation, systemLog);

            _mainLog.WriteLine($"App run ended with {exitCode}");

            return(deviceName, exitCode);
        }
        public IHttpActionResult GetMarksheetData()
        {
            var httpRequest = HttpContext.Current.Request;

            try
            {
                string search = httpRequest.Params["searchFilter"];
                //string draw = httpRequest.Form.GetValues("draw")[0];
                string order         = httpRequest.Params["orderColumn"];
                string orderDir      = httpRequest.Params["orderDir"];
                int    startRec      = Convert.ToInt32(httpRequest.Params["pageNumber"]);
                int    pageSize      = Convert.ToInt32(httpRequest.Params["pageSize"]);
                var    marksheetData = _context.Marksheets.ToList();
                int    totalRecords  = marksheetData.Count;
                if (!string.IsNullOrEmpty(search) &&
                    !string.IsNullOrWhiteSpace(search))
                {
                    marksheetData = marksheetData.Where(p => p.EnrollementNo.ToString().ToLower().Contains(search.ToLower()) ||
                                                        p.StatementNo.ToString().ToLower().Contains(search.ToLower()) ||
                                                        p.Year.ToString().ToLower().Contains(search.ToLower()) ||
                                                        p.Month.ToString().ToLower().Contains(search.ToLower()) ||
                                                        p.ApprovedTime.ToString().ToLower().Contains(search.ToLower()) ||
                                                        p.DisapprovedTime.ToString().ToLower().Contains(search.ToLower()) ||
                                                        p.IsApproved.ToString().ToLower().Contains(search.ToLower()) ||
                                                        p.Semester.ToString().ToLower().Contains(search.ToLower())
                                                        ).ToList();
                }

                marksheetData = SortGetMarksheetData(order, orderDir, marksheetData);

                int recFilter = marksheetData.Count;
                marksheetData = marksheetData.Skip(startRec).Take(pageSize).ToList();
                var modifiedData = marksheetData.Select(d => new
                {
                    enrollementNo   = d.EnrollementNo,
                    statementNo     = d.StatementNo,
                    year            = d.Year,
                    month           = d.Month,
                    semester        = d.Semester,
                    approvedTime    = d.ApprovedTime,
                    disapprovedTime = d.DisapprovedTime,
                    isApproved      = d.IsApproved,
                    marksheetId     = d.MarksheetId
                });
                return(Ok(new
                {
                    count = Convert.ToInt32(totalRecords),
                    recordsTotal = totalRecords,
                    recordsFiltered = recFilter,
                    rows = modifiedData
                }));
            }
            catch (Exception ex)
            {
                Logs.ControllerLogs(ex);
                return(Ok(new
                {
                    count = 0,
                    recordsTotal = "",
                    recordsFiltered = 0,
                    rows = ""
                }));
            }
        }
Пример #18
0
        /// <summary>
        /// Initializes the counter instances and category.
        /// </summary>
        public void InitializePerfCounters(bool enableDebuggingCounters)
        {
            try
            {
                if (!UserHasAccessRights)
                    return;

                lock (this)
                {
                    string instname = _instanceName;

                    _instanceName = instname;
                    if (enableDebuggingCounters)
                    {
                        _pcTcpDownQueueCount = new PerformanceCounter(PC_CATEGORY, "TcpDownQueueCount", _instanceName, false);
                        _pcTcpUpQueueCount = new PerformanceCounter(PC_CATEGORY, "TcpUpQueueCount", _instanceName, false);
                        _pcBcastQueueCount = new PerformanceCounter(PC_CATEGORY, "BcastQueueCount", _instanceName, false);
                        _pcMcastQueueCount = new PerformanceCounter(PC_CATEGORY, "McastQueueCount", _instanceName, false);
                        _pcSocketSendTime = new PerformanceCounter(PC_CATEGORY, "Socket send time (msec)", _instanceName, false);
                        _pcSocketSendSize = new PerformanceCounter(PC_CATEGORY, "Socket send size (bytes)", _instanceName, false);
                        _pcSocketReceiveTime = new PerformanceCounter(PC_CATEGORY, "Socket recv time (msec)", _instanceName, false);
                        _pcSocketReceiveSize = new PerformanceCounter(PC_CATEGORY, "Socket recv size (bytes)", _instanceName, false);
                        _pcNagglingMsgCount = new PerformanceCounter(PC_CATEGORY, "NaglingMsgCount", _instanceName, false);
                        _pcBytesSentPerSec = new PerformanceCounter(PC_CATEGORY, "Bytes sent/sec", _instanceName, false);
                        _pcBytesReceivedPerSec = new PerformanceCounter(PC_CATEGORY, "Bytes received/sec", _instanceName, false);
                    }

                    _pcClusteredOperationsPerSec = new PerformanceCounter(PC_CATEGORY, "Cluster ops/sec", _instanceName, false);

                    if(System.Configuration.ConfigurationSettings.AppSettings["printClusterStats"] != null)
                    {
                        bool printStats = Convert.ToBoolean(System.Configuration.ConfigurationSettings.AppSettings["printClusterStats"]);
                        if (printStats)
                        {
                            if (System.Configuration.ConfigurationSettings.AppSettings["statsPrintInterval"] != null)
                            {
                                _printInterval = new TimeSpan(Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["statsPrintInterval"]),0,0);
                            }

                            _logger = new Logs();
                            _logger.Initialize(instname + ".clstats", "ClusterPerfMonStats");

                            _printThread = new Thread(new ThreadStart(PrintStats));
                            _printThread.Start();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                NCacheLog.Warn("PerfStatsCollector.PerfStatsCollector()    "+ e.Message);
            }
        }
Пример #19
0
        public async Task EndCaptureAsync(TimeSpan timeout)
        {
            // Check for crash reports
            var crash_report_search_done    = false;
            var crash_report_search_timeout = timeout.TotalSeconds;
            var watch = new Stopwatch();

            watch.Start();
            do
            {
                var end_crashes = await Harness.CreateCrashReportsSnapshotAsync(Log, !Device, DeviceName);

                end_crashes.ExceptWith(InitialSet);
                Reports = end_crashes;
                if (end_crashes.Count > 0)
                {
                    Log.WriteLine("Found {0} new crash report(s)", end_crashes.Count);
                    List <ILogFile> crash_reports;
                    if (!Device)
                    {
                        crash_reports = new List <ILogFile> (end_crashes.Count);
                        foreach (var path in end_crashes)
                        {
                            Logs.AddFile(path, $"Crash report: {Path.GetFileName (path)}");
                        }
                    }
                    else
                    {
                        // Download crash reports from the device. We put them in the project directory so that they're automatically deleted on wrench
                        // (if we put them in /tmp, they'd never be deleted).
                        var downloaded_crash_reports = new List <ILogFile> ();
                        foreach (var file in end_crashes)
                        {
                            var name = Path.GetFileName(file);
                            var crash_report_target = Logs.Create(name, $"Crash report: {name}", timestamp: false);
                            var sb = new List <string> ();
                            sb.Add($"--download-crash-report={file}");
                            sb.Add($"--download-crash-report-to={crash_report_target.Path}");
                            sb.Add("--sdkroot");
                            sb.Add(Harness.XcodeRoot);
                            if (!string.IsNullOrEmpty(DeviceName))
                            {
                                sb.Add("--devname");
                                sb.Add(DeviceName);
                            }
                            var result = await ProcessHelper.ExecuteCommandAsync(Harness.MlaunchPath, sb, Log, TimeSpan.FromMinutes(1));

                            if (result.Succeeded)
                            {
                                Log.WriteLine("Downloaded crash report {0} to {1}", file, crash_report_target.Path);
                                crash_report_target = await Harness.SymbolicateCrashReportAsync(Logs, Log, crash_report_target);

                                downloaded_crash_reports.Add(crash_report_target);
                            }
                            else
                            {
                                Log.WriteLine("Could not download crash report {0}", file);
                            }
                        }
                        crash_reports = downloaded_crash_reports;
                    }
                    foreach (var cp in crash_reports)
                    {
                        Harness.LogWrench("@MonkeyWrench: AddFile: {0}", cp.Path);
                        Log.WriteLine("    {0}", cp.Path);
                    }
                    crash_report_search_done = true;
                }
                else
                {
                    if (watch.Elapsed.TotalSeconds > crash_report_search_timeout)
                    {
                        crash_report_search_done = true;
                    }
                    else
                    {
                        Log.WriteLine("No crash reports, waiting a second to see if the crash report service just didn't complete in time ({0})", (int)(crash_report_search_timeout - watch.Elapsed.TotalSeconds));
                        Thread.Sleep(TimeSpan.FromSeconds(1));
                    }
                }
            } while (!crash_report_search_done);
        }
Пример #20
0
 /// <summary>
 /// 添加
 /// </summary>
 /// <param name="entity">业务实体</param>
 public void Add(Logs entity)
 {
     Gateway.Default.Save <Logs>(entity);
 }
Пример #21
0
        internal List<Logs> getLogs()
        {
            String spname = "PKG_MM_LOGS.GET_LOGS";
             List<Logs> currentSysLogs = new List<Logs>();

            using (var conn = new OracleConnection(dbConn))
             using (var command = new OracleCommand(spname, conn)
             {
                 CommandType = CommandType.StoredProcedure
             })
             {
                 OracleParameter[] parameters = new OracleParameter[1];
                 parameters[0] = new OracleParameter();
                 parameters[0].ParameterName = "P_CUR";
                 parameters[0].OracleDbType = OracleDbType.RefCursor;
                 parameters[0].Direction = ParameterDirection.Output;

                 command.Parameters.AddRange(parameters);
                 conn.Open();
                OracleDataReader reader =  command.ExecuteReader();
                while (reader.Read())
                {
                    Logs alog = new Logs();

                    alog.datetime = (DateTime)reader["DATETIME"];
                    alog.log_level = reader["LOG_LEVEL"].ToString();
                    alog.message = reader["MESSAGE"].ToString();
                    alog.msgException = reader["EXCEPTION"].ToString();

                    currentSysLogs.Add(alog);
                }
                reader.Close();
             }

             return currentSysLogs;
        }
Пример #22
0
 protected override void OnException(ExceptionContext filterContext)
 {
     Logs.Write(filterContext.Exception);
 }
Пример #23
0
    protected void RpListLanguageNationals_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        string c = e.CommandName.Trim();
        string p = e.CommandArgument.ToString().Trim();

        switch (c)
        {
            #region delete
            //case "delete":
            //    if (!language.Equals(p))
            //    {
            //        LanguageNational.DeleteLanguageNationalAndLanguageItem(p);
            //    }
            //    else
            //    {
            //        ScriptManager.RegisterStartupScript(this, GetType(), "DeleteItem",
            //                                            "ThongBao(3000, 'Bạn đang sử dụng ngôn ngữ này vì vậy không thể xóa được!');",
            //                                            true);
            //    }
            //    break;
            #endregion

            #region Edit Status
        case "EditStatus":
            top       = "1";
            fields    = "iLanguageNationalEnable, nLanguageNationalName";
            condition = LanguageNationalTSql.GetByiLanguageNationalId(p);
            order     = "";
            DataTable dt = new DataTable();
            dt = LanguageNational.GetLanguageNational(top, fields, condition, order);

            string[] fieldsEditStatus = { "iLanguageNationalEnable" };
            string[] valuesEditStatus = { "" };
            if (dt.Rows[0]["iLanguageNationalEnable"].ToString().Equals("0"))
            {
                valuesEditStatus[0] = "1";
                LanguageNational.UpdateLanguageNational(DataExtension.UpdateTransfer(fieldsEditStatus, valuesEditStatus), condition);
            }
            else
            {
                valuesEditStatus[0] = "0";
                LanguageNational.UpdateLanguageNational(DataExtension.UpdateTransfer(fieldsEditStatus, valuesEditStatus), condition);
            }

            #region Logs
            string logAuthor     = CookieExtension.GetCookies("LoginSetting");
            string logCreateDate = DateTime.Now.ToString();
            Logs.InsertLogs(logCreateDate, Request.Url.ToString(), "", dt.Rows[0]["nLanguageNationalName"].ToString(), logAuthor, "", logCreateDate + ": " + logAuthor + " thay đổi trạng thái ngôn ngữ " + dt.Rows[0]["nLanguageNationalName"].ToString());
            #endregion

            GetListLanguageNationals();

            break;

            #endregion
            #region edit
        case "edit":
            Response.Redirect(LinkUpdate(p));
            break;
            #endregion
        }
    }
    private IEnumerator ImitateClient()
    {
        var connection = Msf.Connection;

        connection.Connect("127.0.0.1", 5000);

        // Wait until connected to master
        while (!connection.IsConnected)
        {
            yield return(null);
        }

        //Msf.Client.Auth.LogInAsGuest((accountInfo, error) =>
        Msf.Client.Auth.LogIn("aaaa", "aaaa", (accountInfo, error) =>
        {
            if (accountInfo == null)
            {
                Logs.Error(error);
                return;
            }

            _username = accountInfo.Username;

            // Create a profile (we're intentionally not constructing all properties)
            var profile = new ObservableProfile()
            {
                new ObservableInt(MyProfileKeys.Coins, 5),
                new ObservableString(MyProfileKeys.Title, "DefaultTitle"),
            };

            // Send a request to master server, to fill profile values
            Msf.Client.Profiles.GetProfileValues(profile, (isSuccessful, profileError) =>
            {
                if (!isSuccessful)
                {
                    Logs.Error(profileError);
                    return;
                }

                // Listen to property updates
                profile.PropertyUpdated += (code, property) =>
                {
                    // Log a message, when property changes
                    Logs.Info("Property changed:" + code + " - " + property.SerializeToString());
                };

                // Imitate game server
                StartCoroutine(ImitateGameServer());
            }, connection);

            // Listen directly to changes in coins property
            var coinsProp      = profile.GetProperty <ObservableInt>(MyProfileKeys.Coins);
            coinsProp.OnDirty += property =>
            {
                Logs.Info("Coins changed to: " + coinsProp.Value);

                // OR
                // Logs.Info("Coins changed to: " + (property as ObservableInt).Value);
            };
        }, connection);
    }
Пример #25
0
 public DailySaleForm( )
 {
     InitializeComponent();
     Logs.LogMe("DailySale: Intizlition done");
     viewModel = new DailySalesVM();
 }
Пример #26
0
            /// <summary>
            /// Gets the prediction.
            /// </summary>
            /// <param name="fromPos">Position where projectile gets fired from.</param>
            /// <param name="targetUnit">The target unit.</param>
            /// <param name="range">The ability range.</param>
            /// <param name="speed">The ability speed.</param>
            /// <param name="radius">The ability radius (for collision).</param>
            /// <param name="fixedDelay">The fixed delay. If greater than 0, will use this fixed delay for calculations instead of getting normal best position prediction</param>
            /// <param name="maxEnemyReactionTime">The maximum enemy reaction time in seconds to calculate HitChance.</param>
            /// <param name="checkCollision">If set to <c>true</c> [check collision].</param>
            /// <param name="ignoreFlags">The ignore flags for collision calculations.</param>
            /// <returns>TestOutput</returns>
            public static Prediction.Output GetPrediction(Vector2 fromPos, Character targetUnit, float range, float speed,
                                                          float radius               = 0f,
                                                          float fixedDelay           = 0f,
                                                          float maxEnemyReactionTime = 1.75f,
                                                          bool checkCollision        = false,
                                                          CollisionFlags ignoreFlags = CollisionFlags.Bush | CollisionFlags.NPCBlocker)
            {
                MapGameObject         mapGameObject         = targetUnit.Get <MapGameObject>();
                NetworkMovementObject networkMovementObject = targetUnit.Get <NetworkMovementObject>();

                if (mapGameObject == null)
                {
                    Logs.Error("TestPrediction: Object of name " + targetUnit.ObjectName + " has no MapGameObject model");
                    return(new Prediction.Output()
                    {
                        CanHit = false,
                        Hitchance = HitChance.Unknown,
                        CastPosition = Vector2.Zero,
                    });
                }

                var targetPos = mapGameObject.Position;

                if (networkMovementObject == null)
                {
                    Logs.Error("TestPrediction: Object of name " + targetUnit.ObjectName + " has no NetworkMovementObject model");
                    return(new Prediction.Output()
                    {
                        CanHit = targetPos.Distance(fromPos) <= range,
                        Hitchance = targetPos.Distance(fromPos) <= range ? HitChance.VeryHigh : HitChance.OutOfRange,
                        HitchancePercentage = targetPos.Distance(fromPos) <= range ? 100f : 0f,
                        CastPosition = targetPos,
                    });
                }

                var targetVelocity = networkMovementObject.Velocity;
                var targetRadius   = targetUnit.Get <SpellCollisionObject>().SpellCollisionRadius; //TODO: Check if MapCollisionRadius is better

                if (fixedDelay < float.Epsilon)                                                    //No fixed delay
                {
                    var predPos = GetStandardPrediction(fromPos, targetPos, speed, targetVelocity);
                    if (predPos == Vector2.Zero)
                    {
                        return(new Prediction.Output()
                        {
                            CanHit = false,
                            Hitchance = HitChance.Unknown,
                            CastPosition = Vector2.Zero,
                        });
                    }


                    var solution = new Prediction.Output()
                    {
                        CanHit       = true,
                        CastPosition = predPos,
                        Target       = targetUnit
                    };

                    var targetCollision = CollisionSolver.CheckThickLineCollision(targetPos, solution.CastPosition, targetRadius);
                    if (targetCollision != null && targetCollision.IsColliding)
                    {
                        solution.CastPosition = targetCollision.CollisionPoint;
                    }

                    if (solution.CastPosition.Distance(fromPos) > range)
                    {
                        solution.CanHit    = false;
                        solution.Hitchance = HitChance.OutOfRange;
                    }

                    if (checkCollision)
                    {
                        solution.CollisionResult = CollisionSolver.CheckThickLineCollision(fromPos, solution.CastPosition,
                                                                                           radius < float.Epsilon ? 0.01f : radius, ignoreFlags);

                        if (solution.CollisionResult.IsColliding)
                        {
                            solution.CanHit    = false;
                            solution.Hitchance = HitChance.Collision;
                        }
                    }

                    solution.HitchancePercentage = GetHitchance(fromPos, solution.CastPosition, speed, maxEnemyReactionTime, false);
                    solution.Hitchance           = GetHitchanceEnum(solution.HitchancePercentage);
                    return(solution);
                }
                else //WITH fixed delay
                {
                    var predPos = GetFixedDelayPrediction(targetPos, fixedDelay, targetVelocity);

                    Prediction.Output solution = new Prediction.Output()
                    {
                        CanHit       = true,
                        CastPosition = predPos,
                    };

                    var targetCollision = CollisionSolver.CheckThickLineCollision(targetPos, solution.CastPosition, targetRadius);
                    if (targetCollision != null && targetCollision.IsColliding)
                    {
                        solution.CastPosition = targetCollision.CollisionPoint;
                    }

                    if (solution.CastPosition.Distance(fromPos) > range)
                    {
                        solution.CanHit    = false;
                        solution.Hitchance = HitChance.OutOfRange;
                    }

                    solution.HitchancePercentage = GetHitchance(fromPos, solution.CastPosition, fixedDelay, maxEnemyReactionTime, true);
                    solution.Hitchance           = GetHitchanceEnum(solution.HitchancePercentage);
                    return(solution);
                }
            }
Пример #27
0
        public override bool OnNoRoot()
        {
            if (ConsoleMode == false)             // GUI Only
            {
                if (Platform.Instance.IsWindowsSystem())
                {
                    // Never occur, root granted by Windows Manifest
                    return(false);
                }
                else if (Platform.Instance.IsLinuxSystem())
                {
                    string command   = "";
                    string arguments = "";


                    string command2       = "";
                    string executablePath = Platform.Instance.GetExecutablePath();
                    string cmdline        = CommandLine.SystemEnvironment.GetFull();
                    if (executablePath.Substring(executablePath.Length - 4).ToLowerInvariant() == ".exe")
                    {
                        command2 += "mono ";
                    }
                    command2 += Platform.Instance.GetExecutablePath();
                    command2 += " ";
                    command2 += cmdline;
                    bool waitEnd = false;

                    if (File.Exists("/usr/bin/kdesudo"))
                    {
                        command    = "kdesudo";
                        arguments  = "";
                        arguments += " -u root";                    // Administrative privileges
                        arguments += " -d";                         // Don't show commandline
                        arguments += " --comment \"" + Messages.AdminRequiredPasswordPrompt + "\"";
                        arguments += " -c ";                        // The command
                        //arguments += " \"" + command2 + "\"";
                        arguments += " \"" + command2 + "\"";
                    }
                    else if (File.Exists("/usr/bin/kdesu"))
                    {
                        command    = "kdesu";
                        arguments  = "";
                        arguments += " -u root";                    // Administrative privileges
                        arguments += " -d";                         // Don't show commandline
                        //arguments += " --comment \"" + Messages.AdminRequiredPasswordPrompt + "\"";
                        arguments += " -c ";                        // The command
                        //arguments += " \"" + command2 + "\"";
                        arguments += " \"" + command2 + "\"";
                    }

                    /*
                     * Under Debian, gksudo don't work, gksu work...
                     * if (File.Exists("/usr/bin/gksudo"))
                     * {
                     *      command = "gksudo";
                     *      arguments = "";
                     *      arguments += " -u root"; // Administrative privileges
                     *      arguments += " -m \"" + Messages.AdminRequiredPasswordPrompt + "\"";
                     *      arguments += " \"" + command2 + "\"";
                     * }
                     * else
                     */
                    else if (File.Exists("/usr/bin/gksu"))
                    {
                        command    = "gksu";
                        arguments  = "";
                        arguments += " -u root";                         // Administrative privileges
                        arguments += " -m \"" + Messages.AdminRequiredPasswordPrompt + "\"";
                        arguments += " \"" + command2 + "\"";
                    }
                    else if (File.Exists("/usr/bin/xdg-su"))                     // OpenSUSE
                    {
                        command    = "xdg-su";
                        arguments  = "";
                        arguments += " -u root";                     // Administrative privileges
                        arguments += " -c ";                         // The command
                        arguments += " \"" + command2 + "\"";
                    }
                    else if (File.Exists("/usr/bin/beesu"))                     // Fedora
                    {
                        command    = "beesu";
                        arguments  = "";
                        arguments += " " + command2 + "";
                    }

                    /*
                     * else if (File.Exists("/usr/bin/pkexec"))
                     * {
                     *      // Different behiavour on different platforms
                     *      command = "pkexec";
                     *      arguments = "";
                     *      arguments = " env DISPLAY=$DISPLAY XAUTHORITY=$XAUTHORITY";
                     *      arguments += " " + command2 + "";
                     *
                     *      // For this bug: https://lists.ubuntu.com/archives/foundations-bugs/2012-July/100103.html
                     *      // We need to keep alive the current process, otherwise 'Refusing to render service to dead parents.'.
                     *      waitEnd = true;
                     *
                     *      // Still don't work.
                     * }
                     */

                    if (command != "")
                    {
                        Logs.Log(LogType.Verbose, Messages.AdminRequiredRestart);

                        //Logs.Log(LogType.Verbose, "Command:'" + command + "', Args:'" + arguments + "'");

                        Platform.Instance.Shell(command, arguments, waitEnd);
                    }
                    else
                    {
                        Logs.Log(LogType.Fatal, Messages.AdminRequiredRestartFailed);
                    }

                    return(true);
                }
            }

            return(false);
        }
Пример #28
0
 public Logs addLog(Logs log)
 {
     return(_logs.Save(log));
 }
Пример #29
0
        public static IServiceCollection AddBTCPayServer(this IServiceCollection services, IConfiguration configuration, Logs logs)
        {
            services.AddSingleton <MvcNewtonsoftJsonOptions>(o => o.GetRequiredService <IOptions <MvcNewtonsoftJsonOptions> >().Value);
            services.AddSingleton <JsonSerializerSettings>(o => o.GetRequiredService <IOptions <MvcNewtonsoftJsonOptions> >().Value.SerializerSettings);
            services.AddDbContext <ApplicationDbContext>((provider, o) =>
            {
                var factory = provider.GetRequiredService <ApplicationDbContextFactory>();
                factory.ConfigureBuilder(o);
            });
            services.AddHttpClient();
            services.AddHttpClient(nameof(ExplorerClientProvider), httpClient =>
            {
                httpClient.Timeout = Timeout.InfiniteTimeSpan;
            });

            services.AddSingleton <Logs>(logs);
            services.AddSingleton <BTCPayNetworkJsonSerializerSettings>();

            services.AddPayJoinServices();
#if ALTCOINS
            if (configuration.SupportChain("xmr"))
            {
                services.AddMoneroLike();
            }
            if (configuration.SupportChain("yec") || configuration.SupportChain("zec"))
            {
                services.AddZcashLike();
            }
#endif
            services.AddScoped <IScopeProvider, ScopeProvider>();
            services.TryAddSingleton <SettingsRepository>();
            services.TryAddSingleton <ISettingsRepository>(provider => provider.GetService <SettingsRepository>());
            services.TryAddSingleton <IStoreRepository>(provider => provider.GetService <StoreRepository>());
            services.TryAddSingleton <LabelFactory>();
            services.TryAddSingleton <TorServices>();
            services.AddSingleton <IHostedService>(provider => provider.GetRequiredService <TorServices>());
            services.AddSingleton <ISwaggerProvider, DefaultSwaggerProvider>();
            services.TryAddSingleton <SocketFactory>();
            services.TryAddSingleton <LightningClientFactoryService>();
            services.AddHttpClient(LightningClientFactoryService.OnionNamedClient)
            .ConfigurePrimaryHttpMessageHandler <Socks5HttpClientHandler>();
            services.TryAddSingleton <InvoicePaymentNotification>();
            services.TryAddSingleton <BTCPayServerOptions>(o =>
                                                           o.GetRequiredService <IOptions <BTCPayServerOptions> >().Value);
            // Don't move this StartupTask, we depend on it being right here
            services.AddStartupTask <MigrationStartupTask>();
            //
            AddSettingsAccessor <PoliciesSettings>(services);
            AddSettingsAccessor <ThemeSettings>(services);
            //
            services.AddStartupTask <BlockExplorerLinkStartupTask>();
            services.TryAddSingleton <InvoiceRepository>();
            services.AddSingleton <PaymentService>();
            services.AddSingleton <BTCPayServerEnvironment>();
            services.TryAddSingleton <TokenRepository>();
            services.TryAddSingleton <WalletRepository>();
            services.TryAddSingleton <EventAggregator>();
            services.TryAddSingleton <PaymentRequestService>();
            services.TryAddSingleton <UserService>();
            services.AddSingleton <CustodianAccountRepository>();


            services.TryAddSingleton <WalletHistogramService>();
            services.TryAddSingleton <CustodianAccountRepository>();
            services.AddSingleton <ApplicationDbContextFactory>();
            services.AddOptions <BTCPayServerOptions>().Configure(
                (options) =>
            {
                options.LoadArgs(configuration, logs);
            });
            services.AddOptions <DataDirectories>().Configure(
                (options) =>
            {
                options.Configure(configuration);
            });
            services.AddOptions <DatabaseOptions>().Configure <IOptions <DataDirectories> >(
                (options, datadirs) =>
            {
                var postgresConnectionString = configuration["postgres"];
                var mySQLConnectionString    = configuration["mysql"];
                var sqliteFileName           = configuration["sqlitefile"];

                if (!string.IsNullOrEmpty(postgresConnectionString))
                {
                    options.DatabaseType     = DatabaseType.Postgres;
                    options.ConnectionString = postgresConnectionString;
                }
                else if (!string.IsNullOrEmpty(mySQLConnectionString))
                {
                    options.DatabaseType     = DatabaseType.MySQL;
                    options.ConnectionString = mySQLConnectionString;
                }
                else if (!string.IsNullOrEmpty(sqliteFileName))
                {
                    var connStr = "Data Source=" + (Path.IsPathRooted(sqliteFileName)
                            ? sqliteFileName
                            : Path.Combine(datadirs.Value.DataDir, sqliteFileName));

                    options.DatabaseType     = DatabaseType.Sqlite;
                    options.ConnectionString = connStr;
                }
                else
                {
                    throw new InvalidOperationException("No database option was configured.");
                }
            });
            services.AddOptions <NBXplorerOptions>().Configure <BTCPayNetworkProvider>(
                (options, btcPayNetworkProvider) =>
            {
                foreach (BTCPayNetwork btcPayNetwork in btcPayNetworkProvider.GetAll().OfType <BTCPayNetwork>())
                {
                    NBXplorerConnectionSetting setting =
                        new NBXplorerConnectionSetting
                    {
                        CryptoCode  = btcPayNetwork.CryptoCode,
                        ExplorerUri = configuration.GetOrDefault <Uri>(
                            $"{btcPayNetwork.CryptoCode}.explorer.url",
                            btcPayNetwork.NBXplorerNetwork.DefaultSettings.DefaultUrl),
                        CookieFile = configuration.GetOrDefault <string>(
                            $"{btcPayNetwork.CryptoCode}.explorer.cookiefile",
                            btcPayNetwork.NBXplorerNetwork.DefaultSettings.DefaultCookieFile)
                    };
                    options.NBXplorerConnectionSettings.Add(setting);
                    options.ConnectionString = configuration.GetOrDefault <string>("explorer.postgres", null);
                }
            });
            services.AddOptions <LightningNetworkOptions>().Configure <BTCPayNetworkProvider>(
                (options, btcPayNetworkProvider) =>
            {
                foreach (var net in btcPayNetworkProvider.GetAll().OfType <BTCPayNetwork>())
                {
                    var lightning = configuration.GetOrDefault <string>($"{net.CryptoCode}.lightning", string.Empty);
                    if (lightning.Length != 0)
                    {
                        if (!LightningConnectionString.TryParse(lightning, true, out var connectionString,
                                                                out var error))
                        {
                            logs.Configuration.LogWarning($"Invalid setting {net.CryptoCode}.lightning, " +
                                                          Environment.NewLine +
                                                          $"If you have a c-lightning server use: 'type=clightning;server=/root/.lightning/lightning-rpc', " +
                                                          Environment.NewLine +
                                                          $"If you have a lightning charge server: 'type=charge;server=https://charge.example.com;api-token=yourapitoken'" +
                                                          Environment.NewLine +
                                                          $"If you have a lnd server: 'type=lnd-rest;server=https://lnd:[email protected];macaroon=abf239...;certthumbprint=2abdf302...'" +
                                                          Environment.NewLine +
                                                          $"              lnd server: 'type=lnd-rest;server=https://lnd:[email protected];macaroonfilepath=/root/.lnd/admin.macaroon;certthumbprint=2abdf302...'" +
                                                          Environment.NewLine +
                                                          $"If you have an eclair server: 'type=eclair;server=http://eclair.com:4570;password=eclairpassword;bitcoin-host=bitcoind:37393;bitcoin-auth=bitcoinrpcuser:bitcoinrpcpassword" +
                                                          Environment.NewLine +
                                                          $"               eclair server: 'type=eclair;server=http://eclair.com:4570;password=eclairpassword;bitcoin-host=bitcoind:37393" +
                                                          Environment.NewLine +
                                                          $"Error: {error}" + Environment.NewLine +
                                                          "This service will not be exposed through BTCPay Server");
                        }
                        else
                        {
                            if (connectionString.IsLegacy)
                            {
                                logs.Configuration.LogWarning(
                                    $"Setting {net.CryptoCode}.lightning is a deprecated format, it will work now, but please replace it for future versions with '{connectionString.ToString()}'");
                            }
                            options.InternalLightningByCryptoCode.Add(net.CryptoCode, connectionString);
                        }
                    }
                }
            });
Пример #30
0
 public void ClearLogs()
 {
     Logs?.Clear();
 }
Пример #31
0
        public void ConfigureServices(IServiceCollection services)
        {
            Logs.Configure(LoggerFactory);
            services.ConfigureBTCPayServer(Configuration);
            services.AddMemoryCache();
            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();
            services.AddSignalR();
            services.AddBTCPayServer();
            services.AddMvc(o =>
            {
                o.Filters.Add(new XFrameOptionsAttribute("DENY"));
                o.Filters.Add(new XContentTypeOptionsAttribute("nosniff"));
                o.Filters.Add(new XXSSProtectionAttribute());
                o.Filters.Add(new ReferrerPolicyAttribute("same-origin"));
                //o.Filters.Add(new ContentSecurityPolicyAttribute()
                //{
                //    FontSrc = "'self' https://fonts.gstatic.com/",
                //    ImgSrc = "'self' data:",
                //    DefaultSrc = "'none'",
                //    StyleSrc = "'self' 'unsafe-inline'",
                //    ScriptSrc = "'self' 'unsafe-inline'"
                //});
            });
            services.TryAddScoped <ContentSecurityPolicies>();
            services.Configure <IdentityOptions>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequiredLength         = 6;
                options.Password.RequireLowercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(5);
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.AllowedForNewUsers      = true;
            });
            // If the HTTPS certificate path is not set this logic will NOT be used and the default Kestrel binding logic will be.
            string httpsCertificateFilePath = Configuration.GetOrDefault <string>("HttpsCertificateFilePath", null);
            bool   useDefaultCertificate    = Configuration.GetOrDefault <bool>("HttpsUseDefaultCertificate", false);
            bool   hasCertPath = !String.IsNullOrEmpty(httpsCertificateFilePath);

            if (hasCertPath || useDefaultCertificate)
            {
                var bindAddress = Configuration.GetOrDefault <IPAddress>("bind", IPAddress.Any);
                int bindPort    = Configuration.GetOrDefault <int>("port", 443);

                services.Configure <KestrelServerOptions>(kestrel =>
                {
                    if (hasCertPath && !File.Exists(httpsCertificateFilePath))
                    {
                        // Note that by design this is a fatal error condition that will cause the process to exit.
                        throw new ConfigException($"The https certificate file could not be found at {httpsCertificateFilePath}.");
                    }
                    if (hasCertPath && useDefaultCertificate)
                    {
                        throw new ConfigException($"Conflicting settings: if HttpsUseDefaultCertificate is true, HttpsCertificateFilePath should not be used");
                    }

                    kestrel.Listen(bindAddress, bindPort, l =>
                    {
                        if (hasCertPath)
                        {
                            Logs.Configuration.LogInformation($"Using HTTPS with the certificate located in {httpsCertificateFilePath}.");
                            l.UseHttps(httpsCertificateFilePath, Configuration.GetOrDefault <string>("HttpsCertificateFilePassword", null));
                        }
                        else
                        {
                            Logs.Configuration.LogInformation($"Using HTTPS with the default certificate");
                            l.UseHttps();
                        }
                    });
                });
            }
        }
Пример #32
0
 public void UpdateLog(string logStr)
 {
     Logs?.AppendLine(logStr);
     ChangeLog?.Invoke(Logs.ToString());
 }
Пример #33
0
 protected override void OnMessage(MessageEventArgs e)
 {
     Logs.Debug($"Message size: {e.RawData.LongLength / 1024f}kb. The number of concurrent clients is: {Sessions.Count}");
     Send(e.Data);
 }
Пример #34
0
    protected void btOK_Click(object sender, EventArgs e)
    {
        string chiTiet = ContentExtendtions.ProcessStringContent(tbChiTiet.Text, hdChiTiet.Value, pic);

        #region Trạng thái
        string trangThai = "0";
        if (cbTrangThai.Checked == true)
        {
            trangThai = "1";
        }
        #endregion
        #region Seo
        if (tbSeoLink.Text.Trim().Equals(""))
        {
            tbSeoLink.Text = tbTitle.Text;
        }
        if (tbSeoTitle.Text.Trim().Equals(""))
        {
            tbSeoTitle.Text = tbTitle.Text;
        }
        if (tbSeoKeyword.Text.Trim().Equals(""))
        {
            tbSeoKeyword.Text = tbTitle.Text;
        }
        if (tbSeoDescription.Text.Trim().Equals(""))
        {
            tbSeoDescription.Text = tbDesc.Text;
        }
        #endregion

        #region Ngày đăng
        if (tbNgayDang.Text == "")
        {
            tbNgayDang.Text = DateTime.Now.ToString();
        }
        #endregion

        #region Các thông tin liên hệ khác như Facebook, Google +, Twitter,...
        string subInfos = StringExtension.GhepChuoi("", tbFacebook.Text, tbGooglePlus.Text, tbTwitter.Text, tbYoutube.Text, tbInstagram.Text, tbPhone.Text, tbEmail.Text, tbSkype.Text, tbViber.Text, tbZalo.Text);
        #endregion

        #region Insert
        if (insert)
        {
            string image = flAnhDaiDien.Save(false, chiTiet);
            GroupsItems.InsertItemsGroupsItems(lang, app, tbKey.Text, tbTitle.Text, tbDesc.Text, chiTiet,
                                               image, "", "", tbSeoTitle.Text, tbSeoLink.Text,
                                               StringExtension.ReplateTitle(tbSeoLink.Text),
                                               tbSeoKeyword.Text, tbSeoDescription.Text, "", "", "", subInfos, "",
                                               "", "", "", tbNgayDang.Text,
                                               DateTime.Now.ToString(), DateTime.Now.ToString(), tbThuTu.Text, ddlParentCate.SelectedValue,
                                               tbNgayDang.Text, DateTime.Now.ToString(), DateTime.Now.ToString(), tbThuTu.Text, trangThai);

            #region Logs
            string logAuthor     = CookieExtension.GetCookies("LoginSetting");
            string logCreateDate = DateTime.Now.ToString();
            Logs.InsertLogs(logCreateDate, Request.Url.ToString(), "", tbTitle.Text, logAuthor, "", logCreateDate + ": " + logAuthor + " tạo mới " + tbTitle.Text);
            #endregion
        }
        #endregion
        #region Update
        else
        {
            string image = flAnhDaiDien.Save(true, chiTiet);

            GroupsItems.DeleteGroupsItems(GroupsItemsTSql.GetGroupsItemsByIgiid(hdGroupsItemId.Value));
            GroupsItems.UpdateItemsGroupsItems(lang, app, tbKey.Text, tbTitle.Text, tbDesc.Text, chiTiet,
                                               image, "", "", tbSeoTitle.Text, tbSeoLink.Text,
                                               StringExtension.ReplateTitle(tbSeoLink.Text),
                                               tbSeoKeyword.Text, tbSeoDescription.Text, "", "", "", subInfos, "",
                                               "", "", hdTotalView.Value,
                                               tbNgayDang.Text, DateTime.Now.ToString(), DateTime.Now.ToString(), tbThuTu.Text,
                                               ddlParentCate.SelectedValue, tbNgayDang.Text, DateTime.Now.ToString(), DateTime.Now.ToString(),
                                               tbThuTu.Text, trangThai, iid);

            #region Logs
            string logAuthor     = CookieExtension.GetCookies("LoginSetting");
            string logCreateDate = DateTime.Now.ToString();
            Logs.InsertLogs(logCreateDate, Request.Url.ToString(), "", tbTitle.Text, logAuthor, "", logCreateDate + ": " + logAuthor + " cập nhật " + tbTitle.Text);
            #endregion
        }
        #endregion

        #region After Insert/Update

        if (cbTiepTuc.Checked == true)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "alertSuccess",
                                                "ThongBao(3000,'Đã tạo: " + tbTitle.Text + "');", true);
            ResetControls();
        }
        else
        {
            Response.Redirect(LinkRedrect());
        }

        #endregion
    }
Пример #35
0
 //
 // GET: /Logs/
 public ActionResult Index()
 {
     ServicesLogs objDB = new ServicesLogs();
     Logs dto = new Logs();
     return View(objDB.SelectWhere(dto));
 }
Пример #36
0
    public void SpawnerApi()
    {
        var defaultOptions = new SpawnerOptions();

        // Registers a spawner to master server, so that master server knows about it's existance.
        // Your spawner will receive requests to spawn processes (or something else,
        // if necessary)
        Msf.Server.Spawners.RegisterSpawner(defaultOptions, (spawner, error) =>
        {
            if (spawner == null)
            {
                Logs.Error(error);
            }
        });

        var spawnerOptions = new SpawnerOptions()
        {
            MaxProcesses = 0,           // Unlimited,
            MachineIp    = "127.0.0.1", // IP address of this machine, will be passed to game servers too
            Region       = "US",        // Region identifier, can be anything
            Properties   = new Dictionary <string, string>()
            {
                // If you need spawner to have some extra properties
                { "ExtraProperty", "Whatever" }
            }
        };

        // Example of a more customized approach
        Msf.Server.Spawners.RegisterSpawner(spawnerOptions, (spawner, error) =>
        {
            if (spawner == null)
            {
                Logs.Error(error);
                return;
            }

            // Set the build path (default ''(empty string))
            spawner.DefaultSpawnerSettings.ExecutablePath = "C:/Win/Build.exe";

            // Change whether or not the spawner process should run in batchmode
            spawner.DefaultSpawnerSettings.SpawnInBatchmode = false;

            // (Optional) If you want to handle spawn requests manually
            spawner.SetSpawnRequestHandler((packet, message) =>
            {
                // We've got a request to spawn a new process
                // packet - contains spawn info
                // message - the original message of the request. You'll need to respond to it
                // with ResponseStatus.Success, if process started successfully
                var hasError = false;
                if (hasError)
                {
                    // Example on how to handle errors
                    message.Respond("A mysterious error", ResponseStatus.Failed);
                    return;
                }

                // TODO Start a process or a virtual game server

                // Respond with success
                message.Respond(ResponseStatus.Success);
            });

            // (Optional) If you want to handle kill requests manually
            spawner.SetKillRequestHandler(spawnId =>
            {
                // This is a request to kill a spawned process
                // TODO Find a process by spawnId and kill it
            });
        });
    }
Пример #37
0
 private void btn_ok_Click(object sender, EventArgs e)
 {
     pings = Logs.ReadTxt(Chemins.CheminPing() + com_registre.Text + ".txt");
     LoadView();
 }
Пример #38
0
    public void RoomsApi()
    {
        // This will register a room to the master server, so that
        // master server would know about it's existance
        // This is a minimal example
        Msf.Server.Rooms.RegisterRoom((controller, error) =>
        {
            if (controller == null)
            {
                Logs.Error(error);
            }
        });

        var roomOptions = new RoomOptions()
        {
            IsPublic   = false,
            MaxPlayers = 5,
            Name       = "My super room",
            Password   = "******",
            Properties = new Dictionary <string, string>()
            {
                { "CustomProperty", "Some extra stuff" }
            },
            RoomIp   = "127.0.0.1",
            RoomPort = 777
        };

        // More customization options
        Msf.Server.Rooms.RegisterRoom(roomOptions, (controller, error) =>
        {
            // Edit the options, to make the room public
            controller.Options.IsPublic = true;

            // Save the options
            controller.SaveOptions(controller.Options);

            // When player sends us an access token, we can confirm if the token is valid
            controller.ValidateAccess("token..", (playerPeerId, confirmationError) =>
            {
                if (playerPeerId == null)
                {
                    Logs.Error("Player provided an invalid token");
                    return;
                }

                // Player provided a valid token
                // TODO Get account info by peer id
                // TODO Spawn a player to the game
            });

            // If we want to handle who gets access, and who doesn't
            controller.SetAccessProvider((requester, giveAccess) =>
            {
                // TODO use the peerId to retrieve account data
                // TODO check if, for example, the username is banned in this room

                // If user is allowed, create a new room access
                giveAccess(new RoomAccessPacket()
                {
                    RoomIp     = controller.Options.RoomIp,
                    RoomPort   = controller.Options.RoomPort,
                    Properties = new Dictionary <string, string>()
                    {
                        // Custom properties
                        { "Color", "#ffffff" }
                    },
                    RoomId    = controller.RoomId,
                    SceneName = SceneManager.GetActiveScene().name,
                    Token     = Guid.NewGuid().ToString()
                }, null);

                // If user is not allowed
                giveAccess(null, "You're not allowed to play!");
            });
        });


        var roomId = 5;

        // Getting access from client
        Msf.Client.Rooms.GetAccess(roomId, (access, error) =>
        {
            if (access == null)
            {
                Debug.LogError(error);
                return;
            }

            // We've received the access
            Debug.Log(access);

            // TODO use ip and port from access to connect to game server
            // TODO send the token to game server  (this will depend on game server technologies used)
        });
    }
Пример #39
0
 public Manager(Logs logs)
 {
     this.commandVerifier = new CommandVerifier();
     this.logs = logs;
 }
Пример #40
0
        public void ConfigureServices(IServiceCollection services)
        {
            Logs.Configure(LoggerFactory);
            services.AddMemoryCache();
            services.AddDataProtection()
            .SetApplicationName("BTCPay Server")
            .PersistKeysToFileSystem(new DirectoryInfo(new DataDirectories().Configure(Configuration).DataDir));
            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();
            services.Configure <AuthenticationOptions>(opts =>
            {
                opts.DefaultAuthenticateScheme = null;
                opts.DefaultChallengeScheme    = null;
                opts.DefaultForbidScheme       = null;
                opts.DefaultScheme             = IdentityConstants.ApplicationScheme;
                opts.DefaultSignInScheme       = null;
                opts.DefaultSignOutScheme      = null;
            });
            services.PostConfigure <CookieAuthenticationOptions>(IdentityConstants.ApplicationScheme, opt =>
            {
                opt.LoginPath = "/login";
            });

            services.Configure <SecurityStampValidatorOptions>(opts =>
            {
                opts.ValidationInterval = TimeSpan.FromMinutes(5.0);
            });

            services.AddBTCPayServer(Configuration);
            services.AddProviderStorage();
            services.AddSession();
            services.AddSignalR();
            services.AddFido2(options =>
            {
                options.ServerName = "BTCPay Server";
            })
            .AddCachedMetadataService(config =>
            {
                //They'll be used in a "first match wins" way in the order registered
                config.AddStaticMetadataRepository();
            });
            var descriptor = services.Single(descriptor => descriptor.ServiceType == typeof(Fido2Configuration));

            services.Remove(descriptor);
            services.AddScoped(provider =>
            {
                var httpContext = provider.GetService <IHttpContextAccessor>();
                return(new Fido2Configuration()
                {
                    ServerName = "BTCPay Server",
                    Origin = $"{httpContext.HttpContext.Request.Scheme}://{httpContext.HttpContext.Request.Host}",
                    ServerDomain = httpContext.HttpContext.Request.Host.Host
                });
            });
            services.AddScoped <Fido2Service>();

            var mvcBuilder = services.AddMvc(o =>
            {
                o.Filters.Add(new XFrameOptionsAttribute("DENY"));
                o.Filters.Add(new XContentTypeOptionsAttribute("nosniff"));
                o.Filters.Add(new XXSSProtectionAttribute());
                o.Filters.Add(new ReferrerPolicyAttribute("same-origin"));
                //o.Filters.Add(new ContentSecurityPolicyAttribute()
                //{
                //    FontSrc = "'self' https://fonts.gstatic.com/",
                //    ImgSrc = "'self' data:",
                //    DefaultSrc = "'none'",
                //    StyleSrc = "'self' 'unsafe-inline'",
                //    ScriptSrc = "'self' 'unsafe-inline'"
                //});
            })
                             .ConfigureApiBehaviorOptions(options =>
            {
                options.InvalidModelStateResponseFactory = context =>
                {
                    return(new UnprocessableEntityObjectResult(context.ModelState.ToGreenfieldValidationError()));
                };
            })
                             .AddRazorOptions(o =>
            {
                // /Components/{View Component Name}/{View Name}.cshtml
                o.ViewLocationFormats.Add("/{0}.cshtml");
                o.PageViewLocationFormats.Add("/{0}.cshtml");
            })
                             .AddNewtonsoftJson()
#if RAZOR_RUNTIME_COMPILE
                             .AddRazorRuntimeCompilation()
#endif
                             .AddPlugins(services, Configuration, LoggerFactory)
                             .AddControllersAsServices();



            services.TryAddScoped <ContentSecurityPolicies>();
            services.Configure <IdentityOptions>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequiredLength         = 6;
                options.Password.RequireLowercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(5);
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.AllowedForNewUsers      = true;
                options.Password.RequireUppercase       = false;
            });
            // If the HTTPS certificate path is not set this logic will NOT be used and the default Kestrel binding logic will be.
            string httpsCertificateFilePath = Configuration.GetOrDefault <string>("HttpsCertificateFilePath", null);
            bool   useDefaultCertificate    = Configuration.GetOrDefault <bool>("HttpsUseDefaultCertificate", false);
            bool   hasCertPath = !String.IsNullOrEmpty(httpsCertificateFilePath);

            services.Configure <KestrelServerOptions>(kestrel =>
            {
                kestrel.Limits.MaxRequestLineSize = 8_192 * 10 * 5; // Around 500K, transactions passed in URI should not be bigger than this
            });
            if (hasCertPath || useDefaultCertificate)
            {
                var bindAddress = Configuration.GetOrDefault <IPAddress>("bind", IPAddress.Any);
                int bindPort    = Configuration.GetOrDefault <int>("port", 443);

                services.Configure <KestrelServerOptions>(kestrel =>
                {
                    if (hasCertPath && !File.Exists(httpsCertificateFilePath))
                    {
                        // Note that by design this is a fatal error condition that will cause the process to exit.
                        throw new ConfigException($"The https certificate file could not be found at {httpsCertificateFilePath}.");
                    }
                    if (hasCertPath && useDefaultCertificate)
                    {
                        throw new ConfigException($"Conflicting settings: if HttpsUseDefaultCertificate is true, HttpsCertificateFilePath should not be used");
                    }

                    kestrel.Listen(bindAddress, bindPort, l =>
                    {
                        if (hasCertPath)
                        {
                            Logs.Configuration.LogInformation($"Using HTTPS with the certificate located in {httpsCertificateFilePath}.");
                            l.UseHttps(httpsCertificateFilePath, Configuration.GetOrDefault <string>("HttpsCertificateFilePassword", null));
                        }
                        else
                        {
                            Logs.Configuration.LogInformation($"Using HTTPS with the default certificate");
                            l.UseHttps();
                        }
                    });
                });
            }
        }
Пример #41
0
 public Configuration(Logs logs)
 {
     this.logs = logs;
 }
Пример #42
0
        public InvoiceModel Create(string email, DateTime due_date, Item[] items, string return_url = "",
                                   string expired_url     = "", string notification_url = "", int tax_cents = 0, int discount_cents                    = 0, string customer_id  = "", bool ignore_due_email = false,
                                   string subscription_id = "", int credits             = 0, Logs logs = null, List <CustomVariables> custom_variables = null, PayerModel payer = null, bool early_payment_discount = false, List <EarlyPaymentDiscounts> early_payment_discounts = null)
        {
            var retorno = CreateAsync(email, due_date, items, return_url, expired_url, notification_url, tax_cents,
                                      discount_cents, customer_id, ignore_due_email, subscription_id, credits, logs,
                                      custom_variables, payer, early_payment_discount, early_payment_discounts).Result;

            return(retorno);
        }
Пример #43
0
 private void RunUpdate()
 {
     var logWriter = new StringWriter();
     var appDeployment = new AppDeployment(config, logWriter);
     appDeployment.SynchroniseAllApplications();
     logWriter.Flush();
     string logContent = logWriter.ToString();
     if (config.InstanceKey.HasValue && !string.IsNullOrWhiteSpace(logContent))
     {
         var logs = new Logs(config);
         logs.AddLogEntry(new LogEntry() { InstanceKey = config.InstanceKey.Value, Status = appDeployment.DeploymentStatus, LogContent = logContent });
     }
 }
    protected void btOK_Click(object sender, EventArgs e)
    {
        string contentDetail = ContentExtendtions.ProcessStringContent(tbDetail.Text, hdOldContent.Value, pic);

        #region Status
        string status = "0";
        if (cbStatus.Checked == true)
        {
            status = "1";
        }
        #endregion

        #region Seo
        if (tbSeoLink.Text.Trim().Equals(""))
        {
            tbSeoLink.Text = tbTitle.Text;
        }
        if (tbSeoTitle.Text.Trim().Equals(""))
        {
            tbSeoTitle.Text = tbTitle.Text;
        }
        if (tbSeoKeyword.Text.Trim().Equals(""))
        {
            tbSeoKeyword.Text = tbTitle.Text;
        }
        if (tbSeoDescription.Text.Trim().Equals(""))
        {
            tbSeoDescription.Text = tbDesc.Text;
        }
        #endregion

        #region Insert
        if (insert)
        {
            string image = flAnhDaiDien.Save(false, contentDetail);

            Groups.InsertGroups(language, app, ddlParentCate.SelectedValue, tbTitle.Text, tbDesc.Text, contentDetail,
                                tbSeoTitle.Text, tbSeoLink.Text, StringExtension.ReplateTitle(tbSeoLink.Text), tbSeoKeyword.Text,
                                tbSeoDescription.Text, "", "", "", image, "", "", tbOrder.Text, DateTime.Now.ToString(),
                                DateTime.Now.ToString(), DateTime.Now.ToString(), status);

            #region Logs
            string logAuthor     = CookieExtension.GetCookies("LoginSetting");
            string logCreateDate = DateTime.Now.ToString();
            Logs.InsertLogs(logCreateDate, Request.Url.ToString(), "", tbTitle.Text, logAuthor, "", logCreateDate + ": " + logAuthor + " tạo mới " + tbTitle.Text);
            #endregion
        }
        #endregion
        #region Update
        else
        {
            string image = flAnhDaiDien.Save(true, contentDetail);

            Groups.UpdateGroups(language, app, tbTitle.Text, tbDesc.Text, contentDetail, tbSeoTitle.Text, tbSeoLink.Text,
                                StringExtension.ReplateTitle(tbSeoLink.Text), tbSeoKeyword.Text, tbSeoDescription.Text, "", "", "",
                                image, "", "", tbOrder.Text, DateTime.Now.ToString(), DateTime.Now.ToString(),
                                DateTime.Now.ToString(), status, igid);
            if (ddlParentCate.SelectedValue != hd_parent)
            {
                Groups.UpdateParentOfGroups(igid, ddlParentCate.SelectedValue);
            }

            #region Logs
            string logAuthor     = CookieExtension.GetCookies("LoginSetting");
            string logCreateDate = DateTime.Now.ToString();
            Logs.InsertLogs(logCreateDate, Request.Url.ToString(), "", tbTitle.Text, logAuthor, "", logCreateDate + ": " + logAuthor + " cập nhật " + tbTitle.Text);
            #endregion
        }
        #endregion

        #region After Insert/Update

        if (ckbContinue.Checked == true)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "alertSuccess",
                                                "ThongBao(3000,'Đã tạo: " + tbTitle.Text + "');", true);
            ResetControls();
            LoadParentCate();
        }
        else
        {
            Response.Redirect(LinkRedrect());
        }

        #endregion
    }
Пример #45
0
        private dynamic GetEzcountRes(dynamic Params, List <dynamic> listProduct, List <dynamic> Payment, int DocType, string IsProduction, DocCreation doc, ref Logs lg, decimal p)
        {
            var reqObjZikuy = new
            {
                api_key   = (string)Params.api_key,
                api_email = (string)Params.api_email,
                ua_uuid   = (string)Params.ua_uuid,

                developer_email = "*****@*****.**",
                developer_phone = "0505913817",
                type            = DocType,
                description     = "",//(bool)Params.isMasKabala ? "" : (string)Params.InvoiceDetails,

                customer_email   = (string)Params.customer_email,
                customer_address = (string)Params.customer_address,
                comment          = (string)Params.comment,
                parent           = (string)Params.parents,

                customer_name    = (string)Params.customer_name,
                customerAction   = "ASSOC_CREATE",
                customer_crn     = (string)Params.customer_crn,
                c_accounting_num = (string)Params.c_accounting_num,
                tag_id           = (string)Params.tag_id,


                item = listProduct,

                payment     = Payment,
                price_total = p,
            };

            lg.Details = " הנפקת זיכוי " + (string)Params.payment_type;
            dynamic responseZikuy = doc.execute(((IsProduction == "0") ? Constants.ENV_TEST : Constants.ENV_PRODUCTION), reqObjZikuy);

            lg.Response = responseZikuy.ToString();
            return(responseZikuy);
        }
Пример #46
0
    protected void btn_insert_update_Click(object sender, EventArgs e)
    {
        string contentDetail = ContentExtendtions.ProcessStringContent(txt_content.Text, hdOldFileLibrary.Value, pic);

        #region Image
        string vimg       = "";
        string vimg_thumb = "";
        if (flimg.PostedFile.ContentLength > 0)
        {
            string filename = flimg.FileName;
            string fileex   = filename.Substring(filename.LastIndexOf("."));
            string path     = Request.PhysicalApplicationPath + "/" + pic + "/";
            if (TatThanhJsc.Extension.ImagesExtension.ValidType(fileex))
            {
                string fileNotEx = StringExtension.ReplateTitle(filename.Remove(filename.LastIndexOf(".") - 1));
                if (fileNotEx.Length > 9)
                {
                    fileNotEx = fileNotEx.Remove(9);
                }
                string ticks = DateTime.Now.Ticks.ToString();
                #region Lưu ảnh đại diện theo 2 trường hợp: tạo ảnh nhỏ hoặc không.
                //Kiểm tra xem có tạo ảnh nhỏ hay ko
                //Nếu không tạo ảnh nhỏ, tên tệp lưu bình thường theo kiểu: tên_tệp.phần_mở_rộng
                //Nếu tạo ảnh nhỏ, tên tệp sẽ theo kiểu: tên_tệp_HasThumb.phần_mở_rộng
                //Khi đó tên tệp ảnh nhỏ sẽ theo kiểu:   tên_tệp_HasThumb_Thumb.phần_mở_rộng
                //Với cách lưu tên ảnh này, khi thực hiện lưu vào csdl chỉ cần lưu tên ảnh gốc
                //khi hiển thị chỉ cần dựa vào tên ảnh gốc để biết ảnh đó có ảnh nhỏ hay không, việc này được thực hiện bởi TatThanhJsc.Extension.ImagesExtension.GetImage, lập trình không cần làm gì thêm.
                if (cbTaoAnhNho.Checked)
                {
                    vimg = fileNotEx + "_" + ticks + "_HasThumb" + fileex;
                }
                else
                {
                    vimg = fileNotEx + "_" + ticks + fileex;
                }
                flimg.SaveAs(path + vimg);
                #endregion
                #region Hạn chế kích thước
                if (cbHanCheKichThuoc.Checked)
                {
                    ImagesExtension.ResizeImage(path + vimg, "", tbHanCheW.Text, tbHanCheH.Text);
                }
                #endregion
                #region Đóng dấu ảnh
                if (cbDongDauAnh.Checked)
                {
                    ImagesExtension.CreateWatermark(path + vimg, path + hdLogoImage.Value, hdViTriDongDau.Value, hdLeX.Value, hdLeY.Value, hdTyLe.Value, hdTrongSuot.Value);
                }
                #endregion
                #region Tạo ảnh nhỏ: Thực hiện cuối để đảm bảo ảnh nhỏ cũng có con dấu
                if (cbTaoAnhNho.Checked)
                {
                    vimg_thumb = fileNotEx + "_" + ticks + "_HasThumb_Thumb" + fileex;
                    ImagesExtension.ResizeImage(path + vimg, path + vimg_thumb, tbAnhNhoW.Text, tbAnhNhoH.Text);
                }
                #endregion
            }
        }
        else
        {
            if (hd_img.Value.Length < 1 || cbLayAnhTuNoiDung.Checked)//nếu không upload ảnh và cũng không có ảnh cũ -> tìm ảnh đầu tiên trong nội dung làm ảnh đại diện
            {
                if (hd_img.Value.Length > 0)
                {
                    TatThanhJsc.Extension.ImagesExtension.DeleteImageWhenDeleteItem(pic, hd_img.Value);
                }

                string urlImg = ImagesExtension.GetFirstImageInContent(contentDetail);

                if (urlImg.Length > 0)
                {
                    string filename = urlImg;
                    string fileex   = filename.Substring(filename.LastIndexOf("."));
                    string path     = Request.PhysicalApplicationPath + "/" + pic + "/";
                    if (TatThanhJsc.Extension.ImagesExtension.ValidType(fileex))
                    {
                        string fileNotEx = StringExtension.ReplateTitle(filename.Remove(filename.LastIndexOf(".") - 1));
                        if (fileNotEx.Length > 9)
                        {
                            fileNotEx = fileNotEx.Remove(9);
                        }
                        string ticks = DateTime.Now.Ticks.ToString();
                        #region Lưu ảnh đại diện theo 2 trường hợp: tạo ảnh nhỏ hoặc không.
                        //Kiểm tra xem có tạo ảnh nhỏ hay ko
                        //Nếu không tạo ảnh nhỏ, tên tệp lưu bình thường theo kiểu: tên_tệp.phần_mở_rộng
                        //Nếu tạo ảnh nhỏ, tên tệp sẽ theo kiểu: tên_tệp_HasThumb.phần_mở_rộng
                        //Khi đó tên tệp ảnh nhỏ sẽ theo kiểu:   tên_tệp_HasThumb_Thumb.phần_mở_rộng
                        //Với cách lưu tên ảnh này, khi thực hiện lưu vào csdl chỉ cần lưu tên ảnh gốc
                        //khi hiển thị chỉ cần dựa vào tên ảnh gốc để biết ảnh đó có ảnh nhỏ hay không, việc này được thực hiện bởi TatThanhJsc.Extension.ImagesExtension.GetImage, lập trình không cần làm gì thêm.
                        if (cbTaoAnhNho.Checked)
                        {
                            vimg = fileNotEx + "_" + ticks + "_HasThumb";
                        }
                        else
                        {
                            vimg = fileNotEx + "_" + ticks;
                        }

                        if (ImagesExtension.SaveImageFromUrl(path + vimg, urlImg).Length > 0)
                        {
                            vimg += fileex;

                            #region Hạn chế kích thước
                            if (cbHanCheKichThuoc.Checked)
                            {
                                ImagesExtension.ResizeImage(path + vimg, "", tbHanCheW.Text, tbHanCheH.Text);
                            }
                            #endregion
                            #region Đóng dấu ảnh
                            if (cbDongDauAnh.Checked)
                            {
                                ImagesExtension.CreateWatermark(path + vimg, path + hdLogoImage.Value, hdViTriDongDau.Value, hdLeX.Value, hdLeY.Value, hdTyLe.Value, hdTrongSuot.Value);
                            }
                            #endregion
                            #region Tạo ảnh nhỏ: Thực hiện cuối để đảm bảo ảnh nhỏ cũng có con dấu
                            if (cbTaoAnhNho.Checked)
                            {
                                vimg_thumb = fileNotEx + "_" + ticks + "_HasThumb_Thumb" + fileex;
                                ImagesExtension.ResizeImage(path + vimg, path + vimg_thumb, tbAnhNhoW.Text, tbAnhNhoH.Text);
                            }
                            #endregion
                        }
                        else
                        {
                            vimg = "";
                        }
                        #endregion
                    }
                }
            }
        }

        #endregion

        #region File
        string file     = "";
        string fileLink = tbFileLink.Text;
        if (flFile.PostedFile.ContentLength > 0)
        {
            string filename = flFile.FileName;
            string fileex   = filename.Substring(filename.LastIndexOf("."));
            string path     = Request.PhysicalApplicationPath + "/" + pic + "/";

            string fileNotEx = StringExtension.ReplateTitle(filename.Remove(filename.LastIndexOf(".") - 1));
            if (fileNotEx.Length > 9)
            {
                fileNotEx = fileNotEx.Remove(9);
            }
            string ticks = DateTime.Now.Ticks.ToString();
            #region Lưu tệp đính kèm
            file = fileNotEx + "_" + ticks + fileex;
            flFile.SaveAs(path + file);
            #endregion
        }
        #endregion

        #region Status
        string status = "0";
        if (chk_status.Checked == true)
        {
            status = "1";
        }
        #endregion

        #region IID người đăng
        string iidNguoiDang    = "";
        string thongtindangbai = "";
        string ngayxuatban     = "";
        if (FileLibraryConfig.KeyDuyetTin)
        {
            if (HorizaMenuConfig.ShowDuyetTin1 || HorizaMenuConfig.ShowDuyetTin2)
            {
                iidNguoiDang = CookieExtension.GetCookies("userId");
                ngayxuatban  = DateTime.Now.ToString();
            }
        }
        #endregion

        #region Time Create Date
        string timeCreateDate = "";
        timeCreateDate = txtCreateDate.Text;
        #endregion
        #region Seo
        if (textLinkRewrite.Text.Trim().Equals(""))
        {
            textLinkRewrite.Text = txt_title.Text;
        }
        if (textTagTitle.Text.Trim().Equals(""))
        {
            textTagTitle.Text = txt_title.Text;
        }
        if (textTagKeyword.Text.Trim().Equals(""))
        {
            textTagKeyword.Text = txt_title.Text;
        }
        if (textTagDescription.Text.Trim().Equals(""))
        {
            textTagDescription.Text = txt_description.Text;
        }
        #endregion

        #region Insert
        if (insert)
        {
            GroupsItems.InsertItemsGroupsItems(language, app, tbKey.Text, txt_title.Text, txt_description.Text, contentDetail, vimg, iidNguoiDang, fileLink, textTagTitle.Text, textLinkRewrite.Text, StringExtension.ReplateTitle(textLinkRewrite.Text), textTagKeyword.Text, textTagDescription.Text, thongtindangbai, ngayxuatban, "", file, "0", "0", "", "", timeCreateDate, DateTime.Now.ToString(), DateTime.Now.ToString(), tbOrder.Text, ddl_group_product.SelectedValue, timeCreateDate, DateTime.Now.ToString(), DateTime.Now.ToString(), tbOrder.Text, status);

            #region Lay ra iid cua item vua duoc luu
            condition = DataExtension.AndConditon(
                ItemsTSql.GetItemsByDicreatedate(timeCreateDate),
                ItemsTSql.GetItemsByViapp(app));
            DataTable dtInsertedItems = new DataTable();
            dtInsertedItems = GroupsItems.GetAllData("1", "Items.iid", condition, ItemsColumns.IidColumn + " desc");
            if (dtInsertedItems.Rows.Count > 0)
            {
                iid = dtInsertedItems.Rows[0][ItemsColumns.IidColumn].ToString();
            }
            #endregion

            #region Logs
            string logAuthor     = CookieExtension.GetCookies("LoginSetting");
            string logCreateDate = DateTime.Now.ToString();
            Logs.InsertLogs(logCreateDate, Request.Url.ToString(), "", txt_title.Text, logAuthor, "", logCreateDate + ": " + logAuthor + " tạo mới " + txt_title.Text);
            #endregion
        }
        #endregion
        #region Update
        else
        {
            if (vimg.Equals(""))
            {
                vimg = hd_img.Value;
            }
            else
            {
                TatThanhJsc.Extension.ImagesExtension.DeleteImageWhenDeleteItem(pic, hd_img.Value);
            }

            if (file.Equals(""))
            {
                file = hdFile.Value;
            }
            else
            {
                TatThanhJsc.Extension.ImagesExtension.DeleteImageWhenDeleteItem(pic, hdFile.Value);
            }

            if (FileLibraryConfig.KeyDuyetTin)
            {
                string userRole = CookieExtension.GetCookies("RolesUser");
                if (HorizaMenuConfig.ShowDuyetTin2)
                {
                    if (hdEnable.Value == PhanQuyen.DuyetTin.Cap1 && StringExtension.RoleInListRoles(PhanQuyen.DuyetTin.Cap1, userRole))
                    {
                        status = "0";
                    }
                    else if (hdEnable.Value == "1" && StringExtension.RoleInListRoles(PhanQuyen.DuyetTin.Cap2, userRole))
                    {
                        status = "1";
                    }
                    else if (hdEnable.Value != "0" && hdEnable.Value != "1")
                    {
                        status = hdEnable.Value;
                    }
                }
                else
                {
                    if (hdEnable.Value == PhanQuyen.DuyetTin.Cap2 && StringExtension.RoleInListRoles(PhanQuyen.DuyetTin.Cap2, userRole))
                    {
                        status = "0";
                    }
                    else if (hdEnable.Value != "0" && hdEnable.Value != "1")
                    {
                        status = hdEnable.Value;
                    }
                }
            }

            string nguoiDangCu   = hdNguoiDangCu.Value;
            string thongtincu    = hdThongTinThem.Value;
            string ngayxuatbancu = hdNgayXuatBan.Value;
            GroupsItems.UpdateItemsGroupsItems(language, app, tbKey.Text, txt_title.Text, txt_description.Text, contentDetail, vimg, nguoiDangCu, fileLink, textTagTitle.Text, textLinkRewrite.Text, StringExtension.ReplateTitle(textLinkRewrite.Text), textTagKeyword.Text, textTagDescription.Text, thongtincu, ngayxuatbancu, "", file, "0", "0", "", HdIitotalview.Value, timeCreateDate, DateTime.Now.ToString(), DateTime.Now.ToString(), tbOrder.Text, ddl_group_product.SelectedValue, timeCreateDate, DateTime.Now.ToString(), DateTime.Now.ToString(), tbOrder.Text, status, iid);

            #region Logs
            string logAuthor     = CookieExtension.GetCookies("LoginSetting");
            string logCreateDate = DateTime.Now.ToString();
            Logs.InsertLogs(logCreateDate, Request.Url.ToString(), "", txt_title.Text, logAuthor, "", logCreateDate + ": " + logAuthor + " cập nhật " + txt_title.Text);
            #endregion
        }
        #endregion

        #region Properties-Chi thực hiện khi chức năng Quản lý thuộc tính được hiển thị
        if (FileLibraryConfig.KeyHienThiQuanLyThuocTinhDuLieu)
        {
            string properties = parramSpitString;
            for (int i = 0; i < rptProperties.Items.Count; i++)
            {
                CheckBox checkBoxProperties = (CheckBox)rptProperties.Items[i].FindControl("checkBoxProperties");
                if (checkBoxProperties.Checked == true)
                {
                    properties += checkBoxProperties.ToolTip + parramSpitString;
                }
            }

            condition = TatThanhJsc.Extension.DataExtension.AndConditon(
                TatThanhJsc.TSql.SubitemsTSql.GetSubitemsByIid(iid),
                TatThanhJsc.TSql.SubitemsTSql.GetSubitemsByVskey(propertyModul));
            fields = DataExtension.GetListColumns(SubitemsColumns.IsidColumn, SubitemsColumns.VscontentColumn);
            DataTable dt = new DataTable();
            dt = Subitems.GetSubItems("", fields, condition, "");

            if (dt.Rows.Count > 0)
            {
                string isid = dt.Rows[0][SubitemsColumns.IsidColumn].ToString();
                //Cap nhat
                Subitems.UpdateSubitems(iid, language, propertyModul, "", properties, "", "", "", "", DateTime.Now.ToString(), DateTime.Now.ToString(), DateTime.Now.ToString(), "1", isid);
            }
            else
            {
                //Them moi
                Subitems.InsertSubitems(iid, language, propertyModul, "", properties, "", "", "", "", DateTime.Now.ToString(), DateTime.Now.ToString(), DateTime.Now.ToString(), "1");
            }
        }
        #endregion

        #region After Insert/Update
        if (ckbContinue.Checked == true)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "alertSuccess", "ThongBao(3000,'Đã tạo: " + txt_title.Text + "');", true);
            ResetControls();
        }
        else
        {
            Response.Redirect(LinkRedrect());
        }
        #endregion
    }
Пример #47
0
        public static void SaveLogs()
        {
            var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
            var filename = Path.Combine (documents, "proscanmobile_logs.xml");

            Logs s_tmp = new Logs ();
            s_tmp.LogsList = new List<LogsDisplay> ();

            foreach (LogsDisplay sd_tmp in _log.LogsList) {
                s_tmp.LogsList.Add (new LogsDisplay () {
                    sys = XmlConvert.EncodeName(sd_tmp.sys),
                    grp = XmlConvert.EncodeName(sd_tmp.grp),
                    alert =  sd_tmp.alert,
                    lastalert = sd_tmp.lastalert
                } );
            }

            XmlSerializer serializer = new XmlSerializer (typeof(Logs));
            TextWriter textWriter = new StreamWriter (filename);
            serializer.Serialize (textWriter, s_tmp);
            textWriter.Close ();

            s_tmp = null;
        }
Пример #48
0
        public static void LogThis(string message, Logs.Log.LogType logType)
        {
            Logs.Log log = new Logs.Log(message, logType);

            formMain.panelLogs.Invoke(new MethodInvoker(delegate
            {
                formMain.panelLogs.AddLog(log);
            }));
        }
Пример #49
0
        public async Task <InvoiceModel> CreateAsync(string email, DateTime due_date, Item[] items, string return_url,
                                                     string expired_url, string notification_url, int tax_cents = 0, int discount_cents = 0, string customer_id = null, bool ignore_due_email = false,
                                                     string subscription_id = null, int?credits = null, Logs logs = null, List <CustomVariables> custom_variables = null, PayerModel payer = null, bool early_payment_discount = false, List <EarlyPaymentDiscounts> early_payment_discounts = null)
        {
            var invoice = new
            {
                email                   = email,
                due_date                = due_date.ToString("dd/MM/yyyy"),
                items                   = items,
                return_url              = return_url,
                expired_url             = expired_url,
                tax_cents               = tax_cents,
                discount_cents          = discount_cents,
                customer_id             = customer_id,
                ignore_due_email        = ignore_due_email,
                subscription_id         = subscription_id,
                credits                 = credits,
                logs                    = logs,
                custom_variables        = custom_variables,
                notification_url        = notification_url,
                early_payment_discount  = early_payment_discount,
                early_payment_discounts = early_payment_discounts,
                payer                   = payer
            };
            var retorno = await PostAsync <InvoiceModel>(invoice).ConfigureAwait(false);

            return(retorno);
        }
 private void HandleUserSideError(TcpSocketSession session, Exception ex)
 {
     Logs.Error(string.Format("Session [{0}] error occurred in user side [{1}].", session, ex.Message), ex);
 }