Exemplo n.º 1
0
        public static void sendUserMsg(string mobile, dynamic json)
        {
            if (string.IsNullOrEmpty(mobile))
            {
                throw new Exception("mobile不能为空");
            }
            string product         = "Dysmsapi";                       //短信API产品名称(短信产品名固定,无需修改)
            string domain          = "dysmsapi.aliyuncs.com";          //短信API产品域名(接口地址固定,无需修改)
            string accessKeyId     = "LTAI4FfhUHPcQ1VHcKN5wEHc";       //你的accessKeyId,参考本文档步骤2
            string accessKeySecret = "F2zwYrZ4xKUwayfhXWXmthzLKiMXnp"; //你的accessKeySecret,参考本文档步骤2

            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);

            DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            var        request   = new SendSmsRequest();

            try
            {
                request.PhoneNumbers = mobile;
                //必填:短信签名-可在短信控制台中找到
                request.SignName = "物业智能维修";
                //必填:短信模板-可在短信控制台中找到,发送国际/港澳台消息时,请使用国际/港澳台短信模版
                request.TemplateCode = "SMS_186599365";
                //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
                request.TemplateParam = JsonConvert.SerializeObject(json);// "{\"name\":\"Tom\",\"code\":\"123\"}";
                //请求失败这里会抛ClientException异常
                var sendSmsResponse = acsClient.GetAcsResponse(request);
                if (sendSmsResponse.BizId == null)
                {
                    throw new ApplicationException(sendSmsResponse.Message);
                }
                Console.WriteLine(sendSmsResponse.Message);
            }
            catch (ServerException ex)
            {
                throw new ApplicationException(ex.Message);
            }
            catch (ClientException ex)
            {
                throw new ApplicationException(ex.Message);
            }
        }
Exemplo n.º 2
0
        public async Task SendAsync(string to, string templateCode, string templateParams)
        {
            DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", "dysmsapi.aliyuncs.com");
            var task = new Task(() =>
            {
                IAcsClient acsClient   = new DefaultAcsClient(profile);
                SendSmsRequest request = new SendSmsRequest();
                try
                {
                    //必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
                    request.PhoneNumbers = to;
                    //必填:短信签名-可在短信控制台中找到
                    request.SignName = _settingManager.GetSettingValue(AppSettings.SMSManagement.SignName);
                    //必填:短信模板-可在短信控制台中找到
                    request.TemplateCode = templateCode;
                    //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
                    request.TemplateParam = templateParams;
                    //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
                    //request.OutId = "yourOutId";
                    //请求失败这里会抛ClientException异常
                    SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);
                    Logger.Info("发送返回:" + sendSmsResponse.Message);
                }
                catch (ServerException e)
                {
                    throw new UserFriendlyException("短信发送失败",
                                                    new Exception(string.Format("to:{0},errCode:{1},errMsg:{2}",
                                                                                to,
                                                                                e.ErrorCode,
                                                                                e.Message)));
                }
                catch (ClientException e)
                {
                    throw new UserFriendlyException("短信发送失败",
                                                    new Exception(string.Format("to:{0},errCode:{1},errMsg:{2}",
                                                                                to,
                                                                                e.ErrorCode,
                                                                                e.Message)));
                }
            });

            task.Start();
        }
Exemplo n.º 3
0
        public void SdkManageTokenTest()
        {
            if (GetRoleArn().Equals("FakeRoleArn"))
            {
                return;
            }

            var profile         = DefaultProfile.GetProfile("cn-hangzhou", GetBasicAccessKeyId(), GetBasicAccessKeySecret());
            var basicCredential = new BasicCredentials(GetBasicAccessKeyId(), GetBasicAccessKeySecret());
            var provider        = new STSAssumeRoleSessionCredentialsProvider(basicCredential, GetRoleArn(), profile);

            var client = new DefaultAcsClient(profile, provider);

            var request  = new DescribeAccessPointsRequest();
            var response = client.GetAcsResponse(request);

            Assert.NotNull(response);
            Assert.True(0 <= response.TotalCount);
        }
Exemplo n.º 4
0
        public void BasicRoaTokenConnection()
        {
            BasicSessionCredentials basciCredential = new BasicSessionCredentials(this.GetBasicAccessKeyId(), this.GetBasicAccessKeySecret(), this.GetToken());
            DefaultProfile          profile         = DefaultProfile.GetProfile(this.regionId, this.GetBasicAccessKeyId(), this.GetBasicAccessKeySecret());
            DefaultAcsClient        client          = new DefaultAcsClient(profile, basciCredential);

            CommonRequest request = new CommonRequest();

            request.Domain     = "ros.aliyuncs.com";
            request.Version    = "2015-09-01";
            request.Action     = "DescribeResourceTypes";
            request.UriPattern = "/resource_types";
            request.Method     = MethodType.GET;

            CommonResponse response = client.GetCommonResponse(request);

            Assert.Equal(200, response.HttpStatus);
            Assert.NotNull(response.Data);
        }
Exemplo n.º 5
0
        /// <summary>
        /// 精准发送(toAddress逗号分隔)一封一封发每日2000封上限
        /// </summary>
        /// <param name="fromEmail"></param>
        /// <param name="fromAlias"></param>
        /// <param name="toAddress"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <param name="consoleTag"></param>
        /// <returns></returns>
        public void SendOneByOne(string fromEmail, string fromAlias, List <dynamic> recieveUsers, dynamic mailContent, string consoleTag)
        {
            Thread _thread = new Thread(new ParameterizedThreadStart(o =>
            {
                IClientProfile profile = DefaultProfile.GetProfile(m_regionId, m_accessKeyId, m_secret);
                IAcsClient client      = new DefaultAcsClient(profile);

                foreach (dynamic _user in recieveUsers)
                {
                    SingleSendMailRequest request = new SingleSendMailRequest();
                    try
                    {
                        request.AccountName    = fromEmail;
                        request.FromAlias      = fromAlias;
                        request.AddressType    = 1;
                        request.TagName        = consoleTag;
                        request.ReplyToAddress = true;
                        request.ToAddress      = _user.email;
                        request.Subject        = mailContent.subject;
                        request.HtmlBody       = string.Format(mailContent.content, _user.email_id, mailContent.msg_id);
                        SingleSendMailResponse httpResponse = client.GetAcsResponse(request);

                        var _reqId = httpResponse.RequestId;

                        //入库状态
                    }
                    catch (ServerException e)
                    {
                        //Console.WriteLine("服务器异常:" + e.Message);
                        //记录日志
                    }
                    catch (ClientException e)
                    {
                        //Console.WriteLine("客户端异常:" + e.Message);
                        //记录日志
                    }

                    Thread.Sleep(200);
                }
            }));

            _thread.Start(null);
        }
Exemplo n.º 6
0
        public void GetCredentialFileAlibabaCloudCredentialWithAKTypeButAKIsEmpty()
        {
            DefaultProfile profile = DefaultProfile.GetProfile();

            profile.DefaultClientName = "default";
            var defaultCredentialProvider = new DefaultCredentialProvider(profile, null);
            var homePath = defaultCredentialProvider.GetHomePath();

            TestHelper.CreateIniFileWithAkTypeWithEmptyAK(homePath);

            var exception = Assert.Throws <ClientException>(() =>
            {
                var credential = (BasicCredentials)defaultCredentialProvider.GetAlibabaCloudClientCredential();
            });

            TestHelper.DeleteIniFile(homePath);

            Assert.Equal("Missing required variable option for 'default Client'", exception.Message);
        }
Exemplo n.º 7
0
        public Task SendAsync(SmsMessage smsMessage)
        {
            CommonRequest request = new CommonRequest
            {
                Method  = MethodType.POST,
                Domain  = Options.Domain,
                Action  = Options.ActionName,
                Version = Options.Version
            };

            TryAddTemplateCode(request, smsMessage);
            TryAddSignName(request, smsMessage);
            TryAddSendPhone(request, smsMessage);
            TryAddTemplateParam(request, smsMessage);

            try
            {
                IClientProfile profile         = DefaultProfile.GetProfile(Options.RegionId, AuthOptions.AccessKeyId, AuthOptions.AccessKeySecret);
                IAcsClient     client          = new DefaultAcsClient(profile);
                CommonResponse response        = client.GetCommonResponse(request);
                var            responseContent = Encoding.Default.GetString(response.HttpResponse.Content);
                var            aliyunResponse  = JsonSerializer.Deserialize <AliyunSmsResponse>(responseContent);
                if (!aliyunResponse.IsSuccess())
                {
                    if (Options.VisableErrorToClient)
                    {
                        throw new AliyunSmsException(aliyunResponse.Code, aliyunResponse.Message);
                    }
                    throw new AbpException($"Text message sending failed, code:{aliyunResponse.Code}, message:{aliyunResponse.Message}!");
                }
            }
            catch (ServerException se)
            {
                throw new AbpException("Sending text messages to aliyun server is abnormal", se);
            }
            catch (ClientException ce)
            {
                throw new AbpException("A client exception occurred in sending SMS messages", ce);
            }

            return(Task.CompletedTask);
        }
Exemplo n.º 8
0
        public static void start()
        {
            DefaultProfile profile = DefaultProfile.GetProfile("cn-hangzhou", "LTAI4FwtwUGNUurDr5vVSVSH", "0WUJolqKrbtLk39ddPGnqZaP9cZUPM"); // todo: 补充AK信息

            profile.AddEndpoint("cn-hangzhou", "cn-hangzhou", "Dybaseapi", "dybaseapi.aliyuncs.com");

            DefaultAcsClient client = new DefaultAcsClient(profile);

            String queueName   = "<QueueName>";   // todo: 补充队列名称
            String messageType = "<MessageType>"; // todo: 补充消息类型

            int maxThread = 2;

            for (int i = 0; i < maxThread; i++)
            {
                TestTask testTask = new TestTask("PullMessageTask-thread-" + i, messageType, queueName, client);
                Thread   t        = new Thread(new ThreadStart(testTask.Handle));
                //启动线程
                t.Start();
            }
            Console.ReadKey();

            try
            {
                QueryTokenForMnsQueueRequest request = new QueryTokenForMnsQueueRequest
                {
                    MessageType = messageType,
                    QueueName   = queueName
                };

                QueryTokenForMnsQueueResponse response = client.GetAcsResponse(request);
                Console.WriteLine(response.MessageTokenDTO.SecurityToken);
            }
            catch (ServerException ex)
            {
                Console.WriteLine(ex.ToString());
            }
            catch (ClientException ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Exemplo n.º 9
0
        public static string Code(string Phone)
        {
            Random random = new Random();
            string q1     = "{\"code\":\"";

            string q2 = "\"}";

            string da = random.Next(100000, 999999).ToString();
            string qq = q1 + da + q2;


            IClientProfile   profile = DefaultProfile.GetProfile("cn-hangzhou", "LTAI4Fudyw1ZdC3aKCXYXk1A", "stRWWoslckoifk3CSj7LZKb93CsCd2");
            DefaultAcsClient client  = new DefaultAcsClient(profile);
            CommonRequest    request = new CommonRequest();

            request.Method  = MethodType.POST;
            request.Domain  = "dysmsapi.aliyuncs.com";
            request.Version = "2017-05-25";
            request.Action  = "SendSms";
            // request.Protocol = ProtocolType.HTTP;
            request.AddQueryParameters("PhoneNumbers", Phone);
            request.AddQueryParameters("SignName", "青衫忆笙yy");
            request.AddQueryParameters("TemplateCode", "SMS_178451830");
            request.AddQueryParameters("TemplateParam", qq);

            try
            {
                CommonResponse response = client.GetCommonResponse(request);
                Console.WriteLine(System.Text.Encoding.Default.GetString(response.HttpResponse.Content));
                return(da);
            }
            catch (ServerException e)
            {
                Console.WriteLine(e);
                return(e.Message);
            }
            catch (ClientException e)
            {
                Console.WriteLine(e);
                return(e.Message);
            }
        }
Exemplo n.º 10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="phone">手机号</param>
        /// <param name="SignName">短信签名</param>
        /// <param name="TemplateCode">短信模板</param>
        /// <param name="TemplateParam">模板中的变量替换JSON串</param>
        /// <returns></returns>
        public string send(string phone, string TemplateCode, string TemplateParam)
        {
            try
            {
                IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);
                //IAcsClient client = new DefaultAcsClient(profile);
                // SingleSendSmsRequest request = new SingleSendSmsRequest();
                //初始化ascClient,暂时不支持多region(请勿修改)
                DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
                IAcsClient     acsClient = new DefaultAcsClient(profile);
                SendSmsRequest request   = new SendSmsRequest();

                //必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
                request.PhoneNumbers = phone;
                //必填:短信签名-可在短信控制台中找到
                request.SignName = "医站通";            //SignName; //"xxxxxxxx";
                //必填:短信模板-可在短信控制台中找到
                request.TemplateCode = TemplateCode; //"SMS_00000001";
                //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为

                string json = "{" + TemplateParam + "}";

                request.TemplateParam = json; //"{\"name\":\"Tom\", \"code\":\"123\"}"; "{\"code\":\"772251\"}"
                //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
                //request.OutId = "yourOutId";
                //请求失败这里会抛ClientException异常
                SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);
                if (!"OK".Equals(sendSmsResponse.Code))
                {
                    return(sendSmsResponse.Message);
                }
                return("Success");
            }
            catch (ServerException e)
            {
                return(e.Message);
            }
            catch (ClientException e)
            {
                return(e.Message);
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// 通过阿里云短信发送API发送验证码
        /// </summary>
        /// <param name="phone">手机号</param>
        /// <param name="templateCode"></param>
        /// <param name="templateParam"></param>
        /// <returns></returns>
        protected virtual SendSmsResponse SendValMsg(string phone, string templateCode, string templateParam)
        {
            //你的accessKeyId和accessKeySecret参考本文档步骤2
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", AccessKeyId, AccessKeySecret);

            //IAcsClient client = new DefaultAcsClient(profile);
            // SingleSendSmsRequest request = new SingleSendSmsRequest();
            //初始化ascClient,暂时不支持多region(请勿修改)
            DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", Product, Domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            var        request   = new SendSmsRequest();

            try
            {
                //必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
                request.PhoneNumbers = phone;
                //必填:短信签名
                request.SignName = "工程易管";
                //必填:短信模板
                request.TemplateCode  = templateCode;
                request.TemplateParam = templateParam;
                //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
                request.OutId = "";
                //请求失败这里会抛ClientException异常
                var sendSmsResponse = acsClient.GetAcsResponse(request);
                return(sendSmsResponse);
            }
            catch (ServerException e)
            {
                return(new SendSmsResponse()
                {
                    Code = "isv.Error", Message = e.Message
                });
            }
            catch (ClientException e)
            {
                return(new SendSmsResponse()
                {
                    Code = "isv.Error", Message = e.Message
                });
            }
        }
Exemplo n.º 12
0
        public void TestMethod1()
        {
            String product         = "Dysmsapi";              //短信API产品名称
            String domain          = "dysmsapi.aliyuncs.com"; //短信API产品域名
            String accessKeyId     = "";                      //你的accessKeyId
            String accessKeySecret = "";                      //你的accessKeySecret

            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);

            //IAcsClient client = new DefaultAcsClient(profile);
            // SingleSendSmsRequest request = new SingleSendSmsRequest();

            DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient     acsClient = new DefaultAcsClient(profile);
            SendSmsRequest request   = new SendSmsRequest();

            try
            {
                //必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为20个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
                request.PhoneNumbers = "13567939495";
                //必填:短信签名-可在短信控制台中找到
                request.SignName = "阿里云短信测试专用";
                //必填:短信模板-可在短信控制台中找到
                request.TemplateCode = "SMS_71135039";
                //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
                request.TemplateParam = "{\"customer\":\"123\"}";
                //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
                request.OutId = "21212121211";
                //请求失败这里会抛ClientException异常
                SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);

                Console.WriteLine(sendSmsResponse.Message);
            }
            catch (ServerException e)
            {
                Console.WriteLine("Hello World!");
            }
            catch (ClientException e)
            {
                Console.WriteLine("Hello World!");
            }
        }
Exemplo n.º 13
0
        public string Code(string Phone)
        {
            Random random = new Random();
            string q1     = "{\"code\":\"";

            string q2 = "\"}";

            string da = random.Next(100000, 999999).ToString();
            string qq = q1 + da + q2;


            IClientProfile   profile = DefaultProfile.GetProfile("cn-hangzhou", "{LTAI4Fnkzz9VEBF2xgauk4pC}", "KUK2uk7yav4n3z6viKk94b0r1hZpMD");
            DefaultAcsClient client  = new DefaultAcsClient(profile);
            CommonRequest    request = new CommonRequest();

            request.Method  = MethodType.POST;
            request.Domain  = "dysmsapi.aliyuncs.com";
            request.Version = "2017-05-25";
            request.Action  = "SendSms";
            // request.Protocol = ProtocolType.HTTP;
            request.AddQueryParameters("PhoneNumbers", Phone);
            request.AddQueryParameters("SignName", "橘子果果");
            request.AddQueryParameters("TemplateCode", "SMS_179616733");
            request.AddQueryParameters("TemplateParam", qq);

            try
            {
                CommonResponse response = client.GetCommonResponse(request);
                Console.WriteLine(System.Text.Encoding.Default.GetString(response.HttpResponse.Content));
                return(qq);
            }
            catch (ServerException e)
            {
                Console.WriteLine(e);
                return(e.Message);
            }
            catch (ClientException e)
            {
                Console.WriteLine(e);
                return(e.Message);
            }
        }
Exemplo n.º 14
0
        public static SendBatchSmsResponse sendBatchSms()
        {
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);

            DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);

            IAcsClient          acsClient = new DefaultAcsClient(profile);
            SendBatchSmsRequest request   = new SendBatchSmsRequest();
            //request.Protocol = ProtocolType.HTTPS;
            //request.TimeoutInMilliSeconds = 1;

            SendBatchSmsResponse response = null;

            try
            {
                //必填:待发送手机号。支持JSON格式的批量调用,批量上限为100个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
                request.PhoneNumberJson = "[\"1500000000\",\"1500000001\"]";
                //必填:短信签名-支持不同的号码发送不同的短信签名
                request.SignNameJson = "[\"云通信\",\"云通信\"]";
                //必填:短信模板-可在短信控制台中找到
                request.TemplateCode = "SMS_1000000";
                //必填:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
                //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
                request.TemplateParamJson = "[{\"name\":\"Tom\", \"code\":\"123\"},{\"name\":\"Jack\", \"code\":\"456\"}]";
                //可选-上行短信扩展码(扩展码字段控制在7位或以下,无特殊需求用户请忽略此字段)
                //request.SmsUpExtendCodeJson = "[\"90997\",\"90998\"]";

                //请求失败这里会抛ClientException异常
                response = acsClient.GetAcsResponse(request);
            }
            catch (ServerException e)
            {
                Console.Write(e.ErrorCode);
            }
            catch (ClientException e)
            {
                Console.Write(e.ErrorCode);
                Console.Write(e.Message);
            }

            return(response);
        }
Exemplo n.º 15
0
        static void Main()
        {
            IClientProfile          clientProfile = DefaultProfile.GetProfile("cn-hangzhou", "<your access key id>", "<your access key secret>");
            DefaultAcsClient        client        = new DefaultAcsClient(clientProfile);
            QueryAppPushStatRequest request       = new QueryAppPushStatRequest();

            request.AppKey = < Your AppKey >;

            request.Granularity = "DAY";
            String startTime = DateTime.UtcNow.AddDays(-7).ToString("yyyy-MM-ddTHH\\:mm\\:ssZ");
            String endTime   = DateTime.UtcNow.ToString("yyyy-MM-ddTHH\\:mm\\:ssZ");

            request.StartTime = startTime;
            request.EndTime   = endTime;

            try
            {
                QueryAppPushStatResponse response = client.GetAcsResponse(request);
                Console.WriteLine("RequestId:" + response.RequestId);
                foreach (QueryAppPushStatResponse.AppPushStat stat in response.AppPushStats)
                {
                    Console.WriteLine("MessageIdt:" + stat.Time);
                    Console.WriteLine("SentCount:" + stat.SentCount);
                    Console.WriteLine("ReceivedCount:" + stat.ReceivedCount);
                    Console.WriteLine("OpenedCount:" + stat.OpenedCount);
                    Console.WriteLine("DeletedCount:" + stat.DeletedCount);
                }
                Console.ReadLine();
            }
            catch (ServerException e)
            {
                Console.WriteLine(e.ErrorCode);
                Console.WriteLine(e.ErrorMessage);
                Console.ReadLine();
            }
            catch (ClientException e)
            {
                Console.WriteLine(e.ErrorCode);
                Console.WriteLine(e.ErrorMessage);
                Console.ReadLine();
            }
        }
Exemplo n.º 16
0
        public void ResolveProxy()
        {
            IClientProfile profile     = DefaultProfile.GetProfile("cn-hangzhou", AKID, AKSE);
            var            httpRequest = new HttpRequest("urls", new Dictionary <string, string>());

            var acsRequest = new AssumeRoleRequest();

            var type         = typeof(DefaultAcsClient);
            var resolveProxy = Activator.CreateInstance(type, profile);
            var methodInfo   = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
                               .Where(x => x.Name == "ResolveProxy" && x.IsPrivate)
                               .First();

            var genericMethod = methodInfo.MakeGenericMethod(typeof(AssumeRoleResponse));

            object[] parameters = { httpRequest, acsRequest };
            genericMethod.Invoke(resolveProxy, parameters);

            acsRequest.Protocol = ProtocolType.HTTP;
            Environment.SetEnvironmentVariable("HTTP_PROXY", "http://*****:*****@192.168.16.1:10");
            Environment.SetEnvironmentVariable("no_proxy", "localhost,127.0.0.1,localaddress,.localdomain.com");

            genericMethod.Invoke(resolveProxy, parameters);
            Assert.True(httpRequest.Headers.ContainsKey("Authorization"));
            Environment.SetEnvironmentVariable("HTTP_PROXY", null);

            acsRequest.Protocol = ProtocolType.HTTPS;
            Environment.SetEnvironmentVariable("HTTPS_PROXY", "https://*****:*****@192.168.16.1:10");
            genericMethod.Invoke(resolveProxy, parameters);
            Assert.True(httpRequest.Headers.ContainsKey("Authorization"));
            Environment.SetEnvironmentVariable("HTTPS_PROXY", null);
            httpRequest.Headers.Remove("Authorization");

            Environment.SetEnvironmentVariable("HTTPS_PROXY", "https://192.168.16.1:10");
            genericMethod.Invoke(resolveProxy, parameters);
            Assert.False(httpRequest.Headers.ContainsKey("Authorization"));

            Environment.SetEnvironmentVariable("HTTPS_PROXY", null);
            Environment.SetEnvironmentVariable("HTTP_PROXY", null);
            Environment.SetEnvironmentVariable("no_proxy", null);
            httpRequest.Headers.Remove("Authorization");
        }
Exemplo n.º 17
0
        public void WithRoleSessionDurationSecondss()
        {
            var mock = new Mock <AlibabaCloudCredentials>();
            AlibabaCloudCredentials longLivedCredentials = mock.Object;
            string         roleArn = "roleArn";
            IClientProfile profile = DefaultProfile.GetProfile("cn-shanghai", "accessKeyId", "accessKeySecret");
            STSAssumeRoleSessionCredentialsProvider instance = new STSAssumeRoleSessionCredentialsProvider(longLivedCredentials, roleArn, profile);

            long roleSessionDurationSeconds = 1000;

            // No Exception
            instance.WithRoleSessionDurationSeconds(roleSessionDurationSeconds);

            Assert.Throws <ArgumentOutOfRangeException>(
                () =>
            {
                instance.WithRoleSessionDurationSeconds(100);
            }
                );
        }
        static void Main(string[] args)
        {
            var accessKey       = Environment.GetEnvironmentVariable("ACCESS_KEY_ID") ?? "AccessKeyId";
            var accessKeySecret = Environment.GetEnvironmentVariable("ACCESS_KEY_SECRET") ?? "AccessKeySecret";

            IClientProfile   profile = DefaultProfile.GetProfile("cn-hangzhou", accessKey, accessKeySecret);
            DefaultAcsClient client  = new DefaultAcsClient(profile);

            var request = new TranslateGeneralRequest();

            request.FormatType     = "text";
            request.SourceLanguage = "zh";
            request.SourceText     = "你好,很高兴见到你";
            request.TargetLanguage = "en";
            request.Method         = MethodType.POST;

            var response = client.GetAcsResponse(request);

            Console.WriteLine(response.Data.Translated);
        }
        public void ResolveProxy()
        {
            IClientProfile profile     = DefaultProfile.GetProfile("cn-hangzhou", AKID, AKSE);
            HttpRequest    httpRequest = new HttpRequest();
            var            request     = new AssumeRoleRequest();

            Type       type         = typeof(DefaultAcsClient);
            var        resolveProxy = Activator.CreateInstance(type, profile);
            MethodInfo methodInfo   = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
                                      .Where(x => x.Name == "ResolveProxy" && x.IsPrivate)
                                      .First();

            MethodInfo genericMethod = methodInfo.MakeGenericMethod(typeof(AssumeRoleResponse));

            object[] parameters = { httpRequest, request };
            genericMethod.Invoke(resolveProxy, parameters);

            request.Protocol = ProtocolType.HTTP;
            genericMethod.Invoke(resolveProxy, parameters);
        }
Exemplo n.º 20
0
        public void GetInstanceRamRoleAlibabaCloudCredential()
        {
            var profile = DefaultProfile.GetProfile();
            var defaultCredentialProvider = new DefaultCredentialProvider(profile, null);

            var exception = Assert.Throws <ClientException>(() =>
            {
                defaultCredentialProvider.GetInstanceRamRoleAlibabaCloudCredential();
            });

            Assert.Equal("RegionID cannot be null or empty.", exception.Message);

            Environment.SetEnvironmentVariable("ALIBABA_CLOUD_REGION_ID", "region_id");
            profile.DefaultClientName = "test";
            defaultCredentialProvider = new DefaultCredentialProvider(profile, null);
            var credentialProvider = defaultCredentialProvider.GetInstanceRamRoleAlibabaCloudCredential();

            Environment.SetEnvironmentVariable("ALIBABA_CLOUD_REGION_ID", null);
            Assert.Null(credentialProvider);
        }
Exemplo n.º 21
0
        private void checkConfig_Click(object sender, EventArgs e)
        {
            try
            {
                localIP.Text  = getLocalIP();
                domainIP.Text = getDomainIP();

                clientProfile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId.Text, accessKeySecret.Text);
                client        = new DefaultAcsClient(clientProfile);
                if (setRecordId())
                {
                    MessageBox.Show("设置正确!");
                }
                if (saveConfigFile())
                {
                    MessageBox.Show("保存成功!");
                }
            }
            catch (Exception) { networkStatus.Text = "无网络"; }
        }
Exemplo n.º 22
0
        public void UnicodeAndQueryTest()
        {
            BasicSessionCredentials basciCredential = new BasicSessionCredentials(this.GetBasicAccessKeyId(), this.GetBasicAccessKeySecret(), this.GetToken());
            DefaultProfile          profile         = DefaultProfile.GetProfile(this.regionId, this.GetBasicAccessKeyId(), this.GetBasicAccessKeySecret());
            DefaultAcsClient        client          = new DefaultAcsClient(profile, basciCredential);

            CommonRequest request = new CommonRequest();

            request.Domain     = "ros.aliyuncs.com";
            request.Version    = "2015-09-01";
            request.Action     = "DescribeResourceTypes";
            request.UriPattern = "/resource_types";
            request.Method     = MethodType.GET;
            request.QueryParameters.Add("testParams", "SDFSDFSAetTEWTEWQO(∩_∩)O哈哈~");

            CommonResponse response = client.GetCommonResponse(request);

            Assert.Equal(200, response.HttpStatus);
            Assert.NotNull(response.Data);
        }
Exemplo n.º 23
0
        public static void DescribeInstances()
        {
            IClientProfile   profile = DefaultProfile.GetProfile("cn-hangzhou", "<accessKeyId>", "<accessSecret>");
            DefaultAcsClient client  = new DefaultAcsClient(profile);

            var request = new DescribeInstancesRequest();

            try {
                var response = client.GetAcsResponse(request);
                Console.WriteLine(System.Text.Encoding.Default.GetString(response.HttpResponse.Content));
            }
            catch (ServerException e)
            {
                Console.WriteLine(e);
            }
            catch (ClientException e)
            {
                Console.WriteLine(e);
            }
        }
Exemplo n.º 24
0
        private async Task send(string[] receivers, SmsInformation information)
        {
            await Task.Run(() =>
            {
                IClientProfile profile  = DefaultProfile.GetProfile(_profile_default, _aliYunApiSetting.accessKeyId, _aliYunApiSetting.secret);
                DefaultAcsClient client = new DefaultAcsClient(profile);
                CommonRequest request   = new CommonRequest();

                request.Method  = MethodType.POST;
                request.Domain  = _aliApiDomain;
                request.Version = _aliApiVersion;
                request.Action  = _AliApiAction;
                // request.Protocol = ProtocolType.HTTP;

                string phoneNumbers = StringUtil.SplitJoint(receivers);

                request.AddQueryParameters(_param_PhoneNumbers, phoneNumbers);
                request.AddQueryParameters(_param_SignName, information.SignName);
                request.AddQueryParameters(_param_TemplateCode, information.TemplateCode);
                request.AddQueryParameters(_param_TemplateParam, information.TemplateParam);

                try
                {
                    CommonResponse response = client.GetCommonResponse(request);
                    var apiResult           = JsonConvert.DeserializeObject <AliApiResult>(response.Data);

                    if (apiResult.Code != _ApiResult_OK)
                    {
                        sendErrorLog(Localization.Sy000100.ToString(), receivers, information);
                    }
                }
                catch (ServerException e)
                {
                    sendErrorLog(e.Message, receivers, information);
                }
                catch (ClientException e)
                {
                    sendErrorLog(e.Message, receivers, information);
                }
            });
        }
Exemplo n.º 25
0
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="PhoneNumbers">电话号码</param>
        /// <param name="code">验证码</param>
        public SendSmsResponse SendResetEmail(string PhoneNumbers, string code)
        {
            String         product         = "Dysmsapi";                           //短信API产品名称
            String         domain          = "dysmsapi.aliyuncs.com";              //短信API产品域名
            String         accessKeyId     = AliyunVariable.AliyunAccessKeyId;     //你的accessKeyId
            String         accessKeySecret = AliyunVariable.AliyunAccessKeySecret; //你的accessKeySecret
            IClientProfile profile         = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);

            DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient     acsClient = new DefaultAcsClient(profile);
            SendSmsRequest request   = new SendSmsRequest();

            try
            {
                //必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为20个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
                request.PhoneNumbers = PhoneNumbers;
                //必填:短信签名-可在短信控制台中找到
                request.SignName = AliyunVariable.AliyunSignName;
                //必填:短信模板-可在短信控制台中找到
                request.TemplateCode = Enum_SendEmailCode.UserRegistrationVerificationCode.Enum_GetString();
                //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
                request.TemplateParam = new ModifyPasswordAuthentication(code).GetString();
                //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
                request.OutId = "21212121211";
                //请求失败这里会抛ClientException异常
                SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);
                return(sendSmsResponse);
            }
            catch (ServerException e)
            {
                Console.WriteLine(e.ErrorCode);
                Console.WriteLine(e.ErrorMessage);
                throw e;
            }
            catch (ClientException e)
            {
                Console.WriteLine(e.ErrorCode);
                Console.WriteLine(e.ErrorMessage);
                throw e;
            }
        }
Exemplo n.º 26
0
        static void Main()
        {
            IClientProfile         clientProfile = DefaultProfile.GetProfile("cn-hangzhou", "<your access key id>", "<your access key secret>");
            DefaultAcsClient       client        = new DefaultAcsClient(clientProfile);
            QueryDeviceStatRequest request       = new QueryDeviceStatRequest();

            request.AppKey = < Your AppKey >;

            request.QueryType  = "Total";
            request.DeviceType = "All";
            String startTime = DateTime.UtcNow.AddDays(-7).ToString("yyyy-MM-ddTHH\\:mm\\:ssZ");
            String endTime   = DateTime.UtcNow.ToString("yyyy-MM-ddTHH\\:mm\\:ssZ");

            request.StartTime = startTime;
            request.EndTime   = endTime;

            try
            {
                QueryDeviceStatResponse response = client.GetAcsResponse(request);
                Console.WriteLine("RequestId:" + response.RequestId);
                foreach (QueryDeviceStatResponse.AppDeviceStat stat in response.AppDeviceStats)
                {
                    Console.WriteLine("time:" + stat.Time);
                    Console.WriteLine("DeviceType:" + stat.DeviceType);
                    Console.WriteLine("count:" + stat.Count);
                }
                Console.ReadLine();
            }
            catch (ServerException e)
            {
                Console.WriteLine(e.ErrorCode);
                Console.WriteLine(e.ErrorMessage);
                Console.ReadLine();
            }
            catch (ClientException e)
            {
                Console.WriteLine(e.ErrorCode);
                Console.WriteLine(e.ErrorMessage);
                Console.ReadLine();
            }
        }
Exemplo n.º 27
0
        public static AssumeRoleResponse.Credentials_ GetSecurityToken()
        {
            if (credentials != null && (DateTime.Now - _timeStamp).Seconds < 30)
            {
                //防止请求过于频繁,设置5分钟请求一次。
                return(credentials);
            }
            // 构建一个 Aliyun Client, 用于发起请求
            // 构建Aliyun Client时需要设置AccessKeyId和AccessKeySevcret
            // STS是Global Service, API入口位于杭州, 这里Region填写"cn-hangzhou"
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);
            var            client  = new DefaultAcsClient(profile);

            // 构造AssumeRole请求
            var request = new AssumeRoleRequest();

            // 指定角色Arn
            request.RoleArn         = "acs:ram::1724377057077130:role/myfirstrole";
            request.RoleSessionName = "alice";
            // 可以设置Token有效期,可选参数,默认3600秒;
            request.DurationSeconds = 3600;
            // 可以设置Token的附加Policy,可以在获取Token时,通过额外设置一个Policy进一步减小Token的权限;
            // request.Policy="<policy-content>"
            try
            {
                AssumeRoleResponse response = client.GetAcsResponse(request);
                //Console.WriteLine("AccessKeyId: " + response.Credentials.AccessKeyId);
                //Console.WriteLine("AccessKeySecret: " + response.Credentials.AccessKeySecret);
                //Console.WriteLine("SecurityToken: " + response.Credentials.SecurityToken);
                ////Token过期时间;服务器返回UTC时间,这里转换成北京时间显示;
                //Console.WriteLine("Expiration: " + DateTime.Parse(response.Credentials.Expiration).ToLocalTime());
                credentials = response.Credentials;
                _timeStamp  = DateTime.Now;
                return(credentials);
            }
            catch (Exception ex)
            {
                return(null);
                //记录错误日志
            }
        }
Exemplo n.º 28
0
 /// <summary>
 /// 预热cdn缓存
 /// </summary>
 public bool PurgeObjectCache(string cdnDomain, string key, out string requestId,
                              out string taskIdOrMsg, string objectType = "File", string regionId = "cn-hangzhou")
 {
     try
     {
         var request = new PurgeObjectCachesRequest()
         {
             DomainName = RemoveHttpString(cdnDomain),
             ObjectPath = key,
             ObjectType = objectType,
         };
         var profile  = DefaultProfile.GetProfile(regionId, _accessKeyId, _accessKeySecret);
         var client   = new DefaultAcsClient(profile);
         var response = client.DoAction(request);
         var xmlTxt   = ConvertToString(response.Content);
         var xmlDoc   = new XmlDocument();
         xmlDoc.LoadXml(xmlTxt);
         if (response.Status == 200)
         {
             var firstNode = xmlDoc.SelectSingleNode("PurgeObjectCachesResponse");
             requestId   = firstNode.SelectSingleNode("RequestId").InnerText;
             taskIdOrMsg = firstNode.SelectSingleNode("RefreshTaskId").InnerText;
             return(true);
         }
         else
         {
             var firstNode = xmlDoc.SelectSingleNode("Error");
             requestId   = firstNode.SelectSingleNode("RequestId").InnerText;
             taskIdOrMsg = string.Format("{0} : {1}",
                                         firstNode.SelectSingleNode("Code").InnerText,
                                         firstNode.SelectSingleNode("Message").InnerText);
             return(false);
         }
     }
     catch (Exception ex)
     {
         requestId   = string.Empty;
         taskIdOrMsg = ex.Message;
         return(false);
     }
 }
Exemplo n.º 29
0
        public void AddEndpoint()
        {
            var                  endpointName  = "AddEndpoint.someString";
            var                  regionId      = "AddEndpoint.someString";
            var                  productName   = "product_name";
            var                  productDomain = "product_domain";
            List <Endpoint>      endpoints;
            List <ProductDomain> products;

            DefaultProfile.ClearProfile();
            var profile = DefaultProfile.GetProfile();

            // Add endpoint
            profile.AddEndpoint(endpointName, regionId, productName, productDomain);
            endpoints = profile.GetEndpoints(regionId, productName);
            Assert.NotNull(endpoints);
            foreach (var endpoint in endpoints)
            {
                Assert.Equal(endpointName, endpoint.Name);
                products = endpoint.ProductDomains;
                foreach (var product in products)
                {
                    Assert.Equal(productName, product.ProductName);
                    Assert.Equal(productDomain, product.DomainName);
                }
            }

            profile.AddEndpoint(endpointName, regionId, productName, productDomain);
            endpoints = profile.GetEndpoints(regionId, productName);
            Assert.NotNull(endpoints);
            foreach (var endpoint in endpoints)
            {
                Assert.Equal(endpointName, endpoint.Name);
                products = endpoint.ProductDomains;
                foreach (var product in products)
                {
                    Assert.Equal(productName, product.ProductName);
                    Assert.Equal(productDomain, product.DomainName);
                }
            }
        }
Exemplo n.º 30
0
        /// <summary>
        /// 发送短信验证码
        /// </summary>
        /// <param name="PhoneNumbers"></param>
        /// <param name="Code"></param>
        /// <returns></returns>
        public static bool SendCode(string PhoneNumbers, string Code)
        {
            bool res = false;

            string         product = "Dysmsapi";              //短信API产品名称(短信产品名固定,无需修改)
            string         domain  = "dysmsapi.aliyuncs.com"; //短信API产品域名(接口地址固定,无需修改)
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);

            //IAcsClient client = new DefaultAcsClient(profile);
            // SingleSendSmsRequest request = new SingleSendSmsRequest();
            //初始化ascClient,暂时不支持多region(请勿修改)
            DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient     acsClient = new DefaultAcsClient(profile);
            SendSmsRequest request   = new SendSmsRequest();

            try
            {
                //必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式,发送国际/港澳台消息时,接收号码格式为00+国际区号+号码,如“0085200000000”
                request.PhoneNumbers = PhoneNumbers;
                //必填:短信签名-可在短信控制台中找到
                request.SignName = SignName;
                //必填:短信模板-可在短信控制台中找到,发送国际/港澳台消息时,请使用国际/港澳台短信模版
                request.TemplateCode = "SMS_156471344";
                //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
                request.TemplateParam = "{\"code\":\"" + Code + "\"}";
                //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
                //request.OutId = "yourOutId";
                //请求失败这里会抛ClientException异常
                SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);

                if (sendSmsResponse.Message == "OK")
                {
                    res = true;
                }
            }
            catch
            {
            }

            return(res);
        }