Esempio n. 1
0
        static void Main(string[] args)
        {
            try
            {
                // 必要步骤:
                // 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。
                // 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。
                // 你也可以直接在代码中写死密钥对,但是小心不要将代码复制、上传或者分享给他人,
                // 以免泄露密钥对危及你的财产安全。
                Credential cred = new Credential {
                    SecretId  = Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_ID"),
                    SecretKey = Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_KEY")
                };

                // 实例化一个client选项,可选的,没有特殊需求可以跳过
                ClientProfile clientProfile = new ClientProfile();
                // 指定签名算法(默认为HmacSHA256)
                clientProfile.SignMethod = ClientProfile.SIGN_TC3SHA256;
                // 非必要步骤
                // 实例化一个客户端配置对象,可以指定超时时间等配置
                HttpProfile httpProfile = new HttpProfile();
                // SDK默认使用POST方法。
                // 如果你一定要使用GET方法,可以在这里设置。GET方法无法处理一些较大的请求。
                httpProfile.ReqMethod = "GET";
                // SDK有默认的超时时间,非必要请不要进行调整。
                // 如有需要请在代码中查阅以获取最新的默认值。
                httpProfile.Timeout = 10; // 请求连接超时时间,单位为秒(默认60秒)
                // SDK会自动指定域名。通常是不需要特地指定域名的,但是如果你访问的是金融区的服务,
                // 则必须手动指定域名,例如云服务器的上海金融区域名: cvm.ap-shanghai-fsi.tencentcloudapi.com
                httpProfile.Endpoint = "cvm.tencentcloudapi.com";
                // 代理服务器,当你的环境下有代理服务器时设定
                httpProfile.WebProxy = Environment.GetEnvironmentVariable("HTTPS_PROXY");

                clientProfile.HttpProfile = httpProfile;

                // 实例化要请求产品(以cvm为例)的client对象
                // 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,或者引用预设的常量,clientProfile是可选的
                CvmClient client = new CvmClient(cred, "ap-guangzhou", clientProfile);

                // 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
                // 你可以直接查询SDK源码确定DescribeInstancesRequest有哪些属性可以设置,
                // 属性可能是基本类型,也可能引用了另一个数据结构。
                // 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明。
                DescribeInstancesRequest req = new DescribeInstancesRequest();

                // 基本类型的设置。
                // 此接口允许设置返回的实例数量。此处指定为只返回一个。
                // SDK采用的是指针风格指定参数,即使对于基本类型你也需要用指针来对参数赋值。
                // SDK提供对基本类型的指针引用封装函数
                req.Limit = 1;
                // 数组类型的设置。
                // 此接口允许指定实例 ID 进行过滤,但是由于和接下来要演示的 Filter 参数冲突,先注释掉。
                // req.InstanceIds = new string[] { "ins-r8hr2upy" };

                // 复杂对象的设置。
                // 在这个接口中,Filters是数组,数组的元素是复杂对象Filter,Filter的成员Values是string数组。
                // 填充请求参数,这里request对象的成员变量即对应接口的入参
                // 你可以通过官网接口文档或跳转到request对象的定义处查看请求参数的定义
                Filter zoneFilter = new Filter(); // 创建Filter对象, 以zone的维度来查询cvm实例
                zoneFilter.Name   = "zone";
                zoneFilter.Values = new string[] { "ap-guangzhou-1", "ap-guangzhou-2" };
                Filter nameFilter = new Filter();
                nameFilter.Name   = "instance-name";
                nameFilter.Values = new string[] { "中文测试" };
                req.Filters       = new Filter[] { zoneFilter, nameFilter }; // Filters 是成员为Filter对象的列表

                //// 这里还支持以标准json格式的string来赋值请求参数的方式。下面的代码跟上面的参数赋值是等效的
                //string strParams = "{\"Filters\":[{\"Name\":\"zone\",\"Values\":[\"ap-guangzhou-1\",\"ap-guangzhou-2\"]}]}";
                //req = DescribeInstancesRequest.FromJsonString<DescribeInstancesRequest>(strParams);

                // 通过client对象调用DescribeInstances方法发起请求。注意请求方法名与请求对象是对应的
                // 返回的resp是一个DescribeInstancesResponse类的实例,与请求对象对应
                DescribeInstancesResponse resp = client.DescribeInstancesSync(req);

                // 输出json格式的字符串回包
                Console.WriteLine(AbstractModel.ToJsonString(resp));

                // 也可以取出单个值。
                // 你可以通过官网接口文档或跳转到response对象的定义处查看返回字段的定义
                Console.WriteLine(resp.TotalCount);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            Console.Read();
        }
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="signMethod">Signature process method.</param>
 /// <param name="httpProfile">HttpProfile instance.</param>
 public ClientProfile(string signMethod, HttpProfile httpProfile)
 {
     this.SignMethod  = signMethod;
     this.HttpProfile = httpProfile;
     this.Language    = Language.DEFAULT;
 }
Esempio n. 3
0
        // 该示例要运行成功,需要修改一些网络和安全组的设置。
        // 请慎重运行该示例,因为创建成功后会产生扣费。
        static void Main1(string[] args)
        {
            try
            {
                // 必要步骤:
                // 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。
                // 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。
                // 你也可以直接在代码中写死密钥对,但是小心不要将代码复制、上传或者分享给他人,
                // 以免泄露密钥对危及你的财产安全。
                Credential cred = new Credential
                {
                    SecretId  = Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_ID"),
                    SecretKey = Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_KEY")
                };

                // 实例化一个client选项,可选的,没有特殊需求可以跳过
                ClientProfile clientProfile = new ClientProfile();
                // 非必要步骤
                // 实例化一个客户端配置对象,可以指定超时时间等配置
                HttpProfile httpProfile = new HttpProfile();
                // 代理服务器,当你的环境下有代理服务器时设定
                httpProfile.WebProxy = Environment.GetEnvironmentVariable("HTTPS_PROXY");

                clientProfile.HttpProfile = httpProfile;

                // 实例化要请求产品(以cvm为例)的client对象
                // 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,或者引用预设的常量,clientProfile是可选的
                CvmClient client = new CvmClient(cred, "ap-guangzhou", clientProfile);

                // 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
                // 你可以直接查询SDK源码确定DescribeZonesRequest有哪些属性可以设置,
                // 属性可能是基本类型,也可能引用了另一个数据结构。
                // 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明。
                RunInstancesRequest req = new RunInstancesRequest();

                Placement placement = new Placement();
                placement.Zone = "ap-guangzhou-3";
                req.Placement  = placement;

                req.ImageId            = "img-8toqc6s3";
                req.InstanceChargeType = "POSTPAID_BY_HOUR";
                req.InstanceName       = "DOTNET_SDK_TEST";
                req.InstanceType       = "S2.SMALL1";

                InternetAccessible ia = new InternetAccessible();
                ia.InternetChargeType      = "BANDWIDTH_POSTPAID_BY_HOUR";
                ia.InternetMaxBandwidthOut = 10;
                ia.PublicIpAssigned        = true;
                req.InternetAccessible     = ia;

                LoginSettings ls = new LoginSettings();
                ls.Password       = "******";
                req.LoginSettings = ls;

                req.SecurityGroupIds = new string[] { "sg-icy671l9" };

                SystemDisk sd = new SystemDisk();
                sd.DiskSize    = 50;
                sd.DiskType    = "CLOUD_BASIC";
                req.SystemDisk = sd;

                VirtualPrivateCloud vpc = new VirtualPrivateCloud();
                vpc.VpcId               = "vpc-8ek64x3d";
                vpc.SubnetId            = "subnet-b1wk8b10";
                req.VirtualPrivateCloud = vpc;

                // 通过client对象调用DescribeInstances方法发起请求。注意请求方法名与请求对象是对应的
                // 返回的resp是一个DescribeInstancesResponse类的实例,与请求对象对应
                RunInstancesResponse resp = client.RunInstancesSync(req);

                // 输出json格式的字符串回包
                Console.WriteLine(AbstractModel.ToJsonString(resp));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            Console.Read();
        }
Esempio n. 4
0
 public ClientProfile()
 {
     SignMethod  = SIGN_MD5;
     HttpProfile = new HttpProfile();
 }
Esempio n. 5
0
        public static Dictionary <string, object> genCredential(Dictionary <string, object> values)
        {
            checkArguments(values, new string[] { "secretId", "secretKey", "region" });

            Credential cred = new Credential {
                SecretId  = (string)values["secretId"],
                SecretKey = (string)values["secretKey"]
            };
            string region = (string)values["region"];

            ClientProfile clientProfile = new ClientProfile();
            HttpProfile   httpProfile   = new HttpProfile();
            String        endpoint      = values.ContainsKey("Domain") ? (string)values["Domain"]:
                                          "sts.tencentcloudapi.com";

            httpProfile.Endpoint      = endpoint;
            clientProfile.HttpProfile = httpProfile;

            // get policy
            string policy = null;

            if (values.ContainsKey("policy"))
            {
                policy = (string)values["policy"];
            }
            if (policy == null)
            {
                checkArguments(values, new string[] { "bucket", "allowActions" });
                string   bucket       = (string)values["bucket"];
                string[] allowActions = (string[])values["allowActions"];
                string[] allowPrefixes;
                if (values.ContainsKey("allowPrefix"))
                {
                    allowPrefixes = new string[] { (string)values["allowPrefix"] };
                }
                else if (values.ContainsKey("allowPrefixes"))
                {
                    allowPrefixes = (string[])values["allowPrefixes"];
                }
                else
                {
                    throw new System.ArgumentException("allowPrefix and allowPrefixes are both null.");
                }
                policy = getPolicy(region, bucket, allowPrefixes, allowActions);
            }

            // duration
            Int32 durationSeconds = 1800;

            if (values.ContainsKey("durationSeconds"))
            {
                durationSeconds = (Int32)values["durationSeconds"];
            }

            Dictionary <string, object> body = new Dictionary <string, object>();

            body.Add("DurationSeconds", durationSeconds);
            body.Add("Name", "cos-sts-sdk-dotnet");
            body.Add("Policy", policy);

            StsClient client = new StsClient(cred, region, clientProfile);
            GetFederationTokenRequest req = new GetFederationTokenRequest();

            string strParams = JsonConvert.SerializeObject(body);

            req = GetFederationTokenRequest.FromJsonString <GetFederationTokenRequest>(strParams);
            GetFederationTokenResponse resp = client.GetFederationToken(req).
                                              ConfigureAwait(false).GetAwaiter().GetResult();
            string jsonString = JsonConvert.SerializeObject(resp);
            Dictionary <string, object> dic = JsonConvert.DeserializeObject <Dictionary <string, object> >(jsonString);

            if (dic.ContainsKey("ExpiredTime"))
            {
                dic.Add("StartTime", Int32.Parse(dic["ExpiredTime"].ToString()) - durationSeconds);
            }
            return(dic);
        }
Esempio n. 6
0
        public ActionResult <HttpListener> PutHttpListener([FromBody] HttpListener httpListener)
        {
            Listener listener = _context.Listeners.FirstOrDefault(L => L.Id == httpListener.Id);

            if (listener == null)
            {
                return(NotFound());
            }
            ListenerType listenerType = _context.ListenerTypes.FirstOrDefault(L => L.Id == listener.ListenerTypeId);

            if (listenerType == null || listenerType.Name != "HTTP")
            {
                return(NotFound());
            }
            HttpListener savedhttpListener = (HttpListener)listener;

            // URL is calculated from BindAddress, BindPort, UseSSL components
            // Default to setting based on URL if requested URL differs
            if (savedhttpListener.Url != httpListener.Url)
            {
                savedhttpListener.Url = httpListener.Url;
            }
            else
            {
                savedhttpListener.BindAddress    = httpListener.BindAddress;
                savedhttpListener.BindPort       = httpListener.BindPort;
                savedhttpListener.ConnectAddress = httpListener.ConnectAddress;
                savedhttpListener.UseSSL         = httpListener.UseSSL;
            }
            savedhttpListener.ProfileId      = httpListener.ProfileId;
            savedhttpListener.Name           = httpListener.Name;
            savedhttpListener.SSLCertificate = httpListener.SSLCertificate;

            if (savedhttpListener.Status == Listener.ListenerStatus.Active && httpListener.Status == Listener.ListenerStatus.Stopped)
            {
                savedhttpListener.Stop(_cancellationTokens[savedhttpListener.Id]);
                savedhttpListener.Status = httpListener.Status;
            }
            else if (savedhttpListener.Status != Listener.ListenerStatus.Active && httpListener.Status == Listener.ListenerStatus.Active)
            {
                if (savedhttpListener.UseSSL && (savedhttpListener.SSLCertHash == "" || savedhttpListener.SSLCertificate == ""))
                {
                    return(BadRequest());
                }
                else if (_context.Listeners.Where(L => L.Status == Listener.ListenerStatus.Active && L.BindPort == listener.BindPort).Any())
                {
                    return(BadRequest());
                }
                HttpProfile             profile = (HttpProfile)_context.Profiles.FirstOrDefault(HP => HP.Id == savedhttpListener.ProfileId);
                CancellationTokenSource listenerCancellationToken = savedhttpListener.Start(profile);
                if (listenerCancellationToken == null)
                {
                    return(BadRequest());
                }
                NetworkIndicator httpIndicator = new NetworkIndicator
                {
                    Protocol  = "http",
                    Domain    = Utilities.IsIPAddress(savedhttpListener.ConnectAddress) ? "" : savedhttpListener.ConnectAddress,
                    IPAddress = Utilities.IsIPAddress(savedhttpListener.ConnectAddress) ? savedhttpListener.ConnectAddress : "",
                    Port      = savedhttpListener.BindPort,
                    URI       = savedhttpListener.Url
                };
                if (_context.Indicators.Where(I => I.Name == "NetworkIndicator")
                    .Select(I => (NetworkIndicator)I)
                    .FirstOrDefault(I => I.IPAddress == httpIndicator.IPAddress && I.Domain == httpIndicator.Domain) == null)
                {
                    _context.Indicators.Add(httpIndicator);
                }
                _cancellationTokens[savedhttpListener.Id] = listenerCancellationToken;
            }

            _context.Listeners.Update(savedhttpListener);
            _context.SaveChanges();

            return(Ok(listener));
        }
Esempio n. 7
0
        public int GetDefaultProfile()
        {
            if (defaultprofileid == 0)
            {
                if (Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), WORKSPACE_FOLDER, PROFILES_FOLDER)))
                {
                    string[] fileEntries = Directory.GetFiles(Path.Combine(Directory.GetCurrentDirectory(), WORKSPACE_FOLDER, PROFILES_FOLDER));

                    foreach (string filepath in fileEntries)
                    {
                        string filename = Path.GetFileName(filepath);

                        if (filename.EndsWith(".json") && filename.Split('_').Length == 2)
                        {
                            try
                            {
                                string profileidstr = filename.Split('_')[1].Split('.')[0];

                                if (Int32.TryParse(profileidstr, out int profileid))
                                {
                                    string      profilefilecont = File.ReadAllText(filepath);
                                    HttpProfile profile         = JsonConvert.DeserializeObject <HttpProfile>(profilefilecont);

                                    if (profile.Default)
                                    {
                                        defaultprofileid = profileid;
                                    }

                                    availableprofile.Add(profileid, profile);
                                }
                            }
                            catch
                            {
                            }
                        }
                    }

                    if (availableprofile.Count == 0)
                    {
                        Console.WriteLine("[*] No profile avalilable, creating new one...");

                        var profile = new HttpProfile
                        {
                            Delay            = 5000,
                            Default          = true,
                            Name             = "Default",
                            UserAgent        = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36",
                            ContentUri       = "/content/",
                            Spawn            = "notepad.exe",
                            HtmlCovered      = false,
                            InjectionManaged = true
                        };

                        HttpGet httpget = new HttpGet
                        {
                            ApiPath = new string[] { "/newslist.jsp" }
                        };

                        HttpClient getclient = new HttpClient();

                        HttpHeader[] headers = new HttpHeader[3];

                        HttpHeader header = new HttpHeader
                        {
                            Name  = "Cache-Control",
                            Value = "no-cache"
                        };

                        headers[0] = header;

                        header = new HttpHeader
                        {
                            Name  = "Connection",
                            Value = "Keep-Alive"
                        };

                        headers[1] = header;

                        header = new HttpHeader
                        {
                            Name  = "Pragma",
                            Value = "no-cache"
                        };

                        headers[2] = header;

                        getclient.Headers = headers;

                        httpget.Client = getclient;

                        HttpServer getserver = new HttpServer();

                        HttpHeader[] serverheaders = new HttpHeader[3];

                        HttpHeader serverheader = new HttpHeader
                        {
                            Name  = "Content-Type",
                            Value = "application/octet-stream"
                        };

                        serverheaders[0] = serverheader;

                        serverheader = new HttpHeader
                        {
                            Name  = "Connection",
                            Value = "Keep-Alive"
                        };

                        serverheaders[1] = serverheader;

                        serverheader = new HttpHeader
                        {
                            Name  = "Server",
                            Value = "Apache"
                        };

                        serverheaders[2] = serverheader;

                        getserver.Headers = serverheaders;

                        httpget.Server = getserver;

                        profile.HttpGet = httpget;

                        var httppost = new HttpPost
                        {
                            ApiPath = new string[] { "/newslist.jsp" },
                            Client  = getclient,
                            Server  = getserver,
                            Param   = "stocklevel",
                            Mask    = @"{0}={1}"
                        };
                        profile.HttpPost = httppost;

                        string deser = JsonConvert.SerializeObject(profile, Formatting.Indented);
                        File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), WORKSPACE_FOLDER, PROFILES_FOLDER, "default_1.json"), deser);

                        defaultprofileid = 1;
                        availableprofile.Add(defaultprofileid, profile);
                    }
                }
                else
                {
                    Console.WriteLine(Path.Combine(Directory.GetCurrentDirectory(), WORKSPACE_FOLDER, PROFILES_FOLDER));
                }

                if (defaultprofileid == 0 && availableprofile.Count > 0)
                {
                    availableprofile.First().Value.Default = true;
                    defaultprofileid = availableprofile.First().Key;
                }

                return(defaultprofileid);
            }
            else
            {
                return(defaultprofileid);
            }
        }
Esempio n. 8
0
        static void Main(string[] args)
        {
            try
            {
                /* 必要步骤:
                 * 实例化一个认证对象,入参需要传入腾讯云账户密钥对 secretId 和 secretKey
                 * 本示例采用从环境变量读取的方式,需要预先在环境变量中设置这两个值
                 * 您也可以直接在代码中写入密钥对,但需谨防泄露,不要将代码复制、上传或者分享给他人
                 * CAM 密匙查询:https://console.cloud.tencent.com/cam/capi*/
                Credential cred = new Credential
                {
                    SecretId  = "xxx",
                    SecretKey = "xxx"
                };

                /*
                 * Credential cred = new Credential {
                 *  SecretId = Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_ID"),
                 *  SecretKey = Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_KEY")
                 * };*/

                /* 非必要步骤:
                 * 实例化一个客户端配置对象,可以指定超时时间等配置 */
                ClientProfile clientProfile = new ClientProfile();

                /* SDK 默认用 TC3-HMAC-SHA256 进行签名
                 * 非必要请不要修改该字段 */
                clientProfile.SignMethod = ClientProfile.SIGN_TC3SHA256;

                /* 非必要步骤
                 * 实例化一个客户端配置对象,可以指定超时时间等配置 */
                HttpProfile httpProfile = new HttpProfile();

                /* SDK 默认使用 POST 方法
                 * 如需使用 GET 方法,可以在此处设置,但 GET 方法无法处理较大的请求 */
                httpProfile.ReqMethod = "POST";

                /* SDK 有默认的超时时间,非必要请不要进行调整
                 * 如有需要请在代码中查阅以获取最新的默认值 */
                httpProfile.Timeout = 10; // 请求连接超时时间,单位为秒(默认60秒)

                /* SDK 会自动指定域名,通常无需指定域名,但访问金融区的服务时必须手动指定域名
                 * 例如 SMS 的上海金融区域名为 sms.ap-shanghai-fsi.tencentcloudapi.com */
                httpProfile.Endpoint = "sms.tencentcloudapi.com";
                // 代理服务器,当您的环境下有代理服务器时设定
                httpProfile.WebProxy = Environment.GetEnvironmentVariable("HTTPS_PROXY");

                clientProfile.HttpProfile = httpProfile;

                /* 实例化 SMS 的 client 对象
                 * 第二个参数是地域信息,可以直接填写字符串 ap-guangzhou,或者引用预设的常量 */
                SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);

                /* 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
                 * 您可以直接查询 SDK 源码确定 SendSmsRequest 有哪些属性可以设置
                 * 属性可能是基本类型,也可能引用了另一个数据结构
                 * 推荐使用 IDE 进行开发,可以方便地跳转查阅各个接口和数据结构的文档说明 */
                PullSmsSendStatusRequest req = new PullSmsSendStatusRequest();

                /* 基本类型的设置:
                 * SDK 采用的是指针风格指定参数,即使对于基本类型也需要用指针来对参数赋值
                 * SDK 提供对基本类型的指针引用封装函数
                 * 帮助链接:
                 * 短信控制台:https://console.cloud.tencent.com/sms/smslist
                 * sms helper:https://cloud.tencent.com/document/product/382/3773 */

                // 设置拉取最大条数,最多100条
                req.Limit = 100;
                /* 短信应用 ID: 在 [短信控制台] 添加应用后生成的实际 SDKAppID,例如1400006666 */
                req.SmsSdkAppid = "1400009099";

                // 通过 client 对象调用 AddSmsTemplateRequest 方法发起请求,注意请求方法名与请求对象是对应的
                // 返回的 resp 是一个 AddSmsTemplateResponse 类的实例,与请求对象对应
                PullSmsSendStatusResponse resp = client.PullSmsSendStatusRequest(req);

                // 输出 JSON 格式的字符串回包
                Console.WriteLine(AbstractModel.ToJsonString(resp));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            Console.Read();
        }
Esempio n. 9
0
        /// <summary>
        /// 发送模板短信
        /// </summary>
        /// <param name="mobile">多个手机号用英文状态下的逗号分隔</param>
        /// <param name="tempCode">模板ID</param>
        /// <param name="tempParams">多个参数英文状态下的逗号分隔,模板中的{数字}代表一个参数</param>
        /// <returns></returns>
        public async Task <(bool isSuccess, string errMsg)> SendMsgAsync(string mobile, string tempCode, string tempParams)
        {
            try
            {
                /* 必要步骤:
                 * 实例化一个认证对象,入参需要传入腾讯云账户密钥对 secretId 和 secretKey
                 * 本示例采用从环境变量读取的方式,需要预先在环境变量中设置这两个值
                 * 您也可以直接在代码中写入密钥对,但需谨防泄露,不要将代码复制、上传或者分享给他人
                 * CAM 密匙查询:https://console.cloud.tencent.com/cam/capi
                 */
                Credential cred = new Credential
                {
                    SecretId  = Config.SMSUId,
                    SecretKey = Config.SMSPwd
                };

                /*
                 * Credential cred = new Credential {
                 *  SecretId = Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_ID"),
                 *  SecretKey = Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_KEY")
                 * };*/

                /* 非必要步骤:
                 * 实例化一个客户端配置对象,可以指定超时时间等配置 */
                ClientProfile clientProfile = new ClientProfile();

                /* SDK 默认用 TC3-HMAC-SHA256 进行签名
                 * 非必要请不要修改该字段 */
                clientProfile.SignMethod = ClientProfile.SIGN_TC3SHA256;

                /* 非必要步骤
                 * 实例化一个客户端配置对象,可以指定超时时间等配置 */
                HttpProfile httpProfile = new HttpProfile();

                /* SDK 默认使用 POST 方法
                 * 如需使用 GET 方法,可以在此处设置,但 GET 方法无法处理较大的请求 */
                httpProfile.ReqMethod = "POST";

                /* SDK 有默认的超时时间,非必要请不要进行调整
                 * 如有需要请在代码中查阅以获取最新的默认值 */
                httpProfile.Timeout = 10; // 请求连接超时时间,单位为秒(默认60秒)

                /* SDK 会自动指定域名,通常无需指定域名,但访问金融区的服务时必须手动指定域名
                 * 例如 SMS 的上海金融区域名为 sms.ap-shanghai-fsi.tencentcloudapi.com */
                httpProfile.Endpoint = Config.EndPoint;
                // 代理服务器,当您的环境下有代理服务器时设定
                //httpProfile.WebProxy = Environment.GetEnvironmentVariable("HTTPS_PROXY");

                clientProfile.HttpProfile = httpProfile;

                /* 实例化 SMS 的 client 对象
                 * 第二个参数是地域信息,可以直接填写字符串 ap-guangzhou,或者引用预设的常量 */
                SmsClient client = new SmsClient(cred, Config.RegionId, clientProfile);

                /* 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
                 * 您可以直接查询 SDK 源码确定 SendSmsRequest 有哪些属性可以设置
                 * 属性可能是基本类型,也可能引用了另一个数据结构
                 * 推荐使用 IDE 进行开发,可以方便地跳转查阅各个接口和数据结构的文档说明 */
                SendSmsRequest req = new SendSmsRequest();

                /* 基本类型的设置:
                 * SDK 采用的是指针风格指定参数,即使对于基本类型也需要用指针来对参数赋值
                 * SDK 提供对基本类型的指针引用封装函数
                 * 帮助链接:
                 * 短信控制台:https://console.cloud.tencent.com/sms/smslist
                 * sms helper:https://cloud.tencent.com/document/product/382/3773
                 */

                req.SmsSdkAppid = Config.APPID;
                /* 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名,可登录 [短信控制台] 查看签名信息 */
                req.Sign = Config.SignName;
                /* 短信码号扩展号: 默认未开通,如需开通请联系 [sms helper] */
                //req.ExtendCode = "x";
                /* 国际/港澳台短信 senderid: 国内短信填空,默认未开通,如需开通请联系 [sms helper] */
                req.SenderId = "";
                /* 用户的 session 内容: 可以携带用户侧 ID 等上下文信息,server 会原样返回 */
                req.SessionContext = System.DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(10000, 100000 - 1).ToString();;

                /* 下发手机号码,采用 e.164 标准,+[国家或地区码][手机号]
                 * 例如+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号*/
                var arrPhones = mobile.Split(',');
                var lstPhone  = new List <string>();
                foreach (var item in arrPhones)
                {
                    if (item.Trim().Length > 0)
                    {
                        lstPhone.Add("+86" + item);
                    }
                }
                req.PhoneNumberSet = lstPhone.ToArray();
                /* 模板 ID: 必须填写已审核通过的模板 ID,可登录 [短信控制台] 查看模板 ID */
                req.TemplateID = tempCode;
                /* 模板参数: 若无模板参数,则设置为空*/
                var arrParams = tempParams.Split(',');
                var lstParams = new List <string>();
                foreach (var item in arrParams)
                {
                    if (item.Trim().Length > 0)
                    {
                        lstParams.Add(item);
                    }
                }
                req.TemplateParamSet = lstParams.ToArray();


                // 通过 client 对象调用 SendSms 方法发起请求,注意请求方法名与请求对象是对应的
                // 返回的 resp 是一个 SendSmsResponse 类的实例,与请求对象对应
                SendSmsResponse resp = await client.SendSms(req);

                // 输出 JSON 格式的字符串回包
                if (resp.SendStatusSet.Length > 0)
                {
                    if (resp.SendStatusSet[0].Code == "Ok")
                    {
                        return(true, "");
                    }
                    else
                    {
                        return(false, resp.SendStatusSet[0].Message);
                    }
                }
                else
                {
                    return(false, "未返回值");
                }

                //Console.WriteLine(AbstractModel.ToJsonString(resp));
            }
            catch (Exception ex)
            {
                return(false, ex.Message);
                //Console.WriteLine(e.ToString());
            }
        }
Esempio n. 10
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="signMethod">Signature process method.</param>
 /// <param name="httpProfile">HttpProfile instance.</param>
 public ClientProfile(string signMethod, HttpProfile httpProfile)
 {
     this.SignMethod  = signMethod;
     this.HttpProfile = httpProfile;
 }
Esempio n. 11
0
 public ClientProfile()
 {
     SignMethod  = SIGN_SHA256;
     HttpProfile = new HttpProfile();
 }
Esempio n. 12
0
 public Startup(IConfiguration configuration)
 {
     Configuration = configuration;
     profile       = RedPeanutC2.server.GetProfile(Int32.Parse(Configuration["FrameworkProfileid"]));
     ssl           = bool.Parse(Configuration["FrameworkSSL"]);
 }
Esempio n. 13
0
        /// <summary>
        ///     注意使用时,要缩小图片的尺寸
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static DetectionResult Detection(byte[] bytes)
        {
            try
            {
                var cred = new Credential
                {
                    SecretId  = API_KEY,
                    SecretKey = SECRET_KEY
                };

                var clientProfile = new ClientProfile();
                var httpProfile   = new HttpProfile();
                httpProfile.Endpoint      = "tiia.tencentcloudapi.com";
                clientProfile.HttpProfile = httpProfile;

                var client = new TiiaClient(cred, Region_Id, clientProfile);
                var req    = new ImageModerationRequest();
                req.Scenes      = new[] { "P**N" };
                req.ImageBase64 = Convert.ToBase64String(bytes);

                var resp = client.ImageModeration(req).ConfigureAwait(false).GetAwaiter().GetResult();

                var ret = new DetectionResult {
                    Platform = "腾讯"
                };

                switch (resp.PornResult.Type.ToLower())
                {
                case "normal":
                    ret.Result = DetectionResultType.Normal;
                    break;

                case "p**n":
                    ret.Result = DetectionResultType.P**n;
                    break;

                case "hot":
                    ret.Result = DetectionResultType.Sexy;
                    break;

                case "breast":
                case "ass":
                case "bareBody":
                case "unrealHotPeople":
                    ret.Result = resp.PornResult.Suggestion == "PASS"
                            ? DetectionResultType.Sexy
                            : DetectionResultType.P**n;
                    break;

                default:
                    ret.Result = DetectionResultType.Unknow;
                    break;
                }

                ret.Items.Add(new DetectionResultItem
                {
                    Suggestion = resp.PornResult.Confidence ?? 0, TypeName = resp.PornResult.Type
                });
                ret.SourceResult = JsonConvert.SerializeObject(resp, Formatting.Indented);
                return(ret);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return(new DetectionResult {
                    Error = ex.Message, Platform = "腾讯"
                });
            }
        }
Esempio n. 14
0
        public void Test()
        {
            int createFileIndex = 1;

            string[] allFiles = Directory.GetFiles(path, "*.xlsx");
            foreach (string strFile in allFiles)
            {
                File.Delete(strFile);
            }
            ListBoxItemAdd(this, this.listBox1, "프로그램 시작 합니다. ^_^");
            foreach (int indexChecked in checkedListBox1.CheckedIndices)
            {
                String lineStr = tt[indexChecked].ToString();
                Console.WriteLine(lineStr);
                try
                {
                    string[] sArray = lineStr.Split('	');
                    if (sArray.Count() < 2)                                      //작업완료 판단
                    {
                        break;
                    }

                    Company            = sArray[0];
                    UIN                = sArray[1].Replace(" ", "");
                    SecretIdfromeFile  = sArray[2].Replace(" ", "");
                    SecretKeyfromeFile = sArray[3].Replace(" ", "");
                    SecretKeyfromeFile = sArray[3].Replace(" ", "");
                    CVMRegion          = sArray[4].Replace(" ", "");

                    BeginTime = dateTimePicker1.Value.ToString("yyyy-MM-01 00:00:00");
                    EndTime   = dateTimePicker1.Value.ToString("yyyy-MM-01 00:00:01");
                    months    = dateTimePicker1.Value.ToString("yyyy년MM월");
                    Console.WriteLine(Company);
                    Console.WriteLine(UIN);
                    Console.WriteLine(SecretIdfromeFile);
                    Console.WriteLine(SecretKeyfromeFile);
                    Console.WriteLine(BeginTime);
                    Console.WriteLine(EndTime);
                    Thread.Sleep(1000);
                    ListBoxItemAdd(this, this.listBox1, "======<< 업체명 : " + Company + " >>=====");

                    fileName = createFileIndex + "-" + Company + "-" + months + ".xlsx";   //파일생성
                    WriteExel(fileName, 1, 1, "TotalCost");
                    WriteExel("모든업체-" + months + ".xlsx", allCompanyIndex, 1, Company);

                    Credential cred = new Credential
                    {
                        SecretId  = SecretIdfromeFile,
                        SecretKey = SecretKeyfromeFile
                    };

                    ClientProfile clientProfile = new ClientProfile();
                    HttpProfile   httpProfile   = new HttpProfile();
                    httpProfile.Endpoint      = ("billing.tencentcloudapi.com");
                    clientProfile.HttpProfile = httpProfile;
                    BillingClient client = new BillingClient(cred, CVMRegion, clientProfile);
                    DescribeBillSummaryByProductRequest req = new DescribeBillSummaryByProductRequest();
                    string strParams = "{\"PayerUin\":\"" + UIN + "\",\"BeginTime\":\"" + BeginTime + "\",\"EndTime\":\"" + EndTime + "\"}";
                    req = DescribeBillSummaryByProductRequest.FromJsonString <DescribeBillSummaryByProductRequest>(strParams);
                    DescribeBillSummaryByProductResponse resp = client.DescribeBillSummaryByProduct(req).ConfigureAwait(false).GetAwaiter().GetResult();
                    //  Console.WriteLine(AbstractModel.ToJsonString(resp));
                    String ttt = AbstractModel.ToJsonString(resp);

                    String total = GetSummaryTotal(ttt);
                    WriteExel(fileName, 1, 2, total);
                    WriteExel("모든업체-" + months + ".xlsx", allCompanyIndex, 2, total);
                    allCompanyIndex++;

                    ListBoxItemAdd(this, this.listBox1, "Total : =》  " + total);

                    Dictionary <string, string> Overview = GetSummaryOverview(ttt);
                    exelIndex = 2;
                    foreach (var item in Overview)
                    {
                        Console.WriteLine(item.Key + item.Value);
                        WriteExel(fileName, exelIndex, 1, item.Key);
                        WriteExel(fileName, exelIndex, 2, item.Value);
                        exelIndex++;
                        ListBoxItemAdd(this, this.listBox1, item.Key + "  --->    " + item.Value);
                    }
                    createFileIndex++;
                    Thread.Sleep(100);
                }
                catch (Exception e)
                {
                    //WriteExel(fileName, exelIndex, 1, Company);
                    WriteExel("모든업체-" + months + ".xlsx", allCompanyIndex, 2, "에러");
                    createFileIndex++;
                    ListBoxItemAdd(this, this.listBox1, "<< 업체명 : " + Company + " >> 요금 실패~~");
                }
                ListBoxItemAdd(this, this.listBox1, " ");
                ListBoxItemAdd(this, this.listBox1, " ");
            }
        }
Esempio n. 15
0
        public override async void Command(MenuItem menuItem, string UserInput)
        {
            try
            {
                HttpListener httpListener = ((HTTPListenerMenuItem)menuItem).HttpListener;
                string[]     commands     = UserInput.Split(" ");
                if (commands.Length != 3 || !commands[0].Equals(this.Name, StringComparison.OrdinalIgnoreCase))
                {
                    menuItem.PrintInvalidOptionError(UserInput);
                    return;
                }
                if (this.Parameters.FirstOrDefault(P => P.Name == "Option").Values.Select(V => V.Value).Contains(commands[1], StringComparer.OrdinalIgnoreCase))
                {
                    if (commands[1].Equals("name", StringComparison.OrdinalIgnoreCase))
                    {
                        httpListener.Name = commands[2];
                    }
                    else if (commands[1].Equals("url", StringComparison.OrdinalIgnoreCase))
                    {
                        try
                        {
                            httpListener.Url = commands[2];
                            Uri uri = new Uri(httpListener.Url);
                            httpListener.UseSSL         = uri.Scheme == "https";
                            httpListener.ConnectAddress = uri.Host;
                            httpListener.BindPort       = uri.Port;
                        }
                        catch (Exception)
                        {
                            EliteConsole.PrintFormattedErrorLine("Specified URL: \"" + commands[2] + "\" is not a valid URI");
                            menuItem.PrintInvalidOptionError(UserInput);
                            return;
                        }
                    }
                    else if (commands[1].Equals("connectaddress", StringComparison.OrdinalIgnoreCase))
                    {
                        httpListener.ConnectAddress = commands[2];
                        string scheme = (httpListener.UseSSL ?? default) ? "https://" : "http://";
                        Uri    uri    = new Uri(scheme + httpListener.ConnectAddress + ":" + httpListener.BindPort);
                        httpListener.Url = uri.ToString();
                    }
                    else if (commands[1].Equals("bindaddress", StringComparison.OrdinalIgnoreCase))
                    {
                        httpListener.BindAddress = commands[2];
                    }
                    else if (commands[1].Equals("bindport", StringComparison.OrdinalIgnoreCase))
                    {
                        int.TryParse(commands[2], out int n);
                        httpListener.BindPort = n;
                        string scheme = (httpListener.UseSSL ?? default) ? "https://" : "http://";
                        Uri    uri    = new Uri(scheme + httpListener.ConnectAddress + ":" + httpListener.BindPort);
                        httpListener.Url = uri.ToString();
                    }
                    else if (commands[1].Equals("usessl", StringComparison.OrdinalIgnoreCase))
                    {
                        httpListener.UseSSL = commands[2].StartsWith("t", StringComparison.OrdinalIgnoreCase);
                        string scheme = (httpListener.UseSSL ?? default) ? "https://" : "http://";
                        Uri    uri    = new Uri(scheme + httpListener.ConnectAddress + ":" + httpListener.BindPort);
                        httpListener.Url = uri.ToString();
                    }
                    else if (commands[1].Equals("sslcertpath", StringComparison.OrdinalIgnoreCase))
                    {
                        string FileName = Path.Combine(Common.EliteDataFolder, commands[2]);
                        if (!File.Exists(FileName))
                        {
                            menuItem.PrintInvalidOptionError(UserInput);
                            EliteConsole.PrintFormattedErrorLine("File: \"" + FileName + "\" does not exist on the local system.");
                            return;
                        }
                        X509Certificate2 certificate = new X509Certificate2(FileName, httpListener.SslCertificatePassword);
                        httpListener.SslCertificate = Convert.ToBase64String(File.ReadAllBytes(FileName));
                        ((HTTPListenerMenuItem)menuItem).SSLCertPath = FileName;
                    }
                    else if (commands[1].Equals("sslcertpassword", StringComparison.OrdinalIgnoreCase))
                    {
                        httpListener.SslCertificatePassword = commands[2];
                    }
                    else if (commands[1].Equals("httpprofile", StringComparison.OrdinalIgnoreCase))
                    {
                        HttpProfile profile = ((HTTPListenerMenuItem)menuItem).HttpProfiles.FirstOrDefault(HP => HP.Name.Equals(commands[2], StringComparison.OrdinalIgnoreCase));
                        if (profile == null)
                        {
                            menuItem.PrintInvalidOptionError(UserInput);
                            EliteConsole.PrintFormattedErrorLine("HttpProfile: \"" + commands[2] + "\" does not exist.");
                            return;
                        }
                        httpListener.ProfileId = profile.Id;
                    }
                    await this.CovenantClient.ApiListenersHttpPutAsync(httpListener);

                    menuItem.Refresh();
                }
                else
                {
                    menuItem.PrintInvalidOptionError(UserInput);
                }
            }
            catch (HttpOperationException e)
            {
                EliteConsole.PrintFormattedWarningLine("CovenantException: " + e.Response.Content);
            }
        }
Esempio n. 16
0
        public override string GetLauncher(Listener listener, Grunt grunt, HttpProfile profile, ImplantTemplate template)
        {
            this.StagerCode         = listener.GetGruntStagerCode(grunt, profile, template);
            this.Base64ILByteString = listener.CompileGruntStagerCode(grunt, profile, template, this.OutputKind, false);

            // Credit DotNetToJscript (tyranid - James Forshaw)
            byte[] serializedDelegate = Convert.FromBase64String(FrontBinaryFormattedDelegate).Concat(Convert.FromBase64String(this.Base64ILByteString)).Concat(Convert.FromBase64String(EndBinaryFormattedDelegate)).ToArray();
            int    ofs = serializedDelegate.Length % 3;

            if (ofs != 0)
            {
                int length = serializedDelegate.Length + (3 - ofs);
                Array.Resize(ref serializedDelegate, length);
            }
            string        base64Delegate = Convert.ToBase64String(serializedDelegate);
            int           lineLength     = 80;
            List <String> splitString    = new List <String>();

            for (int i = 0; i < base64Delegate.Length; i += lineLength)
            {
                splitString.Add(base64Delegate.Substring(i, Math.Min(lineLength, base64Delegate.Length - i)));
            }

            string language = "";
            string code     = "";

            if (this.ScriptLanguage == ScriptingLanguage.JScript)
            {
                string DelegateBlock = String.Join("\"+\r\n\"", splitString.ToArray());
                code     = JScriptTemplate.Replace(Environment.NewLine, "\r\n").Replace("{{REPLACE_GRUNT_IL_BYTE_STRING}}", DelegateBlock);
                language = "JScript";
            }
            else if (this.ScriptLanguage == ScriptingLanguage.VBScript)
            {
                string DelegateBlock = String.Join("\"\r\ns = s & \"", splitString.ToArray());
                code = VBScriptTemplate.Replace(Environment.NewLine, "\r\n").Replace("{{REPLACE_GRUNT_IL_BYTE_STRING}}", DelegateBlock);
                if (this.ScriptType == ScriptletType.Stylesheet)
                {
                    code = "<![CDATA[\r\n" + code + "\r\n]]>";
                }
                language = "VBScript";
            }

            if (this.ScriptType == ScriptletType.Plain)
            {
                this.DiskCode = code;
            }
            else if (this.ScriptType == ScriptletType.Scriptlet || this.ScriptType == ScriptletType.TaggedScript)
            {
                string TaggedScript = TaggedScriptTemplate.Replace(Environment.NewLine, "\r\n").Replace("{{REPLACE_SCRIPT_LANGUAGE}}", language);
                TaggedScript = TaggedScript.Replace("{{REPLACE_SCRIPT}}", code);
                if (this.ScriptType == ScriptletType.TaggedScript)
                {
                    this.DiskCode = TaggedScript;
                }
                else
                {
                    this.DiskCode = ScriptletCodeTemplate.Replace(Environment.NewLine, "\r\n").Replace("{{REPLACE_TAGGED_SCRIPT}}", TaggedScript).Replace("{{REPLACE_PROGID}}", this.ProgId);
                }
            }
            else if (this.ScriptType == ScriptletType.Stylesheet)
            {
                this.DiskCode = StylesheetCodeTemplate.Replace(Environment.NewLine, "\r\n").Replace("{{REPLACE_SCRIPT_LANGUAGE}}", language);
                this.DiskCode = DiskCode.Replace("{{REPLACE_SCRIPT}}", code);
            }

            if (this.DotNetFrameworkVersion == Common.DotNetVersion.Net35)
            {
                this.DiskCode = this.DiskCode.Replace("{{REPLACE_VERSION_SETTER}}", "");
            }
            else if (this.DotNetFrameworkVersion == Common.DotNetVersion.Net40)
            {
                this.DiskCode = this.DiskCode.Replace("{{REPLACE_VERSION_SETTER}}", JScriptNet40VersionSetter);
            }
            return(GetLauncher(this.DiskCode));
        }
Esempio n. 17
0
        static void Main1(string[] args)
        {
            try
            {
                // 必要步骤:
                // 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。
                // 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。
                // 你也可以直接在代码中写死密钥对,但是小心不要将代码复制、上传或者分享给他人,
                // 以免泄露密钥对危及你的财产安全。
                Credential cred = new Credential {
                    SecretId  = Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_ID"),
                    SecretKey = Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_KEY")
                };

                // 实例化一个client选项,可选的,没有特殊需求可以跳过
                ClientProfile clientProfile = new ClientProfile();
                // 指定签名算法(默认为HmacSHA256)
                clientProfile.SignMethod = ClientProfile.SIGN_SHA1;
                // 非必要步骤
                // 实例化一个客户端配置对象,可以指定超时时间等配置
                HttpProfile httpProfile = new HttpProfile();
                // SDK默认使用POST方法。
                // 如果你一定要使用GET方法,可以在这里设置。GET方法无法处理一些较大的请求。
                httpProfile.ReqMethod = "POST";
                // SDK有默认的超时时间,非必要请不要进行调整。
                // 如有需要请在代码中查阅以获取最新的默认值。
                httpProfile.Timeout = 10; // 请求连接超时时间,单位为秒(默认60秒)
                // SDK会自动指定域名。通常是不需要特地指定域名的,但是如果你访问的是金融区的服务,
                // 则必须手动指定域名,例如云服务器的上海金融区域名: aai.ap-shanghai-fsi.tencentcloudapi.com
                httpProfile.Endpoint = ("aai.tencentcloudapi.com");
                // 代理服务器,当你的环境下有代理服务器时设定
                httpProfile.WebProxy = Environment.GetEnvironmentVariable("HTTPS_PROXY");

                clientProfile.HttpProfile = httpProfile;

                // 实例化要请求产品(以cvm为例)的client对象
                // 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,或者引用预设的常量,clientProfile是可选的
                AaiClient client = new AaiClient(cred, "ap-guangzhou", clientProfile);

                // 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
                // 你可以直接查询SDK源码确定DescribeInstancesRequest有哪些属性可以设置,
                // 属性可能是基本类型,也可能引用了另一个数据结构。
                // 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明。
                SentenceRecognitionRequest req = new SentenceRecognitionRequest();
                string     path = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "test.mp3";
                FileStream fs   = new FileStream(path, FileMode.Open);
                byte[]     raw  = new byte[fs.Length];
                fs.Read(raw, 0, raw.Length);
                string base64data = Convert.ToBase64String(raw);
                fs.Close();
                // 基本类型的设置。
                req.ProjectId      = 0;
                req.SubServiceType = 2;
                req.EngSerViceType = "16k";
                req.SourceType     = 1;
                req.VoiceFormat    = "mp3";
                req.UsrAudioKey    = "5c79510a12da-whatever";
                req.Data           = base64data;
                req.DataLen        = base64data.Length;
                // 数组类型的设置。

                // 复杂对象的设置。


                //// 这里还支持以标准json格式的string来赋值请求参数的方式。下面的代码跟上面的参数赋值是等效的
                //string strParams = "{\"Filters\":[{\"Name\":\"zone\",\"Values\":[\"ap-guangzhou-1\",\"ap-guangzhou-2\"]}]}";
                //req = DescribeInstancesRequest.FromJsonString<DescribeInstancesRequest>(strParams);

                // 通过client对象调用DescribeInstances方法发起请求。注意请求方法名与请求对象是对应的
                // 返回的resp是一个DescribeInstancesResponse类的实例,与请求对象对应
                SentenceRecognitionResponse resp = client.SentenceRecognitionSync(req);

                // 输出json格式的字符串回包
                Console.WriteLine(AbstractModel.ToJsonString(resp));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            Console.Read();
        }
Esempio n. 18
0
 public virtual string GetLauncher(Listener listener, Grunt grunt, HttpProfile profile, ImplantTemplate template)
 {
     return("");
 }
Esempio n. 19
0
 public ActionResult <HttpProfile> CreateHttpProfile([FromBody] HttpProfile profile)
 {
     _context.Profiles.Add(profile);
     _context.SaveChanges();
     return(CreatedAtRoute(nameof(GetHttpProfile), new { id = profile.Id }, profile));
 }
Esempio n. 20
0
        static void Main1(string[] args)
        {
            try
            {
                /* 必要步骤:
                 * 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。
                 * 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。
                 * 你也可以直接在代码中写死密钥对,但是小心不要将代码复制、上传或者分享给他人,
                 * 以免泄露密钥对危及你的财产安全。
                 * CAM密匙查询: https://console.cloud.tencent.com/cam/capi*/
                Credential cred = new Credential {
                    SecretId  = "xxx",
                    SecretKey = "xxx"
                };

                /*
                 * Credential cred = new Credential {
                 *  SecretId = Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_ID"),
                 *  SecretKey = Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_KEY")
                 * };*/

                /* 非必要步骤:
                 * 实例化一个客户端配置对象,可以指定超时时间等配置 */
                ClientProfile clientProfile = new ClientProfile();

                /* SDK默认用TC3-HMAC-SHA256进行签名
                 * 非必要请不要修改这个字段 */
                clientProfile.SignMethod = ClientProfile.SIGN_TC3SHA256;

                /* 非必要步骤
                 * 实例化一个客户端配置对象,可以指定超时时间等配置 */
                HttpProfile httpProfile = new HttpProfile();

                /* SDK默认使用POST方法。
                 * 如果你一定要使用GET方法,可以在这里设置。GET方法无法处理一些较大的请求 */
                httpProfile.ReqMethod = "GET";

                /* SDK有默认的超时时间,非必要请不要进行调整
                * 如有需要请在代码中查阅以获取最新的默认值 */
                httpProfile.Timeout = 10; // 请求连接超时时间,单位为秒(默认60秒)

                /* SDK会自动指定域名。通常是不需要特地指定域名的,但是如果你访问的是金融区的服务
                 * 则必须手动指定域名,例如sms的上海金融区域名: sms.ap-shanghai-fsi.tencentcloudapi.com */
                httpProfile.Endpoint = "sms.tencentcloudapi.com";
                // 代理服务器,当你的环境下有代理服务器时设定
                httpProfile.WebProxy = Environment.GetEnvironmentVariable("HTTPS_PROXY");

                clientProfile.HttpProfile = httpProfile;

                /* 实例化要请求产品(以sms为例)的client对象
                 * 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,或者引用预设的常量 */
                SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);

                /* 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
                 * 你可以直接查询SDK源码确定SendSmsRequest有哪些属性可以设置
                 * 属性可能是基本类型,也可能引用了另一个数据结构
                 * 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明 */
                SendSmsRequest req = new SendSmsRequest();

                /* 基本类型的设置:
                 * SDK采用的是指针风格指定参数,即使对于基本类型你也需要用指针来对参数赋值。
                 * SDK提供对基本类型的指针引用封装函数
                 * 帮助链接:
                 * 短信控制台: https://console.cloud.tencent.com/sms/smslist
                 * sms helper: https://cloud.tencent.com/document/product/382/3773 */

                req.SmsSdkAppid = "1400787878";
                /* 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名,签名信息可登录 [短信控制台] 查看 */
                req.Sign = "xxx";
                /* 短信码号扩展号: 默认未开通,如需开通请联系 [sms helper] */
                req.ExtendCode = "x";
                /* 国际/港澳台短信 senderid: 国内短信填空,默认未开通,如需开通请联系 [sms helper] */
                req.SenderId = "";
                /* 用户的 session 内容: 可以携带用户侧 ID 等上下文信息,server 会原样返回 */
                req.SessionContext = "";

                /* 下发手机号码,采用 e.164 标准,+[国家或地区码][手机号]
                 * 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号*/
                req.PhoneNumberSet = new String[] { "+8613711112222" };
                /* 模板 ID: 必须填写已审核通过的模板 ID。模板ID可登录 [短信控制台] 查看 */
                req.TemplateID = "449739";
                /* 模板参数: 若无模板参数,则设置为空*/
                req.TemplateParamSet = new String[] { "666" };


                // 通过client对象调用DescribeInstances方法发起请求。注意请求方法名与请求对象是对应的
                // 返回的resp是一个DescribeInstancesResponse类的实例,与请求对象对应
                SendSmsResponse resp = client.SendSmsSync(req);

                // 输出json格式的字符串回包
                Console.WriteLine(AbstractModel.ToJsonString(resp));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            Console.Read();
        }
Esempio n. 21
0
 public Task <HttpProfile> EditHttpProfile(HttpProfile profile, CovenantUser currentUser)
 {
     return(_connection.InvokeAsync <HttpProfile>("EditHttpProfile", profile, currentUser));
 }
Esempio n. 22
0
        private void search_button_Click(object sender, EventArgs e)
        //搜索功能
        {
            //更改界面状态
            file_slide.Visible     = false;
            panelResult.Visible    = true;
            map_webbrowser.Visible = false;
            treeView1.Nodes.Clear();

            //进度显示
            textBoxHint.Visible = true;
            textBoxHint.Text    = "加载中...";
            textBoxHint.Refresh();

            //nlp分析器创建
            ClientProfile clientProfile = new ClientProfile();
            HttpProfile   httpProfile   = new HttpProfile();

            httpProfile.Endpoint      = ("nlp.tencentcloudapi.com");
            clientProfile.HttpProfile = httpProfile;
            NlpClient            client = new NlpClient(cred, "ap-guangzhou", clientProfile);
            SimilarWordsRequest  req;
            SimilarWordsResponse resp;

            string[] seperator = { " ", ",", ";" };
            string[] keywords  = bunifuMaterialTextbox1.Text.Split(seperator, 15, StringSplitOptions.RemoveEmptyEntries);
            string   regexp    = "";

            for (int i = 0; i < keywords.Length; i++)
            {
                try
                {
                    textBoxHint.Text = String.Format("检索第{0}个关键词,共{1}个", i + 1, keywords.Length);
                    textBoxHint.Refresh();
                    req = new SimilarWordsRequest();
                    string strParams = "{\"Text\":\"" + keywords[i] + "\",\"WordNumber\":20}";
                    req  = SimilarWordsRequest.FromJsonString <SimilarWordsRequest>(strParams);
                    resp = client.SimilarWordsSync(req);
                    if (i > 0)
                    {
                        regexp += "|";
                    }
                    regexp += keywords[i] + "|" + string.Join("|", resp.SimilarWords);
                }
                catch (Exception error)
                {
                    MessageBox.Show(error.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            string query = "select poiid, title, public_grading from public_grading " +
                           "where poiid in " +
                           "(SELECT poiid FROM poi.pois_features where keywords regexp '" +
                           regexp +
                           "') order by public_grading desc";

            textBoxHint.Text = "加载查询中...";
            textBoxHint.Refresh();
            SelectinGeneral(query);
            textBoxHint.Text = String.Format("查询得到{0}个地点", progressBar1.Maximum);
            textBoxHint.Refresh();
        }