public KeyValuePair <int, string> this[EnumErrorCode errorCode, params object[] formatter]
 {
     get
     {
         return(base[(int)errorCode, formatter]);
     }
 }
        private static TextResult[] DecodeFile(string strImagePath, int mode, int iLeft, int iTop, int iRight, int iBottom)
        {
            BarcodeReader _br = new BarcodeReader();

            _br.ProductKeys = "t0068MgAAADaH8yokXmKf3axcV99lMBDDRYEZIsBZ5PPiekmW820HqSR2tQ/VOjuXPvq1FCvla7eS6KmEMUFgHZR9X7GuR2s=";
            string[] strTemplateNameArray       = { "All_DEFAULT", "All_DEFAULT_WITHREGION" };
            string   tempDefaultTemplateJson    = "{\"Version\": \"2.0\",\"ImageParameter\": {\"Name\": \"" + strTemplateNameArray[0] + "\",\"BarcodeFormatIds\": [\"BF_ALL\"],\"RegionPredetectionModes\": [{\"Mode\":\"RPM_GENERAL_RGB_CONTRAST\"}]}}";
            string   tempTemplateJsonWithRegion = "{\"Version\": \"2.0\",\"ImageParameter\": {\"Name\": \"" + strTemplateNameArray[1] + "\",\"BarcodeFormatIds\": [\"BF_ALL\"],\"RegionPredetectionModes\": [{\"Mode\":\"RPM_GENERAL\"}],\"RegionDefinitionNameArray\": [\"Region\"]},\"RegionDefinitionArray\": [{\"Name\": \"Region\",\"MeasuredByPercentage\": 1" + ",\"Left\":" + iLeft.ToString() + ",\"Top\":" + iTop.ToString() + ",\"Right\":" + iRight.ToString() + ",\"Bottom\":" + iBottom.ToString() + "}]}";

            if (mode == 0)
            {
                // load template json as a string.
                string        errorstring   = "";
                EnumErrorCode temperrorcode = _br.InitRuntimeSettingsWithString(tempDefaultTemplateJson, EnumConflictMode.CM_OVERWRITE, out errorstring);
            }
            else
            {
                // load template json as a string.
                string        errorstring   = "";
                EnumErrorCode temperrorcode = _br.InitRuntimeSettingsWithString(tempTemplateJsonWithRegion, EnumConflictMode.CM_OVERWRITE, out errorstring);
            }
            _br.DecodeFile(strImagePath, strTemplateNameArray[mode]);
            TextResult[] result = _br.DecodeFile(strImagePath, strTemplateNameArray[mode]);

            return(result);
        }
Beispiel #3
0
        public override void HandleMsg(params object[] _params)
        {
            EnumMsgCode   enumMsgCode   = (EnumMsgCode)_params[0];
            EnumErrorCode enumErrorCode = (EnumErrorCode)_params[1];

            MyJson.JsonNode_Object json = new MyJson.JsonNode_Object();
            if (enumMsgCode == EnumMsgCode.SignSuc)
            {
                byte[] _outdata  = (byte[])_params[1];
                var    pubkeylen = _outdata[0];
                var    pubkey    = new byte[pubkeylen];
                Array.Copy(_outdata, 1, pubkey, 0, pubkeylen);
                var signdata = _outdata.Skip(pubkeylen + 1).ToArray();
                json["signdata"] = new MyJson.JsonNode_ValueString(SignTool.Bytes2HexString(signdata, 0, signdata.Length));
                json["pubkey"]   = new MyJson.JsonNode_ValueString(SignTool.Bytes2HexString(pubkey, 0, pubkey.Length));
                json["tag"]      = new MyJson.JsonNode_ValueNumber(0);
            }
            else
            {
                json["signdata"] = new MyJson.JsonNode_ValueString("");
                json["pubkey"]   = new MyJson.JsonNode_ValueString("");
                json["tag"]      = new MyJson.JsonNode_ValueNumber(0);
            }
            result.msgCode = enumMsgCode;
            result.data    = json;
        }
Beispiel #4
0
        private static TextResult[] DecodeFile(string strImagePath, int mode, int iLeft, int iTop, int iRight, int iBottom)
        {
            BarcodeReader _br = new BarcodeReader();

            _br.LicenseKeys = "t0068MgAAAJbpvFwUvsodF81FjWojDo91ZYmDf3+aNdOGPOBOygS6Yte0JFqPMt/DnNMdfGS4gInUd+5RYOCX6IramuO+m4A=";
            string[] strTemplateNameArray       = { "All_DEFAULT", "All_DEFAULT_WITHREGION" };
            string   tempDefaultTemplateJson    = "{\"Version\": \"2.0\",\"ImageParameter\": {\"Name\": \"" + strTemplateNameArray[0] + "\",\"BarcodeFormatIds\": [\"All\"],\"RegionPredetectionMode\": \"Enable\"}}";
            string   tempTemplateJsonWithRegion = "{\"Version\": \"2.0\",\"ImageParameter\": {\"Name\": \"" + strTemplateNameArray[1] + "\",\"BarcodeFormatIds\": [\"All\"],\"RegionPredetectionMode\": \"Disable\",\"RegionDefinitionNameArray\": [\"Region\"]},\"RegionDefinitionArray\": [{\"Name\": \"Region\",\"MeasuredByPercentage\": true" + ",\"Left\":" + iLeft.ToString() + ",\"Top\":" + iTop.ToString() + ",\"Right\":" + iRight.ToString() + ",\"Bottom\":" + iBottom.ToString() + "}]}";

            if (mode == 0)
            {
                // load template json as a string.
                string        errorstring   = "";
                EnumErrorCode temperrorcode = _br.InitRuntimeSettingsWithString(tempDefaultTemplateJson, EnumConflictMode.ECM_Overwrite, out errorstring);
            }
            else
            {
                // load template json as a string.
                string        errorstring   = "";
                EnumErrorCode temperrorcode = _br.InitRuntimeSettingsWithString(tempTemplateJsonWithRegion, EnumConflictMode.ECM_Overwrite, out errorstring);
            }
            _br.DecodeFile(strImagePath, strTemplateNameArray[mode]);
            TextResult[] result = _br.DecodeFile(strImagePath, strTemplateNameArray[mode]);

            return(result);
        }
Beispiel #5
0
        public override void HandleMsg(params object[] _params)
        {
            EnumMsgCode   enumMsgCode   = (EnumMsgCode)_params[0];
            EnumErrorCode enumErrorCode = (EnumErrorCode)_params[1];

            result.msgCode   = enumMsgCode;
            result.errorCode = enumErrorCode;
        }
Beispiel #6
0
        private static string GetMessageFromEnumErrorCode(EnumErrorCode enumErrorCode)
        {
            string message = "Server Error";

            switch (enumErrorCode)
            {
            case EnumErrorCode.USER_WRONG_EMAIL:
                message = "User with given mobile is already registered with another email. Please contact administrator.";
                break;

            case EnumErrorCode.USER_BLOCKED:
                message = "User is blocked. Please contact administrator.";
                break;

            case EnumErrorCode.USER_REJECTED:
                message = "User  is rejected. Please contact administrator.";
                break;

            case EnumErrorCode.USER_NOTREGISTERED:
                message = "User  is not registered. Please register first.";
                break;

            case EnumErrorCode.USER_ALREADY_REGISTERED:
                message = "User  is already registered. Please login.";
                break;

            case EnumErrorCode.USER_OTP_NOT_VALID:
                message = "The OTP is not valid. Please retry.";
                break;

            case EnumErrorCode.USER_INVALID:
                message = "User is no longer valid. Please contact administrator.";
                break;

            case EnumErrorCode.USER_STATE_MAPPING_NOT_PRESENT:
                message = "User state is not present. Please contact administrator.";
                break;

            case EnumErrorCode.COUNTRY_ID_NOT_PRESENT:
                message = "Country is not provided. Please contact administrator.";
                break;

            case EnumErrorCode.STATE_ID_NOT_PRESENT:
                message = "State is not provided. Please contact administrator.";
                break;

            case EnumErrorCode.APPLICATION_LIMIT_EXCEEDED:
                message = "Application limit exceeded. Please contact administrator.";
                break;

            default:
                message = "Some error occurred";
                break;
            }
            return(message);
        }
Beispiel #7
0
        private string Error2Word(EnumErrorCode enumErrorCode)
        {
            string errorCode = "$error_" + ((uint)enumErrorCode).ToString("x4");

            if (curDic.ContainsKey(errorCode))
            {
                return(curDic[errorCode]);
            }
            return("");
        }
Beispiel #8
0
        public override void HandleMsg(params object[] _params)
        {
            EnumMsgCode   enumMsgCode   = (EnumMsgCode)_params[0];
            EnumErrorCode enumErrorCode = (EnumErrorCode)_params[1];

            if (enumMsgCode == EnumMsgCode.BuildSecurityChannelSuc)
            {
                byte[] data = (byte[])_params[2];
                ECDH.Ins.pubKey_B = data;
                ECDH.Ins.CalM(data);
            }
        }
Beispiel #9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="KinveyException"/> class.
        /// </summary>
        /// <param name="errorCategory">The <see cref="EnumErrorCategory"/>  of the exception.</param>
        /// <param name="errorCode">The <see cref="EnumErrorCode"/>  of the exception.</param>
        /// <param name="info">Additional information about the exception.</param>
        /// <param name="innerException">[optional] Inner exception thrown, if available.</param>
        public KinveyException(EnumErrorCategory errorCategory, EnumErrorCode errorCode, string info, Exception innerException = null)
            : base(MessageFromErrorCode(errorCategory, errorCode), innerException)
        {
            this.errorCategory = errorCategory;
            this.errorCode     = errorCode;
            this.info          = info;

            Tuple <string, string, string> errorInfo = InfoFromErrorCode(errorCategory, errorCode);

            this.error       = errorInfo.Item1;
            this.debug       = errorInfo.Item2;
            this.description = errorInfo.Item3;
        }
Beispiel #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="KinveyException"/> class.
        /// </summary>
        /// <param name="errorCategory">The <see cref="EnumErrorCategory"/>  of the exception.</param>
        /// <param name="errorCode">The <see cref="EnumErrorCode"/>  of the exception.</param>
        /// <param name="response">Http response.</param>
        /// <param name="innerException">Inner exception thrown, if available.</param>
        public KinveyException(EnumErrorCategory errorCategory, EnumErrorCode errorCode, HttpResponseMessage response, Exception innerException)
            : base(innerException.Message, innerException)
        {
            this.errorCategory = errorCategory;
            this.errorCode     = errorCode;

            Tuple <string, string, string> errorInfo = InfoFromErrorCode(errorCategory, errorCode);

            StatusCode = (int)response.StatusCode;

            try
            {
                KinveyJsonError errorJSON = KinveyJsonError.parse(response);
                this.error       = errorJSON.Error ?? errorInfo.Item1;
                this.debug       = errorJSON.Debug ?? errorInfo.Item2;
                this.description = errorJSON.Description ?? errorInfo.Item3;
                this.requestID   = HelperMethods.getRequestID(response);
            }
            catch (Exception) {
                //Catch any exceptions thrown while parsing an unknown responseJSON
            }
        }
Beispiel #11
0
        private static TextResult[] DecodeFile(string strImagePath, int mode, int iLeft, int iTop, int iRight, int iBottom)
        {
            BarcodeReader _br = new BarcodeReader();

            _br.ProductKeys = "t0068MgAAAEUWFzAvIFjWdsOhURov3SljTtFakKFsHemq+2NKnvb5tEihIDmWlZsFpCWpVOnWr1Uw1NzIQ2EcnLj9Hxxvjfs=";

            string strErrorMSG = "";

            //Best coverage settings
            _br.InitRuntimeSettingsWithString("{\"ImageParameter\":{\"Name\":\"BestCoverage\",\"DeblurLevel\":9,\"ExpectedBarcodesCount\":512,\"ScaleDownThreshold\":100000,\"LocalizationModes\":[{\"Mode\":\"LM_CONNECTED_BLOCKS\"},{\"Mode\":\"LM_SCAN_DIRECTLY\"},{\"Mode\":\"LM_STATISTICS\"},{\"Mode\":\"LM_LINES\"},{\"Mode\":\"LM_STATISTICS_MARKS\"}],\"GrayscaleTransformationModes\":[{\"Mode\":\"GTM_ORIGINAL\"},{\"Mode\":\"GTM_INVERTED\"}]}}", EnumConflictMode.CM_OVERWRITE, out strErrorMSG);
            //Best speed settings
            //_br.InitRuntimeSettingsWithString("{\"ImageParameter\":{\"Name\":\"BestSpeed\",\"DeblurLevel\":3,\"ExpectedBarcodesCount\":512,\"LocalizationModes\":[{\"Mode\":\"LM_SCAN_DIRECTLY\"}],\"TextFilterModes\":[{\"MinImageDimension\":262144,\"Mode\":\"TFM_GENERAL_CONTOUR\"}]}}", EnumConflictMode.CM_OVERWRITE, out strErrorMSG);
            //Balance settings
            //_br.InitRuntimeSettingsWithString("{\"ImageParameter\":{\"Name\":\"Balance\",\"DeblurLevel\":5,\"ExpectedBarcodesCount\":512,\"LocalizationModes\":[{\"Mode\":\"LM_CONNECTED_BLOCKS\"},{\"Mode\":\"LM_STATISTICS\"}]}}", EnumConflictMode.CM_OVERWRITE, out strErrorMSG);


            string[] strTemplateNameArray       = { "All_DEFAULT", "All_DEFAULT_WITHREGION" };
            string   tempDefaultTemplateJson    = "{\"Version\": \"2.0\",\"ImageParameter\": {\"Name\": \"" + strTemplateNameArray[0] + "\",\"BarcodeFormatIds\": [\"BF_ALL\"],\"RegionPredetectionModes\": [{\"Mode\":\"RPM_GENERAL_RGB_CONTRAST\"}]}}";
            string   tempTemplateJsonWithRegion = "{\"Version\": \"2.0\",\"ImageParameter\": {\"Name\": \"" + strTemplateNameArray[1] + "\",\"BarcodeFormatIds\": [\"BF_ALL\"],\"RegionPredetectionModes\": [{\"Mode\":\"RPM_GENERAL\"}],\"RegionDefinitionNameArray\": [\"Region\"]},\"RegionDefinitionArray\": [{\"Name\": \"Region\",\"MeasuredByPercentage\": 1" + ",\"Left\":" + iLeft.ToString() + ",\"Top\":" + iTop.ToString() + ",\"Right\":" + iRight.ToString() + ",\"Bottom\":" + iBottom.ToString() + "}]}";

            if (mode == 0)
            {
                // load template json as a string.
                string        errorstring   = "";
                EnumErrorCode temperrorcode = _br.AppendTplStringToRuntimeSettings(tempDefaultTemplateJson, EnumConflictMode.CM_OVERWRITE, out errorstring);
            }
            else
            {
                // load template json as a string.
                string        errorstring   = "";
                EnumErrorCode temperrorcode = _br.AppendTplStringToRuntimeSettings(tempTemplateJsonWithRegion, EnumConflictMode.CM_OVERWRITE, out errorstring);
            }

            TextResult[] result = _br.DecodeFile(strImagePath, "");

            return(result);
        }
Beispiel #12
0
        void OnMsg(Message msg)
        {
            Message srcmsg = null;

            if (msg.tag1 == 0x00 || msg.tag2 >= 0xa0)//如果是一条回复消息,找原始消息
            {
                if (this.needBackMessage.ContainsKey(msg.msgid))
                {
                    srcmsg = this.needBackMessage[msg.msgid];
                }
                else
                {
                    return;
                }
            }


            System.Threading.ThreadPool.QueueUserWorkItem(async(_state) =>
            {
                #region 0x01
                if (msg.tag1 == 0x01 && msg.tag2 == 0x01)
                {
                    //recv a file
                    var len   = msg.readUInt32(0);
                    var hash  = msg.readHash256(4);
                    var block = dataTable.newOrGet(hash, len, NeoDun.DataBlockFrom.FromSigner);

                    var piececount = len / 50;
                    if (len % 50 > 0)
                    {
                        piececount++;
                    }

                    await System.Threading.Tasks.Task.Delay(50);//add bu hkh 1216

                    System.Threading.ThreadPool.QueueUserWorkItem((__state) =>
                    {
                        NeoDun.Message _msg = new NeoDun.Message();
                        _msg.tag1           = 0x01;
                        _msg.tag2           = 0x10;
                        _msg.msgid          = NeoDun.SignTool.RandomShort();
                        _msg.writeUInt16(0, 0);
                        _msg.writeUInt16(2, (UInt16)(piececount - 1));
                        _msg.writeHash256(4, hash);
                        SendMessage(_msg, true);
                    });
                }
                if (msg.tag1 == 0x01 && msg.tag2 == 0x10)//请求数据
                {
                    int blockbegin = BitConverter.ToUInt16(msg.data, 0);
                    int blockend   = BitConverter.ToUInt16(msg.data, 2);
                    string hash    = SignTool.Bytes2HexString(msg.data, 4, 32);
                    var block      = dataTable.getBlockBySha256(hash);
                    if (block == null)
                    {
                        //发送错误回应,下一步再说
                    }
                    else
                    {
                        for (var i = blockbegin; i < blockend + 1; i++)
                        {
                            Message msg1 = new Message();
                            block.FillPieceMessage(msg1, msg.msgid, (UInt16)i);
                            SendMessage(msg1, false);
                        }
                        //Send0103
                        Message msg2 = new Message();
                        msg2.tag1    = 0x01;
                        msg2.tag2    = 0xa3;
                        msg2.msgid   = msg.msgid;//这是一条回复消息
                        SendMessage(msg2, false);
                    }
                }
                if (msg.tag1 == 0x01 && msg.tag2 == 0x11)//给数据分配编号
                {
                    var remoteid       = msg.readUInt32(0);
                    var hash           = msg.readHash256(4);
                    var block          = dataTable.getBlockBySha256(hash);
                    block.dataidRemote = (uint)remoteid;
                }
                if (msg.tag1 == 0x01 && msg.tag2 == 0x12)
                {
                    var remoteid       = msg.readUInt32(0);
                    var hash           = msg.readHash256(4);
                    var block          = dataTable.getBlockBySha256(hash);
                    block.dataidRemote = (uint)remoteid;
                }
                if (msg.tag1 == 0x01 && msg.tag2 == 0xa2)//收到一个分片
                {
                    var hash = srcmsg.readHash256(4);
                    var data = dataTable.getBlockBySha256(hash);
                    data.FromPieceMsg(msg);
                }
                if (msg.tag1 == 0x01 && msg.tag2 == 0xa3)//接收完毕
                {
                    var hash    = srcmsg.readHash256(4);
                    var data    = dataTable.getBlockBySha256(hash);
                    bool bcheck = data.Check();
                    if (bcheck)
                    {//数据接收完整
                        System.Threading.ThreadPool.QueueUserWorkItem((__state) =>
                        {
                            NeoDun.Message _msg = new NeoDun.Message();
                            _msg.tag1           = 0x01;
                            _msg.tag2           = 0x11;
                            _msg.msgid          = NeoDun.SignTool.RandomShort();
                            _msg.writeUInt32(0, data.dataid);
                            _msg.writeHash256(4, hash);
                            SendMessage(_msg, false);
                        });
                    }
                    else
                    {//数据接收完毕,但是hash256 不匹配
                        System.Threading.ThreadPool.QueueUserWorkItem((__state) =>
                        {
                            NeoDun.Message _msg = new NeoDun.Message();
                            _msg.tag1           = 0x01;
                            _msg.tag2           = 0x12;
                            _msg.msgid          = NeoDun.SignTool.RandomShort();
                            _msg.writeUInt32(0, data.dataid);
                            _msg.writeHash256(4, hash);
                            SendMessage(_msg, false);
                        });
                    }
                }
                #endregion

                //设置地址名称失败
                if (msg.tag1 == 0x02 && msg.tag2 == 0xe2)
                {
                    EnumErrorCode errorCode = (EnumErrorCode)msg.readUInt16(0);
                    eventHandler(EnumControl.SetName, EnumMsgCode.SetNameFailed, errorCode);
                }
                //删除地址失败
                if (msg.tag1 == 0x02 && msg.tag2 == 0xe3)
                {
                    EnumErrorCode errorCode = (EnumErrorCode)msg.readUInt16(0);
                    eventHandler(EnumControl.DelAddress, EnumMsgCode.DeleteNameFailed, errorCode);
                }
                //增加地址失败
                if (msg.tag1 == 0x02 && msg.tag2 == 0xe4)
                {
                    EnumErrorCode errorCode = (EnumErrorCode)msg.readUInt16(0);
                    eventHandler(EnumControl.AddAddress, EnumMsgCode.AddAddressFailed, errorCode);
                }
                //签名失败
                if (msg.tag1 == 0x02 && msg.tag2 == 0xe5)
                {
                    EnumErrorCode errorCode = (EnumErrorCode)msg.readUInt16(0);
                    eventHandler(EnumControl.SignData, EnumMsgCode.SignFailed, errorCode);
                }
                //安装失败
                if (msg.tag1 == 0x03 && msg.tag2 == 0xe1)
                {
                    EnumErrorCode errorCode = (EnumErrorCode)msg.readUInt16(0);
                    eventHandler(EnumControl.Common, EnumMsgCode.InstallFailed, errorCode);
                }
                //拒绝更新固件
                if (msg.tag1 == 0x03 && msg.tag2 == 0xe2)
                {
                    eventHandler(EnumControl.ApplyInstallFramework, EnumMsgCode.RefuseUpdate, EnumErrorCode.NoError);
                }
                //卸载失败
                if (msg.tag1 == 0x03 && msg.tag2 == 0xe3)
                {
                    EnumErrorCode errorCode = (EnumErrorCode)msg.readUInt16(0);
                    eventHandler(EnumControl.UninstallPlugin, EnumMsgCode.UninstallFailed, errorCode);
                }
                //收到地址,//加进地址池子里
                if (msg.tag1 == 0x02 && msg.tag2 == 0xa0)
                {
                    var epoch       = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
                    var pos         = msg.readUInt16(0);
                    var count       = msg.readUInt16(2);
                    var type        = (NeoDun.AddressType)msg.readUInt16(4);
                    var add         = new NeoDun.Address();
                    add.type        = type;
                    add.AddressText = SignTool.EncodeBase58(msg.data, 6, 25);
                    add.name        = System.Text.Encoding.UTF8.GetString(msg.data, 32, 6).Replace("\0", "");
                    addressPool.addresses.Add(add);
                }
                //地址接受完毕
                if (msg.tag1 == 0x02 && msg.tag2 == 0xa1)
                {
                    eventHandler(EnumControl.GetAddress, EnumMsgCode.GetAddressSuc, EnumErrorCode.NoError);
                }
                //设置地址名称成功
                if (msg.tag1 == 0x02 && msg.tag2 == 0xa2)
                {
                    eventHandler(EnumControl.SetName, EnumMsgCode.SetNameSuc, EnumErrorCode.NoError);
                }
                //删除地址成功
                if (msg.tag1 == 0x02 && msg.tag2 == 0xa3)
                {
                    eventHandler(EnumControl.DelAddress, EnumMsgCode.DeleteNameSuc, EnumErrorCode.NoError);
                }
                //增加地址成功
                if (msg.tag1 == 0x02 && msg.tag2 == 0xa4)
                {
                    eventHandler(EnumControl.AddAddress, EnumMsgCode.AddAddressSuc, EnumErrorCode.NoError);
                }
                //签名成功
                if (msg.tag1 == 0x02 && msg.tag2 == 0xa5)
                {
                    byte[] outdata     = null;
                    string outdatahash = null;
                    outdatahash        = msg.readHash256(4);
                    //轮询直到reciveid的数据被收到
                    while (true)
                    {
                        await Task.Delay(5);
                        var __block = dataTable.getBlockBySha256(outdatahash);
                        if (__block != null && __block.Check())
                        {
                            outdata = __block.data;
                            break;
                        }
                    }
                    eventHandler(EnumControl.SignData, EnumMsgCode.SignSuc, EnumErrorCode.NoError, outdata);
                }
                //安装成功
                if (msg.tag1 == 0x03 && msg.tag2 == 0xa1)
                {
                    eventHandler(EnumControl.Common, EnumMsgCode.InstallSuc, EnumErrorCode.NoError);
                }
                //同意更新固件
                if (msg.tag1 == 0x03 && msg.tag2 == 0xa2)
                {
                    eventHandler(EnumControl.ApplyInstallFramework, EnumMsgCode.AgreeUpdate, EnumErrorCode.NoError);
                }
                //卸载成功
                if (msg.tag1 == 0x03 && msg.tag2 == 0xa3)
                {
                    eventHandler(EnumControl.UninstallPlugin, EnumMsgCode.UninstallSuc, EnumErrorCode.NoError);
                }
                //查询固件插件版本回复
                if (msg.tag1 == 0x03 && msg.tag2 == 0xa4)
                {
                    byte[] outdata = null;
                    outdata        = msg.data;
                    eventHandler(EnumControl.GetPackage, EnumMsgCode.GetMessageSuc, EnumErrorCode.NoError, outdata);
                }
                //下位机请求更新固件
                if (msg.tag1 == 0x03 && msg.tag2 == 0x11)
                {
                    deleInstallFramework();
                }
                //安全通道回复
                if (msg.tag1 == 0x04 && msg.tag2 == 0xa1)
                {
                    byte[] outdata     = null;
                    string outdatahash = null;
                    outdatahash        = msg.readHash256(4);
                    //轮询直到reciveid的数据被收到
                    while (true)
                    {
                        await Task.Delay(5);
                        var __block = dataTable.getBlockBySha256(outdatahash);
                        if (__block != null && __block.Check())
                        {
                            outdata = __block.data;
                            break;
                        }
                    }
                    eventHandler(EnumControl.SecurityChannel, EnumMsgCode.BuildSecurityChannelSuc, EnumErrorCode.NoError, outdata);
                }
            });
            watcherColl.OnRecv(msg, srcmsg);
            //if (userHandleRecv != null)
            //{
            //    userHandleRecv(msg, srcmsg);
            //}
        }
 public ResultWrap(EnumResultFlagType flag, String message, EnumErrorCode errorCode)
 {
     this.SIGN      = flag;
     this.MESSAGE   = message;
     this.ERRORCODE = errorCode;
 }
Beispiel #14
0
 public string Code2Word(EnumMsgCode enumMsgCode, EnumErrorCode enumErrorCode)
 {
     return(Msg2Word(enumMsgCode) + Error2Word(enumErrorCode));
 }
 public void AddErrorCode(EnumErrorCode errorCode, string message)
 {
     base.AddErrorCode((int)errorCode, message);
 }
 private void ThrowExceptionIfOnlyErrors(KinveyMultiInsertResponse <T> kinveyDataStoreResponse, EnumErrorCategory errorCategory, EnumErrorCode errorCode)
 {
     if (kinveyDataStoreResponse.Entities.All(e => e == null) && kinveyDataStoreResponse.Errors.Count > 0)
     {
         throw new KinveyException(errorCategory, errorCode, kinveyDataStoreResponse.Errors[0].Errmsg);
     }
 }
Beispiel #17
0
        private static Tuple <string, string, string> InfoFromErrorCode(EnumErrorCategory category, EnumErrorCode code)
        {
            string error       = "";
            string debug       = "";
            string description = "";

            switch (code)
            {
            case EnumErrorCode.ERROR_JSON_INVALID:
                error       = "";
                debug       = "";
                description = "";
                break;

            case EnumErrorCode.ERROR_JSON_PARSE:
                error       = "Unable to parse the json in the repsonse";
                debug       = "examine BL or DLC to ensure data format is correct.";
                description = "If the exception is caused by `Path <somekey>`, then <somekey> might be a different type than is expected (int instead of of string)";
                break;

            case EnumErrorCode.ERROR_MIC_HOSTNAME_REQUIREMENT_HTTPS:
                error       = "MIC Hostname must use the https protocol, trying to set: ";
                debug       = "";
                description = "";
                break;

            case EnumErrorCode.ERROR_MIC_MISSING_REDIRECT_CODE:
                error       = "Redirect does not contain `code=`, was: ";
                debug       = "";
                description = "";
                break;

            case EnumErrorCode.ERROR_MIC_REDIRECT_ERROR:
                error       = "Redirect contains an `error=`, was: ";
                debug       = "";
                description = "";
                break;

            case EnumErrorCode.ERROR_MIC_CREDENTIAL_SAVE:
                error       = "Could not save account to KeyChain.";
                debug       = "";
                description = "";
                break;

            case EnumErrorCode.ERROR_MIC_CREDENTIAL_DELETE:
                error       = "Could not delete account from KeyChain.";
                debug       = "";
                description = "";
                break;

            case EnumErrorCode.ERROR_REQUIREMENT_CONTENT_TYPE_HEADER:
                error       = "The response expects `Content-Type` header to be \"application/json\", but was instead: ";
                debug       = "";
                description = "";
                break;

            case EnumErrorCode.ERROR_REQUIREMENT_CUSTOM_REQUEST_PROPERTY_LIMIT:
                error       = "Cannot attach more than 2k of Custom Request Properties";
                debug       = "";
                description = "";
                break;

            case EnumErrorCode.ERROR_REQUIREMENT_HTTPS:
                error       = "Kinvey requires the usage of SSL over http.  Use `https` as the protocol when setting a base URL";
                debug       = "";
                description = "";
                break;

            case EnumErrorCode.ERROR_REQUIREMENT_MISSING_USERNAME_PASSWORD:
                error       = "Kinvey requires a valid username and password for this login attempt.";
                debug       = "Please enter in a valid username and password.";
                description = "A valid username and password is required for login.";
                break;

            case EnumErrorCode.ERROR_REQUIREMENT_MISSING_PUSH_CONFIGURATION_RECEIVERS:
                error       = "FCM receivers are absent for push configuration.";
                debug       = "";
                description = "To use FCM for push notifications, add com.google.firebase.iid.FirebaseInstanceIdInternalReceiver and com.google.firebase.iid.FirebaseInstanceIdReceiver to your project.";
                break;

            case EnumErrorCode.ERROR_REQUIREMENT_MISSING_PUSH_CONFIGURATION_CLASS_OVERRIDE:
                error       = "KinveyFCMService class override is absent for push configuration.";
                debug       = "";
                description = "To use FCM for push notifications, add KinveyFCMService class override to your project.";
                break;

            case EnumErrorCode.ERROR_REQUIREMENT_MISSING_GET_SET_ACCESSORS:
                error       = "Missing the get and set accessors.";
                debug       = "";
                description = "Kinvey requires the usage of the get and set accessors for fields with the JsonProperty attribute.";
                break;

            case EnumErrorCode.ERROR_USER_ALREADY_LOGGED_IN:
                error       = "Attempting to login when a user is already logged in";
                debug       = "call `myClient.user().logout().execute() first -or- check `myClient.user().isUserLoggedIn()` before attempting to login again";
                description = "Only one user can be active at a time, and logging in a new user will replace the current user which might not be intended\")";
                break;

            case EnumErrorCode.ERROR_USER_NO_ACTIVE:
                error       = "No Active User.";
                debug       = "Please log in a user before retrying this request.";
                description = "There is currently no active user.";
                break;

            case EnumErrorCode.ERROR_USER_LOGIN_ATTEMPT:
                error       = "Error attempting to log in.";
                debug       = "";
                description = "";
                break;

            case EnumErrorCode.ERROR_CLIENT_SHARED_CLIENT_NULL:
                error       = "SharedClient is null.";
                debug       = "Call Client.Builder(...).build() to build a new Kinvey shared client.";
                description = "A Client must be initialized in the app before using other Kinvey SDK methods. This error indicates that a SharedClient is being accessed by the app before it has been built.";
                break;

            case EnumErrorCode.ERROR_DATASTORE_INVALID_PULL_OPERATION:
                error       = "Invalid operation for this data store";
                debug       = "Calling pull() on a Network store is not allowed. Use a different type of data store if you need data to be stored locally and pushed to the backend.";
                description = "Refer to the documentation on DataStore types for proper usage of the DataStore caching and syncing APIs.";
                break;

            case EnumErrorCode.ERROR_DATASTORE_PULL_ONLY_ON_CLEAN_SYNC_QUEUE:
                error       = "Cannot pull until all local changes are pushed to the backend.";
                debug       = "Call store.push() to push pending local changes, or store.purge() to clean local changes.";
                description = "Refer to the documentation on DataStore types for proper usage of the DataStore caching and syncing APIs.";
                break;

            case EnumErrorCode.ERROR_DATASTORE_INVALID_PUSH_OPERATION:
                error       = "Invalid operation for this data store";
                debug       = "Calling push() on a Network store is not allowed. Use a different type of data store if you need data to be stored locally and pushed to the backend.";
                description = "Refer to the documentation on DataStore types for proper usage of the DataStore caching and syncing APIs.";
                break;

            case EnumErrorCode.ERROR_DATASTORE_INVALID_SYNC_OPERATION:
                error       = "Invalid operation for this data store";
                debug       = "Calling sync() on a Network store is not allowed. Use a different type of data store if you need data to be stored locally and pushed to the backend.";
                description = "Refer to the documentation on DataStore types for proper usage of the DataStore caching and syncing APIs.";
                break;

            case EnumErrorCode.ERROR_DATASTORE_INVALID_CLEAR_CACHE_OPERATION:
                error       = "Invalid operation for this data store";
                debug       = "Calling ClearCache() on this type of data store is not allowed. Use a different type of data store if you need to remove data from local storage.";
                description = "Refer to the documentation on DataStore types for proper usage of removing data from local storage.";
                break;

            case EnumErrorCode.ERROR_DATASTORE_INVALID_PURGE_OPERATION:
                error       = "Invalid operation for this data store";
                debug       = "Calling Purge() on this type of data store is not allowed. Use a different type of data store if you need to remove pending write operations from local storage.";
                description = "Refer to the documentation on DataStore types for proper usage of removing pending write operations from local storage.";
                break;

            case EnumErrorCode.ERROR_DATASTORE_INVALID_SYNC_COUNT_OPERATION:
                error       = "Invalid operation for this data store";
                debug       = "Calling GetSyncCount() on this type of data store is not allowed. Use a different type of data store if you need to get the current count of items in the sync queue.";
                description = "Refer to the documentation on DataStore types for proper usage of getting the current count of items in the sync queue.";
                break;

            case EnumErrorCode.ERROR_DATASTORE_CACHE_SAVE_INSERT_ENTITY:
                error       = "An exception was thrown while trying to save an entity in the cache.";
                debug       = "";
                description = "Error in inserting new entity cache with temporary ID.";
                break;

            case EnumErrorCode.ERROR_DATASTORE_CACHE_MULTIPLE_SAVE:
                error       = "An exception was thrown while trying to save multiple entities to the cache.";
                debug       = "";
                description = "An error in multiple inserting new entities or updating existing ones.";
                break;

            case EnumErrorCode.ERROR_DATASTORE_CACHE_SAVE_UPDATE_ENTITY:
                error       = "An exception was thrown while trying to update an entity in the cache.";
                debug       = "";
                description = "Error in updating an existing entity in the cache.";
                break;

            case EnumErrorCode.ERROR_DATASTORE_CACHE_FIND_QUERY:
                error       = "An exception was thrown while trying to find entities in the cache.";
                debug       = "";
                description = "Error in the query expression used to find entities in the cache.";
                break;

            case EnumErrorCode.ERROR_DATASTORE_CACHE_FIND_BY_ID_GENERAL:
                error       = "An exception was thrown while trying to find entity by id in the cache.";
                debug       = "";
                description = "Error in finding an entity by id in the cache";
                break;

            case EnumErrorCode.ERROR_DATASTORE_CACHE_FIND_BY_ID_NOT_FOUND:
                error       = "";
                debug       = "";
                description = "Response status code does not indicate success: 404 (Not Found).";
                break;

            case EnumErrorCode.ERROR_DATASTORE_CACHE_SAVE_UPDATE_ID:
                error       = "An exception was thrown while trying to save an entity in the cache.";
                debug       = "";
                description = "Error in updating cache with permanent entity ID.";
                break;

            case EnumErrorCode.ERROR_DATASTORE_CACHE_REFRESH:
                error       = "An exception was thrown while trying to refresh entities in the cache.";
                debug       = "";
                description = "Error in trying to insert or update entities in the cache based on the list of given entities.";
                break;

            case EnumErrorCode.ERROR_DATASTORE_CACHE_REMOVE_ENTITY:
                error       = "An exception was thrown while trying to remove an entity from the cache.";
                debug       = "";
                description = "Error in trying to delete an entity from the cache based on the given entity ID.";
                break;

            case EnumErrorCode.ERROR_DATASTORE_CACHE_CLEAR:
                error       = "An exception was thrown while trying clear all the entities from the cache.";
                debug       = "";
                description = "Error while trying to clear all the data in the cache.  No data was deleted from the cache.";
                break;

            case EnumErrorCode.ERROR_DATASTORE_CACHE_CLEAR_QUERY:
                error       = "An exception was thrown while trying clear entities from the cache based on a query.";
                debug       = "Call Clear() to clear the entire cache";
                description = "Error while trying to clear data in the cache based on a query.  No data was deleted from the cache.";
                break;

            case EnumErrorCode.ERROR_DATASTORE_NOT_COMPATIBLE_KINVEY_API_VERSION:
                error       = "Not compatible Kinvey api version.";
                debug       = "";
                description = "The current functionality is not compatible with the existing Kinvey api version.";
                break;

            case EnumErrorCode.ERROR_DATASTORE_EMPTY_ARRAY_OF_ENTITIES:
                error       = "An empty array of entities.";
                debug       = "";
                description = "An array of entities to be saved must not be empty.";
                break;

            case EnumErrorCode.ERROR_DATASTORE_LIMIT_OF_ENTITIES_TO_BE_SAVED:
                error       = "Entities count limit was exceeded.";
                debug       = "";
                description = string.Concat("The current limit of entities count is ", Constants.NUMBER_LIMIT_OF_ENTITIES);
                break;

            case EnumErrorCode.ERROR_METHOD_NOT_IMPLEMENTED:
                error       = "An exception was thrown while trying to call a method that is not implemented.";
                debug       = "Consult the reference guides for information on supported methods for the given class.";
                description = "The method being called on this class/object is not currently implemnted by the SDK.";
                break;

            case EnumErrorCode.ERROR_LINQ_WHERE_CLAUSE_NOT_SUPPORTED:
                error       = "An exception was thrown while trying to use a LINQ `Where` clause that is not supported.";
                debug       = "Consult the reference guides for information on supported LINQ clauses.";
                description = "The LINQ `Where` clause being called is not supported by the SDK.";
                break;

            case EnumErrorCode.ERROR_CUSTOM_ENDPOINT_ERROR:
                error       = "An exception was thrown while trying to execute a custom endpoint.";
                debug       = "Inspect the StatusCode property to determine the cause of the exception.";
                description = "A 4xx/5xx status code was set in the response by the custom endpoint.";
                break;

                #region Realtime errors

            case EnumErrorCode.ERROR_REALTIME_ERROR:
                error       = "An exception was thrown while trying to execute a realtime request.";
                debug       = "Inspect the StatusCode property to determine the cause of the exception.";
                description = "A 4xx/5xx status code was set in the response by the realtime service.";
                break;

            case EnumErrorCode.ERROR_REALTIME_CRITICAL_VERIFY_CIPHER_KEY:
                error       = "Invalid cipher key.";
                debug       = "Verify your cipher key.";
                description = "";
                break;

            case EnumErrorCode.ERROR_REALTIME_CRITICAL_INCORRECT_SUBSBRIBE_KEY:
                error       = "Incorrect subscribe key.";
                debug       = "Please provide correct subscribe key.";
                description = "This corresponds to a 401 on the server due to a bad sub key.";
                break;

            case EnumErrorCode.ERROR_REALTIME_CRITICAL_NOT_AUTHORIZED_ON_CHANNEL:
                error       = "Not authorized.";
                debug       = "Check the permissions on the channel.  Also verify authentication key, to check access.";
                description = "This corresponds to the user not being authorized to publish and/or subscribe on this channel.";
                break;

            case EnumErrorCode.ERROR_REALTIME_CRITICAL_INTERNAL_SERVER_ERROR:
                error       = "Internal Server Error.";
                debug       = "Please try again. If same problem persists, please contact PubNub support.";
                description = "Unexpected error occured at PubNub Server";
                break;

            case EnumErrorCode.ERROR_REALTIME_CRITICAL_BAD_GATEWAY:
                error       = "Bad Gateway.";
                debug       = "Please try again. If same problem persists, please contact PubNub support.";
                description = "Unexpected error occured at PubNub Server.";
                break;

            case EnumErrorCode.ERROR_REALTIME_CRITICAL_GATEWAY_TIMEOUT:
                error       = "Gateway Timeout.";
                debug       = "Please try again. If same problem persists, please contact PubNub support.";
                description = "No response from server due to PubNub server timeout.";
                break;

            case EnumErrorCode.ERROR_REALTIME_CRITICAL_UNKNOWN:
                error       = "Unknown critical PubNub error.";
                debug       = "";
                description = "";
                break;

                #endregion

            default:
                error       = "Unknown error";
                debug       = "Unknown error";
                description = "Unknown error";
                break;
            }

            return(new Tuple <string, string, string>(error, debug, description));
        }
Beispiel #18
0
        private static string MessageFromErrorCode(EnumErrorCategory category, EnumErrorCode code)
        {
            Tuple <string, string, string> errorInfo = InfoFromErrorCode(category, code);

            return(errorInfo.Item1 + errorInfo.Item2 + errorInfo.Item3);
        }
Beispiel #19
0
        /// <summary>
        /// encrypts an image
        /// </summary>
        /// <param name="image">the image that will be encrypted</param>
        /// <param name="roIs">the Region of Interests</param>
        /// <param name="password">the password used for encryption</param>
        /// <param name="cryptoFlags">determines which encryption mode will be applied</param>
        /// <param name="errorCode">if an error occurs this value will be set is not 0</param>
        /// <returns>returns an encrypted image</returns>
        public static Image EncryptJPG(Image image, IList<RoI> roIs, string password, CryptoFlags cryptoFlags, out EnumErrorCode errorCode)
        {
            // create JpegOperation from business logic
            IBusinessLogic businessLogic = new BusinessLogic();
            IJpegOperation jpegOperation = businessLogic.CreateJpegOperationBL();

            // convert Image to byte array
            byte[] in_jpegToEncrypt = jpegOperation.ConvertImageToByteArray(image);
            Int32 in_size = in_jpegToEncrypt.Length;

            // convert RoIs to the correct format
            int counter = 0;
            Int32[] in_roiArray = new Int32[roIs.Count() * 4];
            foreach (RoI roi in roIs)
            {
                in_roiArray[(counter * 4) + 0] = roIs[counter].X;
                in_roiArray[(counter * 4) + 1] = roIs[counter].Y;
                in_roiArray[(counter * 4) + 2] = roIs[counter].Width;
                in_roiArray[(counter * 4) + 3] = roIs[counter].Height;
                counter++;
            }
            Int32 in_roiArraySize = roIs.Count() * 4;

            // create MD5 hash of the password
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] textToHash = Encoding.Default.GetBytes(password);
            byte[] in_encryptionKey = md5.ComputeHash(textToHash);
            Int32 in_encryptionKeySize = in_encryptionKey.Length;

            // convert crypto flags 
            byte in_cryptoFlags = cryptoFlags.ToByte();

            // get memory for the encrypted image
            byte[] out_jpegEncrypted = new byte[in_size*2];
            byte[] out_statistics   =  new byte[in_size];
            IntPtr out_jpegEncryptedSize = new IntPtr();
            int[] ia2 = new int[1];
            GCHandle gch1 = GCHandle.Alloc(ia2);
            out_jpegEncryptedSize = Marshal.UnsafeAddrOfPinnedArrayElement(ia2, 0);

            // create a pointer for the error code (will be set from C-code)
            IntPtr out_errorCode = new IntPtr();
            int[] ia = new int[1];
            GCHandle gch = GCHandle.Alloc(ia);
            out_errorCode = Marshal.UnsafeAddrOfPinnedArrayElement(ia, 0);

            // now try to call the encryption algorithm
            try
            {
                encJpeg(
                    in_jpegToEncrypt,
                    in_size,
                    in_roiArray,
                    in_roiArraySize,
                    in_encryptionKey,
                    in_encryptionKeySize,
                    in_cryptoFlags,
                    out_jpegEncrypted,
                    ref out_jpegEncryptedSize,
                    ref out_errorCode
                );

                // get the error code
                errorCode = ConvertIntToErrorCode(out_errorCode.ToInt32());

                // truncate byte array
                out_jpegEncrypted = out_jpegEncrypted.Take(out_jpegEncryptedSize.ToInt32()).ToArray();
            }
            catch 
            {
                throw new EncryptionException("Error while encrypting!");
            }

            // convert byte array to Image and return
            return jpegOperation.ConvertByteArrayToImage(out_jpegEncrypted);
        }
Beispiel #20
0
        /// <summary>
        /// encrypts an image
        /// </summary>
        /// <param name="image">the image that will be encrypted</param>
        /// <param name="roIs">the Region of Interests</param>
        /// <param name="password">the password used for encryption</param>
        /// <param name="cryptoFlags">determines which encryption mode will be applied</param>
        /// <param name="errorCode">if an error occurs this value will be set is not 0</param>
        /// <returns>returns an encrypted image</returns>
        public static Image EncryptJPG(Image image, IList <RoI> roIs, string password, CryptoFlags cryptoFlags, out EnumErrorCode errorCode)
        {
            // create JpegOperation from business logic
            IBusinessLogic businessLogic = new BusinessLogic();
            IJpegOperation jpegOperation = businessLogic.CreateJpegOperationBL();

            // convert Image to byte array
            byte[] in_jpegToEncrypt = jpegOperation.ConvertImageToByteArray(image);
            Int32  in_size          = in_jpegToEncrypt.Length;

            // convert RoIs to the correct format
            int counter = 0;

            Int32[] in_roiArray = new Int32[roIs.Count() * 4];
            foreach (RoI roi in roIs)
            {
                in_roiArray[(counter * 4) + 0] = roIs[counter].X;
                in_roiArray[(counter * 4) + 1] = roIs[counter].Y;
                in_roiArray[(counter * 4) + 2] = roIs[counter].Width;
                in_roiArray[(counter * 4) + 3] = roIs[counter].Height;
                counter++;
            }
            Int32 in_roiArraySize = roIs.Count() * 4;

            // create MD5 hash of the password
            MD5 md5 = new MD5CryptoServiceProvider();

            byte[] textToHash           = Encoding.Default.GetBytes(password);
            byte[] in_encryptionKey     = md5.ComputeHash(textToHash);
            Int32  in_encryptionKeySize = in_encryptionKey.Length;

            // convert crypto flags
            byte in_cryptoFlags = cryptoFlags.ToByte();

            // get memory for the encrypted image
            byte[] out_jpegEncrypted     = new byte[in_size * 2];
            byte[] out_statistics        = new byte[in_size];
            IntPtr out_jpegEncryptedSize = new IntPtr();

            int[]    ia2  = new int[1];
            GCHandle gch1 = GCHandle.Alloc(ia2);

            out_jpegEncryptedSize = Marshal.UnsafeAddrOfPinnedArrayElement(ia2, 0);

            // create a pointer for the error code (will be set from C-code)
            IntPtr out_errorCode = new IntPtr();

            int[]    ia  = new int[1];
            GCHandle gch = GCHandle.Alloc(ia);

            out_errorCode = Marshal.UnsafeAddrOfPinnedArrayElement(ia, 0);

            // now try to call the encryption algorithm
            try
            {
                encJpeg(
                    in_jpegToEncrypt,
                    in_size,
                    in_roiArray,
                    in_roiArraySize,
                    in_encryptionKey,
                    in_encryptionKeySize,
                    in_cryptoFlags,
                    out_jpegEncrypted,
                    ref out_jpegEncryptedSize,
                    ref out_errorCode
                    );

                // get the error code
                errorCode = ConvertIntToErrorCode(out_errorCode.ToInt32());

                // truncate byte array
                out_jpegEncrypted = out_jpegEncrypted.Take(out_jpegEncryptedSize.ToInt32()).ToArray();
            }
            catch
            {
                throw new EncryptionException("Error while encrypting!");
            }

            // convert byte array to Image and return
            return(jpegOperation.ConvertByteArrayToImage(out_jpegEncrypted));
        }