Ejemplo n.º 1
0
        // This method is called by the timer delegate.
        private void TimerCallBack(Object stateInfo)
        {
            JobWatcher jobWatcher = (JobWatcher)stateInfo;

            jobWatcher.Timeout = true;
            jobWatcher.AutoResetEvent.Set();
        }
Ejemplo n.º 2
0
        private void WatcherErrors_Created(object sender, FileSystemEventArgs e)
        {
            FileSystemWatcher watcher    = (FileSystemWatcher)sender;
            JobWatcher        jobWatcher = _watchers.Where(w => w.Errors == watcher).FirstOrDefault();

            if (jobWatcher != null)
            {
                jobWatcher.Error = true;
                jobWatcher.AutoResetEvent.Set();
            }
        }
Ejemplo n.º 3
0
        private void WatcherProcessed_Created(object sender, FileSystemEventArgs e)
        {
            FileSystemWatcher watcher    = (FileSystemWatcher)sender;
            JobWatcher        jobWatcher = _watchers.Where(w => w.Processed == watcher).FirstOrDefault();

            if (jobWatcher != null)
            {
                if (jobWatcher.PdfFileName == e.Name)
                {
                    jobWatcher.AutoResetEvent.Set();
                }
            }
        }
Ejemplo n.º 4
0
        public string PrintReport(int userId, int workspaceId, int fpId, int subsystemId, string reportName, string[] paramTypes, string[] paramValues, out string exceptionStr)
        {
            exceptionStr = "";
            if (string.IsNullOrEmpty(QueuePath))
            {
                exceptionStr = "0"; // "مسیر چاپ تعیین نشده است.";
                return(null);
            }

            if (paramTypes.Length != paramValues.Length)
            {
                exceptionStr = $"paramValues count ({paramValues.Length}) <> paramTypes count ({paramTypes.Length})";
                return(null);
            }

            try
            {
                List <string> lines = new List <string>();

                /*
                 ****************************************************** FILE FORMAT STARTING FROM LINE 1:
                 * LINE 1: UserId
                 * LINE 2: WsId
                 * LINE 3: FpId
                 * LINE 4:Output File Path (c:\test\1.pdf) //unused - you can put anything here
                 * LINE 5:Tadbir Report Name //If this string contains $ it means it is a QuickReport and it's format is: QueryName$PrintTitle$HiddenColumnsCount$ColumnWidth1$ColumnWidth2$...$ColumnWidthN
                 * LINE 6:Parameters Count:
                 * LINE 7: Param1... (For Quick Print => Param1 = ParamVal$ParamText$ParamIsHidden$ParamWidth)
                 * LINE 7 + (Parameters Count) : ParamN
                 * LINE 1 + 7 + (Parameters Count): SubSystem
                 * LINE 2 + 7 + (Parameters Count): Width(1200 - 4800) //unused - you can put anything here
                 * LINE 3 + 7 + (Parameters Count): Height(1600 - 6400) //unused - you can put anything here
                 * LINE 4 + 7 + (Parameters Count): C:\Program Files(x86)\PDFCreator\Images2PDF\Images2PDFC.exe //unused - you can put anything here
                 ****************************************************** THE ABOVE WAS THE LAST LINE
                 */


                lines.Add(userId.ToString());                     //LINE 1
                lines.Add(workspaceId.ToString());                //LINE 2
                lines.Add(fpId.ToString());                       //LINE 3
                lines.Add("NOT EMPTY LINE");                      //LINE 4
                lines.Add(_codepageService.toTadbir(reportName)); //LINE 5
                lines.Add(paramValues.Length.ToString());         //LINE 6

                for (int i = 0; i < paramValues.Length; i++)
                {
                    if (paramTypes[i] == "TEXT")
                    {
                        lines.Add(_codepageService.toTadbir(paramValues[i]));
                    }
                    else
                    if (paramTypes[i] == "DATE")
                    {
                        string   paramValue = paramValues[i];
                        string[] parts      = paramValue.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
                        if (parts.Length == 3)
                        {
                            int year  = int.Parse(parts[0]);
                            int month = int.Parse(parts[1]);
                            int day   = int.Parse(parts[2]);

                            paramValue = String.Format("{0:D2}/{1:D2}/{2:D4}", month, day, year);
                        }
                        lines.Add(paramValue);
                    }
                    else
                    {
                        lines.Add(paramValues[i]);
                    }
                }

                lines.Add(subsystemId.ToString()); //LINE 1 + 7 + (Parameters Count): SubSystem

                //last three lines:
                lines.Add("NOT EMPTY LINE");
                lines.Add("NOT EMPTY LINE");
                lines.Add("NOT EMPTY LINE");

                string queueTextFileName = GenerateJobFileName() + ".txt";


                JobWatcher jobWatcher =
                    (
                        new JobWatcher()
                {
                    PdfFileName = Path.GetFileNameWithoutExtension(queueTextFileName) + ".pdf",
                    Processed = new FileSystemWatcher(ProcessedPath, "*.pdf"),
                    Errors = new FileSystemWatcher(ErrorsPath, "*.txt"),
                    AutoResetEvent = new AutoResetEvent(false),
                    Error = false,
                    Timeout = false
                }
                    );

                jobWatcher.Timer = new Timer(TimerCallBack, jobWatcher, 30000, 1000);

                jobWatcher.Processed.Created += WatcherProcessed_Created;
                jobWatcher.Processed.Renamed += Processed_Renamed;
                jobWatcher.Errors.Created    += WatcherErrors_Created;

                jobWatcher.Processed.EnableRaisingEvents = true;
                jobWatcher.Errors.EnableRaisingEvents    = true;
                _watchers.Add(jobWatcher);

                var enc1256 = Encoding.GetEncoding(1256);// CodePagesEncodingProvider.Instance.GetEncoding("windows-1256");
                using (FileStream fs = new FileStream(queueTextFileName, FileMode.Create, FileAccess.Write, FileShare.None, 32768, FileOptions.WriteThrough))
                {
                    using (StreamWriter sw = new StreamWriter(fs, enc1256))
                    {
                        foreach (string line in lines)
                        {
                            sw.WriteLine(line);
                        }
                    }
                }
                jobWatcher.AutoResetEvent.WaitOne();

                jobWatcher.Processed.Dispose();
                jobWatcher.Errors.Dispose();
                jobWatcher.Timer.Dispose();
                _watchers.Remove(jobWatcher);

                if (jobWatcher.Timeout)
                {
                    exceptionStr = "-1";  //"لطفا مطمئن شوید برنامه TadRepPdf روی سرور در حال اجراست.";
                    return(null);
                }

                if (jobWatcher.Error)
                {
                    exceptionStr = "-2";  //"برنامه چاپ سرور روی چاپ این فرم خطا داده است.";
                    return(null);
                }

                Task.Delay(TadbirPrintAccessFileDelay).Wait(); //برای جلوگیری از تداخل با TadRepPdf

                return(Path.Combine(ProcessedPath, Path.GetFileNameWithoutExtension(queueTextFileName) + ".pdf"));
            }
            catch (Exception exp)
            {
                exceptionStr = "-3"; //exp.ToString();
                return(null);
            }
        }
Ejemplo n.º 5
0
        /*
         *  Hi Frederic,
         *
         *  Per approval by Eric Lang, GM, your lab account  MFALA, has been set up.
         *
         *  Your permissions have been setup as requested. We've granted you smart card
         *  bypass access to http://Codesignaoc and permissions to sign with the four most
         *  commonly used Authenticode certificates
         *
         #2 Microsoft Corporation (Internal Use Only)
         #23 Microsoft Corporation (MD5 MS Root)
         #98 Microsoft Corporation ClickOnce Signing
         #72 Microsoft Shared Libraries (.NET 2.0).
         *
         *  On each computer you would submit, approve or search job from, you must follow the 3 steps outlined outline below.
         *
         *      1) You need to have .NET Framework 2.0 or higher installed on your machine.
         *         (Already installed on for Vista users.)
         *         It can be found at \\products\public\Products\Developers\NET Micro Framework SDK 2.0.
         *
         *      2) You will need to install the Codesign.Object which can be found in:
         \\CSNEOVLT.dns.corp.microsoft.com\Public\Submitter Tool for Download\SubmitterV2.3_.NET2.0 .
         *         Copy Codesign.Submitter.msi to your local drive and then install it from there.
         *
         *      3) SmartCard - The CodeSign process is an important piece of protecting our corporate assets,
         *         therefore use of this site and related activities are secured appropriately.
         *         Users that wish to use code sign's website services must have permissions granted to
         *         do so and use a corporate issued SmartCard as a means of verifying their identity.
         *
         *  SMARTCARDS ARE CREATED AND DISTRIBUTED BY CORPORATE SECURITY - PLEASE GOTO http://csamweb/smartcards/default.asp TO OBTAIN A SMARTCARD.
         *
         *  Verify your installations, you can go the http://codesignaoc and click on the  Diagnostics  tab.
         *  There you will find 2 buttons:  Verify Installation  and  Verify Smart Card .
         *  Please click on both of them.  If you get the "Good to go!" message on both of them,
         *  then you are able to fully access the site.  If you get an error, please take a screen
         *  shot of the error and e-mail it to [email protected]. We will troubleshoot your installation.
         *
         *  You will need two FTEs with codesign accounts to act as approvers in the codesugn submission stage.
         *
         *  We will send any updates about codesign system to SIGNNEWS. Please join this autogroup if you have not already done so.
         *
         *  http://AutoGroup/JoinGroup.asp?GroupAlias=signnews
         *
         *  Please let us know if you need any further assistance.
         *
         *  Thanks,
         *  DBRICK
         *  Release Technical Solutions Centre
         +1 (425) 7032736 X32736
         *  [email protected]
         *  -Helping Our Customers Reach Theirs
         */
        #endregion

        private static bool SubmitJob(string unsignedDirectory, string signedDirectory)
        {
            // use env var so it is dynamic for the machine running this build to help prevent
            // accidentally leaving this setting enabled in a code check-in.
            var fakeSign = Environment.GetEnvironmentVariable("DEVFAKESIGN") != null;

            CODESIGN.Submitter.Job job = null;
            try
            {
                //Initialize the Codesign.Submitter object
                //"Codesign" represents the server - static variable do not change
                //9556 represents the port - constant value do not change
                job = CODESIGN.Submitter.Job.Initialize("codesign.gtm.microsoft.com", 9556, true);

                // Sets the Partial return flag option.
                // False - If any files fail signing you will not get any files back.
                // True - Only retrieve successfully signed files.
                job.IsAllowReturnPartial = false;               // default is false

                // Set this flag true to ensure that the file types you are submitting can be signed
                // with the selected certificates, false to let the system try (bypass filetype
                // validation). This is particularly useful if your file type is new and unknown to
                // the system.
                job.IsRequireVerifyCerts = false;               // default is false

                // Set this flag true to enforce hash checking during copies as well as staging; this
                // isn’t normally necessary but is provided for network integrity. It does slow copy
                // performance significantly
                job.IsRequireHash = false;                              // default is false

                // This is reference information that can be displayed or used in searches
                job.Description = m_Info.jobDescription;
                job.Keywords    = m_Info.jobKeywords;

                // This call selects a certificate from the ones allowed for this user
                // You must have permissions to the requested cert or this call throws an exception
                if (!fakeSign)
                {
                    job.SelectCertificate(m_Info.certificate);
                }

                // These calls add notification subscriptions to the job. A number of others are
                // available, these are the standard ones.
                job.SetNotification(
                    job.Submitter,
                    new CODESIGN.NotificationEventTypeEnum[]
                {
                    CODESIGN.NotificationEventTypeEnum.JobCompletionFailure,
                    CODESIGN.NotificationEventTypeEnum.JobCompletionSuccess,
                    CODESIGN.NotificationEventTypeEnum.JobVirusScanFailure
                });

                foreach (string approver in m_Info.Approvers)
                {
                    job.AddApprover(approver);
                }

                //This will remove all notifications
                job.ClearTargets();  //Clears notification for all but submitter

                // This call adds an entire directory tree to the job, duplicating its structure in
                // the submission share and making all metadata the same for each file.
                job.AddFile(
                    unsignedDirectory + "Client",
                    m_Info.displayName,
                    m_Info.displayURL,
                    CODESIGN.JavaPermissionsTypeEnum.None);

                job.AddFile(
                    unsignedDirectory + "Server",
                    m_Info.displayName,
                    m_Info.displayURL,
                    CODESIGN.JavaPermissionsTypeEnum.None);

                // This call sends the job to the back end for processing
                if (!fakeSign)
                {
                    job.Send();
                }
                else
                {
                    m_CallingTask.Log.LogMessage("!!!!**** DEVFAKESIGN is set, skipping submit and just copying files for development testing ****!!!!");
                    var userTemp           = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Temp");
                    var fakeCompletionPath = Path.Combine(userTemp, Path.GetRandomFileName());
                    Directory.CreateDirectory(fakeCompletionPath);
                    job.JobCompletionPath = fakeCompletionPath;
                    job.JobNumber         = "DEVFAKESIGN";
                    CopyTree(unsignedDirectory, fakeCompletionPath);
                }

                // This call displays the job number, assigned during the send process
                m_CallingTask.Log.LogMessage("Job Number is: {0}", job.JobNumber);
                m_CallingTask.Log.LogMessage("Job Completion Path is: {0}", job.JobCompletionPath);

                JobWatcher jw = new JobWatcher();
                if (!fakeSign)
                {
                    // These calls optionally wait till the job is finished
                    // WARNING: this completely block execution for the specified timespan
                    int Milliseconds = -1;      // -1: wait forever
                    jw.Watch(job, Milliseconds);
                    //jw.Watch(job);		// you can also call the Watch method this way and wait forever
                }

                // Now we're done, so display any errors or warnings (in case we are in non-event mode)
                bool retVal = true;
                m_CallingTask.Log.LogMessage(
                    "Job is finished, Success={0}  Signed={1}  BytesSigned={2}",
                    fakeSign ? true : jw.IsSuccess,
                    fakeSign ? 0 : jw.TotalSigned,
                    fakeSign ? 0 : jw.TotalByteSize);

                if (!fakeSign)
                {
                    if (jw.IsPartial)
                    {
                        m_CallingTask.Log.LogError("Partial Success: {0}", jw.IsPartial);
                        retVal = false;
                    }

                    foreach (JobError je in job.ErrorList.Values)
                    {
                        m_CallingTask.Log.LogError(je.Number + ":" + je.Description + " {" + je.Explanation + "}");
                        retVal = false;
                    }
                    foreach (JobFile jf in jw.FailedFileList.Values)
                    {
                        m_CallingTask.Log.LogError("Failed -> " + jf.FileFullPath);
                        retVal = false;
                    }
                }
                m_CallingTask.Log.LogMessage("Copying files from codesign server");
                var completionPath = fakeSign ? job.JobCompletionPath : jw.CompletionPath;
                CopyTree(completionPath, signedDirectory);

                return(retVal);
            }
            catch (Exception exc)
            {
                m_CallingTask.Log.LogError("Job submission failed: {0}", CODESIGN.EventLogProxy.GetMessage(exc));
                foreach (JobError je in job.ErrorList.Values)
                {
                    m_CallingTask.Log.LogError(je.Number + ":" + je.Description + " {" + je.Explanation + "}");
                }

                return(false);
            }
        }
Ejemplo n.º 6
0
 public static void StartJobWatcher() => JobWatcher.Start();
Ejemplo n.º 7
0
        /*
            Hi Frederic,

            Per approval by Eric Lang, GM, your lab account  MFALA, has been set up.

            Your permissions have been setup as requested. We've granted you smart card 
            bypass access to http://Codesignaoc and permissions to sign with the four most 
            commonly used Authenticode certificates 
                
                #2 Microsoft Corporation (Internal Use Only)  
                #23 Microsoft Corporation (MD5 MS Root) 
                #98 Microsoft Corporation ClickOnce Signing 
                #72 Microsoft Shared Libraries (.NET 2.0).

            On each computer you would submit, approve or search job from, you must follow the 3 steps outlined outline below.

                1) You need to have .NET Framework 2.0 or higher installed on your machine. 
                   (Already installed on for Vista users.)  
                   It can be found at \\products\public\Products\Developers\NET Micro Framework SDK 2.0. 

                2) You will need to install the Codesign.Object which can be found in: 
                   \\CSNEOVLT.dns.corp.microsoft.com\Public\Submitter Tool for Download\SubmitterV2.3_.NET2.0 . 
                   Copy Codesign.Submitter.msi to your local drive and then install it from there. 

                3) SmartCard - The CodeSign process is an important piece of protecting our corporate assets, 
                   therefore use of this site and related activities are secured appropriately. 
                   Users that wish to use code sign's website services must have permissions granted to
                   do so and use a corporate issued SmartCard as a means of verifying their identity.

            SMARTCARDS ARE CREATED AND DISTRIBUTED BY CORPORATE SECURITY - PLEASE GOTO http://csamweb/smartcards/default.asp TO OBTAIN A SMARTCARD. 

            Verify your installations, you can go the http://codesignaoc and click on the  Diagnostics  tab.  
            There you will find 2 buttons:  Verify Installation  and  Verify Smart Card . 
            Please click on both of them.  If you get the "Good to go!" message on both of them, 
            then you are able to fully access the site.  If you get an error, please take a screen 
            shot of the error and e-mail it to [email protected]. We will troubleshoot your installation.

            You will need two FTEs with codesign accounts to act as approvers in the codesugn submission stage. 

            We will send any updates about codesign system to SIGNNEWS. Please join this autogroup if you have not already done so.

            http://AutoGroup/JoinGroup.asp?GroupAlias=signnews

            Please let us know if you need any further assistance.

            Thanks,
            DBRICK
            Release Technical Solutions Centre
            +1 (425) 7032736 X32736
            [email protected]
            -Helping Our Customers Reach Theirs
        */
        #endregion

        private static bool SubmitJob(string unsignedDirectory, string signedDirectory)
        {
            // use env var so it is dynamic for the machine running this build to help prevent
            // accidentally leaving this setting enabled in a code check-in.
            var fakeSign = Environment.GetEnvironmentVariable("DEVFAKESIGN") != null;

            CODESIGN.Submitter.Job job = null;
            try
            {
                //Initialize the Codesign.Submitter object
                //"Codesign" represents the server - static variable do not change
                //9556 represents the port - constant value do not change
                job = CODESIGN.Submitter.Job.Initialize("codesign.gtm.microsoft.com", 9556, true);

                // Sets the Partial return flag option.
                // False - If any files fail signing you will not get any files back.
                // True - Only retrieve successfully signed files.
                job.IsAllowReturnPartial = false;		// default is false

                // Set this flag true to ensure that the file types you are submitting can be signed
                // with the selected certificates, false to let the system try (bypass filetype 
                // validation). This is particularly useful if your file type is new and unknown to
                // the system.
                job.IsRequireVerifyCerts = false;		// default is false 

                // Set this flag true to enforce hash checking during copies as well as staging; this
                // isn’t normally necessary but is provided for network integrity. It does slow copy
                // performance significantly
                job.IsRequireHash = false;				// default is false

                // This is reference information that can be displayed or used in searches
                job.Description = m_Info.jobDescription;
                job.Keywords = m_Info.jobKeywords;

                // This call selects a certificate from the ones allowed for this user
                // You must have permissions to the requested cert or this call throws an exception
                if(!fakeSign)
                    job.SelectCertificate(m_Info.certificate);	

                // These calls add notification subscriptions to the job. A number of others are 
                // available, these are the standard ones.
                job.SetNotification(
                    job.Submitter, 
                    new CODESIGN.NotificationEventTypeEnum[] 
                        { 
                            CODESIGN.NotificationEventTypeEnum.JobCompletionFailure, 
                            CODESIGN.NotificationEventTypeEnum.JobCompletionSuccess, 
                            CODESIGN.NotificationEventTypeEnum.JobVirusScanFailure 
                        });

                foreach (string approver in m_Info.Approvers)
                {
                    job.AddApprover(approver);
                }
                
                //This will remove all notifications
                job.ClearTargets();  //Clears notification for all but submitter

                // This call adds an entire directory tree to the job, duplicating its structure in
                // the submission share and making all metadata the same for each file.
                job.AddFile(
                    unsignedDirectory + "Client", 
                    m_Info.displayName, 
                    m_Info.displayURL, 
                    CODESIGN.JavaPermissionsTypeEnum.None);
                
                job.AddFile(
                    unsignedDirectory + "Server",
                    m_Info.displayName,
                    m_Info.displayURL,
                    CODESIGN.JavaPermissionsTypeEnum.None);

                // This call sends the job to the back end for processing
                if (!fakeSign)
                    job.Send();
                else
                {
                    m_CallingTask.Log.LogMessage("!!!!**** DEVFAKESIGN is set, skipping submit and just copying files for development testing ****!!!!");
                    var userTemp = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Temp");
                    var fakeCompletionPath = Path.Combine(userTemp, Path.GetRandomFileName());
                    Directory.CreateDirectory(fakeCompletionPath);
                    job.JobCompletionPath = fakeCompletionPath;
                    job.JobNumber = "DEVFAKESIGN";
                    CopyTree(unsignedDirectory, fakeCompletionPath );
                }

                // This call displays the job number, assigned during the send process
                m_CallingTask.Log.LogMessage("Job Number is: {0}", job.JobNumber);
                m_CallingTask.Log.LogMessage("Job Completion Path is: {0}", job.JobCompletionPath);

                JobWatcher jw = new JobWatcher();
                if (!fakeSign)
                {
                    // These calls optionally wait till the job is finished
                    // WARNING: this completely block execution for the specified timespan
                    int Milliseconds = -1;	// -1: wait forever
                    jw.Watch(job, Milliseconds);
                    //jw.Watch(job);		// you can also call the Watch method this way and wait forever
                }

                // Now we're done, so display any errors or warnings (in case we are in non-event mode)
                bool retVal = true;
                m_CallingTask.Log.LogMessage(
                    "Job is finished, Success={0}  Signed={1}  BytesSigned={2}", 
                    fakeSign ? true : jw.IsSuccess, 
                    fakeSign ? 0 : jw.TotalSigned, 
                    fakeSign ? 0 : jw.TotalByteSize);

                if (!fakeSign)
                {
                    if (jw.IsPartial)
                    {
                        m_CallingTask.Log.LogError("Partial Success: {0}", jw.IsPartial);
                        retVal = false;
                    }

                    foreach (JobError je in job.ErrorList.Values)
                    {
                        m_CallingTask.Log.LogError(je.Number + ":" + je.Description + " {" + je.Explanation + "}");
                        retVal = false;
                    }
                    foreach (JobFile jf in jw.FailedFileList.Values)
                    {
                        m_CallingTask.Log.LogError("Failed -> " + jf.FileFullPath);
                        retVal = false;
                    }
                }
                m_CallingTask.Log.LogMessage("Copying files from codesign server");
                var completionPath = fakeSign ? job.JobCompletionPath : jw.CompletionPath;
                CopyTree( completionPath, signedDirectory);

                return retVal;
            }
            catch (Exception exc)
            {
                m_CallingTask.Log.LogError("Job submission failed: {0}", CODESIGN.EventLogProxy.GetMessage(exc));
                foreach (JobError je in job.ErrorList.Values)
                {
                    m_CallingTask.Log.LogError(je.Number + ":" + je.Description + " {" + je.Explanation + "}");
                }

                return false;
            }

        }
 public IDPJobManagerStarter UsingJobWatcher(JobWatcher jobWatcher)
 {
     this.jobWatcher = jobWatcher;
     return(this);
 }
Ejemplo n.º 9
0
 public WebServer(JobWatcher jobWatcher)
 {
     Ensure.Requires <ArgumentNullException>(jobWatcher != null, "`jobWatcher` should not be null.");
     jobWatcher.OnChangeCompleted = Reload;
     this.jobWatcher = jobWatcher;
 }