Esempio n. 1
0
        public async Task<WriteResult> WriteTag(NdefMessage message, CancellationToken cancellationToken, TimeSpan timeout)
        {
            if (!IsSupported)
            {
                if (_dontThrowExpceptionWhenNotSupported)
                {
                    return null;
                }
                throw new NotSupportedException("This device does not support NFC (or perhaps it's disabled)");
            }
            Task timeoutTask = null;
            if (timeout != default(TimeSpan))
            {
                timeoutTask = Task.Delay(timeout);
            }
            long subscription;

            TaskCompletionSource<WriteResult> resultSource = new TaskCompletionSource<WriteResult>(); //needs a message type

            using (cancellationToken.Register((s => ((TaskCompletionSource<WriteResult>)s).TrySetCanceled()), resultSource))
            {
                
                byte[] theMessage=message.ToByteArray();
                subscription = _proximityDevice.PublishBinaryMessage("NDEF:WriteTag", theMessage.AsBuffer(), (sender, id) =>
                {
                    WriteResult result = new WriteResult();
                    result.NFCTag = new NFCTag();
                    result.ReasonForFailure = FailureReasons.DidNotFail;
                    resultSource.TrySetResult(result);
                });                    
                try
                {

                    if (timeoutTask != null)
                    {
                        await Task.WhenAny(timeoutTask, resultSource.Task);



                        if (timeoutTask.IsCompleted)
                        {
                            throw new TimeoutException("NFC message not recieved in time");
                        }
                    }
                    if (resultSource.Task.IsCanceled)
                    {
                        return null;
                    }
                    return await resultSource.Task;
                }
                finally
                {
                    _proximityDevice.StopPublishingMessage(subscription);

                }
            }
        }
Esempio n. 2
0
        /// <summary>
        ///  Txn is used to apply multiple KV operations in a single, atomic transaction.
        /// </summary>
        /// <remarks>
        /// Transactions are defined as a
        /// list of operations to perform, using the KVOp constants and KVTxnOp structure
        /// to define operations. If any operation fails, none of the changes are applied
        /// to the state store. Note that this hides the internal raw transaction interface
        /// and munges the input and output types into KV-specific ones for ease of use.
        /// If there are more non-KV operations in the future we may break out a new
        /// transaction API client, but it will be easy to keep this KV-specific variant
        /// supported.
        ///
        /// Even though this is generally a write operation, we take a QueryOptions input
        /// and return a QueryMeta output. If the transaction contains only read ops, then
        /// Consul will fast-path it to a different endpoint internally which supports
        /// consistency controls, but not blocking. If there are write operations then
        /// the request will always be routed through raft and any consistency settings
        /// will be ignored.
        ///
        /// // If there is a problem making the transaction request then an error will be
        /// returned. Otherwise, the ok value will be true if the transaction succeeded
        /// or false if it was rolled back. The response is a structured return value which
        /// will have the outcome of the transaction. Its Results member will have entries
        /// for each operation. Deleted keys will have a nil entry in the, and to save
        /// space, the Value of each key in the Results will be nil unless the operation
        /// is a KVGet. If the transaction was rolled back, the Errors member will have
        /// entries referencing the index of the operation that failed along with an error
        /// message.
        /// </remarks>
        /// <param name="txn">The constructed transaction</param>
        /// <param name="q">Customized write options</param>
        /// <param name="ct">A CancellationToken to prematurely end the request</param>
        /// <returns>The transaction response</returns>
        public async Task <WriteResult <KVTxnResponse> > Txn(List <KVTxnOp> txn, WriteOptions q, CancellationToken ct = default(CancellationToken))
        {
            var txnOps = new List <TxnOp>(txn.Count);

            foreach (var kvTxnOp in txn)
            {
                txnOps.Add(new TxnOp()
                {
                    KV = kvTxnOp
                });
            }

            var req    = _client.Put <List <TxnOp>, TxnResponse>("/v1/txn", txnOps, q);
            var txnRes = await req.Execute(ct);

            var res = new WriteResult <KVTxnResponse>(txnRes, new KVTxnResponse(txnRes.Response));

            res.Response.Success = txnRes.StatusCode == System.Net.HttpStatusCode.OK;

            return(res);
        }
        /// <summary>
        /// 执行继电器控制命令
        /// </summary>
        /// <param name="client">PcbTesterClient句柄</param>
        /// <param name="parameter">命令参数</param>
        /// <param name="context">不同命令之间的通信参数</param>
        /// <returns>检测结果</returns>
        public CommandResult Execute(PcbTesterClient client, CommandParameter parameter, CommandContext context)
        {
            var         relayParameter = parameter as RelayControlCommandParameter;
            WriteResult writeResult    = client.Write(Obis, FormatWriteParameter(relayParameter));

            var result = new CommandResult(writeResult.Success);

            if (!result.Success)
            {
                string message = string.Format(
                    Resources.RelayControlCommand_WriteFailedMessageFormat,
                    this.Name,
                    writeResult.Error.ToString(),
                    relayParameter.ToString());

                logger.Error(message);
                throw new CommunicationException(message);
            }

            return(result);
        }
Esempio n. 4
0
        //[Authorize(Roles ="SAdmin")]
        public async Task <HttpResponseMessage> TruncateUserMaster()
        {
            //Db = con.SurgeryCenterDb(UMD.Project_ID);
            UserResponse Response = new UserResponse();

            try
            {
                MT_User             User         = new MT_User();
                CollectionReference docRef       = Db.Collection("MT_User");
                QuerySnapshot       ObjQuerySnap = await docRef.GetSnapshotAsync();

                if (ObjQuerySnap != null)
                {
                    foreach (DocumentSnapshot Docsnapshot in ObjQuerySnap.Documents)
                    {
                        User = Docsnapshot.ConvertTo <MT_User>();
                        if (User.UM_Unique_ID != "28bLAlDi21ab1a937541a6")
                        {
                            DocumentReference DocRef = Db.Collection("MT_User").Document(User.UM_Unique_ID);
                            WriteResult       Result = await DocRef.DeleteAsync();

                            if (Result != null)
                            {
                                Response.Status  = con.StatusSuccess;
                                Response.Message = con.MessageSuccess;
                                Response.Data    = null;
                            }
                        }
                    }
                }
                Response.Status  = con.StatusSuccess;
                Response.Message = con.MessageSuccess;
            }
            catch (Exception ex)
            {
                Response.Status  = con.StatusFailed;
                Response.Message = con.MessageFailed + ", Exception : " + ex.Message;
            }
            return(ConvertToJSON(Response));
        }
Esempio n. 5
0
        public bool WriteApplication(string packageName, object tag)
        {
            if (!(tag is Tag))
            {
                return(false);
            }
            if (string.IsNullOrEmpty(packageName))
            {
                return(false);
            }

            WriteResult writeResult = WriteResult.FAILED;

            try
            {
                NdefRecord  packageRecord = NdefRecord.CreateApplicationRecord(packageName);
                NdefMessage ndefMessage   = new NdefMessage(new NdefRecord[] { packageRecord });
                writeResult = WriteTag(ndefMessage, (Tag)tag);
            }
            catch { }
            return(writeResult == WriteResult.OK);
        }
Esempio n. 6
0
        public bool WriteMimeMedia(string mimeType, byte[] mimeData, object tag)
        {
            if (!(tag is Tag))
            {
                return(false);
            }
            if (string.IsNullOrEmpty(mimeType) || mimeData.Length == 0)
            {
                return(false);
            }

            WriteResult writeResult = WriteResult.FAILED;

            try
            {
                NdefRecord  mimeRecord  = NdefRecord.CreateMime(mimeType, mimeData);
                NdefMessage ndefMessage = new NdefMessage(new NdefRecord[] { mimeRecord });
                writeResult = WriteTag(ndefMessage, (Tag)tag);
            }
            catch { }
            return(writeResult == WriteResult.OK);
        }
Esempio n. 7
0
        public static void Example()
        {
            string strPath = System.AppDomain.CurrentDomain.BaseDirectory;

            // Instantiate Object
            APOCR.Net45.OCR ocr = new APOCR.Net45.OCR();

            // Enable extra logging (logging should only be used while
            // troubleshooting) C:\ProgramData\activePDF\Logs\
            ocr.Settings.Debug = true;

            // Linearize the output PDF
            ocr.Settings.PDF.Linearize = true;

            // Convert the file to PDF
            OCRDK.Results.OCRResult result =
                ocr.Convert(
                    inputFile: $"{strPath}..\\..\\..\\Input\\OCR.TIF.Input.tif",
                    outputFile: $"{strPath}..\\..\\..\\Output\\OCR.LinearizeFile.Output.pdf");

            WriteResult.Write(result);
        }
Esempio n. 8
0
        static void StartEchoServer()
        {
            Console.WriteLine("[Server] starting TCP/9000");

            _Server = new CavemanTcpServer("127.0.0.01", 9000, false, null, null);
            _Server.Events.ClientConnected += (s, e) =>
            {
                _LastIpPort = e.IpPort;
                Console.WriteLine("[Server] " + e.IpPort + " connected");
            };

            _Server.Events.ClientDisconnected += (s, e) =>
            {
                _LastIpPort = null;
                Console.WriteLine("[Server] " + e.IpPort + " disconnected");
            };

            _Server.Logger = Console.WriteLine;

            _Server.Start();

            Console.WriteLine("[Server] started TCP/9000");

            while (true)
            {
                if (String.IsNullOrEmpty(_LastIpPort))
                {
                    Task.Delay(100).Wait();
                    continue;
                }

                ReadResult rr = _Server.Read(_LastIpPort, 10);
                if (rr.Status == ReadResultStatus.Success)
                {
                    Console.WriteLine("[Server] received " + Encoding.UTF8.GetString(rr.Data));
                    WriteResult wr = _Server.Send(_LastIpPort, "serverecho");
                }
            }
        }
Esempio n. 9
0
        public async Task <HttpResponseMessage> UpdateAsync(MT_Instrument IMD)
        {
            Db = con.SurgeryCenterDb(IMD.Slug);
            InstrumentResponse Response = new InstrumentResponse();

            try
            {
                Dictionary <string, object> initialData = new Dictionary <string, object>
                {
                    { "Instru_Name", IMD.Instru_Name },
                    { "Instru_Type", IMD.Instru_Type },
                    { "Instru_Description", IMD.Instru_Description },
                    { "Instru_Modify_Date", con.ConvertTimeZone(IMD.Instru_TimeZone, Convert.ToDateTime(IMD.Instru_Modify_Date)) },
                    { "Instru_Surgery_Physician_Id", IMD.Instru_Surgery_Physician_Id }
                };

                DocumentReference docRef = Db.Collection("MT_Instrument").Document(IMD.Instru_Unique_ID);
                WriteResult       Result = await docRef.UpdateAsync(initialData);

                if (Result != null)
                {
                    Response.Status  = con.StatusSuccess;
                    Response.Message = con.MessageSuccess;
                    Response.Data    = IMD;
                }
                else
                {
                    Response.Status  = con.StatusNotUpdate;
                    Response.Message = con.MessageNotUpdate;
                    Response.Data    = null;
                }
            }
            catch (Exception ex)
            {
                Response.Status  = con.StatusFailed;
                Response.Message = con.MessageFailed + ", Exception : " + ex.Message;
            }
            return(ConvertToJSON(Response));
        }
Esempio n. 10
0
        public async Task <HttpResponseMessage> UpdateAsync(MT_CPT CMD)
        {
            Db = con.SurgeryCenterDb(CMD.Slug);
            CPTResponse Response = new CPTResponse();

            try
            {
                Dictionary <string, object> initialData = new Dictionary <string, object>
                {
                    { "CPT_Code", CMD.CPT_Code },
                    { "CPT_Code_Description", CMD.CPT_Code_Description },
                    { "CPT_Status", CMD.CPT_Status },
                    { "CPT_Procedure_Code_Category", CMD.CPT_Procedure_Code_Category.ToUpper() },
                    { "CPT_Modify_Date", con.ConvertTimeZone(CMD.CPT_TimeZone, Convert.ToDateTime(CMD.CPT_Modify_Date)) }
                };

                DocumentReference docRef = Db.Collection("MT_CPT").Document(CMD.CPT_Unique_ID);
                WriteResult       Result = await docRef.UpdateAsync(initialData);

                if (Result != null)
                {
                    Response.Status  = con.StatusSuccess;
                    Response.Message = con.MessageSuccess;
                    Response.Data    = CMD;
                }
                else
                {
                    Response.Status  = con.StatusNotUpdate;
                    Response.Message = con.MessageNotUpdate;
                    Response.Data    = null;
                }
            }
            catch (Exception ex)
            {
                Response.Status  = con.StatusFailed;
                Response.Message = con.MessageFailed + ", Exception : " + ex.Message;
            }
            return(ConvertToJSON(Response));
        }
Esempio n. 11
0
        public async Task <HttpResponseMessage> Update(MT_Localization LOMD)
        {
            Db = con.SurgeryCenterDb(LOMD.Slug);
            LocalizationResponse Response = new LocalizationResponse();

            try
            {
                Dictionary <string, object> initialData = new Dictionary <string, object>
                {
                    { "Loc_Resource_ID", LOMD.Loc_Resource_ID },
                    { "Loc_Resource_Type", LOMD.Loc_Resource_Type },
                    { "Loc_Value", LOMD.Loc_Value },
                    { "Loc_Modify_Date", con.ConvertTimeZone(LOMD.Loc_TimeZone, Convert.ToDateTime(LOMD.Loc_Modify_Date)) },
                    { "Loc_TimeZone", LOMD.Loc_TimeZone }
                };

                DocumentReference docRef = Db.Collection("MT_Localization").Document(LOMD.Loc_Unique_ID);
                WriteResult       Result = await docRef.UpdateAsync(initialData);

                if (Result != null)
                {
                    Response.Status  = con.StatusSuccess;
                    Response.Message = con.MessageSuccess;
                    Response.Data    = LOMD;
                }
                else
                {
                    Response.Status  = con.StatusNotUpdate;
                    Response.Message = con.MessageNotUpdate;
                    Response.Data    = null;
                }
            }
            catch (Exception ex)
            {
                Response.Status  = con.StatusFailed;
                Response.Message = con.MessageFailed + ", Exception : " + ex.Message;
            }
            return(ConvertToJSON(Response));
        }
Esempio n. 12
0
        public async Task <HttpResponseMessage> Create(MT_Category_Master CMD)
        {
            Db = con.SurgeryCenterDb(CMD.Slug);
            CategoryResponse Response = new CategoryResponse();

            try
            {
                UniqueID         = con.GetUniqueKey();
                CMD.CM_Unique_ID = UniqueID;
                if (CMD.CM_Detail != null)
                {
                    foreach (MT_Category_Detail detail in CMD.CM_Detail)
                    {
                        detail.CD_Unique_ID = con.GetUniqueKey();
                    }
                }
                DocumentReference docRef = Db.Collection("MT_Category_Master").Document(UniqueID);
                WriteResult       Result = await docRef.SetAsync(CMD);

                if (Result != null)
                {
                    Response.Status  = con.StatusSuccess;
                    Response.Message = con.MessageSuccess;
                    Response.Data    = CMD;
                }
                else
                {
                    Response.Status  = con.StatusNotInsert;
                    Response.Message = con.MessageNotInsert;
                    Response.Data    = null;
                }
            }
            catch (Exception ex)
            {
                Response.Status  = con.StatusFailed;
                Response.Message = con.MessageFailed + ", Exception : " + ex.Message;
            }
            return(ConvertToJSON(Response));
        }
Esempio n. 13
0
        /// <summary>
        /// 开启透明通道
        /// </summary>
        /// <param name="client">PcbTesterClient实例</param>
        /// <param name="parameter">端口参数</param>
        /// <returns>运行结果</returns>
        public static CommandResult OpenTransparentChannel(PcbTesterClient client, CommandParameter parameter)
        {
            var communicationParameter        = parameter as MeterCommunicationCommandParameter;
            MeterCommunicationCommand command = new MeterCommunicationCommand();

            //打开透明通道
            WriteResult writeResult = client.Write(command.Obis, command.FormatWriteParameter(communicationParameter));
            var         result      = new CommandResult(writeResult.Success);

            if (!result.Success)  //应答错误
            {
                string message = string.Format(
                    Resources.MeterCommunicationCommand_WriteFailedMessageFormat,
                    command.Name,
                    writeResult.Error.ToString(),
                    communicationParameter.ToString());
                logger.Error(message);
                throw new CommunicationException(message);
            }

            return(result);
        }
Esempio n. 14
0
        public void TestBasicWrite()
        {
            string collectionName = MongoDbPopulatorTestHelper.GetCollectionNameForTest("TestBasicWrite");
            var    adapter        = new MongoDbAdapter("TestApplication", _helper.Globals.MongoDatabases.DicomStoreOptions,
                                                       collectionName);

            var testDoc = new BsonDocument
            {
                { "hello", "world" }
            };

            WriteResult result = adapter.WriteMany(new List <BsonDocument> {
                testDoc
            });

            Assert.True(result == WriteResult.Success);
            Assert.True(_helper.TestDatabase.GetCollection <BsonDocument>(collectionName)
                        .CountDocuments(new BsonDocument()) == 1);

            BsonDocument doc =
                _helper.TestDatabase.GetCollection <BsonDocument>(collectionName).Find(_ => true).ToList()[0];

            Assert.True(doc.Equals(testDoc));

            var toWrite = new List <BsonDocument>();

            for (var i = 0; i < 99; i++)
            {
                toWrite.Add(new BsonDocument {
                    { "hello", i }
                });
            }

            result = adapter.WriteMany(toWrite);

            Assert.True(result == WriteResult.Success);
            Assert.True(_helper.TestDatabase.GetCollection <BsonDocument>(collectionName)
                        .CountDocuments(new BsonDocument()) == 100);
        }
Esempio n. 15
0
        public bool WriteExternalType(string domain, string type, string payload, object tag)
        {
            if (!(tag is Tag))
            {
                return(false);
            }
            if (string.IsNullOrEmpty(domain) || string.IsNullOrEmpty(type) || string.IsNullOrEmpty(payload))
            {
                return(false);
            }

            WriteResult writeResult = WriteResult.FAILED;

            try
            {
                NdefRecord  extRecord   = NdefRecord.CreateExternal(domain, type, Encoding.UTF8.GetBytes(payload));
                NdefMessage ndefMessage = new NdefMessage(new NdefRecord[] { extRecord });
                writeResult = WriteTag(ndefMessage, (Tag)tag);
            }
            catch { }
            return(writeResult == WriteResult.OK);
        }
Esempio n. 16
0
            public override IWriteResult WritePageArea(IRenderContext context, PageArea pageArea)
            {
                if (pageArea == PageArea.Head)
                {
                    if (_styleUrls != null)
                    {
                        foreach (var url in _styleUrls)
                        {
                            context.Html.WriteElementLine("link", string.Empty, "rel", "stylesheet", "href", url);
                        }
                    }
                    if (_scriptUrls != null)
                    {
                        foreach (var url in _scriptUrls)
                        {
                            context.Html.WriteElementLine("script", string.Empty, "src", url);
                        }
                    }
                }

                return(WriteResult.Continue());
            }
Esempio n. 17
0
        public async Task <HttpResponseMessage> UpdateAsync(MT_Block BMD)
        {
            Db = con.SurgeryCenterDb(BMD.Slug);
            BlockResponse Response = new BlockResponse();

            try
            {
                Dictionary <string, object> initialData = new Dictionary <string, object>
                {
                    { "Block_Type", BMD.Block_Type },
                    { "Block_Name", BMD.Block_Name },
                    { "Block_Modify_Date", con.ConvertTimeZone(BMD.Block_TimeZone, Convert.ToDateTime(BMD.Block_Modify_Date)) },
                    { "Block_Is_Active", BMD.Block_Is_Active },
                    { "Block_Is_Deleted", BMD.Block_Is_Deleted }
                };

                DocumentReference docRef = Db.Collection("MT_Block").Document(BMD.Block_Unique_ID);
                WriteResult       Result = await docRef.UpdateAsync(initialData);

                if (Result != null)
                {
                    Response.Status  = con.StatusSuccess;
                    Response.Message = con.MessageSuccess;
                    Response.Data    = BMD;
                }
                else
                {
                    Response.Status  = con.StatusNotUpdate;
                    Response.Message = con.MessageNotUpdate;
                    Response.Data    = null;
                }
            }
            catch (Exception ex)
            {
                Response.Status  = con.StatusFailed;
                Response.Message = con.MessageFailed + ", Exception : " + ex.Message;
            }
            return(ConvertToJSON(Response));
        }
Esempio n. 18
0
        public async Task <HttpResponseMessage> CreateAsync(MT_Patient_Forms_URLs PMD)
        {
            Db = con.SurgeryCenterDb(PMD.Slug);
            PFURLResponse Response = new PFURLResponse();

            try
            {
                UniqueID           = con.GetUniqueKey();
                PMD.PFU_Unique_ID  = UniqueID;
                PMD.PFU_Actual_URL = "https://dev.tchdemo.com/in/" + PMD.PFU_Booking_ID + "/" + PMD.PFU_Form_ID;
                PMD.PFU_Dummy_URL  = "https://dev.tchdemo.com/r/" + con.GetUrlToken() + "/" + UniqueID;
                PMD.PFU_Is_Active  = true;
                //PMD.PFU_Passcode=

                DocumentReference docRef = Db.Collection("MT_Patient_Forms_URLs").Document(UniqueID);
                WriteResult       Result = await docRef.SetAsync(PMD);

                if (Result != null)
                {
                    Response.Status    = con.StatusSuccess;
                    Response.Message   = con.MessageSuccess;
                    PMD.PFU_Actual_URL = "";
                    Response.Data      = PMD;
                }
                else
                {
                    Response.Status  = con.StatusNotInsert;
                    Response.Message = con.MessageNotInsert;
                    Response.Data    = null;
                }
            }
            catch (Exception ex)
            {
                Response.Status  = con.StatusFailed;
                Response.Message = con.MessageFailed + ", Exception : " + ex.Message;
            }
            return(ConvertToJSON(Response));
        }
Esempio n. 19
0
        public async Task <HttpResponseMessage> CreateAsync(MT_Right RMD)
        {
            RightResponse Response = new RightResponse();

            try
            {
                //Right Master
                UniqueID           = con.GetUniqueKey();
                UniqueID_Detail    = con.GetUniqueKey();
                RMD.RM_Unique_ID   = UniqueID;
                RMD.RM_Create_Date = con.ConvertTimeZone(RMD.RM_TimeZone, Convert.ToDateTime(RMD.RM_Create_Date));
                RMD.RM_Modify_Date = con.ConvertTimeZone(RMD.RM_TimeZone, Convert.ToDateTime(RMD.RM_Modify_Date));
                //Right Details
                RMD.RM_Right_Details.RD_Unique_ID       = UniqueID_Detail;
                RMD.RM_Right_Details.RD_Right_Master_ID = UniqueID;
                DocumentReference docRef = Db.Collection("MT_Right").Document(UniqueID);
                WriteResult       Result = await docRef.SetAsync(RMD);

                if (Result != null)
                {
                    Response.Status  = con.StatusSuccess;
                    Response.Message = con.MessageSuccess;
                    Response.Data    = RMD;
                }
                else
                {
                    Response.Status  = con.StatusNotInsert;
                    Response.Message = con.MessageNotInsert;
                    Response.Data    = null;
                }
            }
            catch (Exception ex)
            {
                Response.Status  = con.StatusFailed;
                Response.Message = con.MessageFailed + ", Exception : " + ex.Message;
            }
            return(ConvertToJSON(Response));
        }
Esempio n. 20
0
        private void RegisterService(string Ip, int Port)
        {
            string serviceId = $"{Ip}-{Port}";
            IEnumerable <IConfigurationSection> options = _configuration?.GetSection("ConsulOptions").GetChildren();

            ConsulConfig consulConfig = new ConsulConfig();

            if (options?.Count() > 0)
            {
                consulConfig.CheckInterval    = int.Parse(options.First(x => x.Key == "CheckInterval").Value);
                consulConfig.CriticalInterval = int.Parse(options.First(x => x.Key == "CriticalInterval").Value);
            }

            AgentCheckRegistration acr = new AgentCheckRegistration
            {
                TCP      = $"{Ip}:{Port}",
                Name     = serviceId,
                ID       = serviceId,
                Interval = TimeSpan.FromSeconds(consulConfig.CheckInterval),
                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(consulConfig.CriticalInterval)
            };
            AgentServiceRegistration asr = new AgentServiceRegistration
            {
                Address = Ip,
                ID      = serviceId,
                Name    = serviceId,
                Port    = Port,
                Check   = acr
            };
            WriteResult res = _consulClient.Agent.ServiceRegister(asr).Result;

            if (res.StatusCode != HttpStatusCode.OK)
            {
                ApplicationException ex = new ApplicationException($"Failed to register service {Ip} on port {Port}");
                _logger.Error($"Failed to register service {Ip} on port {Port}", ex);
                throw ex;
            }
        }
Esempio n. 21
0
        public override Task <WriteResult> WriteVariables(Origin origin, VariableValue[] values, Duration?timeout)
        {
            var failures = new List <VariableError>();

            foreach (VariableValue vv in values)
            {
                string error = null;
                if (varVals.ContainsKey(vv.Variable.Object))
                {
                    VariableValue[] currentValues = varVals[vv.Variable.Object];
                    bool            variableFound = false;
                    for (int i = 0; i < currentValues.Length; ++i)
                    {
                        if (currentValues[i].Variable == vv.Variable)
                        {
                            currentValues[i]            = vv;
                            varVals[vv.Variable.Object] = currentValues;
                            variableFound = true;
                            break;
                        }
                    }
                    if (!variableFound)
                    {
                        error = "No variable found with name " + vv.Variable;
                    }
                }
                else
                {
                    error = "No object found with id " + vv.Variable.Object.ToString();
                }

                if (error != null)
                {
                    failures.Add(new VariableError(vv.Variable, error));
                }
            }
            return(Task.FromResult(failures.Count == 0 ? WriteResult.OK : WriteResult.Failure(failures.ToArray())));
        }
Esempio n. 22
0
        public void Test_ReadWrite(string path)
        {
            string     inputPath = InputPath(path);
            ReadResult expected  = ObjFile.Read(inputPath);

            Assert.IsTrue(expected.Succeeded);

            Mesh mesh = expected.Mesh;

            WriteResult writeResult = ObjFile.Write(mesh, this.outputPath);

            Assert.IsTrue(writeResult.Succeeded);

            ReadResult actual = ObjFile.Read(this.outputPath);

            Assert.IsTrue(actual.Succeeded);

            Assert.AreEqual(expected.Mesh.vertices, actual.Mesh.vertices);
            Assert.AreEqual(expected.Mesh.normals, actual.Mesh.normals);
            Assert.AreEqual(expected.Mesh.triangles, actual.Mesh.triangles);
            Assert.AreEqual(expected.Mesh.uv2, actual.Mesh.uv2);
            Assert.AreEqual(expected.Mesh.uv3, actual.Mesh.uv3);
        }
        public static void Example()
        {
            string strPath = System.AppDomain.CurrentDomain.BaseDirectory;

            // Instantiate Object
            APOCR.Net45.OCR ocr = new APOCR.Net45.OCR();

            // Remote connection settings
            ocr.Settings.ServerAddress = "127.0.0.1";
            ocr.Settings.PortNumber    = 62625;

            // Enable extra logging (logging should only be used while
            // troubleshooting) C:\ProgramData\activePDF\Logs\
            ocr.Settings.Debug = true;

            // Convert the file to PDF
            OCRDK.Results.OCRResult result =
                ocr.Convert(
                    inputFile: $"{strPath}..\\..\\..\\Input\\OCR.TIF.Input.tif",
                    outputFile: $"{strPath}..\\..\\..\\Output\\OCR.RemoteConversion.Output.pdf");

            WriteResult.Write(result);
        }
        public async Task <HttpResponseMessage> IsDeleted(MT_Knowledger_Base KCMD)
        {
            Db = con.SurgeryCenterDb(KCMD.Slug);
            KnowledgeBaseResponse Response = new KnowledgeBaseResponse();

            try
            {
                Dictionary <string, object> initialData = new Dictionary <string, object>
                {
                    { "KNB_Is_Deleted", KCMD.KNB_Is_Deleted },
                    { "KNB_Modify_Date", con.ConvertTimeZone(KCMD.KNB_TimeZone, Convert.ToDateTime(KCMD.KNB_Modify_Date)) },
                    { "KNB_TimeZone", KCMD.KNB_TimeZone }
                };

                DocumentReference docRef = Db.Collection("MT_Knowledger_Base").Document(KCMD.KNB_Unique_ID);
                WriteResult       Result = await docRef.UpdateAsync(initialData);

                if (Result != null)
                {
                    Response.Status  = con.StatusSuccess;
                    Response.Message = con.MessageSuccess;
                    Response.Data    = KCMD;
                }
                else
                {
                    Response.Status  = con.StatusNotUpdate;
                    Response.Message = con.MessageNotUpdate;
                    Response.Data    = null;
                }
            }
            catch (Exception ex)
            {
                Response.Status  = con.StatusFailed;
                Response.Message = con.MessageFailed + ", Exception : " + ex.Message;
            }
            return(ConvertToJSON(Response));
        }
Esempio n. 25
0
        public async Task <HttpResponseMessage> IsActive(MT_Patient_Intake PIMD)
        {
            Db = con.SurgeryCenterDb(PIMD.Slug);
            PatientIntakeResponse Response = new PatientIntakeResponse();

            try
            {
                Dictionary <string, object> initialData = new Dictionary <string, object>
                {
                    { "PIT_Is_Active", PIMD.PIT_Is_Active },
                    { "PIT_Modify_Date", con.ConvertTimeZone(PIMD.PIT_TimeZone, Convert.ToDateTime(PIMD.PIT_Modify_Date)) },
                    { "PIT_TimeZone", PIMD.PIT_TimeZone }
                };

                DocumentReference docRef = Db.Collection("MT_Patient_Intake").Document(PIMD.PIT_Unique_ID);
                WriteResult       Result = await docRef.UpdateAsync(initialData);

                if (Result != null)
                {
                    Response.Status  = con.StatusSuccess;
                    Response.Message = con.MessageSuccess;
                    Response.Data    = PIMD;
                }
                else
                {
                    Response.Status  = con.StatusNotInsert;
                    Response.Message = con.MessageNotInsert;
                    Response.Data    = null;
                }
            }
            catch (Exception ex)
            {
                Response.Status  = con.StatusFailed;
                Response.Message = con.MessageFailed + ", Exception : " + ex.Message;
            }
            return(ConvertToJSON(Response));
        }
Esempio n. 26
0
        public async Task <HttpResponseMessage> UpdateAsync(MT_Language LMD)
        {
            Db = con.SurgeryCenterDb(LMD.Slug);
            LanguageResponse Response = new LanguageResponse();

            try
            {
                Dictionary <string, object> initialData = new Dictionary <string, object>
                {
                    { "Lang_Name", LMD.Lang_Name },
                    { "Lang_Shotname", LMD.Lang_Shotname },
                    { "Lang_Modify_Date", con.ConvertTimeZone(LMD.Lang_TimeZone, Convert.ToDateTime(LMD.Lang_Modify_Date)) }
                };

                DocumentReference docRef = Db.Collection("MT_Language").Document(LMD.Lang_Unique_ID);
                WriteResult       Result = await docRef.UpdateAsync(initialData);

                if (Result != null)
                {
                    Response.Status  = con.StatusSuccess;
                    Response.Message = con.MessageSuccess;
                    Response.Data    = LMD;
                }
                else
                {
                    Response.Status  = con.StatusNotUpdate;
                    Response.Message = con.MessageNotUpdate;
                    Response.Data    = null;
                }
            }
            catch (Exception ex)
            {
                Response.Status  = con.StatusFailed;
                Response.Message = con.MessageFailed + ", Exception : " + ex.Message;
            }
            return(ConvertToJSON(Response));
        }
Esempio n. 27
0
        private string RSA_Endoce_Bigramm(string text, long e, long n)
        {
            string     result = "";
            BigInteger bi;

            WriteResult?.Invoke("Длина текста " + text.Length);
            WriteResult?.Invoke("Для каждой пары символов считаем:");
            for (int i = 0; i < text.Length; i += 2)
            {
                int index1 = _characters.IndexOf(text[i]);
                if (i == text.Length - 1)
                {
                    WriteResult?.Invoke("\nШифруем один символ с индексом " + index1);
                    bi = BigInteger.Pow(index1, (int)e);
                    WriteResult?.Invoke("Возводим индекс " + index1 + " умноженный на длину алфавита " + _characters.Length + " в степень e " + e + " = " + bi);
                }
                else
                {
                    int index2 = _characters.IndexOf(text[i + 1]);
                    WriteResult?.Invoke("\nШифруем два символа: с индексами " + index1 + " " + index2);
                    bi = BigInteger.Pow(index2 + index1 * _characters.Length, (int)e);
                    WriteResult?.Invoke("Умножаем индекс первого символа на длину алфавита " + index1 * _characters.Length + " складываем с индексом второго символа " + index2 + " = " + (index1 * _characters.Length + index2));
                    WriteResult?.Invoke("Возводим сумму " + (index1 * _characters.Length + index2) + " в степень e " + e + " = " + bi);
                }
                BigInteger n_ = new BigInteger((int)n);
                bi = bi % n_;
                WriteResult?.Invoke("Находим остаток от деления полученного числа на N " + n_ + " = " + bi);
                result += bi.ToString();
                if (i != text.Length - 1)
                {
                    result += ' ';
                }
                WriteResult?.Invoke("Полученное число - зашифрованный биграмм записываем в результат: " + result);
            }

            return(result);
        }
Esempio n. 28
0
        public override void Do()
        {
            var msg = "g=" + _g;

            WriteResult?.Invoke(msg);
            msg = "p=" + _p;
            WriteResult?.Invoke(msg);
            msg = "a=" + _a;
            WriteResult?.Invoke(msg);
            msg = "b=" + _b;
            WriteResult?.Invoke(msg);

            UInt64 A = MyPow(_g, _a, _p);

            msg = "1)\n(1)A=g^a modp=" + A;
            WriteResult?.Invoke(msg);
            UInt64 B = MyPow(_g, _b, _p);

            msg = "(2)B=g^b modp=" + B;
            WriteResult?.Invoke(msg);
            UInt64 B2 = MyPow(B, _a, _p);

            msg = "2)\n(3)B^a modp=g^ab modp=" + B2;
            WriteResult?.Invoke(msg);
            UInt64 A2 = MyPow(A, _b, _p);

            msg = "(4)A^b modp=g^ab modp=" + A2;
            WriteResult?.Invoke(msg);
            if (A2 != B2)
            {
                return;
            }
            ulong K = A2;

            msg = "3)\n(5)K=g^ab modp=" + K;
            WriteResult?.Invoke(msg);
        }
Esempio n. 29
0
        public virtual IWriteResult WritePageArea(
            IRenderContext context,
            PageArea pageArea,
            Func <IRenderContext, PageArea, string, IWriteResult> childWriter)
        {
            var result = WriteResult.Continue();

#if TRACE
            context.Trace(() => ToString() + " writing layout body");
            context.TraceIndent();
#endif

            if (context.IncludeComments)
            {
                context.Html.WriteComment("layout " + this.FullyQualifiedName());
            }

            for (var i = 0; i < _visualElements.Length; i++)
            {
                var visualElement = _visualElements[i];

                if (pageArea == PageArea.Body && !ReferenceEquals(visualElement.StaticHtml, null))
                {
                    visualElement.StaticHtml.WriteAction(context.Html);
                }

                if (!ReferenceEquals(visualElement.ZoneName, null))
                {
                    result.Add(childWriter(context, pageArea, visualElement.ZoneName));
                }
            }

#if TRACE
            context.TraceOutdent();
#endif
            return(result);
        }
Esempio n. 30
0
        public async Task <HttpResponseMessage> Update(MT_Page_Master PMD)
        {
            Db = con.SurgeryCenterDb(PMD.Slug);
            PageMasterResponse Response = new PageMasterResponse();

            try
            {
                Dictionary <string, object> initialData = new Dictionary <string, object>
                {
                    { "PM_Is_View", PMD.Is_View },
                    { "PM_Is_Add", PMD.Is_Add },
                    { "PM_Is_Edit", PMD.Is_Edit },
                    { "PM_Is_Deleted", PMD.Is_Delete },
                };
                DocumentReference docRef = Db.Collection("MT_Page_Master").Document(PMD.PM_Unique_ID);
                WriteResult       Result = await docRef.UpdateAsync(initialData);

                if (Result != null)
                {
                    Response.Status  = con.StatusSuccess;
                    Response.Message = con.MessageSuccess;
                    Response.Data    = PMD;
                }
                else
                {
                    Response.Status  = con.StatusNotUpdate;
                    Response.Message = con.MessageNotUpdate;
                    Response.Data    = null;
                }
            }
            catch (Exception ex)
            {
                Response.Status  = con.StatusFailed;
                Response.Message = con.MessageFailed + ", Exception : " + ex.Message;
            }
            return(ConvertToJSON(Response));
        }
        public async Task <HttpResponseMessage> CreateAsync(MT_Knowledger_Base KCMD)
        {
            Db = con.SurgeryCenterDb(KCMD.Slug);
            KnowledgeBaseResponse Response = new KnowledgeBaseResponse();

            try
            {
                List <string> List = new List <string>();
                UniqueID             = con.GetUniqueKey();
                KCMD.KNB_Unique_ID   = UniqueID;
                KCMD.KNB_Create_Date = con.ConvertTimeZone(KCMD.KNB_TimeZone, Convert.ToDateTime(KCMD.KNB_Create_Date));
                KCMD.KNB_Modify_Date = con.ConvertTimeZone(KCMD.KNB_TimeZone, Convert.ToDateTime(KCMD.KNB_Modify_Date));

                DocumentReference docRef = Db.Collection("MT_Knowledger_Base").Document(UniqueID);
                WriteResult       Result = await docRef.SetAsync(KCMD);

                if (Result != null)
                {
                    Response.Status  = con.StatusSuccess;
                    Response.Message = con.MessageSuccess;
                    Response.Data    = KCMD;
                }
                else
                {
                    Response.Status  = con.StatusNotInsert;
                    Response.Message = con.MessageNotInsert;
                    Response.Data    = null;
                }
            }
            catch (Exception ex)
            {
                Response.Status  = con.StatusFailed;
                Response.Message = con.MessageFailed + ", Exception : " + ex.Message;
            }
            return(ConvertToJSON(Response));
        }
Esempio n. 32
0
 /// <summary>
 /// Fire is used to fire a new user event. Only the Name, Payload and Filters are respected. This returns the ID or an associated error. Cross DC requests are supported.
 /// </summary>
 /// <param name="ue">A User Event definition</param>
 /// <param name="q">Customized write options</param>
 /// <returns></returns>
 public WriteResult<string> Fire(UserEvent ue, WriteOptions q)
 {
     var req =
         _client.CreateWrite<byte[], EventCreationResult>(string.Format("/v1/event/fire/{0}", ue.Name),
             ue.Payload, q);
     if (!string.IsNullOrEmpty(ue.NodeFilter))
     {
         req.Params["node"] = ue.NodeFilter;
     }
     if (!string.IsNullOrEmpty(ue.ServiceFilter))
     {
         req.Params["service"] = ue.ServiceFilter;
     }
     if (!string.IsNullOrEmpty(ue.TagFilter))
     {
         req.Params["tag"] = ue.TagFilter;
     }
     var res = req.Execute();
     var ret = new WriteResult<string>()
     {
         RequestTime = res.RequestTime,
         Response = res.Response.ID
     };
     return ret;
 }
Esempio n. 33
0
        protected override async void NewIntent(Cirrious.CrossCore.Core.MvxValueEventArgs<Intent> e)
        {
            WriteResult writeResult = new WriteResult();
            writeResult.ReasonForFailure = FailureReasons.Unkown;


            var id = GetIdFromTag(e.Value);
            var intent = e.Value;
            Tag tag = (Tag) intent.GetParcelableExtra(NfcAdapter.ExtraTag);

            Ndef ndef = Ndef.Get(tag);
            if (ndef != null)
            {
                ndef.Connect();
                if (!ndef.IsWritable)
                {
                    writeResult.ReasonForFailure = FailureReasons.TagReadOnly;
                    _taskCompletionSource.TrySetResult(writeResult);
                    return;
                }
                byte[] message = _messageToWrite.ToByteArray();
                if (ndef.MaxSize < message.Length)
                {
                    writeResult.ReasonForFailure = FailureReasons.TagTooSmall;
                    _taskCompletionSource.TrySetResult(writeResult);
                    return;
                }

                try
                {
                    await ndef.WriteNdefMessageAsync(new Android.Nfc.NdefMessage(message));
                    writeResult.ReasonForFailure = FailureReasons.DidNotFail;
                    writeResult.NFCTag = new NFCTag()
                    {
                        Id = id
                    };
                    _taskCompletionSource.TrySetResult(writeResult);
                    return;
                }
                catch (TagLostException tagLost)
                {
                    writeResult.ReasonForFailure = FailureReasons.TagLostDuringWrite;
                    _taskCompletionSource.TrySetResult(writeResult);
                    return;
                }
                catch (Exception err)
                {
                    Mvx.Error("Error writing Tag: " + err.ToString());
                    writeResult.ReasonForFailure = FailureReasons.ErrorDuringWrite;
                    _taskCompletionSource.TrySetResult(writeResult);
                    return;
                }
            }
            else
            {
                writeResult.ReasonForFailure = FailureReasons.UnableToFormatTag;
                _taskCompletionSource.TrySetResult(writeResult);
                return;
            }


        }
Esempio n. 34
0
 /// <summary>
 /// 結果を取得します
 /// 多少遅延が発生します
 /// TODO:非同期対応
 /// </summary>
 public void GetResult()
 {
     if (this.isGet)
     {
         return;
     }
     this.Html = this.GetResponseHtml();
     this.Title = this.GetHTMLTitle();
     this.Tag2ch = this.GetHTML2chTag();
     this.Result = WriteResponse.GetWriteResult(this.Title, this.Tag2ch);
     this.isGet = true;
 }