示例#1
0
            /// <summary>
            /// the command that is run and retried for actually
            /// obtaining the lock </summary>
            /// <returns> if the command was successful or not </returns>
            public async Task <bool> execute()
            {
                do
                {
                    if (outerInstance.Id == null)
                    {
                        long   sessionId = outerInstance.zookeeper.getSessionId();
                        string prefix    = "x-" + sessionId + "-";
                        // lets try look up the current ID if we failed
                        // in the middle of creating the znode
                        await findPrefixInChildren(prefix, outerInstance.zookeeper, outerInstance.dir);

                        outerInstance.idName = new ZNodeName(outerInstance.Id);
                    }
                    if (outerInstance.Id != null)
                    {
                        List <string> names = (await outerInstance.zookeeper.getChildrenAsync(outerInstance.dir).ConfigureAwait(false)).Children;
                        if (names.Count == 0)
                        {
                            LOG.warn("No children in: " + outerInstance.dir + " when we've just " + "created one! Lets recreate it...");
                            // lets force the recreation of the id
                            outerInstance.Id = null;
                        }
                        else
                        {
                            // lets sort them explicitly (though they do seem to come back in order ususally :)
                            SortedSet <ZNodeName> sortedNames = new SortedSet <ZNodeName>();
                            foreach (string name in names)
                            {
                                sortedNames.Add(new ZNodeName(outerInstance.dir + "/" + name));
                            }
                            outerInstance.ownerId = sortedNames.Min.Name;
                            SortedSet <ZNodeName> lessThanMe = new SortedSet <ZNodeName>();

                            foreach (ZNodeName name in sortedNames)
                            {
                                if (outerInstance.idName.CompareTo(name) > 0)
                                {
                                    lessThanMe.Add(name);
                                }
                                else
                                {
                                    break;
                                }
                            }

                            if (lessThanMe.Count > 0)
                            {
                                ZNodeName lastChildName = lessThanMe.Max;
                                outerInstance.lastChildId = lastChildName.Name;
                                if (LOG.isDebugEnabled())
                                {
                                    LOG.debug("watching less than me node: " + outerInstance.lastChildId);
                                }
                                Stat stat = await outerInstance.zookeeper.existsAsync(outerInstance.lastChildId, new LockWatcher(outerInstance));

                                if (stat != null)
                                {
                                    return(false);
                                }
                                LOG.warn("Could not find the" + " stats for less than me: " + lastChildName.Name);
                            }
                            else
                            {
                                if (outerInstance.Owner)
                                {
                                    lock (outerInstance.callback) {
                                        if (outerInstance.callback != null)
                                        {
                                            outerInstance.callback.lockAcquired();
                                        }
                                    }
                                    return(true);
                                }
                            }
                        }
                    }
                } while (outerInstance.Id == null);
                return(false);
            }
示例#2
0
 private void LOG_TextChanged(object sender, EventArgs e)
 {
     LOG.SelectionStart = LOG.Text.Length;
     LOG.ScrollToCaret();
 }
示例#3
0
 private void SendAT_Click(object sender, EventArgs e)
 {
     gsm.sendATCommand(MSG.Text);
     LOG.AppendText(MSG.Text + "\r\n");
     MSG.Text = "";
 }
示例#4
0
        /// <summary>
        /// Use the GDI+ blur effect on the bitmap
        /// </summary>
        /// <param name="destinationBitmap">Bitmap to apply the effect to</param>
        /// <param name="area">Rectangle to apply the blur effect to</param>
        /// <param name="radius">0-255</param>
        /// <param name="expandEdges">bool true if the edges are expanded with the radius</param>
        /// <returns>false if there is no GDI+ available or an exception occured</returns>
        public static bool ApplyBlur(Bitmap destinationBitmap, Rectangle area, int radius, bool expandEdges)
        {
            if (!IsBlurPossible(radius))
            {
                return(false);
            }
            IntPtr hBlurParams = IntPtr.Zero;
            IntPtr hEffect     = IntPtr.Zero;

            try
            {
                // Create a BlurParams struct and set the values
                BlurParams blurParams = new BlurParams();
                blurParams.Radius      = radius;
                blurParams.ExpandEdges = expandEdges;

                // Allocate space in unmanaged memory
                hBlurParams = Marshal.AllocHGlobal(Marshal.SizeOf(blurParams));
                // Copy the structure to the unmanaged memory
                Marshal.StructureToPtr(blurParams, hBlurParams, false);

                // Create the GDI+ BlurEffect, using the Guid
                int status = GdipCreateEffect(BlurEffectGuid, out hEffect);

                // Set the blurParams to the effect
                GdipSetEffectParameters(hEffect, hBlurParams, (uint)Marshal.SizeOf(blurParams));

                // Somewhere it said we can use destinationBitmap.GetHbitmap(), this doesn't work!!
                // Get the private nativeImage property from the Bitmap
                IntPtr hBitmap = GetNativeImage(destinationBitmap);

                // Create a RECT from the Rectangle
                RECT rec = new RECT(area);
                // Apply the effect to the bitmap in the specified area
                GdipBitmapApplyEffect(hBitmap, hEffect, ref rec, false, IntPtr.Zero, 0);

                // Everything worked, return true
                return(true);
            }
            catch (Exception ex)
            {
                LOG.Error("Problem using GdipBitmapApplyEffect: ", ex);
                return(false);
            }
            finally
            {
                try
                {
                    if (hEffect != IntPtr.Zero)
                    {
                        // Delete the effect
                        GdipDeleteEffect(hEffect);
                    }
                    if (hBlurParams != IntPtr.Zero)
                    {
                        // Free the memory
                        Marshal.FreeHGlobal(hBlurParams);
                    }
                }
                catch (Exception ex)
                {
                    LOG.Error("Problem cleaning up ApplyBlur: ", ex);
                }
            }
        }
示例#5
0
        }        // --

        /// <summary>
        /// SELECT FILES TO JOIN
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void join_files_Click(object sender, EventArgs e)
        {
            FILES_TO_JOIN   = FormTools.fileLoadDialog("all", "", true);
            join_files.Text = FILES_TO_JOIN.ToString();
            LOG.log(FILES_TO_JOIN);
        } //--
示例#6
0
 private void OnSessionStopped(object sender, SessionEventArgs e)
 {
     LOG.NoJumpNext();
     LOG.WriteLine(LLV.DEV, $"{DateTime.Now.ToString(TimeUtil.FormatYMDHMSms)} {GetType().Name}({GetTargetRecognizeLanguage()}).OnSessionStopped : {e}");
 }
示例#7
0
        //---------------------------------------------------------------------------
        public void fn_Update(EN_SEQ_STATE iSeqStat)
        {
            //if(SEQ._bRun) return;

            bool bLotOpen  = LOT._bLotOpen;
            bool bDoorOpen = SEQ.fn_IsAnyDoorOpen(true);

            //Set Start.
            m_dSeqSrtTime = TICK._GetTickTime();

            //Get During Seq Time.
            m_dDrngSeqTime = m_dSeqSrtTime - m_dSeqEndTime;


            EN_ERR_KIND iLastErrKind = (EN_ERR_KIND)EPU.fn_GetKind(EPU._nLastErr);


            //Clear. //86400000 == 24:00:00

            //Day Sequence 별 시간 증가.
            //dPMTime : PM Time / dDownTime : 비가동 / dRunTime : 가동


            switch (iSeqStat)
            {
            case EN_SEQ_STATE.RUNNING:
            case EN_SEQ_STATE.RUNWARN:

                DAILY_DATA.dRunTime   += m_dDrngSeqTime;
                DAILY_DATA.dTotalTime += m_dDrngSeqTime;
                break;

            case EN_SEQ_STATE.INIT:
            case EN_SEQ_STATE.WARNING:
            case EN_SEQ_STATE.STOP:
            case EN_SEQ_STATE.IDLE:
                if (bLotOpen)
                {
                    DAILY_DATA.dPMTime += m_dDrngSeqTime;
                }
                else
                {
                    if (bDoorOpen)
                    {
                        DAILY_DATA.dPMTime += m_dDrngSeqTime;
                    }
                    else
                    {
                        DAILY_DATA.dDownTime += m_dDrngSeqTime;
                    }
                }

                DAILY_DATA.dTotalTime += m_dDrngSeqTime;
                break;

            case EN_SEQ_STATE.ERROR:
                if (bLotOpen)
                {
                    DAILY_DATA.dPMTime += m_dDrngSeqTime;
                }
                else
                {
                    if (bDoorOpen)
                    {
                        DAILY_DATA.dPMTime += m_dDrngSeqTime;
                    }
                    else
                    {
                        DAILY_DATA.dDownTime += m_dDrngSeqTime;
                    }
                }

                DAILY_DATA.dErrorTime += m_dDrngSeqTime;
                DAILY_DATA.dTotalTime += m_dDrngSeqTime;
                break;

            default:
                if (bLotOpen)
                {
                    DAILY_DATA.dPMTime += m_dDrngSeqTime;
                }
                else
                {
                    if (bDoorOpen)
                    {
                        DAILY_DATA.dPMTime += m_dDrngSeqTime;
                    }
                    else
                    {
                        DAILY_DATA.dDownTime += m_dDrngSeqTime;
                    }
                }

                DAILY_DATA.dTotalTime += m_dDrngSeqTime;
                break;
            }

            //
            //DAILY_DATA.dTotalTime += m_dDrngSeqTime;


            //Set End Time.
            m_dSeqEndTime = TICK._GetTickTime();

            //Check Changing Time.
            if (!IsChangedDay())
            {
                return;
            }

            string sLog = string.Empty;

            //string sLog = string.Format($"Day Change : MTBI= {CalMTBI(DAILY_DATA.dRunTime, DAILY_DATA.iJamQty)})");
            //fn_WriteLog(sLog);

            sLog = string.Format($"TOTAL TIME : {TICK.ConvTimeTickToStr(SPC.DAILY_DATA.dTotalTime)} / RUN TIME : {TICK.ConvTimeTickToStr(SPC.DAILY_DATA.dRunTime)} / DOWN TIME : {TICK.ConvTimeTickToStr(SPC.DAILY_DATA.dDownTime)} / PM TIME : {TICK.ConvTimeTickToStr(SPC.DAILY_DATA.dPMTime)}");
            fn_WriteLog(sLog);

            //Kill Past Log
            LOG.fn_DeleteOldFile();

            SPC_EFF.ResetData();
            DAILY_DATA.ResetData();
        }
        public Data transform(Data data, XMLCryptoContext context)
        {
            LOG.Log(POILogger.DEBUG, "transform(data,context)");
            LOG.Log(POILogger.DEBUG, "data java type: " + data.Class.Name);
            OctetStreamData octetStreamData = (OctetStreamData)data;

            LOG.Log(POILogger.DEBUG, "URI: " + octetStreamData.URI);
            InputStream octetStream = octetStreamData.OctetStream;

            RelationshipsDocument relDoc;

            try {
                relDoc = RelationshipsDocument.Factory.Parse(octetStream);
            } catch (Exception e) {
                throw new TransformException(e.Message, e);
            }
            LOG.Log(POILogger.DEBUG, "relationships document", relDoc);

            CTRelationships           rels    = relDoc.Relationships;
            List <CTRelationship>     relList = rels.RelationshipList;
            Iterator <CTRelationship> relIter = rels.RelationshipList.Iterator();

            while (relIter.HasNext())
            {
                CTRelationship rel = relIter.Next();

                /*
                 * See: ISO/IEC 29500-2:2008(E) - 13.2.4.24 Relationships Transform
                 * Algorithm.
                 */
                if (!this.sourceIds.Contains(rel.Id))
                {
                    LOG.Log(POILogger.DEBUG, "removing element: " + rel.Id);
                    relIter.Remove();
                }
                else
                {
                    if (!rel.IsSetTargetMode())
                    {
                        rel.TargetMode = (/*setter*/ STTargetMode.INTERNAL);
                    }
                }
            }

            // TODO: remove non element nodes ???
            LOG.Log(POILogger.DEBUG, "# Relationship elements", relList.Size());

            //XmlSort.Sort(rels, new Comparator<XmlCursor>(){
            //    public int Compare(XmlCursor c1, XmlCursor c2) {
            //        String id1 = ((CTRelationship)c1.Object).Id;
            //        String id2 = ((CTRelationship)c2.Object).Id;
            //        return id1.CompareTo(id2);
            //    }
            //});

            try {
                MemoryStream bos = new MemoryStream();
                XmlOptions   xo  = new XmlOptions();
                xo.SaveNoXmlDecl;
                relDoc.Save(bos, xo);
                return(new OctetStreamData(new MemoryStream(bos.ToByteArray())));
            } catch (IOException e) {
                throw new TransformException(e.Message, e);
            }
        }
示例#9
0
 public void NameB(MyToken token)
 {
     LOG.WriteLine(LLV.INF, "NameB OK.");
 }
        /// <summary>
        /// Supply values we can't put as defaults
        /// </summary>
        /// <param name="property">The property to return a default for</param>
        /// <returns>object with the default value for the supplied property</returns>
        public override object GetDefault(string property)
        {
            switch (property)
            {
            case "PluginWhitelist":
            case "PluginBacklist":
                return(new List <string>());

            case "OutputFileAsFullpath":
                if (IniConfig.IsPortable)
                {
                    return(Path.Combine(Application.StartupPath, @"..\..\Documents\Pictures\Greenshots\dummy.png"));
                }
                else
                {
                    return(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "dummy.png"));
                }

            case "OutputFilePath":
                if (IniConfig.IsPortable)
                {
                    string pafOutputFilePath = Path.Combine(Application.StartupPath, @"..\..\Documents\Pictures\Greenshots");
                    if (!Directory.Exists(pafOutputFilePath))
                    {
                        try
                        {
                            Directory.CreateDirectory(pafOutputFilePath);
                            return(pafOutputFilePath);
                        }
                        catch (Exception ex)
                        {
                            LOG.Warn(ex);
                            // Problem creating directory, fallback to Desktop
                        }
                    }
                    else
                    {
                        return(pafOutputFilePath);
                    }
                }
                return(Environment.GetFolderPath(Environment.SpecialFolder.Desktop));

            case "DWMBackgroundColor":
                return(Color.Transparent);

            case "ActiveTitleFixes":
                List <string> activeDefaults = new List <string>();
                activeDefaults.Add("Firefox");
                activeDefaults.Add("IE");
                activeDefaults.Add("Chrome");
                return(activeDefaults);

            case "TitleFixMatcher":
                Dictionary <string, string> matcherDefaults = new Dictionary <string, string>();
                matcherDefaults.Add("Firefox", " - Mozilla Firefox.*");
                matcherDefaults.Add("IE", " - (Microsoft|Windows) Internet Explorer.*");
                matcherDefaults.Add("Chrome", " - Google Chrome.*");
                return(matcherDefaults);

            case "TitleFixReplacer":
                Dictionary <string, string> replacerDefaults = new Dictionary <string, string>();
                replacerDefaults.Add("Firefox", "");
                replacerDefaults.Add("IE", "");
                replacerDefaults.Add("Chrome", "");
                return(replacerDefaults);
            }
            return(null);
        }
示例#11
0
 public AlgorithmParameterSpec GetParameterSpec()
 {
     LOG.Log(POILogger.DEBUG, "getParameterSpec");
     return(null);
 }
示例#12
0
 private void PrintToLog_(PassStringEvent evt) =>
 LOG.Write("Bar(" + evt.Str + ")");
示例#13
0
 private void PrintToLog_(VoidEvent evt) => LOG.Write("Bar");
示例#14
0
        // --
        public JobCrush(CrushParams par) : base("Compress CD")
        {
            p = par;

            // Hack to fix progress
            hack_setExpectedProgTracks(p.expectedTracks + 3);

            // - Read CUE and some init
            // ---------------------------
            add(new CTask((t) => {
                var cd = new cd.CDInfos();

                p.cd = cd;

                try{
                    cd.cueLoad(p.inputFile);
                }catch (haxe.lang.HaxeException e) {
                    t.fail(msg: e.Message); return;
                }

                // Meaning the tracks are going to be CUT in the temp folder, so they are safe to be removed
                p.flag_sourceTracksOnTemp = (!cd.MULTIFILE && cd.tracks.length > 1);

                // In case user named the CD, otherwise it's going to be the same
                if (!string.IsNullOrWhiteSpace(p.cdTitle))
                {
                    cd.CD_TITLE = FileTools.sanitizeFilename(p.cdTitle);
                }

                // Real quality to string name
                cd.CD_AUDIO_QUALITY = AudioMaster.getCodecSettingsInfo(p.audioQuality);

                if (p.mode != 1)      // Convert only does not require an archive
                {
                    // Generate the final ARCHIVE path now that I have the CD TITLE
                    p.finalArcPath = Path.Combine(p.outputDir, cd.CD_TITLE + p.archiver_ext);

                    // Try to create a new archive in case it exists?
                    while (File.Exists(p.finalArcPath))
                    {
                        LOG.log("{0} already exists, adding (_) until unique", p.finalArcPath);
                        // S is entire path without (.ext)
                        string S       = p.finalArcPath.Substring(0, p.finalArcPath.Length - p.archiver_ext.Length);
                        p.finalArcPath = S + "_" + p.archiver_ext;
                    }

                    LOG.log("- Destination Archive : {0}", p.finalArcPath);
                }

                if (p.mode == 1)
                {
                    // : ALWAYS Create a subfolder (when converting) to avoid overwriting the source files
                    p.outputDir = CDCRUSH.checkCreateUniqueOutput(p.outputDir, p.cdTitle + CDCRUSH.RESTORED_FOLDER_SUFFIX);
                    if (p.outputDir == null)
                    {
                        fail("Output Dir Error " + p.outputDir);
                        return;
                    }
                }

                jobData = p;         // Some TASKS read jobData
                t.complete();
            }, "-Reading", "Reading CUE data and preparing"));

            // - Cut tracks
            // ---------------------------
            add(new TaskCutTrackFiles());

            // - Encode tracks
            // ---------------------
            add(new CTask((t) =>
            {
                for (int i = 0; i < p.cd.tracks.length; i++)
                {
                    cd.CDTrack tr = p.cd.tracks[i] as cd.CDTrack;

                    // Do not encode DATA TRACKS to ECM when converting.
                    if (p.mode > 0 && tr.isData)
                    {
                        continue;
                    }

                    addNextAsync(new TaskCompressTrack(tr));
                }

                t.complete();
            }, "-Preparing", "Preparing to compress tracks"));



            // - Prepare Tracks on CONVERT modes
            // - Needed for the new .CUE to be created
            // - if CONVERT MODE, move all files to output
            if (p.mode > 0)
            {
                add(new CTask((t) =>
                {
                    // DEV: So far :
                    // track.trackFile is UNSET. cd.saveCue needs it to be set.
                    // track.workingFile points to a valid file, some might be in TEMP folder and some in input folder (data tracks)

                    int stepProgress = (int)Math.Round(100.0f / p.cd.tracks.length);

                    // -- Move files to output folder
                    for (int i = 0; i < p.cd.tracks.length; i++)
                    {
                        cd.CDTrack track = p.cd.tracks[i] as cd.CDTrack;

                        if (!p.cd.MULTIFILE)
                        {
                            // Fix the index times to start with 00:00:00
                            track.rewriteIndexes_forMultiFile();
                        }

                        string ext = Path.GetExtension(track.workingFile);

                        // This tells what the files should be named in the `.cue` file:
                        track.trackFile = $"{p.cd.CD_TITLE} (track {track.trackNo}){ext}";

                        // Data track was not cut or encoded.
                        // It's in the input folder, don't move it
                        if (track.isData && (p.cd.MULTIFILE || p.cd.tracks.length == 1))
                        {
                            if (p.mode == 1)
                            {
                                FileTools.tryCopy(track.workingFile, Path.Combine(p.outputDir, track.trackFile));
                                track.workingFile = Path.Combine(p.outputDir, track.trackFile);
                            }
                            else
                            {
                                // I need to copy all files to TEMP, so that they can be renamed and archived
                                FileTools.tryCopy(track.workingFile, Path.Combine(p.tempDir, track.trackFile));
                                track.workingFile = Path.Combine(p.tempDir, track.trackFile);
                            }
                        }
                        else         // encoded file that is on TEMP or OUTPUT
                        {
                            if (p.mode == 1)
                            {
                                // TaskCompress already put the audio files on the output folder
                                // But it's no big deal calling it again
                                // This is for the data tracks that are on the temp folder
                                FileTools.tryMove(track.workingFile, Path.Combine(p.outputDir, track.trackFile));
                                track.workingFile = Path.Combine(p.outputDir, track.trackFile);
                            }
                            else
                            {
                                // Track that has been encoded and is on TEMP
                                // It is currently named as "track_xx.xx" so rename it
                                FileTools.tryMove(track.workingFile, Path.Combine(p.tempDir, track.trackFile));
                                track.workingFile = Path.Combine(p.tempDir, track.trackFile);
                            }
                        }

                        t.PROGRESS += stepProgress;
                    }     // -- end processing tracks


                    if (p.mode == 1)
                    {
                        p.new_cue_path = Path.Combine(p.outputDir, p.cd.CD_TITLE + ".cue");
                    }
                    else
                    {
                        p.new_cue_path = Path.Combine(p.tempDir, p.cd.CD_TITLE + ".cue");
                    }

                    //. Create the new CUE file
                    try{
                        p.cd.cueSave(
                            p.new_cue_path,
                            new haxe.root.Array <object>(new [] {
                            "CDCRUSH (dotNet) version : " + CDCRUSH.PROGRAM_VERSION,
                            CDCRUSH.LINK_SOURCE
                        }));
                    }catch (haxe.lang.HaxeException e) {
                        t.fail(msg: e.Message); return;
                    }

                    t.complete();
                }, "Converting"));
            }


            // - Create an Archive
            // Add all tracks to the final archive
            // ---------------------
            if (p.mode != 1)
            {
                add(new CTask((t) =>
                {
                    // -- Get list of files to compress
                    // . Tracks
                    System.Collections.ArrayList files = new System.Collections.ArrayList();
                    for (var i = 0; i < p.cd.tracks.length; i++)
                    {
                        files.Add((p.cd.tracks[i] as cd.CDTrack).workingFile);         // Working file is valid, was set earlier
                    }

                    if (p.mode == 0)  // Only on CDCRUSH add cover and json data
                    {
                        // . Settings
                        string path_settings = Path.Combine(p.tempDir, CDCRUSH.CDCRUSH_SETTINGS);
                        try{
                            p.cd.jsonSave(path_settings);
                            files.Add(path_settings);
                        }catch (haxe.lang.HaxeException e) {
                            t.fail(msg: e.Message); return;
                        }

                        // . Cover Image
                        string path_cover;
                        if (p.cover != null)
                        {
                            path_cover = Path.Combine(p.tempDir, CDCRUSH.CDCRUSH_COVER);
                            File.Copy(p.cover, path_cover);
                            files.Add(path_cover);
                        }
                        else
                        {
                            path_cover = null;
                        }
                    }
                    else
                    {
                        // It must be CONVERT + ARCHIVE
                        files.Add(p.new_cue_path);
                    }

                    // -. Compress whatever files are on
                    var arc = ArchiveMaster.getArchiver(p.finalArcPath);

                    string arcStr = ArchiveMaster.getCompressionSettings(p.archiveSettingsInd).Item2;

                    arc.compress((string[])files.ToArray(typeof(string)), jobData.finalArcPath, -1, arcStr);
                    arc.onProgress = (pr) => t.PROGRESS = pr;
                    arc.onComplete = (s) => {
                        if (s)
                        {
                            // NOTE: This var is autowritten whenever a compress operation is complete
                            p.crushedSize = (int)arc.COMPRESSED_SIZE;
                            // IMPORTANT to write to jobdata, because it is not a pointer and this needs to be read externally
                            jobData = p;
                            t.complete();
                        }
                        else
                        {
                            fail(arc.ERROR);
                        }
                    };

                    t.killExtra = () => arc.kill();
                }, "Compressing", "Compressing everything into an archive"));
            }


            // -- COMPLETE --

            add(new CTask((t) =>
            {
                LOG.log("== Detailed CD INFOS ==");
                LOG.log(p.cd.getDetailedInfo());
                t.complete();
            }, "-complete"));
        }// -----------------------------------------
        protected void ProcessSolicitTransaction(string transactionId)
        {
            using (INodeProcessorMutex mutex = GetMutex(transactionId)) {
                if (!mutex.IsAcquired)
                {
                    LOG.Debug("Exiting ProcessSolicitTransaction(), could not acquire mutex");
                    return;                     // Another thread is already working on this transaction, get out of here
                }
                // Make sure the transaction has not been processed yet
                string transactionModifiedBy;
                if (!TransactionManager.IsUnprocessed(transactionId, out transactionModifiedBy))
                {
                    LOG.Debug("Exiting ProcessSolicitTransaction(), transaction {0} has already been processed",
                              transactionId);
                    return;
                }
                Activity activity = new Activity(NodeMethod.Solicit, null, null, ActivityType.Info, transactionId,
                                                 NetworkUtils.GetLocalIp(),
                                                 "Start processing solicit transaction: \"{0}\"", transactionId);
                activity.ModifiedById = transactionModifiedBy;
                try
                {
                    TransactionManager.SetTransactionStatus(transactionId, CommonTransactionStatusCode.Pending,
                                                            "Processing solicit transaction", false);

                    // Get the request processing service
                    string      requestId, flowName, operation;
                    DataService solicitService =
                        TransactionManager.GetSolicitServiceForTransaction(transactionId, out flowName, out operation, out requestId);
                    if ((solicitService == null) || !solicitService.IsActive)
                    {
                        throw new ArgumentException(string.Format("A valid solicit service was not found for the transaction \"{0}\"",
                                                                  transactionId));
                    }
                    TimeSpan          processLength;
                    ISolicitProcessor plugin;
                    using (IPluginDisposer disposer = PluginLoader.LoadSolicitProcessor(solicitService, out plugin))
                    {
                        TransactionManager.SetTransactionStatus(transactionId, CommonTransactionStatusCode.Processing,
                                                                string.Format("Processing request with transaction id \"{0}\"",
                                                                              transactionId), true);
                        DateTime startTime = DateTime.Now;
                        activity.Append("Set transaction status to Processing");
                        activity.AppendFormat("Processing Solicit transaction for flow \"{0}\" and operation \"{1}\" using plugin \"{2}\"",
                                              flowName, operation, plugin.GetType().FullName);

                        try
                        {
                            plugin.ProcessSolicit(requestId);
                        }
                        finally
                        {
                            activity.Append(plugin.GetAuditLogEvents());
                        }
                        processLength = DateTime.Now - startTime;
                    }

                    activity.AppendFormat("Process time: {0}", processLength.ToString());

                    TransactionStatus transactionStatus =
                        TransactionManager.SetTransactionStatus(transactionId, CommonTransactionStatusCode.Completed,
                                                                string.Format("Completed solicit request with transaction id \"{0}\"",
                                                                              transactionId), true);
                    activity.AppendFormat("Transaction status set to \"{0}\"", transactionStatus.Status.ToString());

                    activity.AppendFormat(TransactionManager.DoTransactionNotifications(transactionId));
                }
                catch (Exception e) {
                    TransactionStatus transactionStatus =
                        TransactionManager.SetTransactionStatusIfNotStatus(transactionId, CommonTransactionStatusCode.Failed,
                                                                           e.Message, CommonTransactionStatusCode.Received, true);

                    activity.AppendFormat("Transaction status set to \"{0}\"", transactionStatus.Status.ToString());
                    activity.Append(ExceptionUtils.ToShortString(e));
                    activity.Type = ActivityType.Error;
                    activity.AppendFormat(TransactionManager.DoTransactionNotifications(transactionId));
                    LOG.Error("ProcessSolicitTransaction() threw an exception.", e);
                }
                finally {
                    ActivityManager.Log(activity);
                }
            }
        }
示例#16
0
        //---------------------------------------------------------------------------
        //Main Process
        private void THREAD_PROCESS_0()
        {
            bool   bGo   = false;
            double Start = 0;
            double Scan  = 0;

            //
            try
            {
                while (m_bThreadRun[TH0])
                {
                    Thread.Sleep(1);

                    if (!bGo)
                    {
                        //-----------------------------------------------
                        Monitor.Enter(Obj);
                        try
                        {
                            m_bWatchDog[TH0] = false;

                            //Main Sequence
                            if (m_bIOOn)
                            {
                                SEQ.fn_Update();
                            }
                            //SEQ.fn_Update1();

                            m_bWatchDog[TH0] = true;
                        }
                        finally
                        {
                            Monitor.Exit(Obj);
                        }
                        //-----------------------------------------------



                        bGo = true;
                        m_tDelayTimer[TH0].Clear();
                    }

                    //if (Scan < THREAD_INTERVAL0)
                    //{
                    //    if (!m_tDelayTimer[TH0].OnDelay(bGo, THREAD_INTERVAL0 - Scan)) continue;
                    //}

                    bGo = false;

                    m_dScanTime[TH0] = TICK._GetTickTime() - Start;
                    Start            = TICK._GetTickTime();


                    //Scan Time Check
                    m_nScanTime [TH0] = (uint)Environment.TickCount - m_nStartTime[TH0];
                    m_nStartTime[TH0] = (uint)Environment.TickCount;
                }
            }
            catch (System.Exception ex)
            {
                m_bWatchDog[TH0] = false;

                System.Diagnostics.Trace.WriteLine(ex.Message);
                LOG.ExceptionTrace("[THREAD_PROCESS_0]", ex);
            }
        }
示例#17
0
    public void LuaSend()
    {
        if (NetworkConfig.single)
        {
            return;
        }
        //if (luaMsgBytes == null || luaMsgBytes.Length <= 0) return;

        if (client == null || !client.Connected)
        {
            PromptDisconnect();
            return;
        }
        ClientHeader header = new ClientHeader();

        header.m_iUin          = 0;
        header.m_cSHFlag       = 0;
        header.m_nOptionLength = 0;
        //header.m_szOption = null;
        header.m_iMessageID     = 0;
        header.m_nPlayerID      = 0;
        header.m_nGroupID       = 0;
        header.m_nPlatformID    = 0;
        header.m_iSequenceID    = 0;
        header.m_iPackageLength = 23 + header.m_nOptionLength + luaMsgBytes.Length;

        byte[] packageBytes = null;
        using (MemoryStream stream = new MemoryStream())
        {
            BinaryWriter bw = new BinaryWriter(stream);

            bw.Write((int)IPAddress.HostToNetworkOrder((int)header.m_iPackageLength));
            bw.Write((short)IPAddress.HostToNetworkOrder((short)header.m_iUin));
            bw.Write((byte)IPAddress.HostToNetworkOrder((byte)header.m_cSHFlag));
            bw.Write((short)IPAddress.HostToNetworkOrder((short)header.m_nOptionLength));
            if (header.m_nOptionLength > 0)
            {
                bw.Write(header.m_szOption);
            }
            bw.Write((short)IPAddress.HostToNetworkOrder((short)header.m_iMessageID));
            bw.Write((short)IPAddress.HostToNetworkOrder((short)header.m_nPlayerID));
            bw.Write((short)IPAddress.HostToNetworkOrder((short)header.m_nGroupID));
            bw.Write((short)IPAddress.HostToNetworkOrder((short)header.m_nPlatformID));
            bw.Write((int)IPAddress.HostToNetworkOrder((int)header.m_iSequenceID));
            bw.Write(luaMsgBytes);

            packageBytes = stream.ToArray();
        }

        if (NetworkConfig.isNetworkEncrypt)
        {
            byte[] key; ushort ksn;
            lock (encryptMutex)
            {
                key = encryptKey;
                ksn = encryptKSN;
            }
            packageBytes = Encrypt(key, packageBytes);
            using (MemoryStream ms = new MemoryStream())
            {
                using (BinaryWriter bw = new BinaryWriter(ms))
                {
                    ushort magic = 0xBEAD;
                    bw.Write((ushort)IPAddress.HostToNetworkOrder((short)magic));
                    bw.Write((ushort)IPAddress.HostToNetworkOrder((short)(packageBytes.Length + 6)));
                    bw.Write((ushort)IPAddress.HostToNetworkOrder((short)ksn));
                    bw.Write(packageBytes);
                }
                packageBytes = ms.ToArray();
            }
        }

        try
        {
            if (client == null || !client.Connected)
            {
                PromptDisconnect();
                return;
            }
            BinaryWriter writer = new BinaryWriter(client.GetStream());
            writer.Write(packageBytes);
            writer.Flush();
            sendTime = Time.realtimeSinceStartup;
        }
        catch (System.Exception ex)
        {
            state = NetworkState.Disconnected;
            client.Close();
#if xue
            EventDispatcher.DispatchEvent("EventShowMessageUI", null, null);
#endif
            disconnectTime = DateTime.Now;
            LOG.Error(DateTime.Now + " Disconnect!" + "  exception: " + ex);
        }
    }
示例#18
0
        //---------------------------------------------------------------------------
        private void THREAD_PROCESS_9()
        {
            bool   bGo      = false;
            double Start    = 0;
            double Scan     = 0;
            int    idx      = TH9;
            int    interval = THREAD_INTERVAL9;

            m_TryCount_Cam = 0;
            //
            try
            {
                while (m_bThreadRun[idx])
                {
                    Thread.Sleep(1);

                    if (!bGo)
                    {
                        Start            = TICK._GetTickTime();
                        m_bWatchDog[TH9] = false;

                        // Cam Connection Try
                        if (g_VisionManager._CamManager.CameraRetryCount < 12)
                        {
                            if (g_VisionManager._CamManager.fn_OpenCam() == true)
                            {
                                g_VisionManager._CamManager.CameraRetryCount = 12;
                            }
                            else
                            {
                                g_VisionManager._CamManager.CameraRetryCount++;
                            }
                        }

                        m_bWatchDog[TH9] = true;

                        Scan = TICK._GetTickTime() - Start;
                        bGo  = true;
                        m_tDelayTimer[idx].Clear();
                    }

                    if (Scan < interval)
                    {
                        if (!m_tDelayTimer[idx].OnDelay(bGo, interval - Scan))
                        {
                            continue;
                        }
                    }

                    bGo = false;



                    //Scan Time Check
                    m_nScanTime [idx] = (uint)(TICK._GetTickTime() - m_nStartTime[idx]);
                    m_nStartTime[idx] = (uint)TICK._GetTickTime();
                }
            }
            catch (System.Exception ex)
            {
                m_bWatchDog[TH9] = false;
                System.Diagnostics.Trace.WriteLine(ex.Message);
                LOG.ExceptionTrace($"[THREAD_PROCESS_{interval}]", ex);
            }
        }
示例#19
0
        }        // --

        private void FormComponentsTest_FormClosing(object sender, FormClosingEventArgs e)
        {
            LOG.log("[FormComponents] Destroying");
            LOG.detachTextBox();
        }        // -----------------------------------------
示例#20
0
        //---------------------------------------------------------------------------
        private void THREAD_PROCESS_10()
        {
            bool   bGo      = false;
            double Start    = 0;
            double Scan     = 0;
            int    idx      = TH10;
            int    interval = THREAD_INTERVAL10;
            int    nIdex    = 0;

            //
            try
            {
                while (m_bThreadRun[idx])
                {
                    Thread.Sleep(1);

                    if (!bGo)
                    {
                        Start = TICK._GetTickTime();

                        //Check Thread
                        for (nIdex = 0; nIdex < MAX_THREAD - 1; nIdex++)
                        {
                            if (!m_bThreadRun[nIdex])
                            {
                                continue;
                            }

                            if (nIdex >= TH7)
                            {
                                continue;
                            }

                            m_tChkTimer[nIdex].OnDelay(!m_bWatchDog[nIdex], 3000);
                            if (m_tChkTimer[nIdex].Out)
                            {
                                //Console.WriteLine(string.Format($"THREAD ERROR_{nIdex}"));
                                //EPU.fn_SetErr(ERRID.EN_ERR_LIST.ERR_0120 + nIdex); //JUNG/200605
                            }
                        }


                        Scan = TICK._GetTickTime() - Start;
                        bGo  = true;
                        m_tDelayTimer[idx].Clear();
                    }

                    if (Scan < interval)
                    {
                        if (!m_tDelayTimer[idx].OnDelay(bGo, interval - Scan))
                        {
                            continue;
                        }
                    }

                    bGo = false;

                    //Scan Time Check
                    m_nScanTime [idx] = (uint)(TICK._GetTickTime() - m_nStartTime[idx]);
                    m_nStartTime[idx] = (uint)TICK._GetTickTime();
                }
            }
            catch (System.Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.Message);
                LOG.ExceptionTrace($"[THREAD_PROCESS_{interval}]", ex);
            }
        }
 public string i(string n, string p, string t)
 {
     LOG.GetDataloginUsuarios(n, p, ref t);
     return(t);
 }
示例#22
0
        public void Dispose()
        {
            try
            {
                RenderFactory.RemoveRenderObject(this);
                AssetBundleManager.UnloadAssetBundle(name);
                if (children != null)
                {
                    for (var n = children.next; n != children;)
                    {
                        var           next  = n.next;
                        IRenderObject child = (IRenderObject)n;
                        if (child != null)
                        {
                            child.Parent = null;
                        }
                        n = next;
                    }
                    children = null;
                }

                if (components != null)
                {
                    if (dict == null)
                    {
                        dict = new Dictionary <IRenderComponent, bool>();
                    }
                    dict.Clear();

                    for (int i = 0; i < tempComponents.Count; i++)
                    {
                        var c = tempComponents[i];
                        if (c == null)
                        {
                            continue;
                        }
                        if (dict.ContainsKey(c))
                        {
                            continue;
                        }
                        dict[c] = true;
                        c.Destroy();
                    }
                    tempComponents.Clear();

                    components.Clear();
                    components = null;
                }

                if (timer != null)
                {
                    timer.Clear();
                }

                this.Parent = null;
                this.OnDestroy();
            }
            catch (Exception e)
            {
                LOG.LogError(e.ToString(), this.gameObject);
            }
        }
示例#23
0
        /// <summary>
        /// Draw the image on the graphics with GDI+ blur effect
        /// </summary>
        /// <returns>false if there is no GDI+ available or an exception occured</returns>
        public static bool DrawWithBlur(Graphics graphics, Bitmap image, Rectangle source, Matrix transform, ImageAttributes imageAttributes, int radius, bool expandEdges)
        {
            if (!IsBlurPossible(radius))
            {
                return(false);
            }

            IntPtr hBlurParams = IntPtr.Zero;
            IntPtr hEffect     = IntPtr.Zero;

            try
            {
                // Create a BlurParams struct and set the values
                BlurParams blurParams = new BlurParams();
                blurParams.Radius = radius;
                //blurParams.Padding = radius;
                blurParams.ExpandEdges = false;

                // Allocate space in unmanaged memory
                hBlurParams = Marshal.AllocHGlobal(Marshal.SizeOf(blurParams));
                // Copy the structure to the unmanaged memory
                Marshal.StructureToPtr(blurParams, hBlurParams, true);

                // Create the GDI+ BlurEffect, using the Guid
                int status = GdipCreateEffect(BlurEffectGuid, out hEffect);

                // Set the blurParams to the effect
                GdipSetEffectParameters(hEffect, hBlurParams, (uint)Marshal.SizeOf(blurParams));

                // Somewhere it said we can use destinationBitmap.GetHbitmap(), this doesn't work!!
                // Get the private nativeImage property from the Bitmap
                IntPtr hBitmap     = GetNativeImage(image);
                IntPtr hGraphics   = GetNativeGraphics(graphics);
                IntPtr hMatrix     = GetNativeMatrix(transform);
                IntPtr hAttributes = GetNativeImageAttributes(imageAttributes);

                // Create a RECT from the Rectangle
                RECTF sourceRECF = new RECTF(source);
                // Apply the effect to the bitmap in the specified area
                GdipDrawImageFX(hGraphics, hBitmap, ref sourceRECF, hMatrix, hEffect, hAttributes, GpUnit.UnitPixel);

                // Everything worked, return true
                return(true);
            }
            catch (Exception ex)
            {
                LOG.Error("Problem using GdipDrawImageFX: ", ex);
                return(false);
            }
            finally
            {
                if (hEffect != null)
                {
                    // Delete the effect
                    GdipDeleteEffect(hEffect);
                }
                if (hBlurParams != IntPtr.Zero)
                {
                    // Free the memory
                    Marshal.FreeHGlobal(hBlurParams);
                }
            }
        }
示例#24
0
            public object Execute(IDictionary <string, object> arguments)
            {
                //
                string fn = String.Empty;
                // create the process info..
                Process process = new Process();

                // set the defaults..
                process.StartInfo.CreateNoWindow         = true;
                process.StartInfo.UseShellExecute        = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError  = true;
                // set the default timeout..
                int timeout = 1000 * 30; // 30 secss
                IDictionary <string, object> result = new Dictionary <string, object>();
                int exitCode = 1;

                try
                {
                    LOG.Info("About to execute script: {0}", _script);
                    // if there are any environment varibles set to false..
                    process.StartInfo.UseShellExecute = false;//arguments.Count == 0;
                    // take out username and password if they're in the options.
                    foreach (KeyValuePair <string, object> kv in arguments)
                    {
                        if (kv.Key.ToUpper().Equals("USERNAME"))
                        {
                            string   domainUser = kv.Value.ToString();
                            string[] split      = domainUser.Split(new char[] { '\\' });
                            if (split.Length == 1)
                            {
                                process.StartInfo.UserName = split[0];
                            }
                            else
                            {
                                process.StartInfo.Domain   = split[0];
                                process.StartInfo.UserName = split[1];
                            }
                        }
                        else if (kv.Key.ToUpper().Equals("PASSWORD"))
                        {
                            if (kv.Value is SecureString)
                            {
                                process.StartInfo.Password = (SecureString)kv.Value;
                            }
                            else if (kv.Value is GuardedString)
                            {
                                process.StartInfo.Password = ((GuardedString)kv.Value).ToSecureString();
                            }
                            else
                            {
                                throw new ArgumentException("Invalid type for password.");
                            }
                        }
                        else if (kv.Key.ToUpper().Equals("WORKINGDIR"))
                        {
                            process.StartInfo.WorkingDirectory = kv.Value.ToString();
                        }
                        else if (kv.Key.ToUpper().Equals("TIMEOUT"))
                        {
                            timeout = Int32.Parse(kv.Value.ToString());
                        }
                        else
                        {
                            if (kv.Value == null)
                            {
                                LOG.Warn("...parameter {0} has null value, skipping it", kv.Key);
                            }
                            else
                            {
                                LOG.Info("...with parameter {0} set to {1}", kv.Key, kv.Value);
                                process.StartInfo.EnvironmentVariables[kv.Key] = kv.Value.ToString();
                            }
                        }
                    }
                    // write out the script..
                    fn = Path.GetTempFileName() + ".cmd";
                    StreamWriter sw = null;
                    try
                    {
                        sw = new StreamWriter(fn);
                        sw.Write(_script);
                    }
                    finally
                    {
                        sw.Close();
                        sw.Dispose();
                    }
                    // set temp file..
                    process.StartInfo.FileName = fn;
                    // execute script..
                    process.Start();
                    string stdout = process.StandardOutput.ReadToEnd();
                    LOG.Info("execution started; stdout = {0}", stdout);      // this is quite suspicious...
                    // http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx
                    // Use asynchronous read operations on at least one of the streams.
                    AsynchronousReader msr_stderr = new AsynchronousReader(process.StandardError);
                    // Create the thread objects to run the code asynchronously
                    Thread t_stderr = new Thread(msr_stderr.Go);
                    t_stderr.Start();
                    t_stderr.Join();
                    // wait for the process to exit..
                    if (!process.WaitForExit(timeout))
                    {
                        throw new TimeoutException("Script failed to exit in time!");
                    }
                    exitCode = process.ExitCode;
                    result.Add("stdout", stdout);
                    result.Add("stderr", msr_stderr.Text);
                    LOG.Info("execution finished; stderr = {0}", msr_stderr.Text);
                }
                catch (Exception e)
                {
                    LOG.Error(e, "Failed to execute script with exception");
                }
                finally
                {
                    // close up the process
                    process.Close();
                    process.Dispose();
                }
                // clean up temp file..
                try
                {
                    File.Delete(fn);
                }
                catch (Exception)
                {
                }
                LOG.Info("exitCode = {0}", exitCode);
                result.Add("exitCode", exitCode);
                return(result);
            }
示例#25
0
 private void SendUSSD_Click(object sender, EventArgs e)
 {
     gsm.sendUSSD(EDUSSD.Text);
     LOG.AppendText(EDUSSD.Text + "\r\n");
     EDUSSD.Text = "";
 }
示例#26
0
        }        // -----------------------------------------

        /// <summary>
        /// Take a crushed archive and extract only the info file, Returns a customized object with some info
        /// </summary>
        /// <param name="arcFile"></param>
        /// <param name="onComplete">(null) on error,
        ///		OBJECT =
        ///			cd:CueReader,
        ///			cover:Path of image cover or null
        ///			sizeArc:Size of ARC in bytes
        ///
        ///	</param>
        /// <returns>Success</returns>
        public static bool loadQuickInfo(string arcFile, Action <Object> onComplete)
        {
            if (LOCKED)
            {
                ERROR = "LOCKED";
                return(false);
            }

            if (!check_file_(arcFile, CDCRUSH_EXTENSIONS))
            {
                ERROR = "Invalid file extension. Supported  = (" + string.Join(" ", CDCRUSH.CDCRUSH_EXTENSIONS) + ")";
                return(false);
            }


            LOCKED = true;

            // Delete old files from previous quickInfos, IF ANY
            FileTools.tryDelete(Path.Combine(TEMP_FOLDER, CDCRUSH_SETTINGS));
            FileTools.tryDelete(Path.Combine(TEMP_FOLDER, CDCRUSH_COVER));

            var arc = ArchiveMaster.getArchiver(arcFile);

            // --
            arc.onComplete = (success) =>
            {
                LOCKED = false;

                if (success)                // OK
                {
                    // Continue
                    var cd = new cd.CDInfos();
                    try{
                        cd.jsonLoad(Path.Combine(TEMP_FOLDER, CDCRUSH_SETTINGS));
                    }catch (haxe.lang.HaxeException e) {
                        ERROR = "Not a valid CDCRUSH Archive.";
                        onComplete(null);
                        return;
                    }

                    // This is the object with the info returned to user
                    var info = new
                    {
                        cd,
                        sizeArc = (int)new FileInfo(arcFile).Length,
                        cover   = Path.Combine(TEMP_FOLDER, CDCRUSH_COVER)
                    };

                    LOG.log("= QuickLoaded `{0}` - [OK]", arcFile);
                    onComplete(info);
                }
                else
                {
                    ERROR = arc.ERROR;
                    onComplete(null);
                }
            };


            // TODO: Make sure ARCHIVE contains proper files
            // : Actually extract
            arc.extract(arcFile, TEMP_FOLDER, new [] { CDCRUSH_SETTINGS, CDCRUSH_COVER });

            return(true);
        }        // -----------------------------------------
示例#27
0
 public void appendLOGText(string str)
 {
     LOG.AppendText(str);
 }
示例#28
0
        public ActionResult GetRidingLogs(int?id)
        {
            Stream req = Request.InputStream;

            req.Seek(0, System.IO.SeekOrigin.Begin);
            string json = new StreamReader(req).ReadToEnd();

            string   actionName = "GetRidingLogs";
            DateTime dtNow      = DateTime.Now;

            // 객체 초기화
            JsonGetRidingLogs  jsonGetRidingLogs = null;
            ResponseRidingLogs resRidingLogs     = new ResponseRidingLogs();
            HKRheader          rHeader           = new HKRheader();
            List <RidingLog>   Body = new List <RidingLog>();

            LOG newLog = new LOG(); // 로그 객체

            // DB Context 가져오기
            HKRiderDBDataContext db    = new HKRiderDBDataContext(/*connectionString here */);
            LOGDBDataContext     logdb = new LOGDBDataContext(/**/);

            try
            {
                jsonGetRidingLogs = JsonConvert.DeserializeObject <JsonGetRidingLogs>(json);

                // Log 처리 루틴 -------------------------------------------------
                newLog.action     = jsonGetRidingLogs.header.action;
                newLog.auth_token = jsonGetRidingLogs.header.auth_token;
                newLog.json       = json;
                newLog.dt_created = dtNow;
                // Log 처리 루틴 -------------------------------------------------

                if (!jsonGetRidingLogs.header.action.Equals(actionName))
                {
                    resRidingLogs.header = setHKRheader_Err(rHeader, 101, "[ERROR] Action is wrong: " + jsonGetRidingLogs.header.action,
                                                            resRidingLogs.header.auth_token, logdb, newLog);
                    return(Json(resRidingLogs, JsonRequestBehavior.AllowGet));
                }
                else if (jsonGetRidingLogs.header.auth_token == null || jsonGetRidingLogs.header.auth_token == "")
                {
                    resRidingLogs.header = setHKRheader_Err(rHeader, 103, "[ERROR] Auth Token is wrong: " + jsonGetRidingLogs.header.auth_token,
                                                            resRidingLogs.header.auth_token, logdb, newLog);
                    return(Json(resRidingLogs, JsonRequestBehavior.AllowGet));
                }

                // Version Check 추가 예정

                // User 가져오기
                USER thisUser = (from u in db.USERs
                                 where   u.Auth_Token == jsonGetRidingLogs.header.auth_token
                                 select u).SingleOrDefault();

                if (thisUser == null)
                {
                    //Error 202: 다시 접속하세요. 유저정보를 확인할 수 없습니다.
                    resRidingLogs.header = setHKRheader_Err(rHeader, 202, "[ERROR] 다시 접속하세요. 유저정보를 확인할 수 없습니다: ",
                                                            resRidingLogs.header.auth_token, logdb, newLog);
                    return(Json(resRidingLogs, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    ROADBIKE theBike = thisUser.ROADBIKEs.Where(r => r.DeviceID == jsonGetRidingLogs.body.mac_address).SingleOrDefault();

                    if (theBike == null) //해당 맥주소가 해당 유저에게는 존재하지 않음.
                    {
                        //Error 203: 주행기록을 저장한 유저정보를 확인할 수 없습니다. 다시 접속하세요.
                        resRidingLogs.header = setHKRheader_Err(rHeader, 203, "[ERROR] 주행기록을 저장한 유저정보를 확인할 수 없습니다. 다시 접속하세요.: ",
                                                                resRidingLogs.header.auth_token, logdb, newLog);
                        return(Json(resRidingLogs, JsonRequestBehavior.AllowGet));
                    }
                    else // 존재함.
                    {
                        if (jsonGetRidingLogs.body.remove_id > 0)
                        {
                            var rDel = db.RIDINGLOGs.Where(r => r.id == jsonGetRidingLogs.body.remove_id).SingleOrDefault();
                            db.RIDINGLOGs.DeleteOnSubmit(rDel);
                            db.SubmitChanges();
                        }

                        DateTime FromDt = FromMillisJava((long)jsonGetRidingLogs.body.from_date).ToLocalTime();
                        DateTime ToDt   = FromMillisJava((long)jsonGetRidingLogs.body.to_date).ToLocalTime();
                        ToDt = ToDt.AddDays(1); // 하루 추가.

                        var ridingLogs = (from l in db.RIDINGLOGs
                                          where l.USERS_id == thisUser.id &&
                                          l.ROADBIKES_id == theBike.id &&
                                          l.DT_Start >= FromDt &&
                                          l.DT_Start < ToDt
                                          select l);

                        List <RidingLog> listRidingLogs = new List <RidingLog>();
                        foreach (var rl in ridingLogs)
                        {
                            RidingLog newRL = new RidingLog();
                            newRL.id             = rl.id;
                            newRL.average_speed  = rl.AverageSpeed;
                            newRL.calories_burn  = rl.CaloriesBurn;
                            newRL.distance       = rl.Distance;
                            newRL.dt_end         = DateTime2Long(rl.DT_End);
                            newRL.dt_start       = DateTime2Long(rl.DT_Start);
                            newRL.duration       = rl.Duration;
                            newRL.start_location = rl.StartLocation;
                            newRL.end_location   = rl.EndLocation;
                            newRL.mac_address    = theBike.DeviceID;
                            newRL.max_speed      = rl.MaxSpeed;
                            newRL.riding_score   = rl.RidingScore;
                            newRL.gps_records    = rl.GPSrecords;
                            newRL.last_gps       = rl.LastGPS;
                            listRidingLogs.Add(newRL);
                        }
                        Body = listRidingLogs;
                    }
                }

                db.SubmitChanges();
                logdb.LOGs.InsertOnSubmit(newLog);

                resRidingLogs.header = rHeader;
                resRidingLogs.body   = Body;

                return(Json(resRidingLogs, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                // Error: Exception
                resRidingLogs.header = setHKRheader_Err(rHeader, 301, "[ERROR] Exception: " + ex.Message
                                                        , jsonGetRidingLogs == null?"jsonGetRidingLogs is null": jsonGetRidingLogs.header.auth_token, logdb, newLog);
                return(Json(resRidingLogs, JsonRequestBehavior.AllowGet));
            }
        }
示例#29
0
        /// <summary>
        /// This method will set the ini value to the supplied value or use the default if non supplied
        /// </summary>
        /// <param name="propertyValue"></param>
        public void UseValueOrDefault(string propertyValue)
        {
            Type   valueType              = ValueType;
            string propertyName           = attributes.Name;
            string defaultValue           = attributes.DefaultValue;
            bool   defaultUsed            = false;
            object defaultValueFromConfig = containingIniSection.GetDefault(propertyName);

            if (string.IsNullOrEmpty(propertyValue))
            {
                if (defaultValue != null && defaultValue.Trim().Length != 0)
                {
                    propertyValue = defaultValue;
                    defaultUsed   = true;
                }
                else if (defaultValueFromConfig != null)
                {
                    LOG.DebugFormat("Default for Property {0} implemented!", propertyName);
                }
                else
                {
                    if (attributes.ExcludeIfNull)
                    {
                        Value = null;
                        return;
                    }
                    LOG.DebugFormat("Property {0} has no value or default value!", propertyName);
                }
            }
            // Now set the value
            if (valueType.IsGenericType && valueType.GetGenericTypeDefinition() == typeof(Dictionary <,>))
            {
                // Logic for Dictionary<,>
                Type type1 = valueType.GetGenericArguments()[0];
                Type type2 = valueType.GetGenericArguments()[1];
                //LOG.Info(String.Format("Found Dictionary<{0},{1}>", type1.Name, type2.Name));
                object     dictionary    = Activator.CreateInstance(valueType);
                MethodInfo addMethodInfo = valueType.GetMethod("Add");
                bool       addedElements = false;
                Dictionary <string, string> properties = IniConfig.PropertiesForSection(containingIniSection);
                foreach (string key in properties.Keys)
                {
                    if (key != null && key.StartsWith(propertyName + "."))
                    {
                        // What "key" do we need to store it under?
                        string subPropertyName = key.Substring(propertyName.Length + 1);
                        string stringValue     = properties[key];
                        object newValue1       = null;
                        object newValue2       = null;
                        try
                        {
                            newValue1 = ConvertStringToValueType(type1, subPropertyName, attributes.Separator);
                        }
                        catch (Exception ex)
                        {
                            LOG.Warn(ex);
                            //LOG.Error("Problem converting " + subPropertyName + " to type " + type1.FullName, e);
                        }
                        try
                        {
                            newValue2 = ConvertStringToValueType(type2, stringValue, attributes.Separator);
                        }
                        catch (Exception ex)
                        {
                            LOG.Warn(ex);
                            //LOG.Error("Problem converting " + stringValue + " to type " + type2.FullName, e);
                        }
                        addMethodInfo.Invoke(dictionary, new object[] { newValue1, newValue2 });
                        addedElements = true;
                    }
                }
                // No need to return something that isn't filled!
                if (addedElements)
                {
                    Value = dictionary;
                    return;
                }
                else if (defaultValueFromConfig != null)
                {
                    Value = defaultValueFromConfig;
                    return;
                }
            }
            else if (propertyValue != null)
            {
                if (valueType.IsGenericType && valueType.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
                {
                    // We are dealing with a generic type that is nullable
                    valueType = Nullable.GetUnderlyingType(valueType);
                }
                object newValue = null;
                try
                {
                    newValue = ConvertStringToValueType(valueType, propertyValue, attributes.Separator);
                }
                catch (Exception ex1)
                {
                    newValue = null;
                    if (!defaultUsed)
                    {
                        try
                        {
                            LOG.WarnFormat("Problem '{0}' while converting {1} to type {2} trying fallback...", ex1.Message, propertyValue, valueType.FullName);
                            newValue = ConvertStringToValueType(valueType, defaultValue, attributes.Separator);
                            ContainingIniSection.IsDirty = true;
                            LOG.InfoFormat("Used default value {0} for property {1}", defaultValue, propertyName);
                        }
                        catch (Exception ex2)
                        {
                            LOG.Warn("Problem converting fallback value " + defaultValue + " to type " + valueType.FullName, ex2);
                        }
                    }
                    else
                    {
                        LOG.Warn("Problem converting " + propertyValue + " to type " + valueType.FullName, ex1);
                    }
                }
                Value = newValue;
                return;
            }

            // If nothing is set, we can use the default value from the config (if we habe one)
            if (defaultValueFromConfig != null)
            {
                Value = defaultValueFromConfig;
                return;
            }
            if (ValueType != typeof(string))
            {
                try
                {
                    Value = Activator.CreateInstance(ValueType);
                }
                catch (Exception)
                {
                    LOG.WarnFormat("Couldn't create instance of {0} for {1}, using default value.", ValueType.FullName, attributes.Name);
                    Value = default(ValueType);
                }
            }
            else
            {
                Value = default(ValueType);
            }
        }
示例#30
0
 private void Start()
 {
     LOG.force("Version {0}", Version.Text);
 }