Exemplo n.º 1
0
 public void OneTimeSetup()
 {
     AppLog.Log("Test log 1");
     AppLog.Error("Test error 1");
     AppLog.Log("Test log 2");
     AppLog.Debug("Test debug 1");
     AppLog.Exception(new AmbiguousMatchException(), "Test exception 1");
     AppLog.Debug("Invalid Format {0}");
 }
Exemplo n.º 2
0
        public static void Execute(string assembly = null)
        {
            ILog log     = new AppLog();
            var  logInfo = new LogInfo
            {
                MethodInstance = MethodBase.GetCurrentMethod(),
                ThreadInstance = Thread.CurrentThread
            };

            try
            {
                // The application must run schedule task by it's own assembly name
                var list = !string.IsNullOrEmpty(assembly)
                    ? Schedule.All().FindAll(x => x.IsActive && x.ScheduleType.Contains(assembly))
                    : Schedule.All().FindAll(x => x.IsActive);

                if (list.Count > 0)
                {
                    foreach (var s in list)
                    {
                        if (s.ShouldExecute())
                        {
                            // Call this method BEFORE processing the ScheduledEvent. This will help protect against long running events
                            // being fired multiple times. Note, it is not absolute protection. App restarts will cause events to look like
                            // they were completed, even if they were not. Again, ScheduledEvents are helpful...but not 100% reliable

                            var instance = s.IScheduleInstance;
                            ManagedThreadPool.QueueUserWorkItem(instance.Execute);

                            s.LastCompletedTime = DateTime.Now;
                            s.Update();

                            log.Debug($"ISchedule: {s.ScheduleType}", logInfo);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Debug(ex, logInfo);

                throw;
            }
        }
Exemplo n.º 3
0
        public Tuple <int, int> LoadBlockLists()
        {
            ListLock.EnterWriteLock();

            TopLevel = new Level(); // clear domain tree

            int counter = 0;
            int errors  = 0;

            var watch = System.Diagnostics.Stopwatch.StartNew();

            try
            {
                //string[] fileEntries = Directory.GetFiles(App.dataPath + @"\DnsBlockLists");
                //foreach (string fileName in fileEntries)
                foreach (DomainBlocklist blocklist in Blocklists.Values)
                {
                    if (!blocklist.Enabled)
                    {
                        continue;
                    }
                    string fileName = App.dataPath + @"\DnsBlockLists\" + blocklist.FileName;
                    if (blocklist.FileName.Length == 0 || !File.Exists(fileName))
                    {
                        continue;
                    }

                    counter++;
                    int count = LoadBlockList(fileName);
                    if (count == 0)
                    {
                        errors++;
                    }

                    blocklist.EntryCount = count;
                }
            }

            /*catch (DirectoryNotFoundException)
             * {
             *  App.LogError("Could not load blocklists from {0}", App.dataPath + @"\DnsBlockLists");
             * }*/
            catch (Exception err)
            {
                AppLog.Exception(err);
            }

            watch.Stop();
            var elapsedMs = watch.ElapsedMilliseconds;

            AppLog.Debug("LoadBlockLists took: " + elapsedMs + "ms");

            ListLock.ExitWriteLock();

            return(Tuple.Create(counter, errors));
        }
Exemplo n.º 4
0
 public bool Load(XmlNode entryNode)
 {
     foreach (XmlNode node in entryNode.ChildNodes)
     {
         if (node.Name == "ID")
         {
             ProgramID id = new ProgramID();
             if (id.Load(node))
             {
                 ID = id;
             }
         }
         else if (node.Name == "Description")
         {
             Description = node.InnerText;
         }
         else if (node.Name == "FwRules")
         {
             foreach (XmlNode childNode in node.ChildNodes)
             {
                 FirewallRuleEx rule = new FirewallRuleEx();
                 rule.ProgID = ID;
                 if (rule.Load(childNode) && !Rules.ContainsKey(rule.guid))
                 {
                     Rules.Add(rule.guid, rule);
                 }
                 else
                 {
                     App.LogError("Failed to load Firewall RuleEx {0} in {1}", rule.Name != null ? rule.Name : "[un named]", this.Description);
                 }
             }
         }
         else if (node.Name == "DnsLog")
         {
             foreach (XmlNode childNode in node.ChildNodes)
             {
                 DnsEntry Entry = new DnsEntry(ID);
                 if (Entry.Load(childNode) && !DnsLog.ContainsKey(Entry.HostName))
                 {
                     DnsLog.Add(Entry.HostName, Entry);
                 }
                 else
                 {
                     App.LogError("Failed to load DnsLog Entry in {0}", this.Description);
                 }
             }
         }
         else
         {
             AppLog.Debug("Unknown Program Value, '{0}':{1}", node.Name, node.InnerText);
         }
     }
     return(ID != null);
 }
Exemplo n.º 5
0
 public DnsInspector()
 {
     try
     {
         InitEtw();
         //AppLog.Debug("Successfully initialized DnsInspectorETW");
     }
     catch
     {
         AppLog.Debug("Failed to initialized DnsInspectorETW");
     }
 }
Exemplo n.º 6
0
        /// <summary>
        /// 登录房间
        /// </summary>
        private void RoomLogin()
        {
            //string login = "******" + ROOM_ID + "/";
            string login = $"type@=loginreq/roomid@={ROOM_ID}/dfl@=sn@AA=105@ASss@AA=1/username@={username}/uid@={userid}/ver@=20190610/aver@=218101901/ct@=0/";

            byte[] loginBytes = DataToBytes(login);
            DanmuClient.Send(loginBytes);
            string joingroup = "type@=joingroup/rid@=" + ROOM_ID + "/gid@=-9999/";

            byte[] joingroupBytes = DataToBytes(joingroup);
            DanmuClient.Send(joingroupBytes);
            AppLog.Debug($"登录房间【{ROOM_ID}】成功");
        }
Exemplo n.º 7
0
        public void UpdateProgramList(List <ProgramSet> progs)
        {
            var watch = System.Diagnostics.Stopwatch.StartNew();

            ProgramList.UpdateItems(progs);

            watch.Stop();
            var elapsedMs = watch.ElapsedMilliseconds;

            AppLog.Debug("UpdateProgramList took: " + elapsedMs + "ms");

            ProgramList.SortAndFitlerList();
        }
Exemplo n.º 8
0
        public NetworkMonitor()
        {
            LastUpdate = MiscFunc.GetTickCount64();

            try
            {
                InitEtw();
                //AppLog.Debug("Successfully initialized NetworkMonitorETW");
            }
            catch
            {
                AppLog.Debug("Failed to initialized NetworkMonitorETW");
            }
        }
Exemplo n.º 9
0
    private void Finish(int Success, int ErrCode, Exception Error = null)
    {
        // Release the HttpWebResponse resource.
        if (response != null)
        {
            response.Close();
            if (streamResponse != null)
            {
                streamResponse.Close();
            }
            if (streamWriter != null)
            {
                streamWriter.Close();
            }
        }
        response       = null;
        request        = null;
        streamResponse = null;
        BufferRead     = null;

        if (Success == 1)
        {
            try
            {
                if (File.Exists(mDlPath + @"\" + mDlName))
                {
                    File.Delete(mDlPath + @"\" + mDlName);
                }
                File.Move(mDlPath + @"\" + mDlName + ".tmp", mDlPath + @"\" + mDlName);
            }
            catch
            {
                AppLog.Debug("Failed to rename download {0}", mDlPath + @"\" + mDlName + ".tmp");
                mDlName += ".tmp";
            }

            try { File.SetLastWriteTime(mDlPath + @"\" + mDlName, lastTime); } catch { } // set last mod time
        }
        else if (Success == 2)
        {
            AppLog.Debug("File already downloaded {0}", mDlPath + @"\" + mDlName);
        }
        else
        {
            try { File.Delete(mDlPath + @"\" + mDlName + ".tmp"); } catch { } // delete partial file
            AppLog.Debug("Failed to download file {0}", mDlPath + @"\" + mDlName);
        }

        Finished?.Invoke(this, new FinishedEventArgs(Success > 0 ? 0 : Canceled ? -1 : ErrCode, Error));
    }
        public string Savedocument(string generatedRequestId)
        {
            string sql = "";
            string destinationLocation = Convert.ToString(ConfigurationManager.AppSettings["CaseDocumentLocation"]);
            string cdeDocLocation      = Convert.ToString(ConfigurationManager.AppSettings["CDEDocumentLocation"]);

            AppLog.Debug("doc save at " + destinationLocation + DateTime.Now);
            bool bdocumentuploaded = false;

            destinationLocation = destinationLocation + "Documents";
            if (!Directory.Exists(destinationLocation))
            {
                Directory.CreateDirectory(destinationLocation);
            }
            destinationLocation = destinationLocation + "\\NewCase";
            if (!Directory.Exists(destinationLocation))
            {
                Directory.CreateDirectory(destinationLocation);
            }
            destinationLocation = destinationLocation + "\\" + generatedRequestId + "\\";
            if (!Directory.Exists(destinationLocation))
            {
                Directory.CreateDirectory(destinationLocation);
            }
            foreach (String documentPath in document)
            {
                string destFile = "";
                try
                {
                    AppLog.Debug("Document Processing");
                    // string documentPath1 = @"Backup\doc\cde_file\2.pdf";
                    string fileName = System.IO.Path.GetFileName(cdeDocLocation + documentPath);
                    destFile = System.IO.Path.Combine(destinationLocation, fileName);
                    string repVal         = @"\";
                    string currectDoCPath = documentPath.Replace("/", repVal);
                    AppLog.Debug("destFile & fileName $ currectDoCPath" + destFile + " " + fileName + "" + cdeDocLocation + currectDoCPath);
                    System.IO.File.Copy(cdeDocLocation + currectDoCPath, destFile, true);
                    AppLog.Debug("data " + cdeDocLocation + " " + currectDoCPath + " " + destinationLocation);
                }
                catch (Exception ex)
                {
                    continue;
                }

                bdocumentuploaded = true;
                UploadDocument(destFile, generatedRequestId);
            }
            document.Clear();
            return(null);
        }
Exemplo n.º 11
0
        /// <summary>
        /// 初始化连接是否成功
        /// </summary>
        /// <returns></returns>
        public bool Initialization()
        {
            try
            {
                //取消之前正在运行的线程
                if (source != null)
                {
                    source.Cancel();
                }
                source = new CancellationTokenSource();

                agent?.RemoveRoom(ROOM_ID);
                var ips = AgentPool.GetAgentIp(ROOM_ID);
                if (ips.Count > 0)
                {
                    agent = ips[0];
                    Console.WriteLine($"{agent.Ip}:{agent.Port}");
                }
                else
                {
                    agent = null;
                }
                AuthClient?.CloseAsync();
                DanmuClient?.CloseAsync();
                //创建实例
                AuthClient = CreateAuthSocket(source.Token);

                //认证
                Authentication();
                //认证通过开启心跳
                AuthKeepAlive(source.Token);

                DanmuClient = CreateDanmuSocket(source.Token);
                //tcpClient = SocketHelper.InitTcp(agent.Ip, agent.Port);
                //ConnectProxyServer(SERVER_DOMAIN, SERVER_PORT, tcpClient);

                //登录房间
                RoomLogin();
                //心跳维持
                DanmmuKeepAlive(source.Token);
                AppLog.Debug($"监控房间【{ROOM_ID}】成功");
                return(true);
            }
            catch (Exception ex)
            {
                AppLog.Error($"【房间:{ROOM_ID}】【监控失败】", ex);
                return(false);
            }
        }
Exemplo n.º 12
0
        static public void Sort(SharpTreeNodeCollection Children, string sortMember, ListSortDirection direction)
        {
            Comparison <SharpTreeNode> comparison = (This, That) =>
            {
                var L = (typeof(TreeItem).GetProperty(sortMember).GetValue(This, null) as IComparable);
                var R = (typeof(TreeItem).GetProperty(sortMember).GetValue(That, null) as IComparable);

                int ret;
                if (L == null && R == null)
                {
                    ret = 0;
                }
                else if (L == null)
                {
                    ret = 1;
                }
                else if (R == null)
                {
                    ret = -1;
                }
                else
                {
                    ret = L.CompareTo(R);
                }

                if (direction == ListSortDirection.Ascending)
                {
                    return(-ret);
                }
                return(ret);
            };

            SwapCount = 0;
            var watch = System.Diagnostics.Stopwatch.StartNew();

            Sort(Children, sortMember, direction, comparison);

            watch.Stop();
            var elapsedMs = watch.ElapsedMilliseconds;

#if DEBUG
            if (elapsedMs > 100)
            {
                AppLog.Debug("TreeView Sorting took very log: {0} ms and required {1} swaps", elapsedMs, SwapCount);
            }
#endif
        }
Exemplo n.º 13
0
    static public bool SkipUacRun(string taskName, string[] args = null)
    {
        bool silent = true;

        try
        {
            TaskScheduler.TaskScheduler service = new TaskScheduler.TaskScheduler();
            service.Connect();
            ITaskFolder     folder = service.GetFolder(@"\"); // root
            IRegisteredTask task   = folder.GetTask(taskName);

            silent = false;
            AppLog.Debug("Trying to SkipUAC ...");

            IExecAction action = (IExecAction)task.Definition.Actions[1];
            if (action.Path.Equals(System.Reflection.Assembly.GetExecutingAssembly().Location, StringComparison.OrdinalIgnoreCase))
            {
                string arguments = args == null ? "" : ("\"" + string.Join("\" \"", args) + "\"");

                IRunningTask running_Task = task.RunEx(arguments, (int)_TASK_RUN_FLAGS.TASK_RUN_NO_FLAGS, 0, null);

                for (int i = 0; i < 5; i++)
                {
                    Thread.Sleep(250);
                    running_Task.Refresh();
                    _TASK_STATE state = running_Task.State;
                    if (state == _TASK_STATE.TASK_STATE_RUNNING || state == _TASK_STATE.TASK_STATE_READY || state == _TASK_STATE.TASK_STATE_DISABLED)
                    {
                        if (state == _TASK_STATE.TASK_STATE_RUNNING || state == _TASK_STATE.TASK_STATE_READY)
                        {
                            return(true);
                        }
                        break;
                    }
                }
            }
        }
        catch (Exception err)
        {
            if (!silent)
            {
                AppLog.Exception(err);
            }
        }
        return(false);
    }
Exemplo n.º 14
0
        public void TestTweaks(bool bAll = true, bool fixChanged = false)
        {
            var watch = System.Diagnostics.Stopwatch.StartNew();

            //foreach (Tweak tweak in TweakList.Values)
            foreach (Tweak tweak in GetAllTweaks())
            {
                if (bAll || tweak.State != Tweak.States.Unsellected)
                {
                    TestTweak(tweak, fixChanged);
                }
            }

            watch.Stop();
            var elapsedMs = watch.ElapsedMilliseconds;

            AppLog.Debug("TestAllTweaks took: " + elapsedMs + "ms");
        }
Exemplo n.º 15
0
        public bool LoadSet(XmlNode entryNode)
        {
            if (entryNode.Name != "ProgramSet")
            {
                return(false);
            }

            foreach (XmlNode node in entryNode.ChildNodes)
            {
                if (node.Name == "Program")
                {
                    Program prog = new Program();
                    if (prog.Load(node))
                    {
                        prog.AssignSet(this);
                    }
                }
                else if (node.Name == "Name")
                {
                    config.Name = node.InnerText;
                }
                else if (node.Name == "Category")
                {
                    config.Category = node.InnerText;
                }
                else if (node.Name == "Icon")
                {
                    config.Icon = node.InnerText;
                }
                else if (node.Name == "NetAccess")
                {
                    Enum.TryParse(node.InnerText, out config.NetAccess);
                }
                else if (node.Name == "Notify")
                {
                    config.Notify = MiscFunc.parseBool(node.InnerText, null);
                }
                else
                {
                    AppLog.Debug("Unknown Program Value, '{0}':{1}", node.Name, node.InnerText);
                }
            }
            return(Programs.Count > 0 && config.Name != null);
        }
Exemplo n.º 16
0
        public bool LoadAppPkgs(bool bWithPackageDetails = false)
        {
            AppPackages.Clear();
            LastAppReload = DateTime.Now;

            if (UwpFunc.IsWindows7OrLower)
            {
                return(false);
            }

            var watch = System.Diagnostics.Stopwatch.StartNew();

            var AppContainers = GetAppContainers();

            foreach (var AppContainer in AppContainers)
            {
                string SID = AppContainer.appContainerSid.ToString();
                if (AppPackages.ContainsKey(SID))
                {
                    continue;
                }

                UwpFunc.AppInfo AppInfo = new UwpFunc.AppInfo();
                AppInfo.ID   = AppContainer.appContainerName;
                AppInfo.SID  = SID;
                AppInfo.Name = AppContainer.displayName;

                if (bWithPackageDetails)
                {
                    var AppInfo2 = App.engine?.PkgMgr?.GetAppInfoByID(AppInfo.ID);
                    AppInfo.Logo = AppInfo2?.Logo;
                }

                AppPackages.Add(SID, AppInfo);
            }

            watch.Stop();
            var elapsedMs = watch.ElapsedMilliseconds;

            AppLog.Debug("LoadAppPkgs took: " + elapsedMs + "ms");

            return(true);
        }
Exemplo n.º 17
0
        /// <summary>
        /// 退出房间
        /// </summary>
        /// <param name="ROOM_ID"></param>
        /// <param name="num"></param>
        public void SignOutRoom(int ROOM_ID, int num = 1)
        {
            if (!douyuRooms.ContainsKey(ROOM_ID))
            {
                throw new Exception($"没有监控该房间【{ROOM_ID}】");
            }
            var rooms        = douyuRooms[ROOM_ID];
            var removeRoonms = rooms.Take(num).ToList();

            Console.WriteLine(removeRoonms.Count);
            removeRoonms.ForEach(p => p.Dispose());
            for (int i = 0; i < removeRoonms.Count; i++)
            {
                var room = removeRoonms[i];
                rooms.Remove(room);
            }
            OnSignOut?.Invoke(ROOM_ID, removeRoonms.Count);
            AppLog.Debug($"【房间:{ROOM_ID}】退出房间人数:{removeRoonms.Count}");
        }
        public string getData()
        {
            try
            {
                AppLog.Debug("Service started");
                string username = Convert.ToString(ConfigurationManager.AppSettings[Constants.Token.username]);
                string password = Convert.ToString(ConfigurationManager.AppSettings[Constants.Token.password]);

                CSPiHelper helper = new CSPiHelper(username, password);
                AppLog.Debug("Step 0");
                var dt = getDatacaseCreation(helper);
                AppLog.Debug("Step 1");
                return(null);
            }
            catch (Exception ex)
            {
                AppLog.Debug("Error:" + ex.StackTrace);
                return(null);
            }
        }
Exemplo n.º 19
0
            public bool Connect(int TimeOut = 10000)
            {
                try
                {
                    pipeStream.Connect(TimeOut);
                }
                catch
                {
                    return(false); // timeout
                }

                DataReceived += (sndr, data) =>
                {
                    RemoteCall call = ByteArrayToObject(data);

                    if (call.type == "push")
                    {
                        PushNotification?.Invoke(this, call);
                    }
                    else if (call.type == "call")
                    {
                        if (call.seqID != seqIDctr)
                        {
                            AppLog.Debug("call.seqID != seqIDctr");
                        }
                        else
                        {
                            retObj = call;
                            done.Set();
                        }
                    }
                };

                PipeClosed += (sndr, args) =>
                {
                    done.Set();
                };

                startRecv();
                return(true);
            }
Exemplo n.º 20
0
        public static bool StartEngine()
        {
            AppLog.Debug("Starting Engine...");

            //ProcessStartInfo startInfo = new ProcessStartInfo(exePath, "-engine");
            ProcessStartInfo startInfo = new ProcessStartInfo(appPath + "\\PrivateService.exe", "-engine");

            startInfo.UseShellExecute = true;
            startInfo.Verb            = "runas";
            try
            {
                EngineProc = Process.Start(startInfo);

                AppLog.Debug("... engine started.");
                return(true);
            }
            catch
            {
                MessageBox.Show(Translate.fmt("msg_engine_fail"), Title);
                return(false);
            }
        }
Exemplo n.º 21
0
        public void UpdateProgramList(List <ProgramSet> progs)
        {
            var watch = System.Diagnostics.Stopwatch.StartNew();

            Dictionary <Guid, ProgramControl> OldProcesses = new Dictionary <Guid, ProgramControl>(Programs);

            foreach (ProgramSet prog in progs)
            {
                ProgramControl item;
                if (Programs.TryGetValue(prog.guid, out item))
                {
                    item.progSet = prog;
                    item.DoUpdate();
                    OldProcesses.Remove(prog.guid);
                }
                else
                {
                    item = AddProgramItem(prog);
                }
            }

            foreach (Guid guid in OldProcesses.Keys)
            {
                Programs.Remove(guid);
                ProgramControl item;
                if (OldProcesses.TryGetValue(guid, out item))
                {
                    this.processGrid.Children.Remove(item);
                }
            }

            watch.Stop();
            var elapsedMs = watch.ElapsedMilliseconds;

            AppLog.Debug("UpdateProgramList took: " + elapsedMs + "ms");

            SortAndFitlerProgList();
        }
Exemplo n.º 22
0
        private void OnDnsQueryEvent(Microsoft.O365.Security.ETW.IEventRecord record)
        {
            // WARNING: this function is called from the worker thread

            if (record.Id != 1001 && record.Id != 1004)
            {
                return;
            }

            DateTime TimeStamp = record.Timestamp;
            UInt32   Status    = record.GetUInt32("Status", 0);
            int      ProcessId = (int)record.ProcessId;
            int      ThreadId  = (int)record.ThreadId;
            var      HostName  = record.GetUnicodeString("NodeName", null);
            var      Results   = record.GetUnicodeString("Result", null);

            if (ProcessId == ProcFunc.CurID)
            {
                return; // ignore these events as thay are the result of reverse dns querries....
            }

            /*
             * "192.168.163.1" "192.168.163.1;"
             * "localhost" "[::1]:8307;127.0.0.1:8307;" <- wtf is this why is there a port?!
             * "DESKTOP" "fe80::189a:f1c3:3e87:be81%12;192.168.10.12;"
             * "telemetry.malwarebytes.com" "54.149.69.204;54.200.191.52;54.70.191.27;54.149.66.105;54.244.17.248;54.148.98.86;"
             * "web.whatsapp.com" "31.13.84.51;"
             */

            AppLog.Debug("Etw dns_query {0} => {1} for {2}", HostName, Results, ProcessId);

            App.engine?.RunInEngineThread(() =>
            {
                // Note: this happens in the engine thread

                List <IPAddress> RemoteAddresses = new List <IPAddress>();

                foreach (string Result in Results.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    IPAddress Address = null;
                    if (!IPAddress.TryParse(Result, out Address) && !IPAddress.TryParse(TextHelpers.Split2(Result, ":", true).Item1, out Address))
                    {
                        continue;
                    }

                    RemoteAddresses.Add(Address);

                    Dictionary <IPAddress, Dictionary <string, HostNameEntry> > dnsCache = dnsQueryCache.GetOrCreate(ProcessId);

                    Dictionary <string, HostNameEntry> cacheEntries = dnsCache.GetOrCreate(Address);

                    HostNameEntry cacheEntry;
                    if (!cacheEntries.TryGetValue(HostName, out cacheEntry))
                    {
                        cacheEntry = new HostNameEntry()
                        {
                            HostName = HostName
                        };
                        cacheEntries.Add(HostName, cacheEntry);
                    }

                    cacheEntry.TimeStamp = TimeStamp;
                }

                DnsQueryEvent?.Invoke(this, new DnsEvent()
                {
                    ProcessId = ProcessId, HostName = HostName, RemoteAddresses = RemoteAddresses, TimeStamp = TimeStamp
                });
            });
        }
Exemplo n.º 23
0
        public bool LoadSet(XmlNode entryNode)
        {
            if (entryNode.Name != "ProgramSet")
            {
                return(false);
            }

            foreach (XmlNode node in entryNode.ChildNodes)
            {
                if (node.Name == "Program")
                {
                    Program prog = new Program();
                    if (prog.Load(node))
                    {
                        // COMPAT: merge "duplicates"
                        Program knownProg;
                        if (Programs.TryGetValue(prog.ID, out knownProg))
                        {
                            foreach (var rule in prog.Rules)
                            {
                                knownProg.Rules.Add(rule.Key, rule.Value);
                            }
                        }
                        else
                        {
                            prog.AssignSet(this);
                        }
                    }
                }
                else if (node.Name == "Guid")
                {
                    guid = Guid.Parse(node.InnerText);
                }
                else if (node.Name == "Name")
                {
                    config.Name = node.InnerText;
                }
                else if (node.Name == "Category")
                {
                    config.Category = node.InnerText;
                }
                else if (node.Name == "Icon")
                {
                    config.Icon = node.InnerText;
                }
                else if (node.Name == "NetAccess")
                {
                    Enum.TryParse(node.InnerText, out config.NetAccess);
                }
                else if (node.Name == "Notify")
                {
                    config.Notify = MiscFunc.parseBool(node.InnerText, null);
                }
                else
                {
                    AppLog.Debug("Unknown Program Value, '{0}':{1}", node.Name, node.InnerText);
                }
            }

            if (Programs.Count > 0 && config.Name == null || config.Name.Substring(0, 2) == "@{")
            {
                config.Name = Programs.First().Value.Description;
            }

            return(Programs.Count > 0 && config.Name != null);
        }
Exemplo n.º 24
0
        static bool ExecuteCommands()
        {
            if (TestArg("-help") || TestArg("/?"))
            {
                string   Message = "Available command line options\r\n";
                string[] Help    =
                {
                    "Available Console Commands:",
                    "========================================",
                    "",
                    "-state\t\t\tShow instalation state",
                    "-uninstall\t\tUninstall Private Win10",
                    "-shutdown\t\tClose Private Win10 instances",
                    "-restart\t\tRestart Win10 and reload settings",
                    "",
                    "-svc_install\t\tInstall priv10 service (invokes -log_install)",
                    "-svc_remove\t\tRemove priv10 service",
                    "",
                    "-log_install\t\tInstall PrivateWin10 Custom Event Log",
                    "-log_remove\t\tRemove PrivateWin10 Custom Event Log",
                    "",
                    "-restore_dns\t\tRestore original DNS Configuration",
                    "",
                    "-console\t\tShow console with debug output",
                    "-help\t\t\tShow this help message"
                };
                if (!HasConsole)
                {
                    MessageBox.Show(Message + string.Join("\r\n", Help));
                }
                else
                {
                    Console.WriteLine(Message);
                    for (int j = 0; j < Help.Length; j++)
                    {
                        Console.WriteLine(" " + Help[j]);
                    }
                }
                return(true);
            }


            bool bDone = false;

            if (TestArg("-uninstall"))
            {
                AppLog.Debug("Uninstalling Private Win10");
                bDone = true;
            }

            if (TestArg("-svc_remove") || (Priv10Service.IsInstalled() && TestArg("-uninstall")))
            {
                AppLog.Debug("Removing Service...");
                Priv10Service.Uninstall();
                bDone = true;
            }

            if (TestArg("-shutdown") || TestArg("-restart") || TestArg("-restore") || TestArg("-uninstall"))
            {
                AppLog.Debug("Closing instances...");
                if (Priv10Service.IsInstalled())
                {
                    Priv10Service.Terminate();
                }

                Thread.Sleep(500);

                foreach (var proc in Process.GetProcessesByName(App.Key))
                {
                    if (proc.Id == ProcFunc.CurID)
                    {
                        continue;
                    }
                    proc.Kill();
                }

                bDone = true;
            }

            if (TestArg("-restore"))
            {
                string zipPath = GetArg("-restore");

                try
                {
                    if (zipPath == null || !File.Exists(zipPath))
                    {
                        throw new Exception("Data backup zip not specifyed or invalid path");
                    }

                    Console.WriteLine("Restoring settings from {0}", zipPath);

                    string extractPath = App.dataPath;

                    // Normalizes the path.
                    extractPath = Path.GetFullPath(extractPath);

                    // Ensures that the last character on the extraction path
                    // is the directory separator char.
                    // Without this, a malicious zip file could try to traverse outside of the expected
                    // extraction path.
                    if (!extractPath.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal))
                    {
                        extractPath += Path.DirectorySeparatorChar;
                    }

                    // create data directory
                    if (!Directory.Exists(dataPath))
                    {
                        Directory.CreateDirectory(dataPath);
                    }

                    // ensure its writable by non administrators
                    FileOps.SetAnyDirSec(dataPath);

                    // Extract the backuped files
                    using (ZipArchive archive = ZipFile.OpenRead(zipPath))
                    {
                        foreach (ZipArchiveEntry entry in archive.Entries)
                        {
                            // Gets the full path to ensure that relative segments are removed.
                            string destinationPath = Path.GetFullPath(Path.Combine(extractPath, entry.FullName));

                            // Ordinal match is safest, case-sensitive volumes can be mounted within volumes that
                            // are case-insensitive.
                            if (!destinationPath.StartsWith(extractPath, StringComparison.Ordinal))
                            {
                                continue;
                            }

                            Console.WriteLine("Restored file {0}", entry.FullName);
                            if (File.Exists(destinationPath))
                            {
                                FileOps.DeleteFile(destinationPath);
                            }
                            else if (!Directory.Exists(Path.GetDirectoryName(destinationPath)))
                            {
                                Directory.CreateDirectory(Path.GetDirectoryName(destinationPath));
                            }

                            entry.ExtractToFile(destinationPath);
                        }
                    }
                }
                catch (Exception err)
                {
                    Console.WriteLine(err.Message);
                    MessageBox.Show(Translate.fmt("msg_restore_error", err.Message), App.Title, MessageBoxButton.OK, MessageBoxImage.Stop);
                }

                bDone = true;
            }

            if (TestArg("-restart") || TestArg("-restore"))
            {
                Thread.Sleep(500);

                AppLog.Debug("Starting instances...");
                if (Priv10Service.IsInstalled())
                {
                    Priv10Service.Startup();
                }

                Thread.Sleep(500);

                ProcessStartInfo startInfo = new ProcessStartInfo(App.exePath);
                startInfo.UseShellExecute = true;
                startInfo.Verb            = "runas";
                Process.Start(startInfo);

                bDone = true;
            }

            if (TestArg("-log_remove") || (Log.UsingEventLog() && TestArg("-uninstall")))
            {
                AppLog.Debug("Removing Event Log...");
                Log.RemoveEventLog(Key);
                bDone = true;
            }

            if (TestArg("-svc_install"))
            {
                AppLog.Debug("Installing Service...");
                Priv10Service.Install(TestArg("-svc_start"));
                bDone = true;
            }

            if (TestArg("-log_install") || TestArg("-svc_install")) // service needs the event log
            {
                AppLog.Debug("Setting up Event Log...");
                Log.SetupEventLog(Key);
                bDone = true;
            }

            if (TestArg("-restore_dns") || (DnsConfigurator.IsAnyLocalDNS() && TestArg("-uninstall")))
            {
                AppLog.Debug("Restoring DNS Config...");
                DnsConfigurator.RestoreDNS();
                bDone = true;
            }

            if (TestArg("-uninstall") && AdminFunc.IsSkipUac(App.Key))
            {
                AppLog.Debug("Removing UAC Bypass...");
                AdminFunc.SkipUacEnable(App.Key, false);
                bDone = true;
            }

            if (TestArg("-uninstall") && App.IsAutoStart())
            {
                AppLog.Debug("Removing Autostart...");
                App.AutoStart(false);
                bDone = true;
            }

            if (bDone)
            {
                AppLog.Debug("done");
            }


            if (TestArg("-state"))
            {
                Console.WriteLine();
                Console.WriteLine("Instalation State:");
                Console.WriteLine("========================="); // 25
                Console.Write("Auto Start:\t");
                Console.WriteLine(App.IsAutoStart());
                Console.Write("UAC Bypass:\t");
                Console.WriteLine(AdminFunc.IsSkipUac(App.Key));
                Console.Write("Service:\t");
                Console.WriteLine(Priv10Service.IsInstalled());
                Console.Write("Event Log:\t");
                Console.WriteLine(Log.UsingEventLog());
                Console.Write("Local DNS:\t");
                Console.WriteLine(DnsConfigurator.IsAnyLocalDNS());
                Console.WriteLine();
                bDone = true;
            }

            if (TestArg("-wait"))
            {
                Console.WriteLine();
                for (int i = 10; i >= 0; i--)
                {
                    Console.Write("\r{0}%   ", i);
                    Thread.Sleep(1000);
                }
            }

            return(bDone);
        }
Exemplo n.º 25
0
        public static void Main(string[] args)
        {
            App.args = args;

            HasConsole = WinConsole.Initialize(TestArg("-console"));

            if (TestArg("-dbg_wait"))
            {
                MessageBox.Show("Waiting for debugger. (press ok when attached)");
            }

            if (TestArg("-dbg_log"))
            {
                AppDomain.CurrentDomain.FirstChanceException += FirstChanceExceptionHandler;
            }

            StartModes startMode = StartModes.Normal; // Normal GUI Mode

            if (TestArg("-svc"))
            {
                startMode = StartModes.Service;
            }
            else if (TestArg("-engine"))
            {
                startMode = StartModes.Engine;
            }

            Log = new AppLog(Key);
            AppLog.ExceptionLogID    = (long)EventIDs.Exception;
            AppLog.ExceptionCategory = (short)EventFlags.DebugEvents;

            if (startMode == StartModes.Normal)
            {
                Log.EnableLogging();
                Log.LoadLog();
            }
            // When running as worker we need the windows event log
            else if (!Log.UsingEventLog())
            {
                Log.SetupEventLog(Key);
            }

            // load current version
            exePath = Process.GetCurrentProcess().MainModule.FileName; //System.Reflection.Assembly.GetExecutingAssembly().Location;
            FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(exePath);

            Version = fvi.FileMajorPart + "." + fvi.FileMinorPart;
            if (fvi.FileBuildPart != 0)
            {
                Version += "." + fvi.FileBuildPart;
            }
            if (fvi.FilePrivatePart != 0)
            {
                Version += (char)('a' + (fvi.FilePrivatePart - 1));
            }
            appPath = Path.GetDirectoryName(exePath);

            Translate.Load();

            dataPath = appPath + @"\Data";
            if (File.Exists(GetINIPath())) // if an ini exists in the app path, its considdered to be a portable run
            {
                isPortable = true;

                AppLog.Debug("Portable Mode");
            }
            else
            {
                string progData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
                if (progData == null)
                {
                    progData = @"C:\ProgramData";
                }

                dataPath = progData + "\\" + Key;
            }

            AppLog.Debug("Config Directory: {0}", dataPath);

            // execute commandline commands
            if (ExecuteCommands())
            {
                return;
            }

            if (!Directory.Exists(dataPath))
            {
                Directory.CreateDirectory(dataPath);
            }
            if (AdminFunc.IsAdministrator())
            {
                FileOps.SetAnyDirSec(dataPath);
            }

            App.LogInfo("PrivateWin10 Process Started, Mode {0}.", startMode.ToString());

            Session = Process.GetCurrentProcess().SessionId;

            // setup custom assembly resolution for x86/x64 synamic compatybility
            AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolveHandler;

            // is the process starting as a service/worker?
            if (startMode != StartModes.Normal)
            {
                engine = new Priv10Engine();
                if (startMode == StartModes.Service)
                {
                    using (Priv10Service svc = new Priv10Service())
                        ServiceBase.Run(svc);
                }
                else
                {
                    engine.Run();
                }
                return;
            }

            Thread.CurrentThread.Name = "Gui";

            client = new Priv10Client();

            // Encure wie have the required privilegs
            //if (!AdminFunc.IsDebugging())
            {
                AppLog.Debug("Trying to connect to Engine...");
                int conRes = client.Connect(1000);
                if (conRes == 0)
                {
                    if (!AdminFunc.IsAdministrator())
                    {
                        AppLog.Debug("Trying to obtain Administrative proivilegs...");
                        if (AdminFunc.SkipUacRun(App.Key, App.args))
                        {
                            return;
                        }

                        AppLog.Debug("Trying to start with 'runas'...");
                        // Restart program and run as admin
                        string           arguments = "\"" + string.Join("\" \"", args) + "\"";
                        ProcessStartInfo startInfo = new ProcessStartInfo(exePath, arguments);
                        startInfo.UseShellExecute = true;
                        startInfo.Verb            = "runas";
                        try
                        {
                            Process.Start(startInfo);
                            return; // we restarted as admin
                        }
                        catch
                        {
                            //MessageBox.Show(Translate.fmt("msg_admin_rights", mName), mName);
                            //return; // no point in cintinuing without admin rights or an already running engine
                        }
                    }
                    else if (Priv10Service.IsInstalled())
                    {
                        AppLog.Debug("Trying to start service...");
                        if (Priv10Service.Startup())
                        {
                            AppLog.Debug("Trying to connect to service...");

                            if (client.Connect() != 0)
                            {
                                AppLog.Debug("Connected to service...");
                            }
                            else
                            {
                                AppLog.Debug("Failed to connect to service...");
                            }
                        }
                        else
                        {
                            AppLog.Debug("Failed to start service...");
                        }
                    }
                }
                else if (conRes == -1)
                {
                    MessageBox.Show(Translate.fmt("msg_dupliate_session", Title), Title);
                    return; // no point in cintinuing without admin rights or an already running engine
                }
            }

            //

            tweaks = new TweakManager();

            // if we couldn't connect to the engine start it and connect
            if (!client.IsConnected() && AdminFunc.IsAdministrator())
            {
                AppLog.Debug("Starting Engine Thread...");

                engine = new Priv10Engine();

                engine.Start();

                AppLog.Debug("... engine started.");

                client.Connect();
            }

            var app = new App();

            app.InitializeComponent();

            InitLicense();

            MainWnd = new MainWindow();

            TrayIcon         = new TrayIcon();
            TrayIcon.Action += TrayAction;
            TrayIcon.Visible = (GetConfigInt("Startup", "Tray", 0) != 0) || App.TestArg("-autorun");

            if (!App.TestArg("-autorun") || !TrayIcon.Visible)
            {
                MainWnd.Show();
            }

            app.Run();

            TrayIcon.DestroyNotifyicon();

            client.Close();

            tweaks.Store();

            if (engine != null)
            {
                engine.Stop();
            }
        }
Exemplo n.º 26
0
 static private void FirstChanceExceptionHandler(object source, FirstChanceExceptionEventArgs e)
 {
     AppLog.Debug("FirstChanceException event raised in {0}: {1}\r\n{2}", AppDomain.CurrentDomain.FriendlyName, e.Exception.Message, e.Exception.StackTrace);
 }
Exemplo n.º 27
0
        public static void Main(string[] args)
        {
            App.args = args;

            HasConsole = WinConsole.Initialize(TestArg("-console"));

            if (TestArg("-dbg_wait"))
            {
                MessageBox.Show("Waiting for debugger. (press ok when attached)");
            }

            if (TestArg("-dbg_log"))
            {
                AppDomain.CurrentDomain.FirstChanceException += FirstChanceExceptionHandler;
            }

            StartModes startMode = StartModes.Normal; // Normal GUI Mode

            if (TestArg("-svc"))
            {
                startMode = StartModes.Service;
            }
            else if (TestArg("-engine"))
            {
                startMode = StartModes.Engine;
            }

            Log = new AppLog(Key);
            AppLog.ExceptionLogID    = (long)Priv10Logger.EventIDs.Exception;
            AppLog.ExceptionCategory = (short)Priv10Logger.EventFlags.DebugEvents;

            // When running as worker we need the windows event log
            if (!Log.UsingEventLog())
            {
                Log.SetupEventLog(Key);
            }

            // load current version
            exePath = Process.GetCurrentProcess().MainModule.FileName; //System.Reflection.Assembly.GetExecutingAssembly().Location;
            //*FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(exePath);
            //Version = fvi.FileMajorPart + "." + fvi.FileMinorPart;
            //if (fvi.FileBuildPart != 0)
            //    Version += "." + fvi.FileBuildPart;
            //if (fvi.FilePrivatePart != 0)
            //    Version += (char)('a' + (fvi.FilePrivatePart - 1));
            appPath = Path.GetDirectoryName(exePath);

            dataPath = appPath + @"\Data";
            if (File.Exists(GetINIPath())) // if an ini exists in the app path, its considdered to be a portable run
            {
                isPortable = true;

                AppLog.Debug("Portable Mode");
            }
            else
            {
                string progData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
                if (progData == null)
                {
                    progData = @"C:\ProgramData";
                }

                dataPath = progData + "\\" + Key;
            }

            AppLog.Debug("Config Directory: {0}", dataPath);

            if (!Directory.Exists(dataPath))
            {
                Directory.CreateDirectory(dataPath);
            }
            if (AdminFunc.IsAdministrator())
            {
                FileOps.SetAnyDirSec(dataPath);
            }

            Priv10Logger.LogInfo("PrivateWin10 Service Process Started, Mode {0}.", startMode.ToString());

            // setup custom assembly resolution for x86/x64 synamic compatybility
            AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolveHandler;

            // is the process starting as a service/worker?
            if (startMode != StartModes.Normal)
            {
                engine = new Priv10Engine();
                if (startMode == StartModes.Service)
                {
                    using (Priv10Service svc = new Priv10Service())
                        ServiceBase.Run(svc);
                }
                else
                {
                    engine.Run();
                }
                return;
            }
        }
Exemplo n.º 28
0
        static bool ExecuteCommands()
        {
            if (TestArg("-help") || TestArg("/?"))
            {
                string   Message = "Available command line options\r\n";
                string[] Help    =
                {
                    "Available Console Commands:",
                    "========================================",
                    "",
                    "-state\t\t\tShow instalation state",
                    "-uninstall\t\tUninstall PrivateWinTen",
                    "",
                    "-svc_install\t\tInstall priv10 service (invokes -log_install)",
                    "-svc_remove\t\tRemove priv10 service",
                    "",
                    "-log_install\t\tInstall PrivateWin10 Custom Event Log",
                    "-log_remove\t\tRemove PrivateWin10 Custom Event Log",
                    "",
                    "-console\t\tShow console with debug output",
                    "-help\t\t\tShow this help message"
                };
                if (!HasConsole)
                {
                    MessageBox.Show(Message + string.Join("\r\n", Help));
                }
                else
                {
                    Console.WriteLine(Message);
                    for (int j = 0; j < Help.Length; j++)
                    {
                        Console.WriteLine(" " + Help[j]);
                    }
                }
                return(true);
            }


            bool bDone = false;

            if (TestArg("-svc_install"))
            {
                AppLog.Debug("Installing Service...");
                svc.Install(TestArg("-svc_start"));
                bDone = true;
            }

            if (TestArg("-log_install") || TestArg("-svc_install")) // service needs the event log
            {
                AppLog.Debug("Setting up Event Log...");
                Log.SetupEventLog(mAppName);
                bDone = true;
            }

            if (TestArg("-uninstall"))
            {
                AppLog.Debug("Uninstalling PrivateWinTen");
                bDone = true;
            }

            if (TestArg("-svc_remove") || (svc.IsInstalled() && TestArg("-uninstall")))
            {
                AppLog.Debug("Removing Service...");
                svc.Uninstall();
                bDone = true;
            }

            if (TestArg("-log_remove") || (Log.UsingEventLog() && TestArg("-uninstall")))
            {
                AppLog.Debug("Removing Event Log...");
                Log.RemoveEventLog(mAppName);
                bDone = true;
            }

            if (TestArg("-uninstall") && AdminFunc.IsSkipUac(mName))
            {
                AppLog.Debug("Removing UAC Bypass...");
                AdminFunc.SkipUacEnable(mName, false);
                bDone = true;
            }

            if (TestArg("-uninstall") && App.IsAutoStart())
            {
                AppLog.Debug("Removing Autostart...");
                App.AutoStart(false);
                bDone = true;
            }

            if (bDone)
            {
                AppLog.Debug("done");
            }


            if (TestArg("-state"))
            {
                Console.WriteLine();
                Console.WriteLine("Instalation State:");
                Console.WriteLine("========================="); // 25
                Console.Write("Auto Start:\t");
                Console.WriteLine(App.IsAutoStart());
                Console.Write("UAC Bypass:\t");
                Console.WriteLine(AdminFunc.IsSkipUac(mName));
                Console.Write("Event Log:\t");
                Console.WriteLine(Log.UsingEventLog());
                Console.Write("Service:\t");
                Console.WriteLine(svc.IsInstalled());
                Console.WriteLine();
            }

            if (TestArg("-wait"))
            {
                Console.WriteLine();
                for (int i = 10; i >= 0; i--)
                {
                    Console.Write("\r{0}%   ", i);
                    Thread.Sleep(1000);
                }
            }

            return(bDone);
        }
Exemplo n.º 29
0
        public bool Load(XmlNode entryNode)
        {
            foreach (XmlNode node in entryNode.ChildNodes)
            {
                if (node.Name == "ID")
                {
                    ProgramID id = new ProgramID();
                    if (id.Load(node))
                    {
                        // COMPAT: remove service tag
                        ID = FirewallRuleEx.AdjustProgID(id);
                    }
                }
                else if (node.Name == "Description")
                {
                    Description = node.InnerText;
                }
                else if (node.Name == "ReceivedBytes")
                {
                    UInt64.TryParse(node.InnerText, out OldDownload);
                }
                else if (node.Name == "SentBytes")
                {
                    UInt64.TryParse(node.InnerText, out OldUpload);
                }
                else if (node.Name == "FwRules")
                {
                    foreach (XmlNode childNode in node.ChildNodes)
                    {
                        FirewallRuleEx rule = new FirewallRuleEx();
                        rule.ProgID = ID; // todo: remove later, load loads this amyways
                        if (rule.Load(childNode) && !Rules.ContainsKey(rule.guid))
                        {
                            // COMPAT: update entry, old version did not save these data separatly
                            //if (ID.Type != ProgramID.Types.Global && (rule.BinaryPath == null && rule.ServiceTag == null && rule.AppSID == null))
                            //    rule.SetProgID(ID);

                            Rules.Add(rule.guid, rule);
                        }
                        else
                        {
                            Priv10Logger.LogError("Failed to load Firewall RuleEx {0} in {1}", rule.Name != null ? rule.Name : "[un named]", this.Description);
                        }
                    }
                }
                else if (node.Name == "DnsLog")
                {
                    foreach (XmlNode childNode in node.ChildNodes)
                    {
                        DnsEntry Entry = new DnsEntry(ID);
                        if (Entry.Load(childNode) && !DnsLog.ContainsKey(Entry.HostName))
                        {
                            DnsLog.Add(Entry.HostName, Entry);
                        }
                        else
                        {
                            Priv10Logger.LogError("Failed to load DnsLog Entry in {0}", this.Description);
                        }
                    }
                }
                else
                {
                    AppLog.Debug("Unknown Program Value, '{0}':{1}", node.Name, node.InnerText);
                }
            }

            if (Description == null || Description.Substring(0, 2) == "@{")
            {
                Description = GetDescription();
            }

            return(ID != null);
        }
        public DataTable getDatacaseCreation(CSPiHelper Helper)
        {
            string connectionStr = ConfigurationManager.ConnectionStrings["CSPiConnection"].ConnectionString;
            string fadvEntityId  = Convert.ToString(ConfigurationManager.AppSettings["Fadv_EntityId"]);

            AppLog.Debug("Step 2");
            using (OracleConnection con = new OracleConnection())
            {
                con.ConnectionString = connectionStr;
                con.Open();
                AppLog.Debug("Step 3");
                Console.WriteLine("Connected to Oracle Database {0}", con.ServerVersion);
                using (OracleCommand cmd = new OracleCommand())
                {
                    AppLog.Debug("Step 4");
                    string dateNow = DateTime.Today.ToShortDateString();
                    //UAT date time
                    string b = Convert.ToDateTime(dateNow).ToString("MM/dd/yyyy");
                    dateNow = b.Replace("-", "/");

                    string dateTommorow = DateTime.Today.AddDays(1).ToShortDateString();
                    //production date time
                    string c = Convert.ToDateTime(dateTommorow).ToString("MM/dd/yyyy");
                    dateTommorow = c.Replace("-", "/");

                    cmd.Connection  = con;
                    cmd.CommandText = "pkg_cspi_rpt_magik_data_apac.fn_get_clienthr_cases_data";
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add(CreateCursor("return_cursor", ParameterDirection.ReturnValue));
                    cmd.Parameters.Add("pi_entity_id", fadvEntityId);
                    cmd.Parameters.Add("pi_Start_date", dateNow);
                    cmd.Parameters.Add("pi_End_date", dateTommorow);
                    AppLog.Debug("Today :" + dateNow + "Tommorow :" + dateTommorow);
                    cmd.Parameters.Add(CreateCursor("po_case_clienthr_cases_data"));
                    cmd.Parameters.Add(CreateCursor("po_client_field_data"));
                    DataSet ds = new DataSet();
                    AppLog.Debug("Step 5");
                    OracleDataAdapter MyDa = new OracleDataAdapter(cmd);
                    MyDa.Fill(ds);
                    AppLog.Debug("Data fetch sucess from Oracle");
                    CSPiModelRequest obj = new CSPiModelRequest();
                    con.Close();
                    var countT = 0;
                    foreach (DataRow dr1 in ds.Tables[1].Rows)
                    {
                        countT++;
                        Json_Format = "";
                        string CRN = Regex.Replace(dr1["CASE_REF_NUMBER"].ToString(), @"[^\u0000-\u007F]+", string.Empty);
                        // if (CRN != "R233-6112490-WEST-2019") continue;
                        AppLog.Debug("Working On CRNNumber :" + CRN);
                        //   DataTable crnNO = CRNDetails(Regex.Replace(dr1["CASE_REF_NUMBER"].ToString(), @"[^\u0000-\u007F]+", string.Empty));
                        DBParameters param = new DBParameters(TBL_Requests.TableName);
                        param.AddParameter(TBL_Requests.CRN_Number, CRN);
                        List <DBTBL_Requests> TaskDestiny = Helper.DBRead_TBL_Requests(param, false);

                        string birthDateStr   = "";
                        string is_dob         = "0";
                        string crnCreatedDate = null;
                        if (TaskDestiny.Count == 0)
                        {
                            try
                            {
                                country = Regex.Replace(dr1["COUNTRY_NAME"].ToString(), @"[^\u0000-\u007F]+", string.Empty);
                                EmailId = Regex.Replace(dr1["EMAIL_ADDRESS"].ToString(), @"[^\u0000-\u007F]+", string.Empty);
                                DateTime birthDate  = DateTime.MinValue;
                                DateTime CreatedCse = DateTime.MinValue;
                                is_dob = "0";


                                if (!string.IsNullOrEmpty(Regex.Replace(dr1["BIRTH_DT"].ToString(), @"[^\u0000-\u007F]+", string.Empty)))
                                {
                                    // birthDate = DateTime.ParseExact(form.dateOfBirth, "dd/MM/yyyy", null);
                                    string[] s2          = (Regex.Replace(dr1["BIRTH_DT"].ToString(), @"[^\u0000-\u007F]+", string.Empty)).Split(' ');
                                    string   dateOfBirth = s2[0];
                                    birthDate = DateTime.Parse(dateOfBirth);
                                    // birthDate = DateTime.ParseExact(dateOfBirth,"dd/MM/yyyy", null);

                                    is_dob = "1";
                                }

                                if (!string.IsNullOrEmpty(Regex.Replace(dr1["Case Date"].ToString(), @"[^\u0000-\u007F]+", string.Empty)))
                                {
                                    string[] s1       = (Regex.Replace(dr1["Case Date"].ToString(), @"[^\u0000-\u007F]+", string.Empty)).Split(' ');
                                    string   caseDate = s1[0];
                                    // crnCreatedDate = (DateTime.ParseExact(CreatedCseDate, "dd/mm/yyyy", null)).ToString();
                                    // String result = String.Join("-", CreatedCseDate.Split('/').Reverse());
                                    //crnCreatedDate = result+" "+s1[1];
                                    CreatedCse     = DateTime.Parse(caseDate);
                                    crnCreatedDate = CreatedCse.ToString("yyyy-MM-dd");
                                }

                                birthDateStr = birthDate.ToString("yyyy-MM-dd");
                            }
                            catch (Exception ex)
                            {
                            }
                            try
                            {
                                stateId           = "REQ-0002";
                                obj.OperationName = "usp_save_request_data_engine";
                                obj.OperationType = "procedure";
                                //Json_Format = getJsonclientSpecificFields(country, EmailId);
                                DataTable ClientCode = ClientDetails(Regex.Replace(dr1["CLIENT_CODE"].ToString(), @"[^\u0000-\u007F]+", string.Empty));

                                if (ClientCode.Rows.Count > 0)
                                {
                                    DataTable SBUID = SBUDetails((Regex.Replace(dr1["SBU Name"].ToString(), @"[^\u0000-\u007F]+", string.Empty)), ClientCode.Rows[0]["ClientID"].ToString());
                                    if (SBUID.Rows.Count > 0)
                                    {
                                        DataTable PackageID = PackageDetails(Regex.Replace(dr1["PACKAGE_NAME"].ToString(), @"[^\u0000-\u007F]+", string.Empty), SBUID.Rows[0]["SBUID"].ToString(), ClientCode.Rows[0]["ClientID"].ToString());

                                        if (PackageID.Rows.Count > 0 && SBUID.Rows.Count > 0 && ClientCode.Rows.Count > 0)
                                        {
                                            // DataTable PackageIDList = PackckageDetailsNew(PackageID.Rows[0]["PackageID"].ToString());
                                            // if (PackageIDList.Rows.Count > 0)
                                            //  {

                                            Json_Format += "{";
                                            Json_Format += "\"requestoremail\":{\"request_field_id\": \"131\",\"data\":\"" + Regex.Replace(dr1["EMAIL_ADDRESS"].ToString(), @"[^\u0000-\u007F]+", string.Empty) + "\",\"text\": \"" + Regex.Replace(dr1["EMAIL_ADDRESS"].ToString(), @"[^\u0000-\u007F]+", string.Empty) + "\"},";
                                            foreach (DataRow dr2 in ds.Tables[2].Rows)
                                            {
                                                string CSPCCase_ID = Regex.Replace(dr2["CASE_ID"].ToString(), @"[^\u0000-\u007F]+", string.Empty);
                                                string Case_ID     = Regex.Replace(dr1["CASE_ID"].ToString(), @"[^\u0000-\u007F]+", string.Empty);
                                                string Clent_Field = Regex.Replace(dr2["Client_Field"].ToString(), @"[^\u0000-\u007F]+", string.Empty);
                                                string ANSWERS     = Regex.Replace(dr2["ANSWERS"].ToString(), @"[^\u0000-\u007F]+", string.Empty);
                                                if (Case_ID == CSPCCase_ID)
                                                {
                                                    DataTable CLIENTSpeccific = PackageDetailsNew(Clent_Field, ClientCode.Rows[0]["ClientID"].ToString());
                                                    if (Clent_Field != "requestoremail")
                                                    {
                                                        if (CLIENTSpeccific.Rows.Count > 0)
                                                        {
                                                            Json_Format += "\"" + CLIENTSpeccific.Rows[0]["field_json_tag"].ToString() + "\": {\"request_field_id\": \"" + CLIENTSpeccific.Rows[0]["request_field_id"].ToString() + "\",\"data\":\"" + ANSWERS + "\",\"text\": \"" + ANSWERS + "\"},";
                                                        }
                                                    }
                                                }
                                            }
                                            // }
                                            Json_Format  = Json_Format.TrimEnd(',');
                                            Json_Format += "}";

                                            //Json_Format = getJsonclientSpecificFields(country, EmailId,ClientCode.Rows[0]["ClientID"].ToString());
                                            AppLog.Debug("Case Strated for CRN :" + CRN);
                                            obj.ParameterList = new List <OperationParameter>();
                                            obj.ParameterList.Add(new OperationParameter("@p_request_id", "0"));
                                            obj.ParameterList.Add(new OperationParameter("@p_client_id", ClientCode.Rows[0]["ClientID"].ToString()));
                                            obj.ParameterList.Add(new OperationParameter("@p_crn_no", Regex.Replace(dr1["CASE_REF_NUMBER"].ToString(), @"[^\u0000-\u007F]+", string.Empty)));
                                            obj.ParameterList.Add(new OperationParameter("@p_crn_created_date", crnCreatedDate));

                                            obj.ParameterList.Add(new OperationParameter("@p_first_name", Regex.Replace(dr1["FIRST_NAME"].ToString(), @"[^\u0000-\u007F]+", string.Empty)));
                                            obj.ParameterList.Add(new OperationParameter("@p_middle_name", Regex.Replace(dr1["MIDDLE_NAME"].ToString(), @"[^\u0000-\u007F]+", string.Empty)));
                                            obj.ParameterList.Add(new OperationParameter("@p_last_name", Regex.Replace(dr1["LAST_NAME"].ToString(), @"[^\u0000-\u007F]+", string.Empty)));
                                            obj.ParameterList.Add(new OperationParameter("@p_client_ref_no", Regex.Replace(dr1["CLIENT_REFERNCE_NO"].ToString(), @"[^\u0000-\u007F]+", string.Empty)));
                                            obj.ParameterList.Add(new OperationParameter("@p_subject_detail", Regex.Replace(dr1["SUBJECT_DETAIL"].ToString(), @"[^\u0000-\u007F]+", string.Empty)));
                                            obj.ParameterList.Add(new OperationParameter("@p_subject_type", Regex.Replace(dr1["SUBJECT_TYPE"].ToString(), @"[^\u0000-\u007F]+", string.Empty)));
                                            obj.ParameterList.Add(new OperationParameter("@p_is_date_of_birth", is_dob));
                                            obj.ParameterList.Add(new OperationParameter("@p_date_of_birth", birthDateStr));
                                            obj.ParameterList.Add(new OperationParameter("@p_type_of_check", Regex.Replace(dr1["TYPE_OF_CHECK"].ToString(), @"[^\u0000-\u007F]+", string.Empty)));
                                            obj.ParameterList.Add(new OperationParameter("@p_candidateauthorizationletter", Regex.Replace(dr1["CANDIDATE_AUTHORIZATION_LETTER"].ToString(), @"[^\u0000-\u007F]+", string.Empty)));
                                            obj.ParameterList.Add(new OperationParameter("@p_package_type", "Soft Copy"));
                                            obj.ParameterList.Add(new OperationParameter("@p_srt_data", "SRT"));
                                            obj.ParameterList.Add(new OperationParameter("@p_sbu_entitiesid", SBUID.Rows[0]["SBUID"].ToString()));
                                            obj.ParameterList.Add(new OperationParameter("@p_loa_submitted", "Yes"));

                                            obj.ParameterList.Add(new OperationParameter("@p_bvf_submitted", "Yes"));

                                            obj.ParameterList.Add(new OperationParameter("@p_json_data", Json_Format));
                                            obj.ParameterList.Add(new OperationParameter("@p_userid", "165"));

                                            obj.ParameterList.Add(new OperationParameter("@p_comment", "Imported from CSPI"));
                                            obj.ParameterList.Add(new OperationParameter("@p_state_id", stateId));
                                            // obj.ParameterList.Add(new OperationParameter("@p_out_request_id", "", a)); s
                                            obj.ParameterList.Add(new OperationParameter("@p_out_request_id", "p_out_request_id"));

                                            CSPiHelper ctr  = new CSPiHelper(ConfigurationManager.AppSettings["username"], ConfigurationManager.AppSettings["password"]);
                                            DataTable  retv = ctr.ExecuteStoredProcedure(obj).Result;
                                            DataRow    dr   = retv.Rows[0];
                                            try
                                            {
                                                String columnValue = dr[0].ToString();
                                                if (retv.Rows.Count > 0)
                                                {
                                                    // dr = retv.Rows[1];
                                                    // generatedRequestId = dr[0].ToString();
                                                    generatedRequestId = columnValue;
                                                    retv.Dispose();
                                                    AppLog.Debug("Case creted" + CRN + "RequestId" + generatedRequestId);
                                                    //DELETEING EXISTING PACKAGE FROM CASE
                                                    obj.OperationName = "DELETE FROM tbl_request_packages WHERE RequestID=@p_request_id";
                                                    obj.OperationType = "query";
                                                    obj.ParameterList = new List <OperationParameter>();
                                                    obj.ParameterList.Add(new OperationParameter("@p_request_id", generatedRequestId));

                                                    DataTable retv1 = ctr.BotTaskExecuteQuery(obj).Result;

                                                    retv.Dispose();
                                                    //  END - DELETEING EXISTING PACKAGE FROM CASE

                                                    // ADDING NEWLY SELECTED PACKAGE INTO CASE
                                                    obj.OperationName = "INSERT INTO tbl_request_packages (`RequestID`,`PackageID`) VALUES (@p_request_id,@p_package_id)";
                                                    obj.OperationType = "query";
                                                    obj.ParameterList = new List <OperationParameter>();
                                                    obj.ParameterList.Add(new OperationParameter("@p_request_id", generatedRequestId));
                                                    obj.ParameterList.Add(new OperationParameter("@p_package_id", PackageID.Rows[0]["PackageID"].ToString()));
                                                    DataTable retv2 = ctr.BotTaskExecuteQuery(obj).Result;
                                                    //  END - ADDING NEWLY SELECTED PACKAGE INTO CASE
                                                    updateStatus(generatedRequestId);

                                                    JsonCaseCreationData  = "{\"Header\": {\"Type\": \"Request\",\"ServiceID\": \"CaseCreation\",\"MessageId\": \"" + Guid.NewGuid().ToString() + "\",\"MessageDate\": \"" + DateTime.Now.ToShortDateString() + "\",\"RequestID\": \"" + generatedRequestId + "\",";
                                                    JsonCaseCreationData += "\"Module\": \"" + "CaseCreation" + "\",\"RetrySequecne\": \"0\",\"BOTID\": \"\",\"CheckPoint\": \"\"},\"Data\":{\"CaseCreation\":{\"" + "requestId" + "\":  \"" + generatedRequestId + "\", \"" + "clientId" + "\":  \"" + ClientCode.Rows[0]["ClientID"].ToString() + "\",";
                                                    JsonCaseCreationData += "\"" + "crnNo" + "\":  \"" + Regex.Replace(dr1["CASE_REF_NUMBER"].ToString(), @"[^\u0000-\u007F]+", string.Empty) + "\",";
                                                    JsonCaseCreationData += "\"" + "crnCreatedDate" + "\":  \"" + Regex.Replace(dr1["Case Date"].ToString(), @"[^\u0000-\u007F]+", string.Empty) + "\",";
                                                    JsonCaseCreationData += "\"" + "firstName" + "\":  \"" + Regex.Replace(dr1["FIRST_NAME"].ToString(), @"[^\u0000-\u007F]+", string.Empty) + "\",\"" + "middleName" + "\":  \"" + Regex.Replace(dr1["MIDDLE_NAME"].ToString(), @"[^\u0000-\u007F]+", string.Empty) + "\",";
                                                    JsonCaseCreationData += "\"" + "lastName" + "\":  \"" + Regex.Replace(dr1["LAST_NAME"].ToString(), @"[^\u0000-\u007F]+", string.Empty) + "\",\"" + "dateOfBirth" + "\":  \"" + birthDateStr + "\",";
                                                    JsonCaseCreationData += "\"" + "sbuEntitiesId" + "\":  \"" + SBUID.Rows[0]["SBUID"].ToString() + "\",\"" + "clientReferenceNo" + "\":  \"" + Regex.Replace(dr1["CASE_REF_NUMBER"].ToString(), @"[^\u0000-\u007F]+", string.Empty) + "\",\"" + "subjectDetails" + "\":  \"" + Regex.Replace(dr1["SUBJECT_DETAIL"].ToString(), @"[^\u0000-\u007F]+", string.Empty) + "\",";
                                                    JsonCaseCreationData += "\"" + "subjectType" + "\":  \"" + Regex.Replace(dr1["SUBJECT_TYPE"].ToString(), @"[^\u0000-\u007F]+", string.Empty) + "\",\"" + "typeOfCheck" + "\":  \"" + Regex.Replace(dr1["TYPE_OF_CHECK"].ToString(), @"[^\u0000-\u007F]+", string.Empty) + "\",";
                                                    JsonCaseCreationData += "\"" + "authorizationLetter" + "\":  \"" + Regex.Replace(dr1["CANDIDATE_AUTHORIZATION_LETTER"].ToString(), @"[^\u0000-\u007F]+", string.Empty) + "\",\"" + "packageType" + "\":  \"" + "Soft Copy" + "\",";
                                                    JsonCaseCreationData += "\"" + "srtData" + "\":  \"" + "SRT" + "\",\"" + "lOASubmited" + "\":  \"" + "Yes" + "\",\"" + "bVFSubmitted" + "\":  \"" + "Yes" + "\",";
                                                    JsonCaseCreationData += "\"" + "isClientSpecificField" + "\":  \"" + "true" + "\",\"" + "clientSpecificFields" + "\":  " + Json_Format + ",";
                                                    JsonCaseCreationData += "\"" + "comment" + "\":  \"" + null + "\",\"" + "request_status" + "\":  \"" + "Complete" + "\",";
                                                    JsonCaseCreationData += "\"" + "packageList" + "\":[  \"" + PackageID.Rows[0]["PackageID"].ToString() + "\"],\"" + "clientName" + "\":  \"" + Regex.Replace(dr1["Client Name"].ToString(), @"[^\u0000-\u007F]+", string.Empty) + "\",";
                                                    JsonCaseCreationData += "\"" + "sbuEntitiesName" + "\":  \"" + Regex.Replace(dr1["SBU Name"].ToString(), @"[^\u0000-\u007F]+", string.Empty) + "\",\"" + "packageName" + "\":  \"" + Regex.Replace(dr1["PACKAGE_NAME"].ToString(), @"[^\u0000-\u007F]+", string.Empty) + "\"";
                                                    JsonCaseCreationData += "}},\"" + "Status" + "\":{  \"" + "Value" + "\":  \"" + "" + "\",";
                                                    JsonCaseCreationData += "\"" + "Description" + "\":  \"" + "" + "\",\"" + "Details" + "\":  \"" + null + "\"}}";
                                                    //SaveJsonData(generatedRequestId, JsonCaseCreationData, "CaseCreation", "1");
                                                    AppLog.Debug("Case Success CRNNumber :" + CRN);

                                                    //For document fetch
                                                    DataTable CheckPackegeCDEMDE = CheckPackegeCDEOrMDE(generatedRequestId);
                                                    if (CheckPackegeCDEMDE.Rows.Count == 0)
                                                    {
                                                        AppLog.Debug("MDE Case :" + CRN);
                                                        DataTable dtDocument = ds.Tables[0];
                                                        foreach (DataRow objDataRow in dtDocument.Rows)
                                                        {
                                                            string CSPCCase_ID  = Regex.Replace(objDataRow["CASE_ID"].ToString(), @"[^\u0000-\u007F]+", string.Empty);
                                                            string Case_ID      = Regex.Replace(dr1["CASE_ID"].ToString(), @"[^\u0000-\u007F]+", string.Empty);
                                                            string documentPath = objDataRow["DOCUMENT_PATH"].ToString();
                                                            if (CSPCCase_ID == Case_ID)
                                                            {
                                                                document.Add(Regex.Replace(objDataRow["DOCUMENT_PATH"].ToString(), @"[^\u0000-\u007F]+", string.Empty));
                                                            }
                                                        }
                                                        AppLog.Debug("Document Upload started :" + CRN);
                                                        Savedocument(generatedRequestId);
                                                    }
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                            }
                                        }
                                    }
                                    else
                                    {
                                        AppLog.Debug("Not Match CRNNumber :" + CRN);
                                    }
                                }
                            }
                            catch (Exception ex)
                            { }
                        }
                        //  }
                    }
                    return(null);
                }
            }
        }