コード例 #1
0
        /// <summary>
        /// 处理视频请求
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override async Task <IResponseMessageBase> OnVideoRequestAsync(RequestMessageVideo requestMessage)
        {
            var responseMessage = CreateResponseMessage <ResponseMessageText>();

            responseMessage.Content = "您发送了一条视频信息,ID:" + requestMessage.MediaId;

            #region    材并推送到客户端

            Task.Factory.StartNew(async() =>
            {
                //上传素材
                var dir          = ServerUtility.ContentRootMapPath("~/App_Data/TempVideo/");
                var file         = await MediaApi.GetAsync(appId, requestMessage.MediaId, dir);
                var uploadResult = await MediaApi.UploadTemporaryMediaAsync(appId, UploadMediaFileType.video, file, 50000);
                await CustomApi.SendVideoAsync(appId, base.WeixinOpenId, uploadResult.media_id, "这是您刚才发送的视频", "这是一条视频消息");
            }).ContinueWith(async task =>
            {
                if (task.Exception != null)
                {
                    WeixinTrace.Log("OnVideoRequest()储存Video过程发生错误:", task.Exception.Message);

                    var msg = string.Format("上传素材出错:{0}\r\n{1}",
                                            task.Exception.Message,
                                            task.Exception.InnerException != null
                                    ? task.Exception.InnerException.Message
                                    : null);
                    await CustomApi.SendTextAsync(appId, base.WeixinOpenId, msg);
                }
            });

            #endregion

            return(responseMessage);
        }
コード例 #2
0
        public ActionResult Post(PostModel postModel)
        {
            var maxRecordCount = 10;

            postModel.Token          = Token;
            postModel.EncodingAESKey = EncodingAESKey;
            postModel.CorpId         = CorpId;


            #region 用于生产环境测试原始数据
            //var ms = new MemoryStream();
            //Request.InputStream.CopyTo(ms);
            //ms.Seek(0, SeekOrigin.Begin);

            //var sr = new StreamReader(ms);
            //var xml = sr.ReadToEnd();
            //var doc = XDocument.Parse(xml);
            //doc.Save(ServerUtility.ContentRootMapPath("~/App_Data/TestWork.log"));
            //return null;
            #endregion

            //自定义MessageHandler,对微信请求的详细判断操作都在这里面。
            var messageHandler = new WorkCustomMessageHandler(Request.GetRequestMemoryStream(), postModel, maxRecordCount);

            if (messageHandler.RequestMessage == null)
            {
                //验证不通过或接受信息有错误
            }

            try
            {
                //测试时可开启此记录,帮助跟踪数据,使用前请确保App_Data文件夹存在,且有读写权限。
                messageHandler.SaveRequestMessageLog();  //记录 Request 日志(可选)

                messageHandler.Execute();                //执行微信处理过程(关键)

                messageHandler.SaveResponseMessageLog(); //记录 Response 日志(可选)

                //自动返回加密后结果
                return(new FixWeixinBugWeixinResult(messageHandler));//为了解决官方微信5.0软件换行bug暂时添加的方法,平时用下面一个方法即可
            }
            catch (Exception ex)
            {
                using (TextWriter tw = new StreamWriter(ServerUtility.ContentRootMapPath("~/App_Data/Work_Error_" + SystemTime.Now.Ticks + ".txt")))
                {
                    tw.WriteLine("ExecptionMessage:" + ex.Message);
                    tw.WriteLine(ex.Source);
                    tw.WriteLine(ex.StackTrace);
                    //tw.WriteLine("InnerExecptionMessage:" + ex.InnerException.Message);

                    if (messageHandler.FinalResponseDocument != null && messageHandler.FinalResponseDocument.Root != null)
                    {
                        tw.WriteLine(messageHandler.FinalResponseDocument.ToString());
                    }
                    tw.Flush();
                    tw.Close();
                }
                return(Content(""));
            }
        }
コード例 #3
0
        /// <summary>
        /// 处理语音请求
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override async Task <IResponseMessageBase> OnVoiceRequestAsync(RequestMessageVoice requestMessage)
        {
            var responseMessage = CreateResponseMessage <ResponseMessageMusic>();
            //上传缩略图
            //var accessToken = Containers.AccessTokenContainer.TryGetAccessToken(appId, appSecret);
            var uploadResult = AdvancedAPIs.MediaApi.UploadTemporaryMedia(appId, UploadMediaFileType.image,
                                                                          ServerUtility.ContentRootMapPath("~/Images/Logo.jpg"));

            //设置音乐信息
            responseMessage.Music.Title        = "天籁之音";
            responseMessage.Music.Description  = "播放您上传的语音";
            responseMessage.Music.MusicUrl     = "https://sdk.weixin.senparc.com/Media/GetVoice?mediaId=" + requestMessage.MediaId;
            responseMessage.Music.HQMusicUrl   = "https://sdk.weixin.senparc.com/Media/GetVoice?mediaId=" + requestMessage.MediaId;
            responseMessage.Music.ThumbMediaId = uploadResult.media_id;

            //推送一条客服消息
            try
            {
                CustomApi.SendText(appId, OpenId, "本次上传的音频MediaId:" + requestMessage.MediaId);
            }
            catch
            {
            }

            return(responseMessage);
        }
コード例 #4
0
        public static string GetOpenTicket(string componentAppId)
        {
            //实际开发过程不一定要用文件记录,也可以用数据库。
            var    openTicketPath = ServerUtility.ContentRootMapPath("~/App_Data/OpenTicket");
            string openTicket     = null;
            var    filePath       = Path.Combine(openTicketPath, string.Format("{0}.txt", componentAppId));

            if (File.Exists(filePath))
            {
                using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    using (TextReader tr = new StreamReader(fs))
                    {
                        openTicket = tr.ReadToEnd();
                    }
                }
            }
            else
            {
                throw new WeixinException("OpenTicket不存在!");
            }

            //其他逻辑

            return(openTicket);
        }
コード例 #5
0
        public ActionResult TestUploadMediaFile(string token, UploadMediaFileType type, int contentLength /*, HttpPostedFileBase postedFile*/)
        {
            var inputStream = Request.Body;

            if (contentLength != inputStream.Length)
            {
                return(Content("ContentLength不正确,可能接收错误!"));
            }

            if (token != "TOKEN")
            {
                return(Content("TOKEN不正确!"));
            }

            if (type != UploadMediaFileType.image)
            {
                return(Content("UploadMediaFileType不正确!"));
            }

            //储存文件,对比是否上传成功
            using (FileStream ms = new FileStream(ServerUtility.ContentRootMapPath("~/TestUploadMediaFile.jpg"), FileMode.OpenOrCreate))
            {
                inputStream.CopyTo(ms, 256);
            }

            return(Content("{\"type\":\"image\",\"media_id\":\"MEDIA_ID\",\"created_at\":123456789}"));
        }
コード例 #6
0
        /// <summary>
        /// 微信MessageHandler事件处理,此代码的简化MessageHandler方法已由/CustomerMessageHandler/CustomerMessageHandler_Event.cs完成,
        /// 此方法不再更新
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public ResponseMessageBase GetResponseMessage(RequestMessageEventBase requestMessage)
        {
            ResponseMessageBase responseMessage = null;

            switch (requestMessage.Event)
            {
            case Event.ENTER:
            {
                var strongResponseMessage = requestMessage.CreateResponseMessage <ResponseMessageText>();
                strongResponseMessage.Content = "您刚才发送了ENTER事件请求。";
                responseMessage = strongResponseMessage;
                break;
            }

            case Event.LOCATION:
                throw new Exception("暂不可用");

            //break;
            case Event.subscribe:    //订阅
            {
                var strongResponseMessage = requestMessage.CreateResponseMessage <ResponseMessageText>();

                //获取Senparc.Weixin.MP.dll版本信息
#if NET45
                var dllPath = HttpContext.Current.Server.MapPath("~/bin/Senparc.Weixin.MP.dll");
#else
                //var dllPath = ServerUtility.ContentRootMapPath("~/bin/Release/netcoreapp2.2/Senparc.Weixin.MP.dll");//本地测试路径
                var dllPath = ServerUtility.ContentRootMapPath("~/Senparc.Weixin.MP.dll");        //发布路径
#endif

                var fileVersionInfo = FileVersionInfo.GetVersionInfo(dllPath);

                var version = fileVersionInfo.FileVersion;
                strongResponseMessage.Content = string.Format(
                    "欢迎关注【Senparc.Weixin.MP 微信公众平台SDK】,当前运行版本:v{0}。\r\n您还可以发送【位置】【图片】【语音】信息,查看不同格式的回复。\r\nSDK官方地址:https://sdk.weixin.senparc.com",
                    version);
                responseMessage = strongResponseMessage;
                break;
            }

            case Event.unsubscribe:    //退订
            {
                //实际上用户无法收到非订阅账号的消息,所以这里可以随便写。
                //unsubscribe事件的意义在于及时删除网站应用中已经记录的OpenID绑定,消除冗余数据。
                var strongResponseMessage = requestMessage.CreateResponseMessage <ResponseMessageText>();
                strongResponseMessage.Content = "有空再来";
                responseMessage = strongResponseMessage;
                break;
            }

            case Event.CLICK:    //菜单点击事件,根据自己需要修改
                //这里的CLICK在此DEMO中不会被执行到,因为已经重写了OnEvent_ClickRequest
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            return(responseMessage);
        }
コード例 #7
0
        public ActionResult PayNotifyUrl()
        {
            try
            {
                ResponseHandler resHandler = new ResponseHandler(HttpContext);

                string return_code = resHandler.GetParameter("return_code");
                string return_msg  = resHandler.GetParameter("return_msg");

                string res = null;

                resHandler.SetKey(TenPyConfigRead.Key);
                //验证请求是否从微信发过来(安全)
                if (resHandler.IsTenpaySign() && return_code.ToUpper() == "SUCCESS")
                {
                    res = "success";//正确的订单处理
                    //直到这里,才能认为交易真正成功了,可以进行数据库操作,但是别忘了返回规定格式的消息!
                }
                else
                {
                    res = "wrong";//错误的订单处理
                }



                #region 记录日志

                var logDir = ServerUtility.ContentRootMapPath(string.Format("~/App_Data/TenPayNotify/{0}", SystemTime.Now.ToString("yyyyMMdd")));
                if (!Directory.Exists(logDir))
                {
                    Directory.CreateDirectory(logDir);
                }

                var logPath = Path.Combine(logDir, string.Format("{0}-{1}-{2}.txt", SystemTime.Now.ToString("yyyyMMdd"), SystemTime.Now.ToString("HHmmss"), Guid.NewGuid().ToString("n").Substring(0, 8)));

                using (var fileStream = System.IO.File.OpenWrite(logPath))
                {
                    var notifyXml = resHandler.ParseXML();
                    //fileStream.Write(Encoding.Default.GetBytes(res), 0, Encoding.Default.GetByteCount(res));

                    fileStream.Write(Encoding.Default.GetBytes(notifyXml), 0, Encoding.Default.GetByteCount(notifyXml));
                    fileStream.Close();
                }

                #endregion


                string xml = string.Format(@"<xml>
<return_code><![CDATA[{0}]]></return_code>
<return_msg><![CDATA[{1}]]></return_msg>
</xml>", return_code, return_msg);
                return(Content(xml, "text/xml"));
            }
            catch (Exception ex)
            {
                WeixinTrace.WeixinExceptionLog(new WeixinException(ex.Message, ex));
                throw;
            }
        }
コード例 #8
0
        public void ContentRootMapPathTest()
        {
            var path   = "~/App_Data/log.log";
            var result = ServerUtility.ContentRootMapPath(path);

            Console.WriteLine(result);
            Assert.IsTrue(result.EndsWith(@"src\Senparc.CO2NET.Tests\App_Data\log.log"));
        }
コード例 #9
0
        public async Task <ActionResult <bool> > PostUserDataAsync(UserData userData)
        {
            userData.IpAddress = ServerUtility.GetIpAddress(Request, HttpContext);

            bool success = await ygApi.PostUserDataAsync(userData);

            return(Ok(success));
        }
コード例 #10
0
        public void DllMapPathTest()
        {
            var path   = "~/App_Data/log.log";
            var result = ServerUtility.DllMapPath(path);

            Console.WriteLine(result);
            Assert.IsTrue(result.EndsWith(@"\bin\Test\netcoreapp2.1\App_Data\log.log"));
        }
コード例 #11
0
        private string GetWelcomeInfo()
        {
            //获取Senparc.Weixin.MP.dll版本信息
            var filePath        = ServerUtility.ContentRootMapPath("~/Senparc.Weixin.MP.dll");//发布路径
            var fileVersionInfo = FileVersionInfo.GetVersionInfo(filePath);

            string version = fileVersionInfo == null
                ? "-"
                : string.Format("{0}.{1}.{2}", fileVersionInfo.FileMajorPart, fileVersionInfo.FileMinorPart, fileVersionInfo.FileBuildPart);

            return(string.Format(
                       @"欢迎关注【Senparc.Weixin 微信公众平台SDK】,当前运行版本:v{0}。
您可以发送【文字】【位置】【图片】【语音】【文件】等不同类型的信息,查看不同格式的回复。

您也可以直接点击菜单查看各种类型的回复。
还可以点击菜单体验微信支付。

SDK官方地址:https://weixin.senparc.com
SDK Demo:https://sdk.weixin.senparc.com
源代码及Demo下载地址:https://github.com/JeffreySu/WeiXinMPSDK
Nuget地址:https://www.nuget.org/packages/Senparc.Weixin.MP
QQ群:289181996

===============
更多:

1、JSSDK测试:https://sdk.weixin.senparc.com/WeixinJSSDK

2、开放平台测试(建议PC上打开):https://sdk.weixin.senparc.com/OpenOAuth/JumpToMpOAuth

3、回复关键字:

【open】   进入第三方开放平台(Senparc.Weixin.Open)测试

【tm】     测试异步模板消息

【openid】 获取OpenId等用户信息

【约束】   测试微信浏览器约束

【AsyncTest】 异步并发测试

【错误】    体验发生错误无法返回正确信息

【容错】    体验去重容错

【ex】      体验错误日志推送提醒

【mute】     不返回任何消息,也无出错信息

【jssdk】    测试JSSDK图文转发接口

格式:【数字#数字】,如2010#0102,调用正则表达式匹配

【订阅】     测试“一次性订阅消息”接口
",
                       version));
        }
コード例 #12
0
        public async Task <ActionResult> PostHighscoreAsync([FromBody] string alias)
        {
            int?submittedHighscore = HttpContext.Session.GetInt32(Constants.SESSION_SUBMITTED_TO_HIGHSCORES_KEY);
            var responseMessage    = new Dictionary <string, string>
            {
                { "errorMessage", "Something went wrong" }
            };

            if (submittedHighscore == 1)
            {
                responseMessage["errorMessage"] = "Highscore have already been submitted";
                return(BadRequest(responseMessage));
            }

            bool result = alias.All(Char.IsLetterOrDigit);

            if (!result)
            {
                responseMessage["errorMessage"] = "Alias contains non alphanumeric values";
                return(BadRequest(responseMessage));
            }

            if (alias == null || alias == String.Empty)
            {
                responseMessage["errorMessage"] = "You have to write an alias";
                return(BadRequest(responseMessage));
            }

            bool isProfanity = await ygApi.IsAliasProfanityAsync(alias);

            if (isProfanity)
            {
                responseMessage["errorMessage"] = "Alias contains profanity";
                return(BadRequest(responseMessage));
            }

            int?guessesCorrect = HttpContext.Session.GetInt32(Constants.SESSION_CORRECT_GUESSES_KEY);

            if (guessesCorrect == null)
            {
                guessesCorrect = 0;
            }

            string ip       = ServerUtility.GetIpAddress(Request, HttpContext);
            string location = await ygApi.GetLocationByIpAsync(ip);

            Highscore highscoreEntry = new Highscore(alias, (int)guessesCorrect, location);

            bool highscorePosted = await ygApi.PostHighscoreAsync(highscoreEntry);

            if (highscorePosted)
            {
                HttpContext.Session.SetInt32(Constants.SESSION_SUBMITTED_TO_HIGHSCORES_KEY, 1);
            }
            return(Ok(highscorePosted));
        }
コード例 #13
0
        public ActionResult Notice(PostModel postModel)
        {
            var logPath = ServerUtility.ContentRootMapPath(string.Format("~/App_Data/Open/{0}/", SystemTime.Now.ToString("yyyy-MM-dd")));

            if (!Directory.Exists(logPath))
            {
                Directory.CreateDirectory(logPath);
            }

            //using (TextWriter tw = new StreamWriter(Path.Combine(logPath, string.Format("{0}_RequestStream.txt", SystemTime.Now.Ticks))))
            //{
            //    using (var sr = new StreamReader(Request.InputStream))
            //    {
            //        tw.WriteLine(sr.ReadToEnd());
            //        tw.Flush();
            //    }
            //}

            //Request.InputStream.Seek(0, SeekOrigin.Begin);

            try
            {
                postModel.Token          = component_Token;
                postModel.EncodingAESKey = component_EncodingAESKey; //根据自己后台的设置保持一致
                postModel.AppId          = component_AppId;          //根据自己后台的设置保持一致



                var messageHandler = new CustomThirdPartyMessageHandler(Request.GetRequestMemoryStream(), postModel);//初始化
                //注意:在进行“全网发布”时使用上面的CustomThirdPartyMessageHandler,发布完成之后使用正常的自定义的MessageHandler,例如下面一行。
                //var messageHandler = new CommonService.CustomMessageHandler.CustomMessageHandler(Request.GetRequestMemoryStream(),
                //    postModel, 10);

                //记录RequestMessage日志(可选)
                //messageHandler.EcryptRequestDocument.Save(Path.Combine(logPath, string.Format("{0}_Request.txt", SystemTime.Now.Ticks)));
                messageHandler.RequestDocument.Save(Path.Combine(logPath, string.Format("{0}_Request_{1}.txt", SystemTime.Now.Ticks, messageHandler.RequestMessage.AppId)));

                messageHandler.Execute();//执行

                //记录ResponseMessage日志(可选)
                using (TextWriter tw = new StreamWriter(Path.Combine(logPath, string.Format("{0}_Response_{1}.txt", SystemTime.Now.Ticks, messageHandler.RequestMessage.AppId))))
                {
                    tw.WriteLine(messageHandler.ResponseMessageText);
                    tw.Flush();
                    tw.Close();
                }

                return(Content(messageHandler.ResponseMessageText));
            }
            catch (Exception ex)
            {
                throw;
                return(Content("error:" + ex.Message));
            }
        }
コード例 #14
0
        /// <summary>
        /// 获取日志保存地址
        /// </summary>
        /// <returns></returns>
        public string GetLogPath()
        {
            var logPath = ServerUtility.ContentRootMapPath($"~/App_Data/{this.MessageEntityEnlightener?.PlatformType.ToString()}/{ SystemTime.Now.ToString("yyyy-MM-dd")}/");

            if (!Directory.Exists(logPath))
            {
                Directory.CreateDirectory(logPath);
            }

            return(logPath);
        }
コード例 #15
0
        public FilesystemInfo GetFilesystemInfo(string path)
        {
            Platform.CheckForEmptyString(path, "requested path is empty or null");

            if (Context.Request.UserLanguages != null && Context.Request.UserLanguages.Length > 0)
            {
                CultureInfo culture = new CultureInfo(Context.Request.UserLanguages[0]);
                Thread.CurrentThread.CurrentCulture   = culture;
                Thread.CurrentThread.CurrentUICulture = culture;
            }
            return(ServerUtility.GetFilesystemInfo(path.Trim()));
        }
コード例 #16
0
        public AuthMechanismProcessorStatus ProcessResponse(string data)
        {
            if (data != null)
            {
                State = States.WaitingForUsername;
            }

            switch (State)
            {
            case States.Initial:
                Connection.WriteResponse(new SmtpResponse(StandardSmtpResponseCode.AuthenticationContinue,
                                                          Convert.ToBase64String(
                                                              Encoding.ASCII.GetBytes("Username:"******"Password:"))));
                State = States.WaitingForPassword;
                return(AuthMechanismProcessorStatus.Continue);

            case States.WaitingForPassword:
                string password = ServerUtility.DecodeBase64(data);
                State = States.Completed;

                Credentials = new LoginAuthenticationCredentials(_username, password);

                AuthenticationResult result =
                    Connection.Server.Behaviour.ValidateAuthenticationCredentials(Connection,
                                                                                  Credentials);

                switch (result)
                {
                case AuthenticationResult.Success:
                    return(AuthMechanismProcessorStatus.Success);

                    break;

                default:
                    return(AuthMechanismProcessorStatus.Failed);

                    break;
                }

            default:
                throw new NotImplementedException();
            }
        }
コード例 #17
0
        /// <summary>
        /// Process returns a copy of the media database, and can be used to return SQL deltas to update
        /// the local copy of the media database
        /// </summary>
        public void Process(UriWrapper uri, IHttpProcessor processor, User user)
        {
            // If ID set, return all queries >= this id
            if (uri.Id != null)
            {
                processor.WriteJson(new DatabaseResponse(null, Injection.Kernel.Get <IDatabase>().QueryLogsSinceId((int)uri.Id)));
                return;
            }

            // No id parameter, so send down the whole backup database
            long   databaseLastQueryId = -1;
            string databaseFileName    = DatabaseBackup.Backup(out databaseLastQueryId);

            // Verify database filename present
            if ((object)databaseFileName == null)
            {
                processor.WriteErrorHeader();
                return;
            }

            try
            {
                // Read in entire database file
                Stream stream      = new FileStream(ServerUtility.RootPath() + databaseFileName, FileMode.Open, FileAccess.Read);
                long   length      = stream.Length;
                int    startOffset = 0;

                // Handle the Range header to start from later in the file if connection interrupted
                if (processor.HttpHeaders.ContainsKey("Range"))
                {
                    string range = (string)processor.HttpHeaders["Range"];
                    string start = range.Split(new char[] { '-', '=' })[1];
                    logger.IfInfo("Connection retried.  Resuming from " + start);
                    startOffset = Convert.ToInt32(start);
                }

                // We send the last query id as a custom header
                IDictionary <string, string> customHeader = new Dictionary <string, string>();
                customHeader["WaveBox-LastQueryId"] = databaseLastQueryId.ToString();

                // Send the database file
                processor.WriteFile(stream, startOffset, length, "application/octet-stream", customHeader, true, new FileInfo(ServerUtility.RootPath() + databaseFileName).LastWriteTimeUtc);
                stream.Close();
            }
            catch
            {
                // Send JSON on error
                processor.WriteJson(new DatabaseResponse("Could not open backup database " + databaseFileName, null));
            }

            return;
        }
コード例 #18
0
 internal void SendMessage(string message, TcpClient client)
 {
     try {
         var encodedMessage = ServerUtility.EncodeMessageAsBytes(message);
         if (Verbose)
         {
             Logger.Info($"Sent [{ServerUtility.EncodeMessage(message)}] to client {Clients[client]}", "INFO-VERBOSE");
         }
         StreamUtil.Write(client.GetStream(), encodedMessage);
     } catch (IOException) {
         Logger.Warn($"Client {Clients[client]} disconnected!");
         faultyClients.Add(client);
     }
 }
コード例 #19
0
        public AuthMechanismProcessorStatus ProcessResponse(string data)
        {
            if (_challenge == null)
            {
                StringBuilder challenge = new StringBuilder();
                challenge.Append(_random.GenerateRandomInteger(0, Int16.MaxValue));
                challenge.Append(".");
                challenge.Append(_dateTimeProvider.GetCurrentDateTime().Ticks.ToString());
                challenge.Append("@");
                challenge.Append(Connection.Server.Behaviour.DomainName);
                _challenge = challenge.ToString();

                string base64Challenge = Convert.ToBase64String(Encoding.ASCII.GetBytes(challenge.ToString()));
                Connection.WriteResponse(new SmtpResponse(StandardSmtpResponseCode.AuthenticationContinue,
                                                          base64Challenge));
                return(AuthMechanismProcessorStatus.Continue);
            }
            else
            {
                string   response      = ServerUtility.DecodeBase64(data);
                string[] responseparts = response.Split(' ');

                if (responseparts.Length != 2)
                {
                    throw new SmtpServerException(new SmtpResponse(StandardSmtpResponseCode.AuthenticationFailure,
                                                                   "Response in incorrect format - should be USERNAME RESPONSE"));
                }

                string username = responseparts[0];
                string hash     = responseparts[1];

                Credentials = new CramMd5AuthenticationCredentials(username, _challenge, hash);

                AuthenticationResult result =
                    Connection.Server.Behaviour.ValidateAuthenticationCredentials(Connection, Credentials);

                switch (result)
                {
                case AuthenticationResult.Success:
                    return(AuthMechanismProcessorStatus.Success);

                    break;

                default:
                    return(AuthMechanismProcessorStatus.Failed);

                    break;
                }
            }
        }
コード例 #20
0
ファイル: ConfigHelper.cs プロジェクト: ofood/WeChat
        public string Download(string version, bool isWebVersion)
        {
            lock (Lock)
            {
                var config = GetConfig();
                config.DownloadCount++;
                Save(config);
            }

            //打包下载文件
            //FileStream fs = new FileStream(_context.ServerUtility.ContentRootMapPath(string.Format("~/App_Data/Document/Files/Senparc.Weixin-v{0}.rar", version)), FileMode.Open);
            //return fs;

            return(ServerUtility.ContentRootMapPath(string.Format("~/App_Data/Document/Files/Senparc.Weixin{0}-v{1}.rar", isWebVersion ? "-Web" : "", version)));
        }
コード例 #21
0
ファイル: EntryPoint.cs プロジェクト: Roker2/Reloaded-II
        /* Initialize Mod Loader (DLL_PROCESS_ATTACH) */

        /// <summary>
        /// Initializes the mod loader.
        /// Returns the port on the local machine (but that wouldn't probably be used).
        /// </summary>
        public static int Initialize(IntPtr unusedPtr, int unusedSize)
        {
            // Setup Loader
            SetupLoader();

            // Write port as a Memory Mapped File, to allow Mod Loader's Launcher to discover the mod port.
            int pid = Process.GetCurrentProcess().Id;

            _memoryMappedFile = MemoryMappedFile.CreateOrOpen(ServerUtility.GetMappedFileNameForPid(pid), sizeof(int));
            var view         = _memoryMappedFile.CreateViewStream();
            var binaryWriter = new BinaryWriter(view);

            binaryWriter.Write(_server.Port);

            return(_server?.Port ?? 0);
        }
コード例 #22
0
        /// <summary>
        /// 日志记录
        /// </summary>
        /// <param name="msg"></param>
        private static void Log(string msg)
        {
            var logDir = ServerUtility.ContentRootMapPath($"~/App_Data/PayNotifyUrl/{SystemTime.Now:yyyyMMdd}");

            if (!Directory.Exists(logDir))
            {
                Directory.CreateDirectory(logDir);
            }
            var logPath = Path.Combine(logDir, $"{SystemTime.Now:yyyyMMdd}-{SystemTime.Now:HHmmss}-{Guid.NewGuid().ToString("n").Substring(0, 8)}.txt");

            using (var fileStream = System.IO.File.OpenWrite(logPath))
            {
                fileStream.Write(Encoding.Default.GetBytes(msg), 0, Encoding.Default.GetByteCount(msg));
                fileStream.Close();
            }
        }
コード例 #23
0
 private void EmitMessage(string message, bool skipEncoding = false)
 {
     try {
         var outBytes = ServerUtility.EncodeMessageAsBytes(message, skipEncoding);
         lastHeartbeatTime = DateTime.Now;
         if (verbose)
         {
             Debug.Log($"Sent message: {ServerUtility.EncodeMessage(message, skipEncoding)}");
         }
         StreamUtil.Write(client.GetStream(), outBytes);
     } catch (Exception e) {
         panelWrapper.AddOutput(e.Message);
         //for quicker testing, we reconnect if something goes wrong.
         client.Close();
         ConnectToServer();
     }
 }
コード例 #24
0
        public AuthMechanismProcessorStatus ProcessResponse(string data)
        {
            if (string.IsNullOrEmpty(data))
            {
                if (State == States.AwaitingResponse)
                {
                    throw new SmtpServerException(new SmtpResponse(StandardSmtpResponseCode.AuthenticationFailure,
                                                                   "Missing auth data"));
                }

                Connection.WriteResponse(new SmtpResponse(StandardSmtpResponseCode.AuthenticationContinue, ""));
                State = States.AwaitingResponse;
                return(AuthMechanismProcessorStatus.Continue);
            }

            string decodedData = ServerUtility.DecodeBase64(data);

            string[] decodedDataParts = decodedData.Split('\0');

            if (decodedDataParts.Length != 3)
            {
                throw new SmtpServerException(new SmtpResponse(StandardSmtpResponseCode.AuthenticationFailure,
                                                               "Auth data in incorrect format"));
            }

            string username = decodedDataParts[1];
            string password = decodedDataParts[2];

            Credentials = new PlainAuthenticationCredentials(username, password);

            AuthenticationResult result =
                Connection.Server.Behaviour.ValidateAuthenticationCredentials(Connection, Credentials);

            switch (result)
            {
            case AuthenticationResult.Success:
                return(AuthMechanismProcessorStatus.Success);

                break;

            default:
                return(AuthMechanismProcessorStatus.Failed);

                break;
            }
        }
コード例 #25
0
        private void ParseBarcodeCommandResponse(string barcode, int counts)
        {
            List <string> cfgLines;

            switch (counts)
            {
            case 1:
                Logger.Info("Get new CFG");

                cfgLines = ServerUtility.GetCfg(_config.ServerUrl, barcode);
                if (cfgLines == null)
                {
                    return;
                }

                ApplyNewCfg(cfgLines);

                _status.LastBarcode = barcode;

                break;

            case 2:
                Logger.Info("Save CFG");

                if (barcode != _status.LastBarcode)
                {
                    Logger.Warn("CFG not saved for different barcode");
                    return;
                }

                cfgLines = GameUtility.DumpCfg();
                if (cfgLines == null)
                {
                    return;
                }

                ServerUtility.SaveCfg(_config.ServerUrl, barcode, cfgLines);

                break;

            default:
                return;
            }
        }
コード例 #26
0
ファイル: LogController.cs プロジェクト: wagnerhsu/oss-SCF
        public ActionResult WebLogList([DefaultValue(1)] int pageIndex)
        {
            int    pageCount  = 31;
            int    skipRecord = Senparc.Scf.Core.Utility.Extensions.GetSkipRecord(pageIndex, pageCount);
            string logFileDir = ServerUtility.ContentRootMapPath("~/App_Data/Log/");
            var    dateDirs   = Directory.GetDirectories(logFileDir, "Logs_*", SearchOption.TopDirectoryOnly);

            Log_WebLogListVD vd = new Log_WebLogListVD()
            {
                DateList = new PagedList <string>(
                    dateDirs.OrderByDescending(z => z)
                    .Select(z => Path.GetFileName(z).Split('_')[1])
                    .Skip(skipRecord)
                    .Take(pageCount).ToList(),
                    pageIndex, pageCount, dateDirs.Length, skipRecord)
            };

            return(View(vd));
        }
コード例 #27
0
        private void InitConfig()
        {
            Logger.Info("Initializing configuration");

            if (_config.GameExe == "")
            {
                Logger.Debug("Getting default game exe path");
                _config.GameExe = GameUtility.DefaultGameExe();
            }

            if (_config.ToolCfg == "")
            {
                Logger.Debug("Getting default tool cfg path");
                _config.ToolCfg = GameUtility.DefaultToolCfg();
            }

            if (_config.ProfileName == "")
            {
                Logger.Debug("Getting default profile name");
                _config.ProfileName = GameUtility.DefaultProfileName();
            }

            if (_config.ProfileCfg == "")
            {
                Logger.Debug("Getting default profile cfg path");
                _config.ProfileCfg = GameUtility.DefaultProfileCfg();
            }

            if (_config.ServerUrl == "")
            {
                Logger.Debug("Getting default server url");
                _config.ServerUrl = ServerUtility.DefaultServerUrl();
            }

            if (_config.SerialPort == "")
            {
                Logger.Debug("Getting default serial port");
                var portNames = SerialPort.GetPortNames();
                var portName  = portNames.Length > 0 ? portNames[0] : "";
                _config.SerialPort = portName;
            }
        }
コード例 #28
0
ファイル: GroupMessageTest.cs プロジェクト: huning1990/123
        public VideoMediaIdResult GetVideoMediaIdResultTest()
        {
            var videoFilePath = ServerUtility.ContentRootMapPath("video-test.mp4");

            Console.WriteLine("Video Path:" + videoFilePath);

            //上传视频
            var uploadResult = MediaApi.UploadTemporaryMedia(_appId, UploadMediaFileType.video, videoFilePath);

            Console.WriteLine("Video Upload Result:" + uploadResult);

            string mediaId = uploadResult.media_id;//也可以通过对公众号发送视频获得

            var result = GroupMessageApi.GetVideoMediaIdResult(_appId, mediaId, "test", "test");

            Assert.IsNotNull(result);
            Console.WriteLine("GetVideoMediaIdResult" + result.ToJson());
            Assert.IsNotNull(result.media_id);
            Assert.IsTrue(result.media_id.Length > 0);
            return(result);
        }
コード例 #29
0
ファイル: EntryPoint.cs プロジェクト: hixio-mh/Reloaded-II
        /* Initialize Mod Loader (DLL_PROCESS_ATTACH) */

        /// <summary>
        /// Initializes the mod loader.
        /// Returns the port on the local machine (but that wouldn't probably be used).
        /// </summary>
        public static int Initialize(IntPtr unusedPtr, int unusedSize)
        {
            // Write port as a Memory Mapped File, to allow Mod Loader's Launcher to discover the mod port.
            // (And to stop bootstrapper from loading loader again).
            int pid = Process.GetCurrentProcess().Id;

            _memoryMappedFile = MemoryMappedFile.CreateOrOpen(ServerUtility.GetMappedFileNameForPid(pid), sizeof(int));
            var view         = _memoryMappedFile.CreateViewStream();
            var binaryWriter = new BinaryWriter(view);

            binaryWriter.Write((int)0);

            // Setup Loader
            SetupLoader();

            // Only write port on completed initialization.
            // If port is 0, assume in loading state
            binaryWriter.Seek(-sizeof(int), SeekOrigin.Current);
            binaryWriter.Write(_server.Port);
            return(_server?.Port ?? 0);
        }
コード例 #30
0
        /// <summary>
        /// Publish ZeroConf, so that WaveBox may advertise itself using mDNS to capable devices
        /// </summary>
        public bool Start()
        {
            string serverUrl = ServerUtility.GetServerUrl();

            if ((object)serverUrl == null)
            {
                logger.Error("Could not start ZeroConf service, due to null ServerUrl");
                return(false);
            }

            // If we're already registered, dispose of it and create a new one
            if ((object)ZeroConf != null)
            {
                this.Stop();
            }

            // Create and register the service
            try
            {
                ZeroConf             = new RegisterService();
                ZeroConf.Name        = Hostname;
                ZeroConf.RegType     = RegType;
                ZeroConf.ReplyDomain = ReplyDomain;
                ZeroConf.Port        = (short)Injection.Kernel.Get <IServerSettings>().Port;

                TxtRecord record = new TxtRecord();
                record.Add(ServerUrlKey, serverUrl);
                ZeroConf.TxtRecord = record;

                ZeroConf.Register();
            }
            catch (Exception e)
            {
                logger.Error(e);
                this.Stop();
                return(false);
            }

            return(true);
        }