public static void SaveAsCsv(Ex.Relational.IRelationalSheet sheet, string path) {
            using (var s = new StreamWriter(path, false, Encoding.UTF8)) {
                var indexLine = new StringBuilder("key");
                var nameLine = new StringBuilder("#");
                var typeLine = new StringBuilder("int32");

                var colIndices = new List<int>();
                foreach (var col in sheet.Header.Columns) {
                    indexLine.AppendFormat(",{0}", col.Index);
                    nameLine.AppendFormat(",{0}", col.Name);
                    typeLine.AppendFormat(",{0}", col.ValueType);

                    colIndices.Add(col.Index);
                }

                s.WriteLine(indexLine);
                s.WriteLine(nameLine);
                s.WriteLine(typeLine);

                foreach (var row in sheet.Cast<Ex.IRow>().OrderBy(_ => _.Key)) {
                    s.Write(row.Key);
                    foreach (var col in colIndices) {
                        var v = row.GetRaw(col);

                        if (v == null)
                            s.Write(",");
                        else if (IsUnescaped(v))
                            s.Write(",{0}", v);
                        else
                            s.Write(",\"{0}\"", v.ToString().Replace("\"", "\"\""));
                    }
                    s.WriteLine();
                }
            }
        }
        public static void SaveAsCsv(Ex.Relational.IRelationalSheet sheet, Language language, string path) {
            using (var s = new StreamWriter(path, false, Encoding.UTF8)) {
                var indexLine = new StringBuilder("key");
                var nameLine = new StringBuilder("#");
                var typeLine = new StringBuilder("int32");

                var colIndices = new List<int>();
                foreach (var col in sheet.Header.Columns) {
                    indexLine.AppendFormat(",{0}", col.Index);
                    nameLine.AppendFormat(",{0}", col.Name);
                    typeLine.AppendFormat(",{0}", col.ValueType);

                    colIndices.Add(col.Index);
                }

                s.WriteLine(indexLine);
                s.WriteLine(nameLine);
                s.WriteLine(typeLine);

                foreach (var row in sheet.Cast<Ex.IRow>().OrderBy(_ => _.Key)) {
                    var useRow = row;

                    if (useRow is IXivRow)
                        useRow = ((IXivRow)row).SourceRow;
                    var multiRow = useRow as IMultiRow;

                    s.Write(useRow.Key);
                    foreach (var col in colIndices) {
                        object v;

                        if (language == Language.None || multiRow == null)
                            v = useRow[col];
                        else
                            v = multiRow[col, language];

                        if (v == null)
                            s.Write(",");
                        else if (IsUnescaped(v))
                            s.Write(",{0}", v);
                        else
                            s.Write(",\"{0}\"", v.ToString().Replace("\"", "\"\""));
                    }
                    s.WriteLine();

                    s.Flush();
                }
            }
        }
Exemple #3
0
 private void button1_Click(object sender, EventArgs e)
 {
     if (textBox1.Text != string.Empty)
     {
         int IDAct = 2;
         int IDOper = (int)Math.Pow(10, (double)numericUpDown1.Value);
         if (checkBox1.Checked) IDAct = 3;
         LE = new Ex[(int)numericUpDown2.Value];
         var q = new Random();
         for (int i = 0; i < LE.Count(); i++)
         {
             LE[i] = new Ex(q.Next(IDAct), q.Next(IDOper - 1), q.Next(IDOper - 1));
         }
         var r = (new HelpForm()).ShowDialog();
         if (r != System.Windows.Forms.DialogResult.OK)
             return;
         (new BodyForm()).ShowDialog();
         listBox1.Items.Add(LR[LR.Count - 1]);
     }
     else textBox1.Focus();
 }
Exemple #4
0
        public static void SaveAsCsv(Ex.Relational.IRelationalSheet sheet, string path) {
            using (var s = new StreamWriter(path, false, Encoding.UTF8)) {
                var indexLine = new StringBuilder("key");
                var nameLine = new StringBuilder("#");
                var typeLine = new StringBuilder("int32");

                var colIndices = new List<int>();
                foreach (var col in sheet.Header.Columns) {
                    indexLine.AppendFormat(",{0}", col.Index);
                    nameLine.AppendFormat(",{0}", col.Name);
                    typeLine.AppendFormat(",{0}", col.ValueType);

                    colIndices.Add(col.Index);
                }

                s.WriteLine(indexLine);
                s.WriteLine(nameLine);
                s.WriteLine(typeLine);

                ExdHelper.WriteRows(s, sheet, Ex.Language.None, colIndices, true);
            }
        }
Exemple #5
0
        public static void SaveAsWiki(Ex.Relational.IRelationalSheet sheet, string path)
        {
            IDictionary<int, string> colIndicesToNames = new Dictionary<int, string>();

            using (var s = new StreamWriter(path, false, Encoding.UTF8))
            {
                foreach (var col in sheet.Header.Columns)
                {
                    colIndicesToNames[col.Index] = col.Name;
                }

                foreach (var row in sheet.Cast<Ex.IRow>().OrderBy(_ => _.Key))
                {
                    s.WriteLine("{{ARR Infobox Item");
                    s.WriteLine("|Index={0}", row.Key.ToString());

                    foreach(KeyValuePair<int, string> entry in colIndicesToNames)
                    {
                        var v = row[entry.Key];
                        var cName = entry.Value;
                        var nv = "";

                        if (cName != null && cName.ToString() != "" && v != null && v.ToString() != "") {
                            nv = v.ToString().Replace("\"", "\"\"");
                            nv = Regex.Replace(nv, @"\t|\n|\r", "");
                            s.WriteLine("|{0}=\"{1}\"", cName, nv);
                        }
                    }
                    s.WriteLine("}}");
                    s.WriteLine();
                    s.WriteLine();

                    s.Flush();
                }
            }
        }
 public AetherytePendulum(IXivSheet sheet, Ex.Relational.IRelationalRow sourceRow) : base(sheet, sourceRow) { }
Exemple #7
0
        /// <summary>
        /// Start the service, set the initial values for service settings variables.
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(string[] args)
        {
            /*
             *      Set initial values and get the values indicating the last state
             *      of the service before stop the last time.
             */
            try
            {
                // Get and Set the initial configuration parameters from the configuration file.
                clsSettings.setServiceSettings();
            }
            catch (Exception Ex)
            {
                clsLogProcessing.WriteToEventLog(string.Format("Error durante la ejecución del procedimiento que " +
                                                               "establece los parámetros de configuración inicial en el evento \"OnStart\" del servicio {0}." +
                                                               "Los detalles de este error se muestran a continuación: " + Environment.NewLine + "{1}", this.ServiceName, Ex.ToString()), EventLogEntryType.Error);
            }

            // Create the worker thread. This will invoque the "begingProcessing" function.
            // when we start it.
            // Since we are using a separate thread, the service's main thread will
            // return quickly, telling Windows that the service has started.
            try
            {
                ThreadStart ts = new ThreadStart(begingProcessing);
                workerThread = new Thread(ts);

                // Set the flag to indicate the workerThread is active.
                serviceStarted = true;

                // Start the thread.
                workerThread.Start();
            }
            catch (System.Exception Ex)
            {
                clsLogProcessing.WriteToEventLog(string.Format("Error durante la ejecución del procedimiento que " +
                                                               "establece el hilo (thread) para este servicio, sucedió en el evento \"OnStart\" del servicio {0}." +
                                                               "Los detalles de este error se muestran a continuación: " + Environment.NewLine + "{1}", this.ServiceName, Ex.ToString()), EventLogEntryType.Error);
            }
        }
 public ChocoboActionReset(IXivSheet sheet, Ex.Relational.IRelationalRow sourceRow) : base(sheet, sourceRow) { }
Exemple #9
0
        static int Main(string[] args)
        {
            // remember the working directory at start, as the game path could be relative to this path
            string InitialCurrentDirectory = Environment.CurrentDirectory;

            // set the working directory to the location of the application (so relative paths always work)
            Environment.CurrentDirectory = Path.GetDirectoryName(Application.ExecutablePath);

            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

            // A simple, top-level try-catch block
            try
            {
                if (!ParseCommandLine(ref args))
                {
                    Log("Usage: iPhonePackager <Command> <GameName> [RPCCommand &| Switch]");
                    Log("");
                    Log("Common commands:");
                    Log(" ... RepackageIPA GameName");
                    Log(" ... PackageIPA GameName");
                    Log(" ... PackageApp GameName");
                    Log(" ... Deploy PathToIPA");
                    Log(" ... RepackageFromStage GameName");
                    Log(" ... Devices");
                    Log(" ... Validate");
                    Log(" ... Install");
                    Log("");
                    Log("Configuration switches:");
                    Log("	 -stagedir <path>		  sets the directory to copy staged files from (defaults to none)");
                    Log("	 -project <path>		  path to the project being packaged");
                    Log("	 -provisioning <uuid>	  uuid of the provisioning selected");
                    Log("	 -compress=fast|best|none  packaging compression level (defaults to none)");
                    Log("	 -strip					strip symbols during packaging");
                    Log("	 -config				   game configuration (e.g., Shipping, Development, etc...)");
                    Log("	 -distribution			 packaging for final distribution");
                    Log("	 -codebased				   packaging a c++ code based project");
                    Log("	 -createstub			   packaging stub IPA for later repackaging");
                    Log("	 -mac <MacName>			overrides the machine to use for any Mac operations");
                    Log("	 -arch <Architecture>	  sets the architecture to use (blank for default, -simulator for simulator builds)");
                    Log("	 -device <DeviceID>		sets the device to install the IPA on");
                    Log("");
                    Log("Commands: RPC, Clean");
                    Log("  StageMacFiles, GetIPA, Deploy, Install, Uninstall");
                    Log("");
                    Log("RPC Commands: SetExec, InstallProvision, MakeApp, DeleteIPA, Copy, Kill, Strip, Zip, GenDSYM");
                    Log("");
                    Log("Sample commandlines:");
                    Log(" ... iPhonePackager Deploy UDKGame Release");
                    Log(" ... iPhonePackager RPC SwordGame Shipping MakeApp");
                    return((int)ErrorCodes.Error_Arguments);
                }

                Log("Executing iPhonePackager " + String.Join(" ", args));
                Log("CWD: " + Directory.GetCurrentDirectory());
                Log("Initial Dir: " + InitialCurrentDirectory);
                Log("Env CWD: " + Environment.CurrentDirectory);

                // Ensure shipping configuration for final distributions
                if (Config.bForDistribution && (GameConfiguration != "Shipping"))
                {
                    Program.Warning("Distribution builds should be made in the Shipping configuration!");
                }

                // process the GamePath (if could be ..\Samples\MyDemo\ or ..\Samples\MyDemo\MyDemo.uproject
                GameName = Path.GetFileNameWithoutExtension(GamePath);
                if (GameName.Equals("UE4", StringComparison.InvariantCultureIgnoreCase) || GameName.Equals("Engine", StringComparison.InvariantCultureIgnoreCase))
                {
                    GameName = "UE4Game";
                }

                // setup configuration
                if (!Config.Initialize(InitialCurrentDirectory, GamePath))
                {
                    return((int)ErrorCodes.Error_Arguments);
                }

                switch (MainCommand.ToLowerInvariant())
                {
                case "validate":
                    // check to see if iTunes is installed
                    string dllPath = "";
                    if (Environment.OSVersion.Platform == PlatformID.MacOSX || Environment.OSVersion.Platform == PlatformID.Unix)
                    {
                        ProcessStartInfo StartInfo = new ProcessStartInfo("/usr/bin/xcode-select", "--print-path");
                        StartInfo.UseShellExecute        = false;
                        StartInfo.RedirectStandardOutput = true;
                        StartInfo.CreateNoWindow         = true;

                        using (Process LocalProcess = Process.Start(StartInfo))
                        {
                            StreamReader OutputReader = LocalProcess.StandardOutput;
                            // trim off any extraneous new lines, helpful for those one-line outputs
                            dllPath = OutputReader.ReadToEnd().Trim();
                        }
                    }
                    else
                    {
                        dllPath = Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Apple Inc.\\Apple Mobile Device Support\\Shared", "iTunesMobileDeviceDLL", null) as string;
                        if (String.IsNullOrEmpty(dllPath) || !File.Exists(dllPath))
                        {
                            dllPath = Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Apple Inc.\\Apple Mobile Device Support\\Shared", "MobileDeviceDLL", null) as string;
                            if (String.IsNullOrEmpty(dllPath) || !File.Exists(dllPath))
                            {
                                dllPath = FindWindowsStoreITunesDLL();
                            }
                        }
                    }
                    if (String.IsNullOrEmpty(dllPath) || (!File.Exists(dllPath) && !Directory.Exists(dllPath)))
                    {
                        Error("iTunes Not Found!!", (int)ErrorCodes.Error_SDKNotFound);
                    }
                    else
                    {
                        // validate there is a useable provision and cert
                        MobileProvision  Provision;
                        X509Certificate2 Cert;
                        bool             bHasOverrides;
                        bool             bNameMatch;
                        bool             foundPlist = CodeSignatureBuilder.FindRequiredFiles(out Provision, out Cert, out bHasOverrides, out bNameMatch);
                        if (!foundPlist)
                        {
                            Error("Could not find a valid plist file!!", (int)ErrorCodes.Error_InfoPListNotFound);
                        }
                        else if (!Config.bAutomaticSigning)
                        {
                            if (Provision == null && Cert == null)
                            {
                                Error("No Provision or cert found!!", (int)ErrorCodes.Error_ProvisionAndCertificateNotFound);
                            }
                            else if (Provision == null)
                            {
                                Error("No Provision found!!", (int)ErrorCodes.Error_ProvisionNotFound);
                            }
                            else if (Cert == null)
                            {
                                Error("No Signing Certificate found!!", (int)ErrorCodes.Error_CertificateNotFound);
                            }
                        }
                        else
                        {
                            if (Config.TeamID == null)
                            {
                                Error("No TeamID for automatic signing!!", (int)ErrorCodes.Error_ProvisionNotFound);
                            }
                        }
                    }
                    break;

                case "packageapp":
                    if (CheckArguments())
                    {
                        if (Config.bCreateStubSet)
                        {
                            Error("packageapp cannot be used with the -createstub switch");
                            Program.ReturnCode = (int)ErrorCodes.Error_Arguments;
                        }
                        else
                        {
                            // Create the .app on the Mac
                            CompileTime.CreateApplicationDirOnMac();
                        }
                    }
                    break;

                case "repackagefromstage":
                    if (CheckArguments())
                    {
                        if (Config.bCreateStubSet)
                        {
                            Error("repackagefromstage cannot be used with the -createstub switches");
                            Program.ReturnCode = (int)ErrorCodes.Error_Arguments;
                        }
                        else
                        {
                            bool bProbablyCreatedStub = Utilities.GetEnvironmentVariable("ue.IOSCreateStubIPA", true);
                            if (!bProbablyCreatedStub)
                            {
                                Warning("ue.IOSCreateStubIPA is currently FALSE, which means you may be repackaging with an out of date stub IPA!");
                            }

                            CookTime.RepackageIPAFromStub();
                        }
                    }
                    break;

                // this is the "super fast just move executable" mode for quick programmer iteration
                case "dangerouslyfast":
                    if (CheckArguments())
                    {
                        CompileTime.DangerouslyFastMode();
                    }
                    break;

                case "packageipa":
                    if (CheckArguments())
                    {
                        CompileTime.PackageIPAOnMac();
                    }
                    break;

                case "install":
                    GameName = "";
                    if (Config.bProvision)
                    {
                        ToolsHub.TryInstallingMobileProvision(Config.Provision, false);
                    }
                    if (Config.bCert)
                    {
                        ToolsHub.TryInstallingCertificate_PromptForKey(Config.Certificate, false);
                    }
                    CodeSignatureBuilder.FindCertificates();
                    CodeSignatureBuilder.FindProvisions(Config.OverrideBundleName);
                    break;

                case "certificates":
                {
                    CodeSignatureBuilder.FindCertificates();
                    CodeSignatureBuilder.FindProvisions(Config.OverrideBundleName);
                }
                break;

                case "resigntool":
                    RunInVisualMode(delegate { return(new GraphicalResignTool()); });
                    break;

                case "certrequest":
                    RunInVisualMode(delegate { return(new GenerateSigningRequestDialog()); });
                    break;

                case "gui":
                    RunInVisualMode(delegate { return(ToolsHub.CreateShowingTools()); });
                    break;

                case "devices":
                    ListDevices();
                    break;

                case "signing_match":
                {
                    MobileProvision  Provision;
                    X509Certificate2 Cert;
                    bool             bNameMatch;
                    bool             bHasOverrideFile;
                    if (CodeSignatureBuilder.FindRequiredFiles(out Provision, out Cert, out bHasOverrideFile, out bNameMatch) && Cert != null)
                    {
                        // print out the provision and cert name
                        Program.LogVerbose("CERTIFICATE-{0},PROVISION-{1}", Cert.FriendlyName, Provision.FileName);
                    }
                    else
                    {
                        Program.LogVerbose("No matching Signing Data found!");
                    }
                }
                break;

                default:
                    // Commands by themself default to packaging for the device
                    if (CheckArguments())
                    {
                        ExecuteCommand(MainCommand, MainRPCCommand);
                    }
                    break;
                }
            }
            catch (Exception Ex)
            {
                Error("Application exception: " + Ex.ToString());
                if (ReturnCode == 0)
                {
                    Program.ReturnCode = (int)ErrorCodes.Error_Unknown;
                }
            }
            finally
            {
                if (DeploymentHelper.DeploymentServerProcess != null)
                {
                    DeploymentHelper.DeploymentServerProcess.Close();
                }
            }

            Environment.ExitCode = ReturnCode;
            return(ReturnCode);
        }
        /// <summary>
        /// 發送資料
        /// </summary>
        /// <param name="SendUrl">網址 <para></para> Ex:http://localhost:12345/AA/BB?TEST=123  http://localhost:12345/AA/BB</param>
        /// <param name="PostString">發送資料<para></para> TEST=123</param>
        /// <param name="methodType">發送形式</param>
        /// <param name="contentType">發送類別</param>
        /// <param name="sendEncoding">發送編碼</param>
        /// <param name="sendEncode">發送編碼型態</param>
        /// <param name="Authorization">發送Auth</param>
        /// <param name="encodingType">讀取編碼</param>
        /// <returns></returns>
        public ReturnResult ResponseData(InResponseData InValue)//string SendUrl, string PostString = "", MethodType methodType = MethodType.Get, ContentType contentType = ContentType.applicationxwwwformurlencoded, SendEncoding sendEncoding = SendEncoding.Default, string sendEncode = "utf-8", string Authorization = "", EncodingType encodingType = EncodingType.UTF8)
        {
            ReturnResult ReturnResult = new ReturnResult();

            string methodTypeVal  = "";
            string contentTypeVal = "";

            System.Reflection.FieldInfo fi         = InValue.sendmethodType.GetType().GetField(InValue.sendmethodType.ToString());
            EnumMemberAttribute[]       attributes = (EnumMemberAttribute[])fi.GetCustomAttributes(typeof(EnumMemberAttribute), false);
            if (attributes.Length > 0)
            {
                methodTypeVal = attributes[0].Value;
            }

            fi         = InValue.sendcontentType.GetType().GetField(InValue.sendcontentType.ToString());
            attributes = (EnumMemberAttribute[])fi.GetCustomAttributes(typeof(EnumMemberAttribute), false);
            if (attributes.Length > 0)
            {
                contentTypeVal = attributes[0].Value;
            }

            if (string.IsNullOrEmpty(methodTypeVal) || string.IsNullOrEmpty(contentTypeVal) || string.IsNullOrEmpty(InValue.reponencodingType.ToString()))
            {
                ReturnResult.ReturnMsgNo = -99;
                ReturnResult.ReturnMsg   = "選擇型別錯誤";
                ReturnResult.ErrorCode   = "SRP0001";
                return(ReturnResult);
            }

            if (string.IsNullOrEmpty(InValue.sendUrl))
            {
                ReturnResult.ReturnMsgNo = -98;
                ReturnResult.ReturnMsg   = "發送網址未填";
                ReturnResult.ErrorCode   = "SRP0002";
                return(ReturnResult);
            }

            try
            {
                HttpWebRequest WebRequest = (HttpWebRequest)HttpWebRequest.Create(InValue.sendUrl.Trim());
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
                if (string.IsNullOrEmpty(InValue.sendAuthorization).Equals(false))
                {
                    WebRequest.Headers.Add("Authorization", InValue.sendAuthorization);
                }

                switch (InValue.sendmethodType)
                {
                case SendMethodType.Get: WebRequest.Method = "GET"; break;

                case SendMethodType.Post:
                    byte[] parameterString = null;
                    switch (InValue.sendEncoding)
                    {
                    case SendEncoding.UTF8: parameterString = Encoding.UTF8.GetBytes(InValue.sendPostString);
                        break;

                    case SendEncoding.ASCII: parameterString = Encoding.ASCII.GetBytes(InValue.sendPostString);
                        break;

                    case SendEncoding.GetEncoding: parameterString = Encoding.GetEncoding(InValue.sendEncode).GetBytes(InValue.sendPostString);
                        break;

                    case SendEncoding.Default: parameterString = Encoding.Default.GetBytes(InValue.sendPostString);
                        break;
                    }
                    WebRequest.Method = "POST";
                    switch (InValue.sendcontentType)
                    {
                    case SendContentType.applicationxwwwformurlencoded:
                        WebRequest.ContentType = "application/x-www-form-urlencoded";
                        break;

                    case SendContentType.textxml:
                        WebRequest.ContentType = "text/xml";
                        break;

                    case SendContentType.applicationjson:
                        WebRequest.ContentType = "application/json";
                        break;
                    }
                    WebRequest.ContentLength = parameterString.Length;
                    //等待要求逾時之前的毫秒數。預設值為 100,000 毫秒 (100 秒)。
                    Stream newStream = WebRequest.GetRequestStream();
                    newStream.Write(parameterString, 0, parameterString.Length);
                    newStream.Close();
                    break;
                }

                HttpWebResponse WebResponse = (HttpWebResponse)WebRequest.GetResponse();

                StreamReader sr;
                string       ReturnString = "";
                switch (InValue.reponencodingType)
                {
                case ReponEncodingType.Default:
                    sr           = new StreamReader(WebResponse.GetResponseStream(), Encoding.Default);
                    ReturnString = sr.ReadToEnd();
                    sr.Close();
                    break;

                case ReponEncodingType.UTF8:
                    sr           = new StreamReader(WebResponse.GetResponseStream(), Encoding.UTF8);
                    ReturnString = sr.ReadToEnd();
                    sr.Close();
                    break;
                }
                //Convert the stream to a string

                if (string.IsNullOrEmpty(ReturnString).Equals(false))
                {
                    ReturnString = ReturnString.Trim();
                }

                WebResponse.Close();
                ReturnResult.ReturnMsgNo = 1;
                ReturnResult.ReturnMsg   = ReturnString;
                ReturnResult.ErrorCode   = "SRP0000";
            }
            catch (Exception Ex)
            {
                ReturnResult.ReturnMsgNo = -999;
                ReturnResult.ReturnMsg   = "發生例外錯誤" + Ex.ToString();
                ReturnResult.ErrorCode   = "SRP0003";
            }
            return(ReturnResult);
        }
Exemple #11
0
        private static Ex MakeIntenalException(XDoc exception)
        {
            if((exception == null) || exception.IsEmpty) {
                throw new ArgumentNullException("exception");
            }
            if(!exception.Name.EqualsInvariant("exception")) {
                throw new ArgumentException("argument must have <exception> as root element", "exception");
            }

            // check for presence of an inner exception
            Ex innerException = null;
            XDoc innerExceptionDoc = exception["exception"];
            if(!innerExceptionDoc.IsEmpty) {
                innerException = MakeIntenalException(innerExceptionDoc);
            }

            // rebuild stack trace
            StringBuilder stacktrace = new StringBuilder();
            List<XDoc> frames = exception["stacktrace/frame"].ToList();
            for(int i = 0; i < frames.Count; ++i) {
                XDoc frame = frames[i];
                string method = frame["@method"].AsText;
                string file = frame["@file"].AsText;
                string line = frame["@line"].AsText;
                string message = frame.AsText;
                if(method != null) {
                    stacktrace.Append("   at ");
                    stacktrace.Append(method);
                }
                if(file != null) {
                    stacktrace.Append(" in ");
                    stacktrace.Append(file);
                }
                if(line != null) {
                    stacktrace.Append(":line ");
                    stacktrace.Append(line);
                }
                if(message != null) {
                    stacktrace.Append(message);
                }
                if(i != (frames.Count - 1)) {
                    stacktrace.AppendLine();
                }
            }

            // build exception
            Ex result = new Ex(exception["type"].AsText ?? typeof(Ex).FullName, exception["message"].AsText, stacktrace.ToString(), innerException);
            result.Source = exception["source"].AsText;
            result.HelpLink = exception["helplink"].AsText;
            return result;
        }
        private void btnCreateTool_Click(object sender, RoutedEventArgs e)
        {
            //creating local variables
            int     intSelectedIndex;
            string  strValueForValidation;
            string  strPartNumber;
            string  strDescription;
            string  strToolID;
            decimal decToolCost        = 0;
            string  strErrorMessage    = "";
            bool    blnThereIsAProblem = false;
            bool    blnFatalError      = false;
            int     intRecordsReturned;

            try
            {
                //data validation
                intSelectedIndex = cboSelectWarehouse.SelectedIndex;
                if (intSelectedIndex < 1)
                {
                    blnFatalError    = true;
                    strErrorMessage += "The Warehouse Was Not Selected\n";
                }
                intSelectedIndex = cboSelectToolCategory.SelectedIndex;
                if (intSelectedIndex < 1)
                {
                    blnFatalError    = true;
                    strErrorMessage += "The Tool Category Was Not Selected\n";
                }
                strToolID = txtToolID.Text;
                if (strToolID == "")
                {
                    blnFatalError    = true;
                    strErrorMessage += "Tool ID Was Not Entered\n";
                }
                else
                {
                    TheFindActiveToolByToolIDDataSet = TheToolsClass.FindActiveToolByToolID(strToolID);

                    intRecordsReturned = TheFindActiveToolByToolIDDataSet.FindActiveToolByToolID.Rows.Count;

                    if (intRecordsReturned > 0)
                    {
                        blnFatalError    = true;
                        strErrorMessage += "There is Already an Active Tool With This ID\n";
                    }
                }
                strPartNumber = txtToolPartNumber.Text;
                if (strPartNumber == "")
                {
                    blnFatalError    = true;
                    strErrorMessage += "The Tool Part Number Was Not Added\n";
                }
                strDescription = txtToolDescription.Text;
                if (strDescription == "")
                {
                    blnFatalError    = true;
                    strErrorMessage += "The Tool Description Was Not Added\n";
                }
                strValueForValidation = txtToolCost.Text;
                blnThereIsAProblem    = TheDataValidationClass.VerifyDoubleData(strValueForValidation);
                if (blnThereIsAProblem == true)
                {
                    blnFatalError    = true;
                    strErrorMessage += "The Tool Cost is not Numeric\n";
                }
                else
                {
                    decToolCost = Convert.ToDecimal(strValueForValidation);
                }
                if (blnFatalError == true)
                {
                    TheMessagesClass.ErrorMessage(strErrorMessage);
                    return;
                }

                if (gblnNewToolCategory == true)
                {
                    blnFatalError = TheToolIDClass.InsertNewToolIDForToolType(MainWindow.gintCategoryID, strToolID);

                    if (blnFatalError == true)
                    {
                        throw new Exception();
                    }
                }
                else if (gblnNewToolCategory == false)
                {
                    blnFatalError = TheToolIDClass.UpdateToolID(gintTransactionID, strToolID);

                    if (blnFatalError == true)
                    {
                        throw new Exception();
                    }
                }

                blnFatalError = TheToolsClass.InsertTools(strToolID, MainWindow.gintWarehouseID, strPartNumber, MainWindow.gintCategoryID, strDescription, decToolCost, MainWindow.gintWarehouseID);

                if (blnFatalError == true)
                {
                    throw new Exception();
                }

                ResetControls();

                TheMessagesClass.InformationMessage("The Tool Has Been Created");
            }
            catch (Exception Ex)
            {
                TheEventLogClass.InsertEventLogEntry(DateTime.Now, "New Blue Jay ERP // Add New Tool // Create Tool Button " + Ex.Message);

                TheSendEmailClass.SendEventLog(Ex.ToString());

                TheMessagesClass.ErrorMessage(Ex.ToString());
            }
        }
        private void expEmailReport_Expanded(object sender, RoutedEventArgs e)
        {
            //setting local variables
            int      intCounter;
            int      intNumberOfRecords;
            string   strEmailAddress = "*****@*****.**";
            string   strHeader;
            string   strMessage;
            DateTime datPayDate    = DateTime.Now;
            bool     blnFatalError = false;

            try
            {
                expEmailReport.IsExpanded = false;
                PleaseWait PleaseWait = new PleaseWait();
                PleaseWait.Show();

                intNumberOfRecords = TheEventLogSecurityDataSet.eventlogsecurity.Rows.Count;

                strHeader = "Server File Access Report Prepared on " + Convert.ToString(datPayDate);

                strMessage  = "<h1>Server File Access Report Prepared on " + Convert.ToString(datPayDate) + "</h1>";
                strMessage += "<p>               </p>";
                strMessage += "<p>               </p>";
                strMessage += "<table>";
                strMessage += "<tr>";
                strMessage += "<td><b>Transaction Date</b></td>";
                strMessage += "<td><b>Logon Name</b></td>";
                strMessage += "<td><b>Item Accessed</b></td>";
                strMessage += "</tr>";
                strMessage += "<p>               </p>";

                if (intNumberOfRecords > 0)
                {
                    for (intCounter = 0; intCounter < intNumberOfRecords; intCounter++)
                    {
                        strMessage += "<tr>";
                        strMessage += "<td>" + Convert.ToString(TheEventLogSecurityDataSet.eventlogsecurity[intCounter].TransactionDate) + "</td>";
                        strMessage += "<td>" + TheEventLogSecurityDataSet.eventlogsecurity[intCounter].LogonName + "</td>";
                        strMessage += "<td>" + TheEventLogSecurityDataSet.eventlogsecurity[intCounter].ItemAccessed + "</td>";
                        strMessage += "</tr>";
                        strMessage += "<p>               </p>";
                    }
                }

                strMessage += "</table>";

                blnFatalError = !(TheSendEmailClass.SendEmail(strEmailAddress, strHeader, strMessage));

                if (blnFatalError == true)
                {
                    throw new Exception();
                }

                PleaseWait.Close();
            }
            catch (Exception Ex)
            {
                TheEventLogClass.InsertEventLogEntry(DateTime.Now, "New Blue Jay ERP // Email Server Report // Email Report Expander " + Ex.Message);

                TheMessagesClass.ErrorMessage(Ex.ToString());
            }
        }
        private void ResetControls()
        {
            //setting up the variables
            int      intCounter;
            int      intNumberOfRecords;
            DateTime datTransactionDate;
            string   strLogonName;
            string   strItemAccessed;
            string   strEventNotes;
            bool     blnItemFound = false;
            int      intSecondCounter;

            try
            {
                PleaseWait PleaseWait = new PleaseWait();
                PleaseWait.Show();

                TheEventLogSecurityDataSet.eventlogsecurity.Rows.Clear();

                TheFindServerEventLogSecurityAccessDataSet = TheEventLogClass.FindServerEventLogSecurityAccess();

                intNumberOfRecords  = TheFindServerEventLogSecurityAccessDataSet.FindServerEventLogSecurityAccess.Rows.Count;
                gintNumberOfRecords = 0;

                if (intNumberOfRecords > 0)
                {
                    for (intCounter = 0; intCounter < intNumberOfRecords; intCounter++)
                    {
                        datTransactionDate = TheFindServerEventLogSecurityAccessDataSet.FindServerEventLogSecurityAccess[intCounter].TransactionDate;
                        strLogonName       = "Just Beginging";
                        strItemAccessed    = "Date Goes Here";
                        strEventNotes      = TheFindServerEventLogSecurityAccessDataSet.FindServerEventLogSecurityAccess[intCounter].EventNotes;

                        char[]   delims      = new[] { '\n', '\t', '\r' };
                        string[] strNewItems = strEventNotes.Split(delims, StringSplitOptions.RemoveEmptyEntries);

                        strLogonName    = strNewItems[5];
                        strItemAccessed = strNewItems[16];
                        blnItemFound    = false;

                        datTransactionDate = TheDateSearchClass.RemoveTime(datTransactionDate);

                        if (gintNumberOfRecords > 0)
                        {
                            for (intSecondCounter = 0; intSecondCounter < gintNumberOfRecords; intSecondCounter++)
                            {
                                if (datTransactionDate == TheEventLogSecurityDataSet.eventlogsecurity[intSecondCounter].TransactionDate)
                                {
                                    if (strLogonName == TheEventLogSecurityDataSet.eventlogsecurity[intSecondCounter].LogonName)
                                    {
                                        if (strItemAccessed == TheEventLogSecurityDataSet.eventlogsecurity[intSecondCounter].ItemAccessed)
                                        {
                                            blnItemFound = true;
                                        }
                                    }
                                }
                            }
                        }

                        if (blnItemFound == false)
                        {
                            EventlLogSecurityDataSet.eventlogsecurityRow NewEventRow = TheEventLogSecurityDataSet.eventlogsecurity.NeweventlogsecurityRow();

                            NewEventRow.TransactionDate = datTransactionDate;
                            NewEventRow.LogonName       = strLogonName;
                            NewEventRow.ItemAccessed    = strItemAccessed;

                            TheEventLogSecurityDataSet.eventlogsecurity.Rows.Add(NewEventRow);
                            gintNumberOfRecords++;
                        }
                    }
                }

                dgrEventLog.ItemsSource = TheEventLogSecurityDataSet.eventlogsecurity;

                TheEmployeeDateEntryClass.InsertIntoEmployeeDateEntry(MainWindow.TheVerifyLogonDataSet.VerifyLogon[0].EmployeeID, "New Blue Jay ERP // Server Security Report");

                PleaseWait.Close();
            }
            catch (Exception Ex)
            {
                TheEventLogClass.InsertEventLogEntry(DateTime.Now, "New Blue Jay ERP // Event Log Security // Reset Controls " + Ex.Message);

                TheMessagesClass.ErrorMessage(Ex.ToString());
            }
        }
        private void expImportExcel_Expanded(object sender, RoutedEventArgs e)
        {
            Excel.Application xlDropOrder;
            Excel.Workbook    xlDropBook;
            Excel.Worksheet   xlDropSheet;
            Excel.Range       range;

            int      intColumnRange = 0;
            int      intCounter;
            int      intNumberOfRecords;
            int      intVehicleID = 0;
            DateTime datStartDate = DateTime.Now;
            DateTime datEndDate   = DateTime.Now;
            string   strItemID;
            int      intItemID = 0;
            string   strItem;
            string   strManufacturer;
            string   strModel;
            string   strSerialNumber;
            string   strQuantity;
            int      intQuantity = 0;
            string   strWarehouse;
            string   strAssetNotes;
            bool     blnFatalError = false;
            int      intWarehouseID;

            try
            {
                TheImportITAssetsDataSet.importitassets.Rows.Clear();

                Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
                dlg.FileName   = "Document";             // Default file name
                dlg.DefaultExt = ".xlsx";                // Default file extension
                dlg.Filter     = "Excel (.xlsx)|*.xlsx"; // Filter files by extension

                // Show open file dialog box
                Nullable <bool> result = dlg.ShowDialog();

                // Process open file dialog box results
                if (result == true)
                {
                    // Open document
                    string filename = dlg.FileName;
                }

                PleaseWait PleaseWait = new PleaseWait();
                PleaseWait.Show();

                xlDropOrder = new Excel.Application();
                xlDropBook  = xlDropOrder.Workbooks.Open(dlg.FileName, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
                xlDropSheet = (Excel.Worksheet)xlDropOrder.Worksheets.get_Item(1);

                range = xlDropSheet.UsedRange;
                intNumberOfRecords = range.Rows.Count;
                intColumnRange     = range.Columns.Count;

                for (intCounter = 5; intCounter <= intNumberOfRecords; intCounter++)
                {
                    strItemID = Convert.ToString((range.Cells[intCounter, 1] as Excel.Range).Value2).ToUpper();

                    blnFatalError = TheDataValidationClass.VerifyIntegerData(strItemID);
                    if (blnFatalError == true)
                    {
                        TheMessagesClass.ErrorMessage("The Item ID is not Numeric at Count " + Convert.ToString(intCounter));
                        return;
                    }
                    else
                    {
                        intItemID = Convert.ToInt32(strItemID);
                    }
                    strItem         = Convert.ToString((range.Cells[intCounter, 2] as Excel.Range).Value2).ToUpper();
                    strManufacturer = Convert.ToString((range.Cells[intCounter, 3] as Excel.Range).Value2).ToUpper();
                    strModel        = Convert.ToString((range.Cells[intCounter, 4] as Excel.Range).Value2).ToUpper();
                    strSerialNumber = Convert.ToString((range.Cells[intCounter, 5] as Excel.Range).Value2).ToUpper();
                    strQuantity     = Convert.ToString((range.Cells[intCounter, 6] as Excel.Range).Value2).ToUpper();
                    blnFatalError   = TheDataValidationClass.VerifyIntegerData(strQuantity);
                    if (blnFatalError == true)
                    {
                        TheMessagesClass.ErrorMessage("The Quantity is not Numeric");
                        return;
                    }
                    else
                    {
                        intQuantity = Convert.ToInt32(strQuantity);
                    }
                    strWarehouse = Convert.ToString((range.Cells[intCounter, 7] as Excel.Range).Value2).ToUpper();
                    TheFindWarehouseByWarehouseNameDataSet = TheEmployeeClass.FindWarehouseByWarehouseName(strWarehouse);
                    intWarehouseID = TheFindWarehouseByWarehouseNameDataSet.FindWarehouseByWarehouseName[0].EmployeeID;
                    strAssetNotes  = Convert.ToString((range.Cells[intCounter, 8] as Excel.Range).Value2).ToUpper();

                    ImportITAssetsDataSet.importitassetsRow NewItAsset = TheImportITAssetsDataSet.importitassets.NewimportitassetsRow();

                    NewItAsset.Item         = strItem;
                    NewItAsset.ItemID       = intItemID;
                    NewItAsset.Location     = strWarehouse;
                    NewItAsset.Manufacturer = strManufacturer;
                    NewItAsset.Model        = strModel;
                    NewItAsset.Notes        = strAssetNotes;
                    NewItAsset.Quantity     = intQuantity;
                    NewItAsset.SerialNumber = strSerialNumber;
                    NewItAsset.WarehouseID  = intWarehouseID;

                    TheImportITAssetsDataSet.importitassets.Rows.Add(NewItAsset);
                }

                dgrAssets.ItemsSource = TheImportITAssetsDataSet.importitassets;


                PleaseWait.Close();
            }
            catch (Exception Ex)
            {
                TheEventLogClass.InsertEventLogEntry(DateTime.Now, "New Blue Jay ERP // Import IT Assets // Import Excel  " + Ex.Message);

                TheMessagesClass.ErrorMessage(Ex.ToString());
            }
        }
Exemple #16
0
        //method to add products

        private void btn_addPro_Click(object sender, EventArgs e)
        {
            int totalbill = 0;

            try
            {
                if (id_box.Text != "" && email_box.Text != "" && phone_box.Text != "" && pro_list.CheckedIndices.Count > 0)
                {
                    using (SqlConnection con = new SqlConnection(cs))
                    {
                        foreach (object item in pro_list.CheckedItems)
                        {
                            DataSet        ds    = new DataSet();
                            string         query = "select * from Cart where 0=1"; //this will load column names
                            SqlDataAdapter adp   = new SqlDataAdapter(query, con);
                            adp.Fill(ds, "cart");

                            DataRow dr = ds.Tables["cart"].NewRow();

                            string product     = "";
                            int    price       = 0;
                            int    quantity    = 1;
                            int    totalamount = 0;

                            //product contain string i.e only product name i.e string before Rs.
                            product = item.ToString().Substring(0, item.ToString().IndexOf("Rs."));

                            //price contain string after the product name
                            price = Int32.Parse(item.ToString().Substring(product.Length + 3)) * quantity;

                            quantity    = Int32.Parse(Interaction.InputBox("Enter Quantity of " + product + " ", "Quantity", "1", -1, -1));
                            totalamount = price * quantity;

                            dr["product"]     = product;
                            dr["price"]       = price;
                            dr["quantity"]    = quantity;
                            dr["id"]          = id_box.Text.ToString();
                            dr["phone"]       = phone_box.Text.ToString();
                            dr["email"]       = email_box.Text.ToString();
                            dr["totalAmount"] = totalamount;

                            ds.Tables["Cart"].Rows.Add(dr);
                            new SqlCommandBuilder(adp);
                            adp.Update(ds, "Cart");
                            totalbill += totalamount;
                        }
                        MessageBox.Show("Record Inserted !");

                        //clear fields method call
                        clear();
                    }
                }
                else
                {
                    MessageBox.Show("Please Fill Form Correctly !");
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.ToString());
            }
        }
        private void expProcessImport_Expanded(object sender, RoutedEventArgs e)
        {
            int     intCounter;
            int     intNumberOfRecords;
            bool    blnFatalError = false;
            int     intItemID;
            string  strItem;
            string  strManufacturer;
            string  strModel;
            string  strSerialNumber;
            int     intQuantity;
            decimal decValue    = 0;
            string  strUpgrades = "NONE";
            int     intWarehouseID;
            int     intRecordsReturned;

            try
            {
                intNumberOfRecords = TheImportITAssetsDataSet.importitassets.Rows.Count;

                for (intCounter = 0; intCounter < intNumberOfRecords; intCounter++)
                {
                    intItemID       = TheImportITAssetsDataSet.importitassets[intCounter].ItemID;
                    strItem         = TheImportITAssetsDataSet.importitassets[intCounter].Item;
                    strManufacturer = TheImportITAssetsDataSet.importitassets[intCounter].Manufacturer;
                    strModel        = TheImportITAssetsDataSet.importitassets[intCounter].Model;
                    strSerialNumber = TheImportITAssetsDataSet.importitassets[intCounter].SerialNumber;
                    intQuantity     = TheImportITAssetsDataSet.importitassets[intCounter].Quantity;
                    intWarehouseID  = TheImportITAssetsDataSet.importitassets[intCounter].WarehouseID;

                    if (intItemID > 1000)
                    {
                        blnFatalError = TheITAssetsClass.UpdateITAssetLocation(intItemID, intWarehouseID);

                        if (blnFatalError == true)
                        {
                            throw new Exception();
                        }
                    }
                    else
                    {
                        TheFindITAssetBySerialNumberDataSet = TheITAssetsClass.FindITAssetBySerialNumber(strSerialNumber);

                        intRecordsReturned = TheFindITAssetByItemIDDataSet.FindITAssetByItemID.Rows.Count;

                        if (intRecordsReturned > 0)
                        {
                            blnFatalError = TheITAssetsClass.UpdateITAssetLocation(intItemID, intWarehouseID);

                            if (blnFatalError == true)
                            {
                                throw new Exception();
                            }
                        }
                        else if (intRecordsReturned < 1)
                        {
                            blnFatalError = TheITAssetsClass.InsertITAsset(strItem, strManufacturer, strModel, strSerialNumber, intQuantity, decValue, strUpgrades, intWarehouseID);

                            if (blnFatalError == true)
                            {
                                throw new Exception();
                            }
                        }
                    }
                }

                TheMessagesClass.InformationMessage("The Records have been Updated");

                ResetControls();
            }
            catch (Exception Ex)
            {
                TheEventLogClass.InsertEventLogEntry(DateTime.Now, "New Blue Jay ERP // Import IT Assets // Process Import Expander " + Ex.Message);

                TheMessagesClass.ErrorMessage(Ex.ToString());
            }
        }
Exemple #18
0
    private static void DiffCookedContent(ProjectParams Params)
    {
        List <TargetPlatformDescriptor> PlatformsToCook = Params.ClientTargetPlatforms;
        string ProjectPath = Params.RawProjectPath.FullName;

        var CookedSandboxesPath = CombinePaths(GetDirectoryName(ProjectPath), "Saved", "Cooked");

        for (int CookPlatformIndex = 0; CookPlatformIndex < PlatformsToCook.Count; ++CookPlatformIndex)
        {
            // temporary directory to save the pak file to (pak file is usually not local and on network drive)
            var TemporaryPakPath = CombinePaths(GetDirectoryName(ProjectPath), "Saved", "Temp", "LocalPKG");
            // extracted files from pak file
            var TemporaryFilesPath = CombinePaths(GetDirectoryName(ProjectPath), "Saved", "Temp", "LocalFiles");



            try
            {
                Directory.Delete(TemporaryPakPath, true);
            }
            catch (Exception Ex)
            {
                if (!(Ex is System.IO.DirectoryNotFoundException))
                {
                    Log("Failed deleting temporary directories " + TemporaryPakPath + " continuing. " + Ex.GetType().ToString());
                }
            }
            try
            {
                Directory.Delete(TemporaryFilesPath, true);
            }
            catch (Exception Ex)
            {
                if (!(Ex is System.IO.DirectoryNotFoundException))
                {
                    Log("Failed deleting temporary directories " + TemporaryFilesPath + " continuing. " + Ex.GetType().ToString());
                }
            }

            try
            {
                Directory.CreateDirectory(TemporaryPakPath);
                Directory.CreateDirectory(TemporaryFilesPath);

                Platform CurrentPlatform = Platform.Platforms[PlatformsToCook[CookPlatformIndex]];

                string SourceCookedContentPath = Params.DiffCookedContentPath;

                List <string> PakFiles = new List <string>();

                string CookPlatformString = CurrentPlatform.GetCookPlatform(false, Params.Client);

                if (Path.HasExtension(SourceCookedContentPath) && (!SourceCookedContentPath.EndsWith(".pak")))
                {
                    // must be a per platform pkg file try this
                    CurrentPlatform.ExtractPackage(Params, Params.DiffCookedContentPath, TemporaryPakPath);

                    // find the pak file
                    PakFiles.AddRange(Directory.EnumerateFiles(TemporaryPakPath, Params.ShortProjectName + "*.pak", SearchOption.AllDirectories));
                    PakFiles.AddRange(Directory.EnumerateFiles(TemporaryPakPath, "pakchunk*.pak", SearchOption.AllDirectories));
                }
                else if (!Path.HasExtension(SourceCookedContentPath))
                {
                    // try find the pak or pkg file
                    string SourceCookedContentPlatformPath = CombinePaths(SourceCookedContentPath, CookPlatformString);

                    foreach (var PakName in Directory.EnumerateFiles(SourceCookedContentPlatformPath, Params.ShortProjectName + "*.pak", SearchOption.AllDirectories))
                    {
                        string TemporaryPakFilename = CombinePaths(TemporaryPakPath, Path.GetFileName(PakName));
                        File.Copy(PakName, TemporaryPakFilename);
                        PakFiles.Add(TemporaryPakFilename);
                    }

                    foreach (var PakName in Directory.EnumerateFiles(SourceCookedContentPlatformPath, "pakchunk*.pak", SearchOption.AllDirectories))
                    {
                        string TemporaryPakFilename = CombinePaths(TemporaryPakPath, Path.GetFileName(PakName));
                        File.Copy(PakName, TemporaryPakFilename);
                        PakFiles.Add(TemporaryPakFilename);
                    }

                    if (PakFiles.Count <= 0)
                    {
                        Log("No Pak files found in " + SourceCookedContentPlatformPath + " :(");
                    }
                }
                else if (SourceCookedContentPath.EndsWith(".pak"))
                {
                    string TemporaryPakFilename = CombinePaths(TemporaryPakPath, Path.GetFileName(SourceCookedContentPath));
                    File.Copy(SourceCookedContentPath, TemporaryPakFilename);
                    PakFiles.Add(TemporaryPakFilename);
                }


                string FullCookPath = CombinePaths(CookedSandboxesPath, CookPlatformString);

                var UnrealPakExe = CombinePaths(CmdEnv.LocalRoot, "Engine/Binaries/Win64/UnrealPak.exe");


                foreach (var Name in PakFiles)
                {
                    Log("Extracting pak " + Name + " for comparision to location " + TemporaryFilesPath);

                    string UnrealPakParams = Name + " -Extract " + " " + TemporaryFilesPath;
                    try
                    {
                        RunAndLog(CmdEnv, UnrealPakExe, UnrealPakParams, Options: ERunOptions.Default | ERunOptions.UTF8Output | ERunOptions.LoggingOfRunDuration);
                    }
                    catch (Exception Ex)
                    {
                        Log("Pak failed to extract because of " + Ex.GetType().ToString());
                    }
                }

                const string RootFailedContentDirectory = "\\\\epicgames.net\\root\\Developers\\Daniel.Lamb";

                string FailedContentDirectory = CombinePaths(RootFailedContentDirectory, CommandUtils.P4Env.Branch + CommandUtils.P4Env.Changelist.ToString(), Params.ShortProjectName, CookPlatformString);

                Directory.CreateDirectory(FailedContentDirectory);

                // diff the content
                List <FileInfo> FileReport = new List <FileInfo>();

                List <string> AllFiles = Directory.EnumerateFiles(FullCookPath, "*.uasset", System.IO.SearchOption.AllDirectories).ToList();
                AllFiles.AddRange(Directory.EnumerateFiles(FullCookPath, "*.umap", System.IO.SearchOption.AllDirectories).ToList());
                foreach (string SourceFilename in AllFiles)
                {
                    // Filename.StartsWith( CookedSandboxesPath );
                    string RelativeFilename = SourceFilename.Remove(0, FullCookPath.Length);

                    string DestFilename = TemporaryFilesPath + RelativeFilename;

                    Log("Comparing file " + RelativeFilename);

                    byte[] SourceFile = null;
                    try
                    {
                        SourceFile = File.ReadAllBytes(SourceFilename);
                    }
                    catch (Exception)
                    {
                        Log("Diff cooked content failed to load file " + SourceFilename);
                    }

                    byte[] DestFile = null;
                    try
                    {
                        DestFile = File.ReadAllBytes(DestFilename);
                    }
                    catch (Exception)
                    {
                        Log("Diff cooked content failed to load file " + DestFilename);
                    }

                    if (SourceFile == null || DestFile == null)
                    {
                        Log("Diff cooked content failed on file " + SourceFilename + " when comparing against " + DestFilename + " " + (SourceFile == null?SourceFilename:DestFilename) + " file is missing");
                    }
                    else if (SourceFile.LongLength == DestFile.LongLength)
                    {
                        /*long FirstByteFailed = -1;
                         * long BytesFailed = 0;*/

                        FileInfo DiffFileInfo = new FileInfo(SourceFilename);
                        DiffFileInfo.File1Size = DiffFileInfo.File2Size = SourceFile.LongLength;

                        bool bFailedDiff = false;
                        for (long Index = 0; Index < SourceFile.LongLength; ++Index)
                        {
                            if (SourceFile[Index] != DestFile[Index])
                            {
                                if (DiffFileInfo.FirstByteFailed == -1)
                                {
                                    DiffFileInfo.FirstByteFailed = Index;
                                }
                                DiffFileInfo.BytesMismatch += 1;

                                if (bFailedDiff == false)
                                {
                                    bFailedDiff = true;

                                    Log("Diff cooked content failed on file " + SourceFilename + " when comparing against " + DestFilename + " at offset " + Index.ToString());
                                    string SavedSourceFilename = CombinePaths(FailedContentDirectory, Path.GetFileName(SourceFilename) + "Source");
                                    string SavedDestFilename   = CombinePaths(FailedContentDirectory, Path.GetFileName(DestFilename) + "Dest");

                                    Log("Creating directory " + Path.GetDirectoryName(SavedSourceFilename));

                                    try
                                    {
                                        Directory.CreateDirectory(Path.GetDirectoryName(SavedSourceFilename));
                                    }
                                    catch (Exception E)
                                    {
                                        Log("Failed to create directory " + Path.GetDirectoryName(SavedSourceFilename) + " Exception " + E.ToString());
                                    }
                                    Log("Creating directory " + Path.GetDirectoryName(SavedDestFilename));
                                    try
                                    {
                                        Directory.CreateDirectory(Path.GetDirectoryName(SavedDestFilename));
                                    }
                                    catch (Exception E)
                                    {
                                        Log("Failed to create directory " + Path.GetDirectoryName(SavedDestFilename) + " Exception " + E.ToString());
                                    }
                                    File.Copy(SourceFilename, SavedSourceFilename, true);
                                    File.Copy(DestFilename, SavedDestFilename, true);
                                    Log("Content temporarily saved to " + SavedSourceFilename + " and " + SavedDestFilename + " at offset " + Index.ToString());
                                }
                                // break;
                            }
                        }
                        if (!bFailedDiff)
                        {
                            Log("Content matches for " + SourceFilename + " and " + DestFilename);
                        }
                        else
                        {
                            FileReport.Add(DiffFileInfo);
                        }
                    }
                    else
                    {
                        Log("Diff cooked content failed on file " + SourceFilename + " when comparing against " + DestFilename + " files are different sizes " + SourceFile.LongLength.ToString() + " " + DestFile.LongLength.ToString());

                        FileInfo DiffFileInfo = new FileInfo(SourceFilename);

                        DiffFileInfo.File1Size = SourceFile.LongLength;
                        DiffFileInfo.File2Size = DestFile.LongLength;

                        FileReport.Add(DiffFileInfo);
                    }
                }

                Log("Mismatching files:");
                foreach (var Report in FileReport)
                {
                    if (Report.FirstByteFailed == -1)
                    {
                        Log("File " + Report.Filename + " size mismatch: " + Report.File1Size + " VS " + Report.File2Size);
                    }
                    else
                    {
                        Log("File " + Report.Filename + " bytes mismatch: " + Report.BytesMismatch + " first byte failed at: " + Report.FirstByteFailed + " file size: " + Report.File1Size);
                    }
                }
            }
            catch (Exception Ex)
            {
                Log("Exception " + Ex.ToString());
                continue;
            }
        }
    }
        private void MitPrint_Click(object sender, RoutedEventArgs e)
        {
            //this will print the report
            int intCurrentRow = 0;
            int intCounter;
            int intColumns;
            int intNumberOfRecords;


            try
            {
                PrintDialog pdProblemReport = new PrintDialog();


                if (pdProblemReport.ShowDialog().Value)
                {
                    FlowDocument fdProjectReport = new FlowDocument();
                    Thickness    thickness       = new Thickness(50, 50, 50, 50);
                    fdProjectReport.PagePadding = thickness;

                    pdProblemReport.PrintTicket.PageOrientation = System.Printing.PageOrientation.Landscape;

                    //Set Up Table Columns
                    Table ProjectReportTable = new Table();
                    fdProjectReport.Blocks.Add(ProjectReportTable);
                    ProjectReportTable.CellSpacing = 0;
                    intColumns = TheFindVehicleInvoicesByDateRangeDataSet.FindVehicleInvoicesByDateRange.Columns.Count;
                    fdProjectReport.ColumnWidth           = 10;
                    fdProjectReport.IsColumnWidthFlexible = false;


                    for (int intColumnCounter = 0; intColumnCounter < intColumns; intColumnCounter++)
                    {
                        ProjectReportTable.Columns.Add(new TableColumn());
                    }
                    ProjectReportTable.RowGroups.Add(new TableRowGroup());

                    //Title row
                    ProjectReportTable.RowGroups[0].Rows.Add(new TableRow());
                    TableRow newTableRow = ProjectReportTable.RowGroups[0].Rows[intCurrentRow];
                    newTableRow.Cells.Add(new TableCell(new Paragraph(new Run("Vehicle Invoice Report"))));
                    newTableRow.Cells[0].FontSize      = 25;
                    newTableRow.Cells[0].FontFamily    = new FontFamily("Times New Roman");
                    newTableRow.Cells[0].ColumnSpan    = intColumns;
                    newTableRow.Cells[0].TextAlignment = TextAlignment.Center;
                    newTableRow.Cells[0].Padding       = new Thickness(0, 0, 0, 10);

                    ProjectReportTable.RowGroups[0].Rows.Add(new TableRow());
                    intCurrentRow++;
                    newTableRow = ProjectReportTable.RowGroups[0].Rows[intCurrentRow];
                    newTableRow.Cells.Add(new TableCell(new Paragraph(new Run("Date Range " + Convert.ToString(MainWindow.gdatStartDate) + " Thru " + Convert.ToString(MainWindow.gdatEndDate)))));
                    newTableRow.Cells[0].FontSize      = 18;
                    newTableRow.Cells[0].FontFamily    = new FontFamily("Times New Roman");
                    newTableRow.Cells[0].ColumnSpan    = intColumns;
                    newTableRow.Cells[0].TextAlignment = TextAlignment.Center;
                    newTableRow.Cells[0].Padding       = new Thickness(0, 0, 0, 10);

                    ProjectReportTable.RowGroups[0].Rows.Add(new TableRow());
                    intCurrentRow++;
                    newTableRow = ProjectReportTable.RowGroups[0].Rows[intCurrentRow];
                    newTableRow.Cells.Add(new TableCell(new Paragraph(new Run("Total Charge Of  " + Convert.ToString(gdecInvoiceTotal)))));
                    newTableRow.Cells[0].FontSize      = 18;
                    newTableRow.Cells[0].FontFamily    = new FontFamily("Times New Roman");
                    newTableRow.Cells[0].ColumnSpan    = intColumns;
                    newTableRow.Cells[0].TextAlignment = TextAlignment.Center;
                    newTableRow.Cells[0].Padding       = new Thickness(0, 0, 0, 10);

                    //Header Row
                    ProjectReportTable.RowGroups[0].Rows.Add(new TableRow());
                    intCurrentRow++;
                    newTableRow = ProjectReportTable.RowGroups[0].Rows[intCurrentRow];
                    newTableRow.Cells.Add(new TableCell(new Paragraph(new Run("Vehicle Number"))));
                    newTableRow.Cells.Add(new TableCell(new Paragraph(new Run("Invoice Number"))));
                    newTableRow.Cells.Add(new TableCell(new Paragraph(new Run("Date"))));
                    newTableRow.Cells.Add(new TableCell(new Paragraph(new Run("Vendor"))));
                    newTableRow.Cells.Add(new TableCell(new Paragraph(new Run("Resolution"))));
                    newTableRow.Cells.Add(new TableCell(new Paragraph(new Run("Invoice Amount"))));

                    //Format Header Row
                    for (intCounter = 0; intCounter < intColumns; intCounter++)
                    {
                        newTableRow.Cells[intCounter].FontSize        = 16;
                        newTableRow.Cells[intCounter].FontFamily      = new FontFamily("Times New Roman");
                        newTableRow.Cells[intCounter].BorderBrush     = Brushes.Black;
                        newTableRow.Cells[intCounter].TextAlignment   = TextAlignment.Center;
                        newTableRow.Cells[intCounter].BorderThickness = new Thickness();
                    }

                    intNumberOfRecords = TheFindVehicleInvoicesByDateRangeDataSet.FindVehicleInvoicesByDateRange.Rows.Count;

                    //Data, Format Data

                    for (int intReportRowCounter = 0; intReportRowCounter < intNumberOfRecords; intReportRowCounter++)
                    {
                        ProjectReportTable.RowGroups[0].Rows.Add(new TableRow());
                        intCurrentRow++;
                        newTableRow = ProjectReportTable.RowGroups[0].Rows[intCurrentRow];
                        for (int intColumnCounter = 0; intColumnCounter < intColumns; intColumnCounter++)
                        {
                            newTableRow.Cells.Add(new TableCell(new Paragraph(new Run(TheFindVehicleInvoicesByDateRangeDataSet.FindVehicleInvoicesByDateRange[intReportRowCounter][intColumnCounter].ToString()))));

                            newTableRow.Cells[intColumnCounter].FontSize = 12;
                            newTableRow.Cells[0].FontFamily = new FontFamily("Times New Roman");
                            newTableRow.Cells[intColumnCounter].BorderBrush     = Brushes.LightSteelBlue;
                            newTableRow.Cells[intColumnCounter].BorderThickness = new Thickness(0, 0, 0, 1);
                            newTableRow.Cells[intColumnCounter].TextAlignment   = TextAlignment.Center;
                        }
                    }

                    //Set up page and print
                    fdProjectReport.ColumnWidth = pdProblemReport.PrintableAreaWidth;
                    fdProjectReport.PageHeight  = pdProblemReport.PrintableAreaHeight;
                    fdProjectReport.PageWidth   = pdProblemReport.PrintableAreaWidth;
                    pdProblemReport.PrintDocument(((IDocumentPaginatorSource)fdProjectReport).DocumentPaginator, "Vehicle Invoice Report");
                    intCurrentRow = 0;
                }
            }
            catch (Exception Ex)
            {
                TheMessagesClass.ErrorMessage(Ex.ToString());

                TheEventLogClass.InsertEventLogEntry(DateTime.Now, "Blue Jay ERP // Vehicle Invoices By Date Range // Print Menu Item " + Ex.Message);
            }
        }
 public DesynthSkillReset(IXivSheet sheet, Ex.Relational.IRelationalRow sourceRow) : base(sheet, sourceRow) { }
Exemple #21
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // Create safe error messages.
            string generalErrorMsg = "Ops, ocorreu um erro no sistema. Favor tente novamente. " +
                                     "Se persistir, favor contatar o suporte técnico.";
            string httpErrorMsg      = "Ops, ocorreu um problema. Tente novamente.";
            string unhandledErrorMsg = "Ops, ocorreu um erro no sistema. Contate o suporte técnico.";

            // Display safe error message.
            FriendlyErrorMsg.Text = generalErrorMsg;

            // Determine where error was handled.
            string errorHandler = Request.QueryString["handler"];

            if (errorHandler == null)
            {
                errorHandler = "Error Page";
            }

            // Get the last error from the server.
            Exception Ex = Server.GetLastError();

            // Get the error number passed as a querystring value.
            string errorMsg = Request.QueryString["msg"];

            if (errorMsg == "404")
            {
                Ex = new HttpException(404, httpErrorMsg, Ex);
                FriendlyErrorMsg.Text = Ex.Message;
            }

            // If the exception no longer exists, create a generic exception.
            if (Ex == null)
            {
                Ex = new Exception(unhandledErrorMsg);
            }

            // Show error details to only you (developer). LOCAL ACCESS ONLY.
            if (Request.IsLocal)
            {
                // Detailed Error Message.
                ErrorDetailedMsg.Text = Ex.Message;

                // Show where the error was handled.
                ErrorHandler.Text = errorHandler;

                // Show local access details.
                DetailedErrorPanel.Visible = true;

                if (Ex.InnerException != null)
                {
                    InnerMessage.Text = Ex.GetType().ToString() + "<br/>" +
                                        Ex.InnerException.Message;
                    //InnerTrace.Text = Ex.InnerException.StackTrace;
                }
                else
                {
                    InnerMessage.Text = Ex.GetType().ToString();
                    if (Ex.StackTrace != null)
                    {
                        //InnerTrace.Text = Ex.StackTrace.ToString().TrimStart();
                    }
                }
            }

            LogException.InsereLogBd(Ex);

            Server.ClearError();
        }
 public ChocoboLevelCapIncrease(IXivSheet sheet, Ex.Relational.IRelationalRow sourceRow) : base(sheet, sourceRow) { }
Exemple #23
0
        private void expImportExcel_Expanded(object sender, RoutedEventArgs e)
        {
            Excel.Application xlDropOrder;
            Excel.Workbook    xlDropBook;
            Excel.Worksheet   xlDropSheet;
            Excel.Range       range;

            int    intColumnRange = 0;
            int    intCounter;
            int    intNumberOfRecords;
            string strPartNumber;
            string strJDEPartNumber;
            int    intPartID = 0;
            string strPartDescription;
            int    intQuantity = 0;
            int    intRecordsReturned;
            bool   blnItemFound;
            bool   blnItemInTable;
            bool   blnFatalError = false;
            int    intSecondCounter;
            string strOldPartNumber = "";

            try
            {
                expImportExcel.IsExpanded = false;

                blnFatalError = TheEmployeeDataEntryClass.InsertIntoEmployeeDateEntry(MainWindow.TheVerifyLogonDataSet.VerifyLogon[0].EmployeeID, "New Blue Jay ERP // Create Spectrum Report // Import Spectrum Count");

                if (blnFatalError == true)
                {
                    throw new Exception();
                }

                if (cboSelectWarehouse.SelectedIndex < 1)
                {
                    TheMessagesClass.ErrorMessage("The Warehouse Was Not Selected");
                    return;
                }

                TheSpectrumCountDataSet.spectrumcount.Rows.Clear();

                Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
                dlg.FileName   = "Document";             // Default file name
                dlg.DefaultExt = ".xlsx";                // Default file extension
                dlg.Filter     = "Excel (.xlsx)|*.xlsx"; // Filter files by extension

                // Show open file dialog box
                Nullable <bool> result = dlg.ShowDialog();

                // Process open file dialog box results
                if (result == true)
                {
                    // Open document
                    string filename = dlg.FileName;
                }

                PleaseWait PleaseWait = new PleaseWait();
                PleaseWait.Show();

                xlDropOrder = new Excel.Application();
                xlDropBook  = xlDropOrder.Workbooks.Open(dlg.FileName, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
                xlDropSheet = (Excel.Worksheet)xlDropOrder.Worksheets.get_Item(1);

                range = xlDropSheet.UsedRange;
                intNumberOfRecords  = range.Rows.Count;
                intColumnRange      = range.Columns.Count;
                gintCounter         = 0;
                gintNumberOfRecords = 0;

                for (intCounter = 1; intCounter <= intNumberOfRecords; intCounter++)
                {
                    blnItemFound       = false;
                    strPartNumber      = Convert.ToString((range.Cells[intCounter, 1] as Excel.Range).Value2).ToUpper();
                    strJDEPartNumber   = Convert.ToString((range.Cells[intCounter, 1] as Excel.Range).Value2).ToUpper();
                    strPartDescription = Convert.ToString((range.Cells[intCounter, 2] as Excel.Range).Value2).ToUpper();

                    TheFindPartByPartNumberDataSet = ThePartNumberClass.FindPartByPartNumber(strPartNumber);

                    intRecordsReturned = TheFindPartByPartNumberDataSet.FindPartByPartNumber.Rows.Count;

                    if (intRecordsReturned > 0)
                    {
                        intPartID        = TheFindPartByPartNumberDataSet.FindPartByPartNumber[0].PartID;
                        strJDEPartNumber = TheFindPartByPartNumberDataSet.FindPartByPartNumber[0].JDEPartNumber;
                        blnItemFound     = true;
                    }
                    else if (intRecordsReturned < 1)
                    {
                        TheFindPartByJDEPartNUmberDataSet = ThePartNumberClass.FindPartByJDEPartNumber(strJDEPartNumber);

                        intRecordsReturned = TheFindPartByJDEPartNUmberDataSet.FindPartByJDEPartNumber.Rows.Count;

                        if (intRecordsReturned > 0)
                        {
                            strPartNumber = TheFindPartByJDEPartNUmberDataSet.FindPartByJDEPartNumber[0].PartNumber;
                            intPartID     = TheFindPartByJDEPartNUmberDataSet.FindPartByJDEPartNumber[0].PartID;
                            blnItemFound  = true;
                        }
                        else if (intRecordsReturned < 1)
                        {
                            if (strPartNumber == "NONE")
                            {
                                SpectrumCountDataSet.spectrumcountRow NewPartCount = TheSpectrumCountDataSet.spectrumcount.NewspectrumcountRow();

                                NewPartCount.ERPQuantity     = 0;
                                NewPartCount.JDEPartNumber   = strPartNumber;
                                NewPartCount.PartDescription = strPartDescription;
                                NewPartCount.PartID          = intCounter * -1;
                                NewPartCount.PartNumber      = strPartNumber;
                                NewPartCount.OldPartNumber   = "UNKNOWN";

                                TheSpectrumCountDataSet.spectrumcount.Rows.Add(NewPartCount);
                            }
                        }
                    }


                    if (blnItemFound == true)
                    {
                        TheFindWarehouseInventoryByPartDataSet = TheInventoryClass.FindWarehouseInventoryPart(intPartID, MainWindow.gintWarehouseID);

                        intRecordsReturned = TheFindWarehouseInventoryByPartDataSet.FindWarehouseInventoryPart.Rows.Count;

                        if (intRecordsReturned > 0)
                        {
                            blnItemInTable = false;

                            if (gintCounter > 0)
                            {
                                for (intSecondCounter = 0; intSecondCounter <= gintNumberOfRecords; intSecondCounter++)
                                {
                                    if (intPartID == TheSpectrumCountDataSet.spectrumcount[intSecondCounter].PartID)
                                    {
                                        blnItemInTable = true;
                                    }
                                }
                            }

                            if (blnItemInTable == false)
                            {
                                intQuantity = TheFindWarehouseInventoryByPartDataSet.FindWarehouseInventoryPart[0].Quantity;

                                TheFindMasterPartByPartIDDataSet = ThePartNumberClass.FindMasterPartByPartID(intPartID);

                                intRecordsReturned = TheFindMasterPartByPartIDDataSet.FindMasterPartListPartByPartID.Rows.Count;

                                if (intRecordsReturned > 0)
                                {
                                    strOldPartNumber = TheFindMasterPartByPartIDDataSet.FindMasterPartListPartByPartID[0].PartNumber;
                                }
                                else
                                {
                                    strOldPartNumber = "NOT FOUND";
                                }

                                SpectrumCountDataSet.spectrumcountRow NewPartCount = TheSpectrumCountDataSet.spectrumcount.NewspectrumcountRow();

                                NewPartCount.ERPQuantity     = intQuantity;
                                NewPartCount.JDEPartNumber   = strJDEPartNumber;
                                NewPartCount.PartDescription = strPartDescription;
                                NewPartCount.PartID          = intPartID;
                                NewPartCount.PartNumber      = strPartNumber;
                                NewPartCount.OldPartNumber   = strOldPartNumber;

                                TheSpectrumCountDataSet.spectrumcount.Rows.Add(NewPartCount);
                            }
                        }
                        else if (intRecordsReturned < 1)
                        {
                            if (strPartDescription.Contains("CABLE RG6") == true)
                            {
                                SpectrumCountDataSet.spectrumcountRow NewPartCount = TheSpectrumCountDataSet.spectrumcount.NewspectrumcountRow();

                                NewPartCount.ERPQuantity     = 0;
                                NewPartCount.JDEPartNumber   = strJDEPartNumber;
                                NewPartCount.PartDescription = strPartDescription;
                                NewPartCount.PartID          = intPartID;
                                NewPartCount.PartNumber      = strPartNumber;
                                NewPartCount.OldPartNumber   = strOldPartNumber;

                                TheSpectrumCountDataSet.spectrumcount.Rows.Add(NewPartCount);
                            }
                            else if (strPartDescription.Contains("CABLE RG11") == true)
                            {
                                SpectrumCountDataSet.spectrumcountRow NewPartCount = TheSpectrumCountDataSet.spectrumcount.NewspectrumcountRow();

                                NewPartCount.ERPQuantity     = 0;
                                NewPartCount.JDEPartNumber   = strJDEPartNumber;
                                NewPartCount.PartDescription = strPartDescription;
                                NewPartCount.PartID          = intPartID;
                                NewPartCount.PartNumber      = strPartNumber;
                                NewPartCount.OldPartNumber   = strOldPartNumber;

                                TheSpectrumCountDataSet.spectrumcount.Rows.Add(NewPartCount);
                            }
                            else if (strPartDescription.Contains("CABLE 875") == true)
                            {
                                SpectrumCountDataSet.spectrumcountRow NewPartCount = TheSpectrumCountDataSet.spectrumcount.NewspectrumcountRow();

                                NewPartCount.ERPQuantity     = 0;
                                NewPartCount.JDEPartNumber   = strJDEPartNumber;
                                NewPartCount.PartDescription = strPartDescription;
                                NewPartCount.PartID          = intPartID;
                                NewPartCount.PartNumber      = strPartNumber;
                                NewPartCount.OldPartNumber   = strOldPartNumber;

                                TheSpectrumCountDataSet.spectrumcount.Rows.Add(NewPartCount);
                            }
                            else if (strPartDescription.Contains("CABLE 625") == true)
                            {
                                SpectrumCountDataSet.spectrumcountRow NewPartCount = TheSpectrumCountDataSet.spectrumcount.NewspectrumcountRow();

                                NewPartCount.ERPQuantity     = 0;
                                NewPartCount.JDEPartNumber   = strJDEPartNumber;
                                NewPartCount.PartDescription = strPartDescription;
                                NewPartCount.PartID          = intPartID;
                                NewPartCount.PartNumber      = strPartNumber;
                                NewPartCount.OldPartNumber   = strOldPartNumber;

                                TheSpectrumCountDataSet.spectrumcount.Rows.Add(NewPartCount);
                            }
                        }
                    }
                }

                dgrResult.ItemsSource = TheSpectrumCountDataSet.spectrumcount;

                PleaseWait.Close();
            }
            catch (Exception Ex)
            {
                TheEventLogClass.InsertEventLogEntry(DateTime.Now, "New Blue Jay ERP // Create Spectrum Report // Import Excel Expander " + Ex.Message);

                TheMessagesClass.ErrorMessage(Ex.ToString());
            }
        }
Exemple #24
0
        public JsonResult Register(int reg_service, string reg_datebegin, string reg_number, string reg_name, string reg_email, string reg_phone, string reg_note, string menuId, List <MenuModel> listMenu, string voucher, string reg_table)
        {
            AjaxResultModel Result = new AjaxResultModel();

            try
            {
                string menu     = "";
                string reg_user = "";
                foreach (var s in listMenu)
                {
                    if (s != null)
                    {
                        menu += s.MdetailId + ",";
                    }
                }
                string result = Registers_Service.RegisterService(reg_service, reg_datebegin, reg_number, reg_name, reg_email, reg_phone, reg_note, reg_user, menuId, menu, voucher, reg_table);
                if (result.Equals("00"))
                {
                    Result.Code   = 000;
                    Result.Result = "Thành công";
                }
                else
                {
                    Result.Code   = 001;
                    Result.Result = "Không thành công";
                }
            }
            catch (Exception Ex)
            {
                Result.Code   = 2000;
                Result.Result = "Có lỗi xảy ra. Vui lòng thử lại sau hoặc liên hệ với người quản trị.";
                CORE.Helpers.IOHelper.WriteLog(StartUpPath, IpAddress, "UpdatePassword :", Ex.Message, Ex.ToString());
            }

            return(Json(Result));
        }
        private void RunResavePackagesCommandlet(ProjectParams Params)
        {
            Log("Running Step:- ResavePackages::RunResavePackagesCommandlet");

            // Find the commandlet binary
            string UE4EditorExe = HostPlatform.Current.GetUE4ExePath(Params.UE4Exe);

            if (!FileExists(UE4EditorExe))
            {
                LogError("Missing " + UE4EditorExe + " executable. Needs to be built first.");
                throw new AutomationException("Missing " + UE4EditorExe + " executable. Needs to be built first.");
            }

            // Now let's rebuild lightmaps for the project
            try
            {
                var CommandletParams = IsBuildMachine ? "-unattended -buildmachine -fileopenlog" : "-fileopenlog";
                CommandletParams += " -AutoCheckOutPackages";
                if (P4Enabled)
                {
                    CommandletParams += String.Format(" -SCCProvider={0} -P4Port={1} -P4User={2} -P4Client={3} -P4Changelist={4} -P4Passwd={5}", "Perforce", P4Env.P4Port, P4Env.User, P4Env.Client, WorkingCL.ToString(), P4.GetAuthenticationToken());
                }
                ResavePackagesCommandlet(Params.RawProjectPath, Params.UE4Exe, Params.MapsToRebuildLightMaps.ToArray(), CommandletParams);
            }
            catch (Exception Ex)
            {
                string FinalLogLines    = "No log file found";
                AutomationException AEx = Ex as AutomationException;
                if (AEx != null)
                {
                    string LogFile = AEx.LogFileName;
                    UnrealBuildTool.Log.TraceWarning("Attempting to load file {0}", LogFile);
                    if (LogFile != "")
                    {
                        UnrealBuildTool.Log.TraceWarning("Attempting to read file {0}", LogFile);
                        try
                        {
                            string[] AllLogFile = ReadAllLines(LogFile);

                            FinalLogLines = "Important log entries\n";
                            foreach (string LogLine in AllLogFile)
                            {
                                if (LogLine.Contains("[REPORT]"))
                                {
                                    FinalLogLines += LogLine + "\n";
                                }
                            }
                        }
                        catch (Exception)
                        {
                            // we don't care about this because if this is hit then there is no log file the exception probably has more info
                            LogError("Could not find log file " + LogFile);
                        }
                    }
                }

                // Something went wrong with the commandlet. Abandon this run, don't check in any updated files, etc.
                LogError("Resave Packages has failed. because " + Ex.ToString());
                throw new AutomationException(ExitCode.Error_Unknown, Ex, "ResavePackages failed. {0}", FinalLogLines);
            }
        }
Exemple #26
0
        static public void ExecuteCommand(string Command, string RPCCommand)
        {
            if (ReturnCode > 0)
            {
                Warning("Error in previous command; suppressing: " + Command + " " + RPCCommand ?? "");
                return;
            }

            if (Config.bVerbose)
            {
                Log("");
                Log("----------");
                Log(String.Format("Executing command '{0}' {1}...", Command, (RPCCommand != null) ? ("'" + RPCCommand + "' ") : ""));
            }

            try
            {
                bool bHandledCommand = CookTime.ExecuteCookCommand(Command, RPCCommand);

                if (!bHandledCommand)
                {
                    bHandledCommand = CompileTime.ExecuteCompileCommand(Command, RPCCommand);
                }

                if (!bHandledCommand)
                {
                    bHandledCommand = DeploymentHelper.ExecuteDeployCommand(Command, GamePath, RPCCommand);
                }

                if (!bHandledCommand)
                {
                    bHandledCommand = true;
                    switch (Command)
                    {
                    case "configure":
                        if (Config.bForDistribution)
                        {
                            Error("configure cannot be used with -distribution");
                            Program.ReturnCode = (int)ErrorCodes.Error_Arguments;
                        }
                        else
                        {
                            RunInVisualMode(delegate { return(new ConfigureMobileGame()); });
                        }
                        break;

                    default:
                        bHandledCommand = false;
                        break;
                    }
                }

                if (!bHandledCommand)
                {
                    Error("Unknown command");
                    Program.ReturnCode = (int)ErrorCodes.Error_UnknownCommand;
                }
            }
            catch (Exception Ex)
            {
                Error("Error while executing command: " + Ex.ToString());
                if (Program.ReturnCode == 0)
                {
                    Program.ReturnCode = (int)ErrorCodes.Error_Unknown;
                }
            }

            Console.WriteLine();
        }
Exemple #27
0
        private void openSelectedRepoBtn_Click(object sender, EventArgs e)
        {
            if (repoListBox.SelectedItem == null)
            {
                string titlefinal   = "Notice";
                string messagefinal = "Please select a repo";
                MessageBox.Show(messagefinal, titlefinal);
                return;
            }
            else
            {
                packagesListBox.Items.Clear();
                if (searchBox.Text != "Search Packages")
                {
                    searchBox.Text = "Search Packages";
                }
                detailsBox.Clear();
                using (var badrepocheck = new WebClient())
                {
                    const string sRepos = "https://sarahh12099.github.io/files/badrepos.txt";
                    Stream       stream = badrepocheck.OpenRead(sRepos);
                    StreamReader reader = new StreamReader(stream);
                    string       check;
                    while ((check = reader.ReadLine()) != null)
                    {
                        if (check == repoListBox.SelectedItem.ToString())
                        {
                            string            title   = "Warning";
                            string            message = "You are about to open a repo that has been flagged as Dangerous, are you sure you want to open it?";
                            MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                            DialogResult      result  = MessageBox.Show(message, title, buttons);
                            if (result == DialogResult.Yes)
                            {
                                continue;
                            }
                            if (result == DialogResult.No)
                            {
                                return;
                            }
                        }
                        else
                        {
                            continue;
                        }
                    }
                    reader.Close();
                }
                packagesListBox.Items.Add("Opening Repo, Please Wait");
                Globals.name.Clear();
                Globals.version.Clear();
                Globals.link.Clear();
                Globals.details.Clear();
                Globals.repo = repoListBox.SelectedItem.ToString();
                const string sPath     = "Packages.bz2";
                const string sGz       = "Packages.gz";
                const string sFolder   = "Packages";
                const string sPackages = "Packages/Packages";
                const string sText     = "Packages.txt";
                if (File.Exists(sPath))
                {
                    File.Delete(sPath);
                }
                if (File.Exists(sGz))
                {
                    File.Delete(sGz);
                }
                if (File.Exists(sText))
                {
                    File.Delete(sText);
                }
                if (Directory.Exists(sFolder))
                {
                    Directory.Delete(sFolder, true);
                }
                using (var client = new WebClient())
                {
                    try
                    {
                        client.Headers.Add("X-Machine", "iPhone8,1");
                        client.Headers.Add("X-Unique-ID", "8843d7f92416211de9ebb963ff4ce28125932878");
                        client.Headers.Add("X-Firmware", "13.1");
                        client.Headers.Add("User-Agent", "Telesphoreo APT-HTTP/1.0.592");
                        client.DownloadFile(repoListBox.SelectedItem + "Packages.bz2", "Packages.bz2");
                    }
                    catch (Exception ExOne)
                    {
                        try
                        {
                            client.Headers.Add("X-Machine", "iPhone8,1");
                            client.Headers.Add("X-Unique-ID", "8843d7f92416211de9ebb963ff4ce28125932878");
                            client.Headers.Add("X-Firmware", "13.1");
                            client.Headers.Add("User-Agent", "Telesphoreo APT-HTTP/1.0.592");
                            client.DownloadFile(repoListBox.SelectedItem + "dists/stable/main/binary-iphoneos-arm/Packages.bz2", "Packages.bz2");
                        }
                        catch (Exception ExTwo)
                        {
                            try
                            {
                                client.Headers.Add("X-Machine", "iPhone8,1");
                                client.Headers.Add("X-Unique-ID", "8843d7f92416211de9ebb963ff4ce28125932878");
                                client.Headers.Add("X-Firmware", "13.1");
                                client.Headers.Add("User-Agent", "Telesphoreo APT-HTTP/1.0.592");
                                client.DownloadFile(repoListBox.SelectedItem + "Packages.gz", "Packages.gz");
                            }
                            catch (Exception ExThree)
                            {
                                string titlefinal   = "Notice";
                                string messagefinal = "Unable to connect to repo, are you connected to the internet and did you type the repo url correctly? \n\n" + ExThree;
                                MessageBox.Show(messagefinal, titlefinal);
                                return;
                            }
                        }
                    }
                    string zPath = "7za.exe";
                    try
                    {
                        ProcessStartInfo pro = new ProcessStartInfo();
                        pro.WindowStyle = ProcessWindowStyle.Hidden;
                        pro.FileName    = zPath;
                        if (File.Exists(sPath))
                        {
                            pro.Arguments = string.Format("x \"{0}\" -y -o\"{1}\"", sPath, sFolder);
                        }
                        if (File.Exists(sGz))
                        {
                            pro.Arguments = string.Format("x \"{0}\" -y -o\"{1}\"", sGz, sFolder);
                        }
                        Process x = Process.Start(pro);
                        x.WaitForExit();
                    }
                    catch (Exception Ex)
                    {
                        string titlefinal   = "Notice";
                        string messagefinal = Ex.ToString();
                        MessageBox.Show(messagefinal, titlefinal);
                        return;
                    }

                    Stream       stream = File.OpenRead(sPackages);
                    StreamReader reader = new StreamReader(stream);
                    string       parse;
                    const string sTath    = "Packages.txt";
                    StreamWriter SaveFile = new StreamWriter(sTath);
                    while ((parse = reader.ReadLine()) != null)
                    {
                        SaveFile.WriteLine(parse.ToString());
                    }
                    SaveFile.Close();
                    reader.Close();
                    string   lines = File.ReadAllText(sText);
                    string[] split = lines.Split(new string[] { "\r\n\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string line in split)
                    {
                        Globals.details.Add(line);
                        string[] check = line.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (string pass in check)
                        {
                            if (pass.StartsWith("Name"))
                            {
                                string name = pass.Substring(6, pass.Length - 6).ToString();
                                Globals.name.Add(name);
                            }
                            if (pass.StartsWith("Version"))
                            {
                                string version = pass.Substring(9, pass.Length - 9).ToString();
                                Globals.version.Add(version);
                            }
                            if (pass.StartsWith("Filename"))
                            {
                                string link = pass.Substring(10, pass.Length - 10).ToString();
                                Globals.link.Add(link);
                            }
                            if (pass.StartsWith("Package"))
                            {
                                string link = pass.Substring(9, pass.Length - 9).ToString();
                                Globals.package.Add(link);
                            }
                        }
                    }
                    packagesListBox.Items.Clear();
                    for (int i = 0; i < Globals.name.Count; i++)
                    {
                        packagesListBox.Items.Add(new ListItem {
                            Name = Globals.name[i] + " v" + Globals.version[i], Link = Globals.link[i], Details = Globals.details[i], Package = Globals.package[i], Version = Globals.version[i]
                        });
                    }
                    packagesListBox.Sorted = true;
                }
            }
        }
Exemple #28
0
        /// <summary>
        /// Loads BuildConfiguration from XML into memory.
        /// </summary>
        private static void LoadData()
        {
            foreach (var PossibleConfigLocation in ConfigLocationHierarchy)
            {
                if (!PossibleConfigLocation.bExists)
                {
                    continue;
                }

                try
                {
                    LoadDataFromFile(PossibleConfigLocation.FSLocation);
                }
                catch (Exception Ex)
                {
                    Console.WriteLine("Problem parsing {0}:\n   {1}", PossibleConfigLocation.FSLocation, Ex.ToString());
                }
            }
        }
        private void mitSave_Click(object sender, RoutedEventArgs e)
        {
            string  strValueForValidation;
            string  strWorkTask;
            decimal decTaskCost        = 1;
            string  strErrorMessage    = "";
            bool    blnFatalError      = false;
            bool    blnThereIsAProblem = false;

            try
            {
                strWorkTask = txtWorkTask.Text;
                if (strWorkTask == "")
                {
                    blnFatalError    = true;
                    strErrorMessage += "The Work Task Was Not Entered\n";
                }
                strValueForValidation = txtTotalCost.Text;
                blnThereIsAProblem    = TheDataValidationClass.VerifyDoubleData(strValueForValidation);
                if (blnThereIsAProblem == true)
                {
                    blnFatalError    = true;
                    strErrorMessage += "The Task Cost Is Not Numeric\n";
                }
                else
                {
                    decTaskCost = Convert.ToDecimal(strValueForValidation);
                }
                if (cboSelectActive.SelectedIndex < 1)
                {
                    blnFatalError    = true;
                    strErrorMessage += "Active Was Not Selected\n";
                }
                if (blnFatalError == true)
                {
                    TheMessagesClass.ErrorMessage(strErrorMessage);
                    return;
                }

                //updating record
                blnFatalError = TheWorkTaskClass.UpdateWorkTask(MainWindow.gintWorkTaskID, strWorkTask, decTaskCost);

                if (blnFatalError == true)
                {
                    throw new Exception();
                }

                blnFatalError = TheWorkTaskClass.UpdateWorkTaskActive(MainWindow.gintWorkTaskID, gblnActive);

                if (blnFatalError == true)
                {
                    throw new Exception();
                }

                if (blnFatalError == false)
                {
                    txtEnterWorkTask.Text           = "";
                    txtTotalCost.Text               = "";
                    txtWorkTask.Text                = "";
                    txtWorkTaskID.Text              = "";
                    cboSelectWorkTask.SelectedIndex = 0;
                    cboSelectActive.SelectedIndex   = 0;
                    mitSave.IsEnabled               = false;
                    TheMessagesClass.InformationMessage("The Record Has Been Updated");
                }
            }
            catch (Exception Ex)
            {
                TheEventLogClass.InsertEventLogEntry(DateTime.Now, "Blue Jay ERP // Edit Work Task // Save Menu Item " + Ex.Message);

                TheMessagesClass.ErrorMessage(Ex.ToString());
            }
        }
Exemple #30
0
        /// <summary>
        /// This function will do all the work, when it finish its tasks,
        /// it will be suspended for some time. It will continue to repeat
        /// this until the service is stopped.
        /// </summary>
        private void begingProcessing()
        {
            try
            {
                // Notify the loaded settings values for this service.
                string strMessage = "VALORES DE CONFIGURACIÓN ENCONTRADOS" + Environment.NewLine;
                strMessage += Environment.NewLine;
                // Localización y descarga de datos primarios
                strMessage += "-Localización y descarga de datos primarios" + Environment.NewLine;
                strMessage += "  Sitio origen del fichero a descargar: " + clsSettings.serviceSettings.downloadUri + Environment.NewLine;
                strMessage += "  User-Agent para solicitudes Internet: " + clsSettings.serviceSettings.downloaderUserAgent + Environment.NewLine;
                strMessage += Environment.NewLine;
                // Rutas temporales para procesamiento
                strMessage += "-Rutas temporales para procesamiento" + Environment.NewLine;
                strMessage += "  Directorio base para procesamiento: " + clsSettings.serviceSettings.workingDirectory + Environment.NewLine;
                strMessage += "  Subdirectorio para almacenar datos: " + clsSettings.serviceSettings.dataDirectory + Environment.NewLine;
                strMessage += "  Subdirectorio para almacenar logs: " + clsSettings.serviceSettings.logsDirectory + Environment.NewLine;
                strMessage += Environment.NewLine;
                // Estado
                strMessage += "-Estado" + Environment.NewLine;
                strMessage += "  Siguiente operación a procesar: " + clsSettings.serviceSettings.currentOperation + Environment.NewLine;
                strMessage += "  Fecha de la última actualización: " + (clsSettings.serviceSettings.downloadedFileLastModifiedDate != DateTime.MinValue ? clsSettings.serviceSettings.downloadedFileLastModifiedDate.ToString() : "Nunca") + Environment.NewLine;
                strMessage += "  Horas entre chequeos para actualización: " + clsSettings.serviceSettings.checkForUpdateInterval.TotalHours + Environment.NewLine;
                strMessage += Environment.NewLine;
                // Servidor SQL
                strMessage += "-Servidor SQL" + Environment.NewLine;
                strMessage += "  Utilizar transacciones: " + (clsSettings.serviceSettings.useSqlTransaction ? "Sí" : "No").ToString() + Environment.NewLine;
                strMessage += Environment.NewLine;
                //Servidor ISA
                strMessage += "-Servidor ISA" + Environment.NewLine;
                strMessage += "  Procesar RuleElements: " + (clsSettings.serviceSettings.processISARuleElements ? "Sí" : "No").ToString() + Environment.NewLine;
                if (clsSettings.serviceSettings.processISARuleElements)
                {
                    strMessage += "  Nombre del servidor: " + (string.IsNullOrEmpty(clsSettings.serviceSettings.ISAServer.Name) ? "No configurado" : clsSettings.serviceSettings.ISAServer.Name).ToString() + Environment.NewLine;
                    strMessage += "  Nombre de usuario: " + (string.IsNullOrEmpty(clsSettings.serviceSettings.ISAServer.UserName) ? "No configurado" : clsSettings.serviceSettings.ISAServer.UserName).ToString() + Environment.NewLine;
                    strMessage += "  Contraseña de usuario: " + (string.IsNullOrEmpty(clsSettings.serviceSettings.ISAServer.UserPasswd) ? "No configurada" : "*****").ToString() + Environment.NewLine;
                    strMessage += "  Dominio de usuario (opcional): " + clsSettings.serviceSettings.ISAServer.UserDomain + Environment.NewLine;
                }
                clsLogProcessing.WriteToEventLog(strMessage, EventLogEntryType.Information);
            }
            catch (System.Exception Ex)
            {
                string ErrMessage = string.Format("Error obteniendo configuraciones. El servicio no efectuará procesamiento alguno " +
                                                  "aunque permanezca en ejecución. Se recomienda revisar los valores de los elementos de configuración del fichero " +
                                                  "\"app.config\". Los detalles de este error se muestran a continuación: {0}", Ex.ToString());
                clsLogProcessing.WriteToEventLog(ErrMessage, EventLogEntryType.Error);
                serviceStarted = false;
            }

            // Start an endless loop; loop will abort only when "serviceStarted" flag = false;
            while (serviceStarted)
            {
                // It's very important to catch errors here, otherwise we will never know what happens if somthing was wrong.
                try
                {
                    switch (clsSettings.serviceSettings.currentOperation)
                    {
                    case operationList.decompressingSourceFile:
                    {
                        // Notify the restoring action.
                        clsLogProcessing.reportRecoveryAction(operationList.decompressingSourceFile);

                        decompressSourceFile();

                        generateXmlFormatedIndex();

                        generateXmlFormatedContent();

                        if (updateSqlDataBase() && clsSettings.serviceSettings.processISARuleElements)
                        {
                            updateISARuleElements();
                        }

                        break;
                    }

                    case operationList.generatingXmlFormatedIndex:
                    {
                        // Notify the restoring action.
                        clsLogProcessing.reportRecoveryAction(operationList.generatingXmlFormatedIndex);

                        generateXmlFormatedIndex();

                        generateXmlFormatedContent();

                        if (updateSqlDataBase() && clsSettings.serviceSettings.processISARuleElements)
                        {
                            updateISARuleElements();
                        }

                        break;
                    }

                    case operationList.generatingXmlFormatedContent:
                    {
                        // Notify the restoring action.
                        clsLogProcessing.reportRecoveryAction(operationList.generatingXmlFormatedContent);

                        generateXmlFormatedContent();

                        if (updateSqlDataBase() && clsSettings.serviceSettings.processISARuleElements)
                        {
                            updateISARuleElements();
                        }

                        break;
                    }

                    case operationList.updatingSqlDataBase:
                    {
                        // Notify the restoring action.
                        clsLogProcessing.reportRecoveryAction(operationList.updatingSqlDataBase);

                        if (updateSqlDataBase() && clsSettings.serviceSettings.processISARuleElements)
                        {
                            updateISARuleElements();
                        }

                        break;
                    }

                    case operationList.updatingISARuleElements:
                    {
                        // Notify the restoring action.
                        clsLogProcessing.reportRecoveryAction(operationList.updatingISARuleElements);

                        if (clsSettings.serviceSettings.processISARuleElements)
                        {
                            updateISARuleElements();
                        }

                        break;
                    }

                    default:                             // Execute all operations in any case diferent the above.
                    {
                        string fileNameFullPath;         // The path and name of the file to save in the local file system.
                        string ETag;                     //ETag Header in the response.

                        if (isThereNewFileToDownload(out fileNameFullPath, out ETag))
                        {
                            if (downloadSourceFile(fileNameFullPath, ETag))
                            {
                                if (decompressSourceFile())
                                {
                                    generateXmlFormatedIndex();
                                    generateXmlFormatedContent();
                                    if (updateSqlDataBase() && clsSettings.serviceSettings.processISARuleElements)
                                    {
                                        updateISARuleElements();
                                    }
                                }
                            }
                        }

                        break;
                    }
                    }

                    // Delete Downloaded files "...data\*-fileName.tar.gz" , BL folder "...data\BL".
                    cleanTrash();

                    // When all operations are finished set the currentOperation to waitingForNextExecution.
                    clsSettings.serviceSettings.currentOperation = operationList.waitingForNextExecution;
                    // Return the operation to waiting for new execution.
                }
                catch (System.Exception Ex)
                {
                    string errMessage = string.Format("Ha ocurrido un error en el método \"beginProcessing\". Los detalles de este error se muestran a continuación: {0}", Ex.ToString());
                    clsLogProcessing.WriteToEventLog(errMessage, EventLogEntryType.Error);
                    // When error, set the currentOperation to waitingForNextExecution to try next time.
                    clsSettings.serviceSettings.currentOperation = operationList.waitingForNextExecution;
                }

                // Put the thread to sleep for a while.
                if (serviceStarted)
                {
                    //Thread.Sleep(new TimeSpan(0, 0, 10));
                    Thread.Sleep(clsSettings.serviceSettings.checkForUpdateInterval);
                }
            }

            // It's time to end the thread.
            Thread.CurrentThread.Abort();
        }         // Fin del método: beginProcessing()
        public static ConfigFile ReadProjectConfigFile(PerforceConnection Perforce, string BranchClientPath, string SelectedClientFileName, TextWriter Log)
        {
            List <string> ConfigFilePaths = Utility.GetConfigFileLocations(BranchClientPath, SelectedClientFileName, '/');

            List <PerforceFileRecord> OpenFiles;

            Perforce.GetOpenFiles(String.Format("{0}/....ini", BranchClientPath), out OpenFiles, Log);

            ConfigFile ProjectConfig = new ConfigFile();

            foreach (string ConfigFilePath in ConfigFilePaths)
            {
                List <string> Lines;
                if (Perforce.Print(ConfigFilePath, out Lines, Log))
                {
                    // If this file is open for edit, read the local version instead
                    if (OpenFiles != null && OpenFiles.Any(x => x.ClientPath.Equals(ConfigFilePath, StringComparison.InvariantCultureIgnoreCase)))
                    {
                        try
                        {
                            string LocalFileName;
                            if (Perforce.ConvertToLocalPath(ConfigFilePath, out LocalFileName, Log))
                            {
                                Lines = File.ReadAllLines(LocalFileName).ToList();
                            }
                        }
                        catch (Exception Ex)
                        {
                            Log.WriteLine("Failed to read local config file for {0}: {1}", ConfigFilePath, Ex.ToString());
                        }
                    }

                    // Merge the text with the config file
                    try
                    {
                        ProjectConfig.Parse(Lines.ToArray());
                        Log.WriteLine("Read config file from {0}", ConfigFilePath);
                    }
                    catch (Exception Ex)
                    {
                        Log.WriteLine("Failed to read config file from {0}: {1}", ConfigFilePath, Ex.ToString());
                    }
                }
            }
            return(ProjectConfig);
        }
        private void ResetControls()
        {
            //setting up the local variables
            int      intCounter;
            int      intNumberOfRecords;
            int      intProjectID;
            DateTime datTransactionDate = DateTime.Now;
            DateTime datStartDate       = DateTime.Now;
            decimal  decAveragePayRate;

            try
            {
                PleaseWait PleaseWait = new PleaseWait();
                PleaseWait.Show();

                TheShopViolatorDataSet.violator.Rows.Clear();

                datTransactionDate = TheDateSearchClass.RemoveTime(datTransactionDate);

                datTransactionDate = TheDateSearchClass.SubtractingDays(datTransactionDate, 31);

                TheFindProjectMatrixByAssignedProjectIDDataSet = TheProjectMatrixClass.FindProjectMatrixByAssignedProjectID("SHOP");

                intProjectID = TheFindProjectMatrixByAssignedProjectIDDataSet.FindProjectMatrixByAssignedProjectID[0].ProjectID;

                datStartDate = TheDateSearchClass.SubtractingDays(datStartDate, 31);

                TheFindProjectStatsDataSet = TheEmployeeProductivityStatsClass.FindProjectStats(intProjectID);

                gdecMean           = TheFindProjectStatsDataSet.FindProjectStats[0].AveHours;
                gdecStandDeviation = Convert.ToDecimal(TheFindProjectStatsDataSet.FindProjectStats[0].HoursSTDev);
                gdecVariance       = Convert.ToDecimal(TheFindProjectStatsDataSet.FindProjectStats[0].HoursVariance);
                gdecTotalHours     = Convert.ToDecimal(TheFindProjectStatsDataSet.FindProjectStats[0].TotalHours);
                decAveragePayRate  = TheFindProjectStatsDataSet.FindProjectStats[0].AveragePayRate;

                gdecMean = Math.Round(gdecMean, 4);

                txtAverageHours.Text = Convert.ToString(gdecMean);

                gdecVariance       = Math.Round(gdecVariance, 4);
                gdecStandDeviation = Math.Round(gdecStandDeviation, 4);

                gdecUpperBound = gdecMean + gdecStandDeviation;

                txtUpperBound.Text = Convert.ToString(gdecUpperBound);

                TheFindProjectHoursAboveLimitDataSet = TheEmployeeProjectAssignmentClass.FindProjectHoursAboveLimit(intProjectID, datStartDate, gdecUpperBound);

                intNumberOfRecords = TheFindProjectHoursAboveLimitDataSet.FindProjectHoursAboveLimit.Rows.Count;

                if (intNumberOfRecords > 0)
                {
                    for (intCounter = 0; intCounter < intNumberOfRecords; intCounter++)
                    {
                        ShopViolatorDataSet.violatorRow NewViolatorRow = TheShopViolatorDataSet.violator.NewviolatorRow();

                        NewViolatorRow.FirstName       = TheFindProjectHoursAboveLimitDataSet.FindProjectHoursAboveLimit[intCounter].FirstName;
                        NewViolatorRow.HomeOffice      = TheFindProjectHoursAboveLimitDataSet.FindProjectHoursAboveLimit[intCounter].HomeOffice;
                        NewViolatorRow.Hours           = TheFindProjectHoursAboveLimitDataSet.FindProjectHoursAboveLimit[intCounter].TotalHours;
                        NewViolatorRow.LastName        = TheFindProjectHoursAboveLimitDataSet.FindProjectHoursAboveLimit[intCounter].LastName;
                        NewViolatorRow.TransactionDate = TheFindProjectHoursAboveLimitDataSet.FindProjectHoursAboveLimit[intCounter].TransactionDate;

                        TheShopViolatorDataSet.violator.Rows.Add(NewViolatorRow);
                    }
                }

                dgrResults.ItemsSource = TheShopViolatorDataSet.violator;

                gdecProjectHours    = TheFindProjectStatsDataSet.FindProjectStats[0].TotalHours;
                txtShopHours.Text   = Convert.ToString(gdecProjectHours);
                gdecProjectCost     = gdecProjectHours * decAveragePayRate;
                gdecProjectCost     = Math.Round(gdecProjectCost, 4);
                txtProjectCost.Text = Convert.ToString(gdecProjectCost);

                PleaseWait.Close();
            }
            catch (Exception Ex)
            {
                TheEventLogClass.InsertEventLogEntry(DateTime.Now, "New Blue Jay ERP // Shop Hours Analysis // Reset Controls " + Ex.Message);

                TheMessagesClass.ErrorMessage(Ex.ToString());
            }
        }
        private void ComputeTotalDays()
        {
            DateTime datStartDate = DateTime.Now;
            DateTime datEndDate   = DateTime.Now;
            int      intCounter;
            int      intNumberOfRecords;
            int      intSecondCounter;
            string   strOffice;
            string   strDepartment;
            int      intTotalCount;
            bool     blnItemFound;

            try
            {
                TheAgedOverdueProjectsDataSet.agedoverdueprojects.Rows.Clear();
                gintCounter         = 0;
                gintNumberOfRecords = 0;

                datStartDate = TheDateSearchClass.SubtractingDays(datStartDate, 30);
                datEndDate   = TheDateSearchClass.AddingDays(datEndDate, 3);

                TheFindOverdueProjectsByDateRangeDataSet = TheProductionProjectClass.FindOverdueProjectsByDateRange(datStartDate, datEndDate);

                intNumberOfRecords = TheFindOverdueProjectsByDateRangeDataSet.FindOverdueProjectsByDateRange.Rows.Count;

                if (intNumberOfRecords > 0)
                {
                    for (intCounter = 0; intCounter < intNumberOfRecords; intCounter++)
                    {
                        strOffice     = TheFindOverdueProjectsByDateRangeDataSet.FindOverdueProjectsByDateRange[intCounter].Office;
                        strDepartment = TheFindOverdueProjectsByDateRangeDataSet.FindOverdueProjectsByDateRange[intCounter].Department;
                        intTotalCount = TheFindOverdueProjectsByDateRangeDataSet.FindOverdueProjectsByDateRange[intCounter].TotalProjects;
                        blnItemFound  = false;

                        if (gintCounter > 0)
                        {
                            for (intSecondCounter = 0; intSecondCounter < gintNumberOfRecords; intSecondCounter++)
                            {
                                if (TheAgedOverdueProjectsDataSet.agedoverdueprojects[intSecondCounter].Office == strOffice)
                                {
                                    if (TheAgedOverdueProjectsDataSet.agedoverdueprojects[intSecondCounter].BusinessLine == strDepartment)
                                    {
                                        blnItemFound = true;
                                        TheAgedOverdueProjectsDataSet.agedoverdueprojects[intSecondCounter].LessThan30 += intTotalCount;
                                    }
                                }
                            }
                        }

                        if (blnItemFound == false)
                        {
                            AgedOverdueProjectsDataSet.agedoverdueprojectsRow NewProjectRow = TheAgedOverdueProjectsDataSet.agedoverdueprojects.NewagedoverdueprojectsRow();

                            NewProjectRow.Between30and60 = 0;
                            NewProjectRow.BusinessLine   = strDepartment;
                            NewProjectRow.LessThan30     = intTotalCount;
                            NewProjectRow.Office         = strOffice;
                            NewProjectRow.Over60         = 0;
                            TheAgedOverdueProjectsDataSet.agedoverdueprojects.Rows.Add(NewProjectRow);
                            gintNumberOfRecords = gintCounter;
                            gintCounter++;
                        }
                    }
                }

                datEndDate   = datStartDate;
                datStartDate = TheDateSearchClass.SubtractingDays(datStartDate, 30);

                TheFindOverdueProjectsByDateRangeDataSet = TheProductionProjectClass.FindOverdueProjectsByDateRange(datStartDate, datEndDate);

                intNumberOfRecords = TheFindOverdueProjectsByDateRangeDataSet.FindOverdueProjectsByDateRange.Rows.Count;

                if (intNumberOfRecords > 0)
                {
                    for (intCounter = 0; intCounter < intNumberOfRecords; intCounter++)
                    {
                        strOffice     = TheFindOverdueProjectsByDateRangeDataSet.FindOverdueProjectsByDateRange[intCounter].Office;
                        strDepartment = TheFindOverdueProjectsByDateRangeDataSet.FindOverdueProjectsByDateRange[intCounter].Department;
                        intTotalCount = TheFindOverdueProjectsByDateRangeDataSet.FindOverdueProjectsByDateRange[intCounter].TotalProjects;
                        blnItemFound  = false;

                        if (gintCounter > 0)
                        {
                            for (intSecondCounter = 0; intSecondCounter < gintNumberOfRecords; intSecondCounter++)
                            {
                                if (TheAgedOverdueProjectsDataSet.agedoverdueprojects[intSecondCounter].Office == strOffice)
                                {
                                    if (TheAgedOverdueProjectsDataSet.agedoverdueprojects[intSecondCounter].BusinessLine == strDepartment)
                                    {
                                        blnItemFound = true;
                                        TheAgedOverdueProjectsDataSet.agedoverdueprojects[intSecondCounter].Between30and60 += intTotalCount;
                                    }
                                }
                            }
                        }

                        if (blnItemFound == false)
                        {
                            AgedOverdueProjectsDataSet.agedoverdueprojectsRow NewProjectRow = TheAgedOverdueProjectsDataSet.agedoverdueprojects.NewagedoverdueprojectsRow();

                            NewProjectRow.Between30and60 = intTotalCount;
                            NewProjectRow.BusinessLine   = strDepartment;
                            NewProjectRow.LessThan30     = 0;
                            NewProjectRow.Office         = strOffice;
                            NewProjectRow.Over60         = 0;
                            TheAgedOverdueProjectsDataSet.agedoverdueprojects.Rows.Add(NewProjectRow);
                            gintNumberOfRecords = gintCounter;
                            gintCounter++;
                        }
                    }
                }

                TheFindOverdueProjectsByOfficeBusinessDataSet = TheProductionProjectClass.FindOverdueProjectsByOfficeBusiness(datStartDate);

                intNumberOfRecords = TheFindOverdueProjectsByOfficeBusinessDataSet.FindOverdueProjectsByOfficeBusiness.Rows.Count;

                if (intNumberOfRecords > 0)
                {
                    for (intCounter = 0; intCounter < intNumberOfRecords; intCounter++)
                    {
                        strOffice     = TheFindOverdueProjectsByOfficeBusinessDataSet.FindOverdueProjectsByOfficeBusiness[intCounter].Office;
                        strDepartment = TheFindOverdueProjectsByOfficeBusinessDataSet.FindOverdueProjectsByOfficeBusiness[intCounter].Department;
                        intTotalCount = TheFindOverdueProjectsByOfficeBusinessDataSet.FindOverdueProjectsByOfficeBusiness[intCounter].TotalProjects;
                        blnItemFound  = false;

                        if (gintCounter > 0)
                        {
                            for (intSecondCounter = 0; intSecondCounter < gintNumberOfRecords; intSecondCounter++)
                            {
                                if (TheAgedOverdueProjectsDataSet.agedoverdueprojects[intSecondCounter].Office == strOffice)
                                {
                                    if (TheAgedOverdueProjectsDataSet.agedoverdueprojects[intSecondCounter].BusinessLine == strDepartment)
                                    {
                                        blnItemFound = true;
                                        TheAgedOverdueProjectsDataSet.agedoverdueprojects[intSecondCounter].Over60 += intTotalCount;
                                    }
                                }
                            }
                        }

                        if (blnItemFound == false)
                        {
                            AgedOverdueProjectsDataSet.agedoverdueprojectsRow NewProjectRow = TheAgedOverdueProjectsDataSet.agedoverdueprojects.NewagedoverdueprojectsRow();

                            NewProjectRow.Between30and60 = 0;
                            NewProjectRow.BusinessLine   = strDepartment;
                            NewProjectRow.LessThan30     = 0;
                            NewProjectRow.Office         = strOffice;
                            NewProjectRow.Over60         = intTotalCount;
                            TheAgedOverdueProjectsDataSet.agedoverdueprojects.Rows.Add(NewProjectRow);
                            gintNumberOfRecords = gintCounter;
                            gintCounter++;
                        }
                    }
                }

                dgrAgedOverdue.ItemsSource = TheAgedOverdueProjectsDataSet.agedoverdueprojects;
            }
            catch (Exception Ex)
            {
                TheEventLogClass.InsertEventLogEntry(DateTime.Now, "New Blue Jay ERP // Overdue Projects Dashboard " + Ex.Message);

                TheMessagesClass.ErrorMessage(Ex.ToString());
            }
        }
 public RealmRebornRed(IXivSheet sheet, Ex.Relational.IRelationalRow sourceRow) : base(sheet, sourceRow) { }
Exemple #35
0
        public JsonResult GetUnitPrice(int serviceId)
        {
            AjaxResultModel Result = new AjaxResultModel();

            Result.Result = "0 VND";

            try
            {
                TB_SERVICES s = Services_Service.GetById(serviceId);
                TB_TYPES    t = Types_Service.GetById(s.ServiceTypeCode);

                Result.Code   = 000;
                Result.Result = new { type = t.TypeType, price = string.Format("{0:N0}", s.ServicePrice) + " " + s.ServiceUnit };
            }
            catch (Exception Ex)
            {
                Result.Code   = 2000;
                Result.Result = 0;
                CORE.Helpers.IOHelper.WriteLog(StartUpPath, IpAddress, "UpdatePassword :", Ex.Message, Ex.ToString());
            }

            return(Json(Result));
        }
 public EternalBondInvitation(IXivSheet sheet, Ex.Relational.IRelationalRow sourceRow) : base(sheet, sourceRow) { }
        public override void ExecuteBuild()
        {
            string Paths = ParseParamValue("Paths", null);

            if (string.IsNullOrWhiteSpace(Paths))
            {
                throw new AutomationException("-Paths must be defined! Usage: -Paths=Path1/...;Path2.txt");
            }

            string Description = ParseParamValue("Description", null);

            if (string.IsNullOrWhiteSpace(Description))
            {
                throw new AutomationException("-Description must be defined!");
            }


            string FileType = ParseParamValue("FileType", null);

            if (!CommandUtils.AllowSubmit)
            {
                LogWarning("Submitting to Perforce is disabled by default. Run with the -submit argument to allow.");
            }
            else
            {
                // Get the connection that we're going to submit with
                P4Connection SubmitP4 = CommandUtils.P4;
                // Reconcile the path against the depot
                int NewCL = SubmitP4.CreateChange(Description: Description.Replace("\\n", "\n"));
                try
                {
                    foreach (string Path in Paths.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        SubmitP4.Sync(String.Format("-k \"{0}\"", Path), AllowSpew: false);
                        SubmitP4.Reconcile(NewCL, Path);
                        if (FileType != null)
                        {
                            SubmitP4.P4(String.Format("reopen -t \"{0}\" \"{1}\"", FileType, Path), AllowSpew: false);
                        }
                    }

                    if (SubmitP4.TryDeleteEmptyChange(NewCL))
                    {
                        CommandUtils.LogInformation("No files to submit; ignored.");
                        return;
                    }

                    // Submit it
                    int SubmittedCL;
                    SubmitP4.Submit(NewCL, out SubmittedCL, true);
                    if (SubmittedCL <= 0)
                    {
                        throw new AutomationException("Submit failed.");
                    }
                    CommandUtils.LogInformation("Submitted in changelist {0}", SubmittedCL);
                }
                catch (Exception Ex)
                {
                    LogError("Failed to reconcile and submit files to P4, reason: {0}, reverting and deleting change.", Ex.ToString());
                    SubmitP4.DeleteChange(NewCL);
                }
            }
        }
Exemple #38
0
        public JsonResult GetPrice(int serviceId, int serviceNum, string code = "", int menuId = 0, int num = 0)
        {
            AjaxResultModel Result = new AjaxResultModel();

            Result.Result = 0;

            try
            {
                TB_SERVICES s = Services_Service.GetById(serviceId);
                decimal     p = s.ServicePrice * serviceNum;

                if (!string.IsNullOrEmpty(code))
                {
                    TB_VOUCHERS v = Voucher_Service.GetByCode(code);
                    if (v != null && v.VoucherDateExpired.Date >= DateTime.Now.Date && v.VoucherState == "A")
                    {
                        if (v.VoucherType == "M")//Giảm tiền
                        {
                            p = p - v.VoucherNum;
                        }
                        else if (v.VoucherType == "P")//Giảm phần trăm
                        {
                            p = p * (100 - v.VoucherNum) / 100;
                        }
                    }
                }

                if (num > 0 && menuId > 0)
                {
                    TB_MENUS m = Menu_Service.GetById(menuId);
                    if (m != null)
                    {
                        p += m.MenuPrice * num;
                    }
                }

                Result.Code   = 000;
                Result.Result = string.Format("{0:N0}", p);
            }
            catch (Exception Ex)
            {
                Result.Code   = 2000;
                Result.Result = 0;
                CORE.Helpers.IOHelper.WriteLog(StartUpPath, IpAddress, "UpdatePassword :", Ex.Message, Ex.ToString());
            }

            return(Json(Result));
        }
Exemple #39
0
        bool ReadEventsFromBackend()
        {
            try
            {
                Stopwatch Timer = Stopwatch.StartNew();
                LogWriter.WriteLine();
                LogWriter.WriteLine("Polling for reviews at {0}...", DateTime.Now.ToString());

                if (LastEventId == 0)
                {
                    using (SqlConnection Connection = new SqlConnection(SqlConnectionString))
                    {
                        Connection.Open();
                        using (SqlCommand Command = new SqlCommand("SELECT MAX(ID) FROM dbo.UserVotes", Connection))
                        {
                            using (SqlDataReader Reader = Command.ExecuteReader())
                            {
                                while (Reader.Read())
                                {
                                    LastEventId = Reader.GetInt64(0);
                                    LastEventId = Math.Max(LastEventId - 5000, 0);
                                    break;
                                }
                            }
                        }
                    }
                }

                using (SqlConnection Connection = new SqlConnection(SqlConnectionString))
                {
                    Connection.Open();
                    using (SqlCommand Command = new SqlCommand("SELECT Id, Changelist, UserName, Verdict, Project FROM dbo.UserVotes WHERE Id > @param1", Connection))
                    {
                        Command.Parameters.AddWithValue("@param1", LastEventId);
                        using (SqlDataReader Reader = Command.ExecuteReader())
                        {
                            while (Reader.Read())
                            {
                                EventData Review = new EventData();
                                Review.Id       = Reader.GetInt64(0);
                                Review.Change   = Reader.GetInt32(1);
                                Review.UserName = Reader.GetString(2);
                                Review.Project  = Reader.IsDBNull(4)? null : Reader.GetString(4);
                                if (Enum.TryParse(Reader.GetString(3), out Review.Type))
                                {
                                    if (Review.Project == null || String.Compare(Review.Project, Project, true) == 0)
                                    {
                                        IncomingEvents.Enqueue(Review);
                                    }
                                    LastEventId = Math.Max(LastEventId, Review.Id);
                                }
                            }
                        }
                    }
                    using (SqlCommand Command = new SqlCommand("SELECT Id, ChangeNumber, UserName, Text, Project FROM dbo.Comments WHERE Id > @param1", Connection))
                    {
                        Command.Parameters.AddWithValue("@param1", LastCommentId);
                        using (SqlDataReader Reader = Command.ExecuteReader())
                        {
                            while (Reader.Read())
                            {
                                CommentData Comment = new CommentData();
                                Comment.Id           = Reader.GetInt32(0);
                                Comment.ChangeNumber = Reader.GetInt32(1);
                                Comment.UserName     = Reader.GetString(2);
                                Comment.Text         = Reader.GetString(3);
                                Comment.Project      = Reader.GetString(4);
                                if (Comment.Project == null || String.Compare(Comment.Project, Project, true) == 0)
                                {
                                    IncomingComments.Enqueue(Comment);
                                }
                                LastCommentId = Math.Max(LastCommentId, Comment.Id);
                            }
                        }
                    }
                    using (SqlCommand Command = new SqlCommand("SELECT Id, ChangeNumber, BuildType, Result, Url, Project FROM dbo.CIS WHERE Id > @param1", Connection))
                    {
                        Command.Parameters.AddWithValue("@param1", LastBuildId);
                        using (SqlDataReader Reader = Command.ExecuteReader())
                        {
                            while (Reader.Read())
                            {
                                BuildData Build = new BuildData();
                                Build.Id           = Reader.GetInt32(0);
                                Build.ChangeNumber = Reader.GetInt32(1);
                                Build.BuildType    = Reader.GetString(2).TrimEnd();
                                if (Enum.TryParse(Reader.GetString(3).TrimEnd(), true, out Build.Result))
                                {
                                    Build.Url     = Reader.GetString(4);
                                    Build.Project = Reader.IsDBNull(5)? null : Reader.GetString(5);
                                    if (Build.Project == null || String.Compare(Build.Project, Project, true) == 0)
                                    {
                                        IncomingBuilds.Enqueue(Build);
                                    }
                                }
                                LastBuildId = Math.Max(LastBuildId, Build.Id);
                            }
                        }
                    }
                }
                LastStatusMessage = String.Format("Last update took {0}ms", Timer.ElapsedMilliseconds);
                LogWriter.WriteLine("Done in {0}ms.", Timer.ElapsedMilliseconds);
                return(true);
            }
            catch (Exception Ex)
            {
                LogWriter.WriteException(Ex, "Failed with exception.");
                LastStatusMessage = String.Format("Last update failed: ({0})", Ex.ToString());
                return(false);
            }
        }
 public EternityRing(IXivSheet sheet, Ex.Relational.IRelationalRow sourceRow) : base(sheet, sourceRow) { }
        private void cboSelectToolCategory_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //setting local variables
            int    intSelectedIndex;
            string strToolCategory;
            int    intRecordsReturned;
            string strToolID;
            int    intToolID;
            bool   blnToolFound;

            try
            {
                intSelectedIndex = cboSelectToolCategory.SelectedIndex - 1;

                if (intSelectedIndex > -1)
                {
                    MainWindow.gintCategoryID = TheFindSortedToolCategoryDataSet.FindSortedToolCategory[intSelectedIndex].CategoryID;
                    strToolCategory           = TheFindSortedToolCategoryDataSet.FindSortedToolCategory[intSelectedIndex].ToolCategory;

                    TheFindToolIDByCategoryDataSet = TheToolIDClass.FindToolIDByCategory(strToolCategory);

                    intRecordsReturned = TheFindToolIDByCategoryDataSet.FindToolIDByCategory.Rows.Count;

                    if (intRecordsReturned > 0)
                    {
                        blnToolFound = true;

                        while (blnToolFound == true)
                        {
                            strToolID = TheFindToolIDByCategoryDataSet.FindToolIDByCategory[0].ToolID;

                            intToolID = Convert.ToInt32(strToolID);

                            intToolID++;

                            strToolID = Convert.ToString(intToolID);

                            TheFindActiveToolByToolIDDataSet = TheToolsClass.FindActiveToolByToolID(strToolID);

                            intRecordsReturned = TheFindActiveToolByToolIDDataSet.FindActiveToolByToolID.Rows.Count;

                            if (intRecordsReturned < 1)
                            {
                                blnToolFound = false;
                            }

                            txtToolID.Text      = strToolID;
                            gintTransactionID   = TheFindToolIDByCategoryDataSet.FindToolIDByCategory[0].TransactionID;
                            gblnNewToolCategory = false;
                        }
                    }
                    else
                    {
                        txtToolID.Text = "None Found";
                        TheMessagesClass.InformationMessage("There is not a Tool ID for this Tool in the Database, Please Contact IT");
                        gblnNewToolCategory = true;
                    }
                }
            }
            catch (Exception Ex)
            {
                TheEventLogClass.InsertEventLogEntry(DateTime.Now, "New Blue Jay ERP // Add New Tool // Tool Category Selection Changed " + Ex.Message);

                TheSendEmailClass.SendEventLog(Ex.ToString());

                TheMessagesClass.ErrorMessage(Ex.ToString());
            }
        }
Exemple #42
0
        public override JobStatus Start(JobParams JP, out string ErrorMsg)
        {
            List <AdvisorVo>           adviserVoList         = new List <AdvisorVo>();
            AdviserMaintenanceBo       adviserMaintenanceBo  = new AdviserMaintenanceBo();
            CustomerPortfolioBo        customerPortfolioBo   = new CustomerPortfolioBo();
            PortfolioBo                portfolioBo           = new PortfolioBo();
            List <CustomerPortfolioVo> customerPortfolioList = new List <CustomerPortfolioVo>();
            List <MFPortfolioVo>       mfPortfolioList       = new List <MFPortfolioVo>();
            List <EQPortfolioVo>       eqPortfolioList       = new List <EQPortfolioVo>();
            List <int> customerList_MF   = new List <int>();
            List <int> customerList_EQ   = new List <int>();
            DataSet    dsMFValuationDate = new DataSet();
            DataSet    dsEQValuationDate = new DataSet();
            DateTime   tradeDate         = new DateTime();
            int        LogId             = 0;

            // if (DateTime.Now.TimeOfDay.Hours < 1)
            tradeDate = DateTime.Today.AddDays(-1);
            // else
            //  tradeDate = DateTime.Today;

            DateTime MFValuationDate;
            DateTime EQValuationDate;

            adviserVoList = adviserMaintenanceBo.GetAdviserList();

            for (int i = 0; i < adviserVoList.Count; i++)
            {
                dsMFValuationDate = customerPortfolioBo.GetAdviserValuationDate(adviserVoList[i].advisorId, "MF", tradeDate.Month, tradeDate.Year);
                dsEQValuationDate = customerPortfolioBo.GetAdviserValuationDate(adviserVoList[i].advisorId, "EQ", tradeDate.Month, tradeDate.Year);
                customerList_MF   = customerPortfolioBo.GetAdviserCustomerList_MF(adviserVoList[i].advisorId);
                customerList_EQ   = customerPortfolioBo.GetAdviserCustomerList_EQ(adviserVoList[i].advisorId);
                foreach (DataRow drMF in dsMFValuationDate.Tables[0].Rows)
                {
                    MFValuationDate = DateTime.Parse(drMF["WTD_Date"].ToString());
                    if (MFValuationDate != DateTime.Today)
                    {
                        if (drMF["STAT"].ToString() == "Pending. Changes Found")
                        {
                            customerPortfolioBo.DeleteAdviserEODLog(adviserVoList[i].advisorId, "MF", MFValuationDate, 0);
                        }
                        if (drMF["STAT"].ToString() != "Completed")
                        {
                            if (DateTime.Compare(MFValuationDate, DateTime.Today) <= 0)
                            {
                                if (customerList_MF != null && customerList_MF.Count != 0)
                                {
                                    LogId = CreateAdviserEODLog("MF", MFValuationDate, adviserVoList[i].advisorId);
                                    for (int j = 0; j < customerList_MF.Count; j++)
                                    {
                                        customerPortfolioList = portfolioBo.GetCustomerPortfolios(customerList_MF[j]);
                                        customerPortfolioBo.DeleteMutualFundNetPosition(customerList_MF[j], MFValuationDate);
                                        if (customerPortfolioList != null && customerPortfolioList.Count != 0)
                                        {
                                            for (int k = 0; k < customerPortfolioList.Count; k++)
                                            {
                                                try
                                                {
                                                    mfPortfolioList = customerPortfolioBo.GetCustomerMFPortfolio(customerList_MF[j], customerPortfolioList[k].PortfolioId, MFValuationDate, "", "", "");
                                                }
                                                catch (Exception ex)
                                                {
                                                    Console.WriteLine("Exception: " + ex.ToString());
                                                }
                                                if (mfPortfolioList != null && mfPortfolioList.Count != 0)
                                                {
                                                    try
                                                    {
                                                        customerPortfolioBo.AddMutualFundNetPosition(mfPortfolioList, adviserVoList[i].UserId);
                                                    }
                                                    catch (Exception Ex)
                                                    {
                                                        Console.WriteLine("Exception: " + Ex.ToString());
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    UpdateAdviserEODLog("MF", 1, LogId);
                                }
                            }
                        }
                    }
                }

                foreach (DataRow drEQ in dsEQValuationDate.Tables[0].Rows)
                {
                    EQValuationDate = DateTime.Parse(drEQ["WTD_Date"].ToString());
                    if (EQValuationDate != DateTime.Today)
                    {
                        if (drEQ["STAT"].ToString() == "Pending. Changes Found")
                        {
                            customerPortfolioBo.DeleteAdviserEODLog(adviserVoList[i].advisorId, "EQ", EQValuationDate, 0);
                        }
                        if (drEQ["STAT"].ToString() != "Completed")
                        {
                            if (DateTime.Compare(EQValuationDate, DateTime.Today) <= 0)
                            {
                                if (customerList_EQ != null && customerList_EQ.Count != 0)
                                {
                                    LogId = CreateAdviserEODLog("EQ", EQValuationDate, adviserVoList[i].advisorId);
                                    for (int j = 0; j < customerList_EQ.Count; j++)
                                    {
                                        customerPortfolioList = portfolioBo.GetCustomerPortfolios(customerList_EQ[j]);
                                        customerPortfolioBo.DeleteEquityNetPosition(customerList_EQ[j], EQValuationDate);
                                        if (customerPortfolioList != null && customerPortfolioList.Count != 0)
                                        {
                                            for (int k = 0; k < customerPortfolioList.Count; k++)
                                            {
                                                try
                                                {
                                                    eqPortfolioList = customerPortfolioBo.GetCustomerEquityPortfolio(customerList_EQ[j], customerPortfolioList[k].PortfolioId, EQValuationDate, "");
                                                }
                                                catch (Exception Ex)
                                                {
                                                    Console.WriteLine("Exception: " + Ex.ToString());
                                                }
                                                if (eqPortfolioList != null && eqPortfolioList.Count != 0)
                                                {
                                                    try
                                                    {
                                                        customerPortfolioBo.AddEquityNetPosition(eqPortfolioList, adviserVoList[i].UserId);
                                                    }
                                                    catch (Exception Ex)
                                                    {
                                                        Console.WriteLine("Exception: " + Ex.ToString());
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    UpdateAdviserEODLog("EQ", 1, LogId);
                                }
                            }
                        }
                    }
                }
            }

            ErrorMsg = "";
            return(JobStatus.SuccessFull);
        }
Exemple #43
0
        public JsonResult CartPay(string regName, string regPhone, string regMail, string regAddress, string regNote
                                  , string regNameOther, string regPhoneOther, string regMailOther, string regAddressOther
                                  , string voucher, string option)
        {
            AjaxResultModel Result = new AjaxResultModel();

            try
            {
                List <CartModel> list = new List <CartModel>();
                if (Session[AppSession.AppSessionKeys.USER_CART] != null)
                {
                    list = (List <CartModel>)Session[AppSession.AppSessionKeys.USER_CART];
                }

                string xmlOrder;
                xmlOrder = "<Order>"
                           + "<OrderName>" + regName + "</OrderName>"
                           + "<OrderPhone>" + regPhone + "</OrderPhone>"
                           + "<OrderMail>" + regMail + "</OrderMail>"
                           + "<OrderAddress>" + regAddress + "</OrderAddress>"
                           + "<OrgerNote>" + regNote + "</OrgerNote>"

                           + "<OrderNameOther>" + regNameOther + "</OrderNameOther>"
                           + "<OrderPhoneOther>" + regPhoneOther + "</OrderPhoneOther>"
                           + "<OrderMailOther>" + regMailOther + "</OrderMailOther>"
                           + "<OrderAddressOther>" + regAddressOther + "</OrderAddressOther>"

                           //+ "<OrderDateCreate>" + DateTime.Now + "</OrderDateCreate>"
                           //+ "<OrderTotal>" + 0 + "</OrderTotal>"
                           + "<OrderVoucher>" + voucher + "</OrderVoucher>"
                           + "<OrderOption>" + option + "</OrderOption>"
                           //+ "<OrderState>" + "A" + "</OrderState>"
                           + "</Order>";
                string xmlDetail;
                xmlDetail = "<row>";
                foreach (CartModel item in list)
                {
                    xmlDetail += "<detail>"
                                 + "<ProductCode>" + item.ProductCode + "</ProductCode>"
                                 + "<Quantity>" + item.Quantity + "</Quantity>"
                                 + "</detail>";
                }
                xmlDetail += "</row>";
                string orderCode = "";
                if (Orders_Service.InsertOrder(xmlOrder, xmlDetail, out orderCode))
                {
                    Session[AppSession.AppSessionKeys.USER_CART] = null;
                    Result.Code   = 000;
                    Result.Result = orderCode;
                }
                else
                {
                    Result.Code   = 001;
                    Result.Result = "Không thành công";
                }
            }
            catch (Exception Ex)
            {
                Result.Code   = 2000;
                Result.Result = "Có lỗi xảy ra. Vui lòng thử lại sau hoặc liên hệ với người quản trị.";
                CORE.Helpers.IOHelper.WriteLog(StartUpPath, IpAddress, "UpdatePassword :", Ex.Message, Ex.ToString());
            }

            return(Json(Result));
        }