예제 #1
0
파일: Song.cs 프로젝트: denghejun/music-app
        /// <summary>
        /// 根据频道和歌曲,得到歌曲列表
        /// </summary>
        /// <param name="channel"></param>
        /// <param name="song"></param>
        /// <param name="type">n-New</param>
        /// <returns></returns>
        public Models.SongList GetSongList(Models.Channel channel, Models.Song song, string type = "n")
        {
            Parameters parameters = new Parameters();
            parameters["from"] = "mainsite";
            parameters["context"] = channel.Context;
            parameters["sid"] = song != null ? song.SongID : null;
            parameters["channel"] = channel.ID.ToString();
            parameters["type"] = type;
            Random rnd = new Random();
            var number = rnd.NextDouble();
            parameters["r"] = number.ToString();

            string url = ConnectionBase.ConstructUrlWithParameters("http://douban.fm/j/mine/playlist", parameters);

            //获取列表
            string json = new ConnectionBase().Get(url, @"application/json, text/javascript, */*; q=0.01", @"http://douban.fm");
            var songList = Framework.Common.Helpers.JsonHelper.Deserialize<Models.SongList>(json);

            //将小图更换为大图
            foreach (var s in songList.Songs)
            {
                s.Picture = new Uri(s.Picture.ToString().Replace("/mpic/", "/lpic/").Replace("//otho.", "//img3."));
            }

            //去广告
            songList.Songs.RemoveAll(s => s.IsAd);

            return songList;
        }
예제 #2
0
 //判断是否有MV
 public bool CanFollowMV(string keyword)
 {
     Parameters parameters = new Parameters();
     parameters.Add("searchType", "mv");
     parameters.Add("keyword", keyword);
     string url = ConnectionBase.ConstructUrlWithParameters("http://www.yinyuetai.com/search/mv", parameters);
     string searchresult = new ConnectionBase().Get(url);
     if (string.IsNullOrEmpty(searchresult))
         return false;
     else
     {
         MatchCollection mc = Regex.Matches(searchresult, @"<div class=""noResult"">");
         if (mc.Count != 0)
         {
             return false;
         }
         else
         {
             MatchCollection mc1 = Regex.Matches(searchresult, @"<div class=""title mv_title"".*?</div>", RegexOptions.Singleline);
             if (mc1.Count == 0)
                 return false;
             else
             {
                 Match tmpmatch = Regex.Match(mc1[0].Groups[0].Value, @"href=""([^\""]+?)""");
                 mvUrl = @"http://www.yinyuetai.com/video/player/" + tmpmatch.Groups[1].Value.Substring(7) + @"/v_0.swf";
                 return true;
             }
         }
     }
 }
예제 #3
0
        private bool GetNewList(string type)
        {
            bool retSuccess = true;
            Song currentSong = currentQueue[currentSongIdx];
            string sidstr = (currentSongIdx == 0) ? string.Empty : currentSong.sid;
            Random random = new Random();
		    byte[] bytes = new byte[8];
            random.NextBytes(bytes);
            string r = (BitConverter.ToUInt64(bytes, 0) % 0xFFFFFFFFFF).ToString("x10");
            Parameters parameters = new Parameters();
            parameters.Add("type", type);
            parameters.Add("pb", "64");
            parameters.Add("sid", sidstr);
            parameters.Add("pt", currentSongPT.ToString());
            parameters.Add("channel", channelNo.ToString());
            parameters.Add("from", "mainsite");
            parameters.Add("r", r);
            string PostUrl = ConnectionBase.ConstructUrlWithParameters(@"http://douban.fm/j/mine/playlist", parameters);
            string SongJson = new ConnectionBase().Get(PostUrl);
            SongResult songresult = SongResult.FromJson(SongJson);
            if (type == "e")
                retSuccess = true;
            else if (songresult == null)
                retSuccess = false;
            else if (songresult != null && songresult.r != 0)
                retSuccess = false;
            else
            {
                if (songresult != null)
                {
                    if (songresult.song.Count == 0)
                        retSuccess = false;
                    else
                    {
                        if (type != "p")
                        {
                            currentQueue.Clear();
                            currentSongIdx = 0;
                        }
                        else
                        {
                            Song lastSong = currentQueue[currentQueue.Count - 1];
                            currentQueue.Clear();
                            currentSongIdx = 0;
                            currentQueue.Add(lastSong);
                        }
                        if (type == "r" || type == "u")
                            currentQueue.Add(currentSong);
                        
                        foreach (Song s in songresult.song)
                        {
                            if (s.subtype != "T")//剔除广告音频
                                currentQueue.Add(s);
                        }
                    }
                }
            }
            return retSuccess;
        }
예제 #4
0
 internal static Stream CreateTracingStream(ConnectionBase connection, Stream stream)
 {
     #if TRACE
       return new TracingStream(connection, stream);
     #else
       return stream;
     #endif
 }
예제 #5
0
 /// <summary>
 /// 得到验证码图片地址
 /// </summary>
 /// <param name="captchaID"></param>
 /// <returns></returns>
 public string GetCaptchaUri(out string captchaID)
 {
     captchaID = new ConnectionBase().Get("http://douban.fm/j/new_captcha");
     if (string.IsNullOrEmpty(captchaID)) return null;
     captchaID = captchaID.Replace("\"", "");
     var uri = string.Format("http://douban.fm/misc/captcha?size=m&id={0}", captchaID);
     return uri;
 }
예제 #6
0
 private static void LogSent(ConnectionBase connection, byte[] sent, int start, int count)
 {
     connection.traceSource.TraceData(TraceEventType.Verbose,
                                connection.Id,
                                new SendTraceData(new ArraySegment<byte>(sent, start, count),
                                                  connection.RemoteEndPoint,
                                                  connection.LocalEndPoint,
                                                  connection.Id));
 }
예제 #7
0
 /// <summary>
 /// 登录操作
 /// </summary>
 /// <param name="userName"></param>
 /// <param name="password"></param>
 /// <param name="captcha"></param>
 /// <param name="captchaID"></param>
 /// <param name="remember"></param>
 public Models.LoginResult Login(string userName, string password, string captcha, string captchaID, bool remember)
 {
     Parameters parameters = new Parameters();
     parameters["source"] = "radio";
     parameters["alias"] = userName;
     parameters["form_password"] = password;
     parameters["captcha_solution"] = captcha;
     parameters["captcha_id"] = captchaID;
     parameters["remember"] = "on";
     string json = new ConnectionBase().Post("http://douban.fm/j/login", Encoding.UTF8.GetBytes(parameters.ToString()));
     var result = Framework.Common.Helpers.JsonHelper.Deserialize<Models.LoginResult>(json);
     return result;
 }
예제 #8
0
        /// <summary>
        /// 从豆瓣获取歌词
        /// </summary>
        /// <param name="song">歌曲</param>
        /// <returns>歌词</returns>
        protected static Lyrics GetDoubanLyrics(Song song)
        {
            Parameters parameters = new Parameters();
            parameters["song_id"] = song.SongId;
            var url = ConnectionBase.ConstructUrlWithParameters("http://music.douban.com/api/song/info", parameters);
            var content = new ConnectionBase().Get(url);
            if (string.IsNullOrEmpty(content)) return null;

            var songInfo = Json.JsonHelper.FromJson<Json.SongInfo>(content);
            if (songInfo == null || string.IsNullOrEmpty(songInfo.Lyric)) return null;
            
            try
            {
                return new Lyrics(songInfo.Lyric);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                return null;
            }
        }
예제 #9
0
        public List<Models.SearchResult> RemoteSearch(string keywords, int pageIndex)
        {
            Parameters parameters = new Parameters();
            parameters["start"] = ((pageIndex - 1) * 15).ToString();
            parameters["search_text"] = keywords;
            string url = ConnectionBase.ConstructUrlWithParameters("http://music.douban.com/subject_search", parameters);

            ConnectionBase connection = new ConnectionBase(true);
            string file = string.Empty;
            try
            {
                file = connection.Get(url);
            }
            catch (Exception ex)
            {
                file = new ConnectionBase().Get("http://music.douban.com");
                file = new ConnectionBase().Get(url);
            }

            var searhResult = GetSearchItems(file);
            var previous = GetPreviousPageLink(file);
            var next = GetNextPageLink(file);
            return searhResult.ToList();
        }
예제 #10
0
 /// <summary>
 /// 使用邮箱登录
 /// </summary>
 /// <param name="email">邮箱</param>
 /// <param name="password">密码</param>
 /// <returns>登录结果</returns>
 private LogOnResult LogOnWithEmail(string email, string password)
 {
     Parameters parameters = new Parameters();
     parameters["app_name"] = "radio_desktop_win";
     parameters["version"] = "100";
     parameters["email"] = email;
     parameters["password"] = password;
     string file = new ConnectionBase().Post("http://www.douban.com/j/app/login",
                                             Encoding.UTF8.GetBytes(parameters.ToString()));
     return JsonHelper.FromJson<LogOnResult>(file);
 }
예제 #11
0
 public ClientPlayingState(ConnectionBase connection) : base(connection)
 {
 }
예제 #12
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="connection">The connection to operate through.</param>
 protected ConnectionAspectBase(ConnectionBase connection)
 {
     m_ctrl = connection.ControllerId;
 }
예제 #13
0
        GetCompletionResponse IProvider.GetCompletion(ConnectionBase connection, IDbTransaction transaction, string text, int position)
        {
            var response = new GetCompletionResponse();

            string[] items        = null;
            var      sqlStatement = new SqlParser(text);

            sqlStatement.FindToken(position, out var previousToken, out var currentToken);

            if (currentToken != null)
            {
                response.StartPosition = currentToken.StartPosition;
                response.Length        = currentToken.EndPosition - currentToken.StartPosition + 1;
            }
            else
            {
                response.StartPosition = position;
                response.Length        = 0;
            }

            var    sqlObject   = sqlStatement.FindSqlObject(previousToken, currentToken);
            string commandText = null;
            var    cs          = new OracleConnectionStringBuilder(connection.ConnectionString);
            var    userId      = cs.UserID;

            if (sqlObject != null)
            {
                string[] parts;
                string   owner;

                switch (sqlObject.Type)
                {
                case SqlObjectTypes.Table:
                    var oracleName = new OracleName(userId, sqlObject.Name);
                    commandText          = $@"select	TABLE_NAME
from	SYS.ALL_TABLES
where	OWNER	= '{oracleName.Owner}'	
order by TABLE_NAME";
                    sqlObject.ParentName = oracleName.Owner;
                    break;

                case SqlObjectTypes.Table | SqlObjectTypes.View | SqlObjectTypes.Function:
                    var name = sqlObject.Name;

                    if (name != null)
                    {
                        parts = name.Split('.');

                        if (parts.Length > 1)
                        {
                            owner = parts[0].ToUpper();
                            sqlObject.ParentName = owner;
                            name = parts[1];
                        }
                        else
                        {
                            owner = userId;
                            sqlObject.ParentName = owner;
                        }
                    }
                    else
                    {
                        owner = userId;
                        sqlObject.ParentName = owner;
                    }

                    commandText =
                        $@"select	OBJECT_NAME
from	SYS.ALL_OBJECTS
where	OWNER	= '{owner}'
	and OBJECT_TYPE in('TABLE','VIEW')
order by OBJECT_NAME";
                    sqlObject.Name = null;

                    break;

                case SqlObjectTypes.Column:
                    var parentName = sqlObject.ParentName;

                    if (parentName != null)
                    {
                        parts = parentName.Split('.');
                        string tableName;

                        if (parts.Length == 2)
                        {
                            owner     = parts[0].ToUpper();
                            tableName = parts[1].ToUpper();
                        }
                        else
                        {
                            owner                = userId;
                            tableName            = sqlObject.ParentName.ToUpper();
                            sqlObject.ParentName = owner + '.' + tableName;
                        }

                        commandText =
                            $@"select	COLUMN_NAME
from	SYS.ALL_TAB_COLUMNS
where	OWNER = '{owner}'
	and TABLE_NAME = '{tableName}'
order by COLUMN_ID";
                    }

                    break;

                case SqlObjectTypes.Function:
                    oracleName  = new OracleName(userId, sqlObject.ParentName);
                    commandText =
                        $@"select	OBJECT_NAME
from	SYS.ALL_OBJECTS
where	OWNER	= '{oracleName.Owner
                                }'
	and OBJECT_TYPE	= 'FUNCTION'
order by OBJECT_NAME";
                    sqlObject.ParentName = oracleName.Owner;
                    break;

                //case SqlObjectTypes.Procedure:
                //    oracleName = new OracleName( userId, sqlObject.Name );
                //    break;

                default:
                    break;
                }
            }

            if (commandText != null)
            {
                var sb = new StringBuilder();
                sb.Append(_objectExplorer.SchemasNode.Connection.DataSource);
                sb.Append('.');
                sb.Append(sqlObject.Type);
                sb.Append('.');
                var parentName = sqlObject.ParentName;

                if (parentName != null)
                {
                    sb.Append(parentName.ToUpper());
                }

                var name = sqlObject.Name;

                if (!string.IsNullOrEmpty(name))
                {
                    sb.Append('.');
                    sb.Append(name.ToUpper());
                }

                var key             = sb.ToString();
                var applicationData = DataCommanderApplication.Instance.ApplicationData;
                var folderName      = ConfigurationNodeName.FromType(typeof(OracleProvider)) + ConfigurationNode.Delimiter + "CompletionCache";
                var folder          = applicationData.CreateNode(folderName);
                var contains        = folder.Attributes.TryGetAttributeValue(key, out items);
                response.FromCache = contains;

                if (!contains)
                {
                    var executor = connection.Connection.CreateCommandExecutor();
                    var table    = executor.ExecuteDataTable(new ExecuteReaderRequest(commandText));
                    var count    = table.Rows.Count;
                    items = new string[count];

                    for (var i = 0; i < count; i++)
                    {
                        items[i] = (string)table.Rows[i][0];
                    }

                    folder.Attributes.Add(key, items, null);
                }
            }

            //			SqlStatement sqlStatement = new SqlStatement(text);
            //			SqlObject sqlObject = sqlStatement.FindSqlObject(position);
            //			string commandText = null;
            //
            //			switch (sqlObject.Type)
            //			{
            //				case SqlObjectType.TableOrView:
            //					string owner = connection.Database;
            //					commandText = string.Format("select * from (select table_name from all_tables where owner = '{0}' union select view_name from all_views where owner = '{0}') order by 1",owner);
            //					break;
            //			}

            //      string commandText;
            //
            //      switch (word)
            //      {
            //        case "from":
            //          commandText = "select * from (select table_name from all_tables where owner = '{0}' union select view_name from all_views where owner = '{0}') order by 1";
            //          commandText = string.Format(commandText,objectBrowser.SchemasNode.SelectedSchema);
            //          break;
            //
            //        case "table":
            //        case "update":
            //          commandText = string.Format("select table_name from all_tables where owner='{0}'",connection.DataSource);
            //          break;
            //
            //        default:
            //          commandText = null;
            //          break;
            //      }
            //
            //      string[] items = null;
            //
            //      if (commandText != null)
            //      {
            //        string key = objectBrowser.SchemasNode.Connection.DataSource + "." +
            //          objectBrowser.SchemasNode.SelectedSchema + '.' + word;
            //
            //        Folder appData = Application.Instance.ApplicationData.CurrentType;
            //
            //        if (appData.SubFolders.Contains("CompletionCache"))
            //        {
            //          appData = (Folder)appData.SubFolders["CompletionCache"];
            //        }
            //        else
            //        {
            //          Folder folder = new Folder(appData,"CompletionCache");
            //        }
            //
            //        bool containsKey = appData.Properties.ContainsKey(key);
            //
            //        if (containsKey)
            //        {
            //          items = (string[])appData.Properties[key];
            //        }
            //        else
            //        {
            //            Cursor.Current = Cursors.WaitCursor;
            //            ArrayList list = new ArrayList();
            //            IDataReader dataReader = DataHelper.ExecuteReader(commandText,connection.Wrapped);
            //
            //            while (dataReader.Read())
            //              list.Add(dataReader.GetString(0));
            //
            //            items = new string[list.Count];
            //            list.CopyTo(items);
            //
            //            appData.Properties[key] = items;
            //
            //            Cursor.Current = Cursors.Default;
            //        }
            //      }
            //
            //      return items;

            throw new NotImplementedException();

            //response.Items = items;
            //return response;
        }
예제 #14
0
 /// <summary>
 /// 获取兆赫列表
 /// </summary>
 /// <param name="type">类型:[0]收藏兆赫 [1]热门兆赫 [2]上升兆赫 [3]搜索到兆赫</param>
 /// <param name="page">页码</param>
 private async void getChannels(string queryKeywrod="")
 {
     string url = string.Empty;
     searchBoxCanvas.Visibility = Visibility.Collapsed;
     if(currentType==1)
         url = string.Format("http://douban.fm/j/explore/hot_channels?start={0}&limit={1}", (currentPage - 1) * 6, 6);
     else if (currentType == 2)
         url = string.Format("http://douban.fm/j/explore/up_trending_channels?start={0}&limit={1}", (currentPage - 1) * 6, 6);
     else if (currentType == 3)
     {
         if (queryKeywrod.Trim() != string.Empty)
             url = string.Format("http://douban.fm/j/explore/search?query={0}&start={1}&limit={2}", queryKeywrod, (currentPage - 1) * 6, 6);
         else
             return;
     }
     else
     {
         List<Channel> favchannels = favChannels.GetChannels(loginUserName);
         totalPage = (favchannels.Count - 1) / 6 + 1;
         if(currentPage==1)
             decPage.Visibility = Visibility.Collapsed;
         if (currentPage == totalPage)
             ascPage.Visibility = Visibility.Collapsed;
         else
             ascPage.Visibility = Visibility.Visible;
         int start = 6 * (currentPage - 1);
         int end = (favchannels.Count >= 6 * currentPage) ? 6 * currentPage - 1 : favchannels.Count - 1;
         channelTable.Children.Clear();
         for (int i = start; i <= end; i++)
         {
             int r = (i - start) / 3;
             int c = (i - start) % 3;
             DefChannelAlbum channelAlbum = new DefChannelAlbum(favchannels[i],true);
             channelAlbum.Margin = new Thickness(20 + 160 * c, 140 * r, 0, 0);
             channelAlbum.favPic.MouseLeftButtonDown += delegate
             {
                 if (channelAlbum.IsFaved)
                 {
                     favChannels.Delete(loginUserName, channelAlbum.channel.id);
                     favChannels.ToJson();
                     getChannels();
                 }
                 else
                 {
                     favChannels.Add(loginUserName, channelAlbum.channel.id, channelAlbum.channel.name, channelAlbum.channel.banner);
                     favChannels.ToJson();
                     getChannels();
                 }
             };
             channelAlbum.albumPic.MouseLeftButtonDown += delegate
             {
                 songControl.channelNo = channelAlbum.channel.id;
                 softwareTitle.Content = string.Format("豆瓣FM--{0}兆赫", channelAlbum.channel.name);
                 getSongList(true);
             };
             channelTable.Children.Add(channelAlbum);
         }
         return;
     }
     ChannelResult cr = new ChannelResult();
     tipLabel.Content = "加载中...";
     await Task.Run(() =>
     {
         string jsonresults = new ConnectionBase().Get(url);
         cr = ChannelResult.FromJson(jsonresults);
     });
     if (cr != null && cr.status)
     {
         tipLabel.Content = string.Empty;
         List<Channel> channels = cr.data.channels;
         totalPage = cr.data.total;
         if (currentPage == 1)
             decPage.Visibility = Visibility.Collapsed;
         if (currentPage == totalPage)
             ascPage.Visibility = Visibility.Collapsed;
         else
             ascPage.Visibility = Visibility.Visible;
         int start = 0;
         int end = channels.Count - 1;
         channelTable.Children.Clear();
         for (int i = start; i <= end; i++)
         {
             int r = (i - start) / 3;
             int c = (i - start) % 3;
             DefChannelAlbum channelAlbum = new DefChannelAlbum(channels[i % 6], favChannels.isFaved(loginUserName, channels[i % 6].id));
             channelAlbum.Margin = new Thickness(20 + 160 * c, 140 * r, 0, 0);
             channelAlbum.favPic.MouseLeftButtonDown += delegate
             {
                 if (channelAlbum.IsFaved)
                 {
                     favChannels.Delete(loginUserName, channelAlbum.channel.id);
                     favChannels.ToJson();
                 }
                 else
                 {
                     favChannels.Add(loginUserName, channelAlbum.channel.id, channelAlbum.channel.name, channelAlbum.channel.banner);
                     favChannels.ToJson();
                 }
             };
             channelAlbum.albumPic.MouseLeftButtonDown += delegate
             {
                 songControl.channelNo = channelAlbum.channel.id;
                 softwareTitle.Content = string.Format("豆瓣FM--{0}兆赫", channelAlbum.channel.name);
                 getSongList(true);
             };
             channelTable.Children.Add(channelAlbum);
         }
     }
     else
         tipLabel.Content = "加载失败...";
 }
예제 #15
0
 private Stream CreateDeflateStream(ConnectionBase connection, Stream baseStream)
 {
     return new ImapDeflateStream(baseStream);
 }
예제 #16
0
 public static void Log(ConnectionBase connection, Exception ex)
 {
     connection.traceSource.TraceData(TraceEventType.Error,
                                connection.Id,
                                new ExceptionTraceData(ex, connection.Id));
 }
예제 #17
0
		/// <summary>
		/// 搜索
		/// </summary>
		/// <param name="text">搜索文本</param>
		/// <param name="start">Start值</param>
		void Search()
		{
			if (IsSearchFinished == false)return;
			SearchResult = null;
			IsSearchFinished = false;
			PreviousPageLink = null;
			NextPageLink = null;
			ThreadPool.QueueUserWorkItem(new WaitCallback((state)=>
				{
					//构造链接
					Parameters parameters = new Parameters();
					parameters["start"] = ((_page - 1) * 15).ToString();
					parameters["search_text"] = _searchText;
					string url = ConnectionBase.ConstructUrlWithParameters("http://music.douban.com/subject_search", parameters);

					//获取网页
					ConnectionBase connection= new ConnectionBase(true);
					string file = string.Empty;
					try
					{
						file = connection.Get(url);
					}
					catch (Exception ex)
					{
						Debug.WriteLine(ex);
						file = new ConnectionBase().Get("http://music.douban.com");
						file = new ConnectionBase().Get(url);
					}

					var searhResult = GetSearchItems(file);
					var previous = GetPreviousPageLink(file);
					var next = GetNextPageLink(file);
					Dispatcher.Invoke(new Action(() =>
						{
							SearchResult = searhResult;
							PreviousPageLink = previous;
							NextPageLink = next;
							IsSearchFinished = true;
						}));
				}));
		}
예제 #18
0
        /// <summary>
        /// 获取歌词
        /// </summary>
        /// <param name="artist">表演者</param>
        /// <param name="title">标题</param>
        public static Lyrics GetLyrics(string artist, string title)
        {
            if (string.IsNullOrEmpty(artist) && string.IsNullOrEmpty(title))
            {
                return(null);
            }
            if (title.ToLower().Contains("instrumental"))
            {
                return(null);
            }

            //获取所有可能的歌词
            Parameters parameters = new Parameters();

            parameters["Artist"] = Encode(artist);
            parameters["Title"]  = Encode(title);
            parameters["Flag"]   = "2";

            foreach (var server in servers)
            {
                string url  = ConnectionBase.ConstructUrlWithParameters("http://" + server + "/dll/lyricsvr.dll?sh", parameters);
                string file = new ConnectionBase().Get(url);

                //分析返回的XML文件
                LyricsResult result = null;
                try
                {
                    using (MemoryStream stream = new MemoryStream())
                        using (StreamWriter writer = new StreamWriter(stream))
                        {
                            writer.Write(file);
                            writer.Flush();
                            XmlSerializer serializer = new XmlSerializer(typeof(LyricsResult));
                            stream.Position = 0;
                            result          = (LyricsResult)serializer.Deserialize(stream);
                        }
                }
                catch { }
                if (result == null || result.Count == 0)
                {
                    continue;
                }

                //选出最合适的歌词文件
                LyricsItem selected = result[0];
                double     dist     = double.MaxValue;
                string     lArtist  = artist.ToLower();
                string     lTitle   = title.ToLower();
                foreach (var item in result)
                {
                    string iArtist = item.Artist.ToLower();
                    string iTitle  = item.Title.ToLower();
                    if (lArtist == iArtist && lTitle == iTitle)
                    {
                        selected = item;
                        break;
                    }
                    else if (lArtist.Length < 100 && lTitle.Length < 100 && iArtist.Length < 100 && iTitle.Length < 100)
                    {
                        int    dist1 = Distance(lArtist, iArtist);
                        int    dist2 = Distance(lTitle, iTitle);
                        double temp  = ((double)(dist1 + dist2)) / (lArtist.Length + lTitle.Length);
                        if (temp < dist)
                        {
                            dist     = temp;
                            selected = item;
                        }
                    }
                }

                //下载歌词文件
                Parameters parameters2 = new Parameters();
                parameters2["Id"]   = selected.Id.ToString();
                parameters2["Code"] = VerifyCode(selected.Artist, selected.Title, selected.Id);
                string url2  = ConnectionBase.ConstructUrlWithParameters("http://" + server + "/dll/lyricsvr.dll?dl", parameters2);
                string file2 = new ConnectionBase().Get(url2);

                //生成Lyrics的实例
                if (string.IsNullOrEmpty(file2))
                {
                    continue;
                }
                try
                {
                    return(new Lyrics(file2));
                }
                catch
                {
                    continue;
                }
            }

            return(null);
        }
 protected CommandWithResultBase(ConnectionBase connection) : base(connection)
 {
 }
예제 #20
0
 public static void SendCommand(this ConnectionBase conn, CommandType type, int mapId, params object[] data)
 {
     SendCommand(conn, type, mapId, ByteWriter.GetBytes(data));
 }
예제 #21
0
        private static void Code(TerminalTabControlItem terminalTabPage, IHostingForm parentForm, FavoriteConfigurationElement favorite, ConnectionBase conn = null)
        {
            if (conn == null)
            {
                conn = CreateConnection(favorite);
                conn.TerminalTabPage       = terminalTabPage;
                terminalTabPage.TabColor   = FavoriteConfigurationElement.TranslateColor(favorite.TabColor);
                terminalTabPage.Connection = conn;
            }

            conn.Favorite   = favorite;
            conn.ParentForm = parentForm;

            if (conn.Connect())
            {
                if (conn.InvokeRequired)
                {
                    conn.Invoke(new MethodInvoker(delegate
                    {
                        conn.BringToFront();
                        conn.Update();
                    }));
                }
                else
                {
                    conn.BringToFront();
                    conn.Update();
                }

                if (parentForm.InvokeRequired)
                {
                    parentForm.Invoke(new MethodInvoker(delegate
                    {
                        parentForm.UpdateControls();

                        if (favorite.DesktopSize == DesktopSize.FullScreen)
                        {
                            parentForm.FullScreen = true;
                        }
                    }));
                }
                else
                {
                    parentForm.UpdateControls();

                    if (favorite.DesktopSize == DesktopSize.FullScreen)
                    {
                        parentForm.FullScreen = true;
                    }
                }

                conn.AfterConnectPlugins();
            }
            else
            {
                string message = "Sorry, " + AssemblyInfo.Title + " was unable to create the connection. Try again or check the log for more information.";

                Log.Error(message);
                MessageBox.Show(message, AssemblyInfo.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);

                if (parentForm.InvokeRequired)
                {
                    parentForm.Invoke(new MethodInvoker(delegate { parentForm.RemoveAndUnSelect(terminalTabPage); }));
                }
                else
                {
                    parentForm.RemoveAndUnSelect(terminalTabPage);
                }
            }

            if (conn.Connected && favorite.NewWindow)
            {
                if (parentForm.InvokeRequired)
                {
                    parentForm.Invoke(new MethodInvoker(delegate { parentForm.DetachTabToNewWindow(terminalTabPage); }));
                }
                else
                {
                    parentForm.DetachTabToNewWindow(terminalTabPage);
                }
            }
        }
예제 #22
0
        /// <summary>
        ///     Creates a new connection by spawning a new thread.
        /// </summary>
        /// <param name="favorite"> </param>
        /// <param name="TerminalTabPage"> </param>
        /// <param name="parentForm"> </param>
        /// <remarks>
        ///     This method calls the <see cref="ConnectionBase.Connect" /> method and requires it to be thread safe.
        /// </remarks>
        public static void CreateConnection(FavoriteConfigurationElement favorite, IHostingForm parentForm, bool waitforEnd, TerminalTabControlItem terminalTabPage, ConnectionBase conn = null)
        {
            // This might happen if the user is not allowed to
            // use all available connections e.g.
            // if the user has a freeware version.
            if (Limit.Contains(favorite.Protocol.ToUpper()) || terminalTabPage == null)
            {
                MessageBox.Show("You are not allowed to use that kind of connection! Please upgrade your license.", AssemblyInfo.Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (!waitforEnd)
            {
                Thread t = new Thread((ThreadStart) delegate
                {
                    Code(terminalTabPage, parentForm, favorite, conn);
                });

                t.SetApartmentState(ApartmentState.STA);
                t.Start();
            }
            else
            {
                Code(terminalTabPage, parentForm, favorite, conn);
            }
        }
예제 #23
0
    GetCompletionResponse IProvider.GetCompletion(ConnectionBase connection, IDbTransaction transaction, string text, int position)
    {
        var response = new GetCompletionResponse();

        string[] array        = null;
        var      sqlStatement = new SqlParser(text);
        var      tokens       = sqlStatement.Tokens;
        var      index        = sqlStatement.FindToken(position);

        if (index >= 0 && index < tokens.Count)
        {
            var token = sqlStatement.Tokens[index];
            var value = token.Value;
        }

        if (array == null)
        {
            var    sqlObject   = sqlStatement.FindSqlObject(index);
            string commandText = null;

            if (sqlObject != null)
            {
                string?name;
                switch (sqlObject.Type)
                {
                case SqlObjectTypes.Table | SqlObjectTypes.View:
                    commandText = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES ORDER BY TABLE_NAME";
                    break;

                case SqlObjectTypes.Table | SqlObjectTypes.View | SqlObjectTypes.Function:
                    commandText = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES ORDER BY TABLE_NAME";
                    break;

                case SqlObjectTypes.Table:
                    commandText = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES ORDER BY TABLE_NAME";
                    break;

                case SqlObjectTypes.Column:
                    name        = sqlObject.ParentName;
                    commandText = $@"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = '{name}'
ORDER BY ORDINAL_POSITION";
                    break;

                case SqlObjectTypes.Value:
                    var    items            = sqlObject.ParentName.Split('.');
                    var    i                = items.Length - 1;
                    var    columnName       = items[i];
                    string tableNameOrAlias = null;
                    if (i > 0)
                    {
                        i--;
                        tableNameOrAlias = items[i];
                    }

                    if (tableNameOrAlias != null)
                    {
                        var contains = sqlStatement.Tables.TryGetValue(tableNameOrAlias, out var tableName);
                        if (contains)
                        {
                            commandText = $"select distinct top 10 {columnName} from {tableName} (nolock) order by 1";
                        }
                    }

                    break;
                }
            }

            if (commandText != null)
            {
                Trace.WriteLine(commandText);
                var list = new List <string>();

                try
                {
                    var executor = connection.Connection.CreateCommandExecutor();
                    list = executor.ExecuteReader(new ExecuteReaderRequest(commandText), 128, dataRecord => dataRecord.GetString(0)).ToList();
                }
                catch
                {
                }

                array = new string[list.Count];
                list.CopyTo(array);
            }
        }

        //  TODO response.Items = array;
        return(response);
    }
예제 #24
0
 public static void Log(ConnectionBase connection, string format, params object[] args)
 {
     connection.traceSource.TraceData(TraceEventType.Information,
                                connection.Id,
                                new MessageTraceData(string.Format(format, args), connection.Id));
 }
예제 #25
0
        private async Task <ResponseBase> ExecuteAction <T>(Type handlerType, IServiceProvider serviceProvider, CommandBase command, ILogger <T> logger,
                                                            HttpInformation information, ConnectionBase connection = null)
        {
            object handler = serviceProvider.GetService(handlerType);

            if (handler != null)
            {
                logger.LogInformation("Handling " + command.GetType().Name + " with " + handler.GetType().Name);
                try
                {
                    if (handler is INeedsConnection handlerWithConnection)
                    {
                        if (handler is ExecuteCommandHandler || connection != null)
                        {
                            handlerWithConnection.Connection = connection;
                        }
                        else
                        {
                            logger.LogError("Cannot handle " + command.GetType().Name + " without realtime connection");
                            return(command.CreateExceptionResponse <ResponseBase>("Cannot handle this command without realtime connection"));
                        }
                    }

                    ResponseBase response = await(dynamic) handlerType.GetMethod("Handle").Invoke(handler, new object[] { information, command });

                    logger.LogInformation("Handled " + command.GetType().Name);

                    if (response?.Error != null)
                    {
                        logger.LogWarning("The handler returned an error for " + command.GetType().Name, response.Error);
                    }

                    return(response);
                }
                catch (Exception ex)
                {
                    logger.LogError("Error handling " + command.GetType().Name);
                    logger.LogError(ex.Message);
                    return(command.CreateExceptionResponse <ResponseBase>(ex));
                }
            }
            else
            {
                logger.LogError("No handler was found to handle " + command.GetType().Name);
                return(command.CreateExceptionResponse <ResponseBase>("No handler was found for command"));
            }
        }
예제 #26
0
 public static T CreateRulesProcessor <T>(ConnectionBase connection)
 {
     return(ReflectionHelper.CreateAndCastInstance <T>(typeof(T), new object[] { connection }));
 }
예제 #27
0
 /// <summary>
 /// 异步加载验证码
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private async void opLoginCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
 {
     if (LoginState != 0)
         return;
     await Task.Run(() =>
         {
             CaptchaID = new ConnectionBase().Get("http://douban.fm/j/new_captcha");
             CaptchaID = CaptchaID.Trim('\"');
             CaptchaUrl = @"http://douban.fm/misc/captcha?size=m&id=" + CaptchaID;
         });
     if (!string.IsNullOrEmpty(CaptchaID))
     {
         BitmapImage captcha = new BitmapImage(new Uri(CaptchaUrl, UriKind.Absolute));
         captchaImage.Source = captcha;
     }
     else
     {
         errorMessage.Content = "验证码加载失败";
     }
 }
예제 #28
0
 public DapperRepository_bak(ConnectionBase db) : base(db)
 {
 }
예제 #29
0
		/// <summary>
		/// 获取歌词
		/// </summary>
		/// <param name="artist">表演者</param>
		/// <param name="title">标题</param>
		public static Lyrics GetLyrics(string artist, string title)
		{
            if (string.IsNullOrEmpty(artist) && string.IsNullOrEmpty(title)) return null;
			if (title.ToLower().Contains("instrumental")) return null;

			//获取所有可能的歌词
			Parameters parameters = new Parameters();
			parameters["Artist"] = Encode(artist);
			parameters["Title"] = Encode(title);
			parameters["Flag"] = "2";

			foreach (var server in servers)
			{
				string url = ConnectionBase.ConstructUrlWithParameters("http://" + server +"/dll/lyricsvr.dll?sh", parameters);
				string file = new ConnectionBase().Get(url);

				//分析返回的XML文件
				LyricsResult result = null;
				try
				{
					using (MemoryStream stream = new MemoryStream())
					using (StreamWriter writer = new StreamWriter(stream))
					{
						writer.Write(file);
						writer.Flush();
						XmlSerializer serializer = new XmlSerializer(typeof(LyricsResult));
						stream.Position = 0;
						result = (LyricsResult)serializer.Deserialize(stream);
					}
				}
				catch { }
				if (result == null || result.Count == 0) continue;

				//选出最合适的歌词文件
				LyricsItem selected = result[0];
				double dist = double.MaxValue;
				string lArtist = artist.ToLower();
				string lTitle = title.ToLower();
				foreach (var item in result)
				{
					string iArtist = item.Artist.ToLower();
					string iTitle = item.Title.ToLower();
					if (lArtist == iArtist && lTitle == iTitle)
					{
						selected = item;
						break;
					}
					else if (lArtist.Length < 100 && lTitle.Length < 100 && iArtist.Length < 100 && iTitle.Length < 100)
					{
						int dist1 = Distance(lArtist, iArtist);
						int dist2 = Distance(lTitle, iTitle);
						double temp = ((double)(dist1 + dist2)) / (lArtist.Length + lTitle.Length);
						if (temp < dist)
						{
							dist = temp;
							selected = item;
						}
					}
				}

				//下载歌词文件
				Parameters parameters2 = new Parameters();
				parameters2["Id"] = selected.Id.ToString();
				parameters2["Code"] = VerifyCode(selected.Artist, selected.Title, selected.Id);
				string url2 = ConnectionBase.ConstructUrlWithParameters("http://" + server + "/dll/lyricsvr.dll?dl", parameters2);
				string file2 = new ConnectionBase().Get(url2);

				//生成Lyrics的实例
				if (string.IsNullOrEmpty(file2)) continue;
				try
				{
					return new Lyrics(file2);
				}
				catch
				{
					continue;
				}
			}

			return null;
		}
 public ConnectionNode(ConnectionBase connection, RoomNode from, RoomNode to)
 {
     Connection = connection;
     From       = from;
     To         = to;
 }
예제 #31
0
        private static void Code(TerminalTabControlItem terminalTabPage, IHostingForm parentForm, FavoriteConfigurationElement favorite, ConnectionBase conn = null)
        {
            if (conn == null)
            {
                conn = CreateConnection(favorite);
                conn.TerminalTabPage = terminalTabPage;
                terminalTabPage.TabColor = FavoriteConfigurationElement.TranslateColor(favorite.TabColor);
                terminalTabPage.Connection = conn;
            }

            conn.Favorite = favorite;
            conn.ParentForm = parentForm;

            if (conn.Connect())
            {
                if (conn.InvokeRequired)
                    conn.Invoke(new MethodInvoker(delegate
                    {
                        conn.BringToFront();
                        conn.Update();
                    }));
                else
                {
                    conn.BringToFront();
                    conn.Update();
                }
                
                if (parentForm.InvokeRequired)
                    parentForm.Invoke(new MethodInvoker(delegate
                    {
                        parentForm.UpdateControls();

                        if (favorite.DesktopSize == DesktopSize.FullScreen)
                            parentForm.FullScreen = true;
                    }));
                else
                {
                    parentForm.UpdateControls();

                    if (favorite.DesktopSize == DesktopSize.FullScreen)
                        parentForm.FullScreen = true;
                }

                conn.AfterConnectPlugins();
            }
            else
            {
            	string message = "Sorry, " + AssemblyInfo.Title + " was unable to create the connection. Try again or check the log for more information.";

                Log.Error(message);
                MessageBox.Show(message, AssemblyInfo.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);

                if (parentForm.InvokeRequired)
                    parentForm.Invoke(new MethodInvoker(delegate { parentForm.RemoveAndUnSelect(terminalTabPage); }));
                else
                    parentForm.RemoveAndUnSelect(terminalTabPage);
            }

            if (conn.Connected && favorite.NewWindow)
            {
                if (parentForm.InvokeRequired)
                    parentForm.Invoke(new MethodInvoker(delegate { parentForm.DetachTabToNewWindow(terminalTabPage); }));
                else
                    parentForm.DetachTabToNewWindow(terminalTabPage);
            }
        }
예제 #32
0
        /// <summary>
        /// 接続をセッションに結びつけます。
        /// </summary>
        /// <param name="connection"></param>
        public void Attach(ConnectionBase connection)
        {
            lock (_connections)
                lock (_server.Sessions)
                {
                    _connections.Add(connection);
                    connection.ConnectionEnded += ConnectionEnded;
                    connection.MessageReceived += MessageReceived;
                    SendGatewayServerMessage("Connection Attached: " + connection.ToString());

                    // ニックネームを合わせる
                    if (String.IsNullOrEmpty(CurrentNick))
                    {
                        CurrentNick = connection.UserInfo.Nick;
                    }
                    else
                    {
                        connection.SendServer(new NickMessage() {NewNick = CurrentNick});
                        connection.UserInfo.Nick = CurrentNick;
                    }

                    OnAttached(connection);
                    OnConnectionAttached(new ConnectionAttachEventArgs {Connection = connection});
                }
        }
예제 #33
0
 public ServerSteamState(ConnectionBase conn) : base(conn)
 {
 }
예제 #34
0
        /// <summary>
        /// 接続をセッションから切り離します。キープアライブが有効な場合を除き接続数が0となるとセッションは終了します。
        /// </summary>
        /// <param name="connection"></param>
        public void Detach(ConnectionBase connection)
        {
            lock (_connections)
                lock (_server.Sessions)
                {
                    connection.ConnectionEnded -= ConnectionEnded;
                    connection.MessageReceived -= MessageReceived;
                    _connections.Remove(connection);
                    SendGatewayServerMessage("Connection Detached: " + connection.ToString());

                    OnDetached(connection);
                    OnConnectionDetached(new ConnectionAttachEventArgs {Connection = connection});

                    // 接続が0になったらセッション終了
                    if (_connections.Count == 0 && !IsKeepAlive)
                    {
                        Close();
                    }
                }
        }
예제 #35
0
 public CopyResultWriter(Action <InfoMessage> addInfoMessage, IProvider destinationProvider, ConnectionBase destinationConnection, string tableName,
                         Action <IDbTransaction> setTransaction, CancellationToken cancellationToken)
 {
     _logResultWriter           = new LogResultWriter(addInfoMessage);
     _addInfoMessage            = addInfoMessage;
     _destinationProvider       = destinationProvider;
     _canConvertCommandToString = destinationProvider.CanConvertCommandToString;
     _destinationConnection     = destinationConnection;
     _tableName         = tableName;
     _setTransaction    = setTransaction;
     _cancellationToken = cancellationToken;
 }
예제 #36
0
 /// <summary>
 /// 接続が切り離されたときの処理です。
 /// </summary>
 /// <param name="connection"></param>
 protected abstract void OnDetached(ConnectionBase connection);
예제 #37
0
        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <returns>是否成功</returns>
	    private bool UpdateUserInfo()
	    {
	        Debug.Assert(!string.IsNullOrEmpty(Settings.User.Token), "!string.IsNullOrEmpty(Settings.User.Token)");
	        Parameters parameters = new Parameters();
	        parameters["app_name"] = "radio_desktop_win";
	        parameters["version"] = "100";
	        parameters["user_id"] = Settings.User.UserID;
	        parameters["token"] = Settings.User.Token;
	        parameters["expire"] = Settings.User.Expire;
	        string file = new ConnectionBase().Post("http://www.douban.com/j/app/radio/user_info",
	                                                Encoding.UTF8.GetBytes(parameters.ToString()));
	        var userInfo = JsonHelper.FromJson<UserInfo>(file);
	        if (userInfo == null || userInfo.r)
	        {
	            return false;
	        }

	        Settings.User.Played = userInfo.played_num;
	        Settings.User.Liked = userInfo.liked_num;
	        Settings.User.Banned = userInfo.banned_num;
	        if (userInfo.pro_status == "S")
	        {
	            if (!Settings.User.IsPro)
	            {
	                Settings.User.IsPro = true;
	                Settings.User.ProRate = ProRate.Kbps64;
	            }
	        }
	        else
	        {
	            Settings.User.IsPro = false;
	            Settings.User.ProRate = ProRate.Kbps64;
	        }

	        return true;
	    }
예제 #38
0
        /// <summary>
        /// Processes the message
        /// </summary>
        /// <param name="connectionBase">The connection base</param>
        /// <param name="message">The playerio message</param>
        /// <param name="handled">Whether the message was already handled</param>
        public void Process(ConnectionBase connectionBase, Message message, bool handled)
        {
            int    userId = message.GetInt(0);
            string text   = message.GetString(1);

            QuickChatMessage quickChatMesssage = QuickChatMessage.Unknown;

            switch (text)
            {
            case "Hi.":
                quickChatMesssage = QuickChatMessage.Hi;
                break;

            case "Goodbye.":
                quickChatMesssage = QuickChatMessage.Bye;
                break;

            case "Help me!":
                quickChatMesssage = QuickChatMessage.Help;
                break;

            case "Thank you.":
                quickChatMesssage = QuickChatMessage.Thanks;
                break;

            case "Follow me.":
                quickChatMesssage = QuickChatMessage.Come;
                break;

            case "Stop!":
                quickChatMesssage = QuickChatMessage.Stop;
                break;

            case "Yes.":
                quickChatMesssage = QuickChatMessage.Yes;
                break;

            case "No.":
                quickChatMesssage = QuickChatMessage.No;
                break;

            case "Right.":
                quickChatMesssage = QuickChatMessage.Right;
                break;

            case "Left.":
                quickChatMesssage = QuickChatMessage.Left;
                break;
            }

            WorldConnection worldCon = (WorldConnection)connectionBase;
            WorldPlayer     player   = worldCon.Players.GetPlayer(userId);

            ChatMessage    chatMessage    = new ChatMessage(player, text);
            QuickChatEvent quickChatEvent = new QuickChatEvent()
            {
                Raw              = message,
                ChatMessage      = chatMessage,
                QuickChatMessage = quickChatMesssage
            };

            connectionBase.RaiseServerEvent <QuickChatEvent>(quickChatEvent);
        }
예제 #39
0
        GetCompletionResponse IProvider.GetCompletion(ConnectionBase connection, IDbTransaction transaction, string text, int position)
        {
            var response = new GetCompletionResponse
            {
                FromCache = false
            };
            List <IObjectName> array = null;
            var   sqlStatement = new SqlParser(text);
            var   tokens = sqlStatement.Tokens;
            Token previousToken, currentToken;

            sqlStatement.FindToken(position, out previousToken, out currentToken);

            if (currentToken != null)
            {
                var parts          = new IdentifierParser(new StringReader(currentToken.Value)).Parse().ToList();
                var lastPart       = parts.Count > 0 ? parts.Last() : null;
                var lastPartLength = lastPart != null ? lastPart.Length : 0;
                response.StartPosition = currentToken.EndPosition - lastPartLength + 1;
                response.Length        = lastPartLength;
                var value = currentToken.Value;
                if (value.Length > 0 && value[0] == '@')
                {
                    if (value.IndexOf("@@") == 0)
                    {
                        // array = keyWords.Where(k => k.StartsWith(value)).Select(keyWord => (IObjectName)new NonSqlObjectName(keyWord)).ToList();
                    }
                    else
                    {
                        var list = new SortedList <string, object>();

                        for (var i = 0; i < tokens.Count; i++)
                        {
                            var token   = tokens[i];
                            var keyWord = token.Value;

                            if (keyWord != null && keyWord.Length >= 2 && keyWord.IndexOf(value) == 0 && keyWord != value)
                            {
                                if (!list.ContainsKey(token.Value))
                                {
                                    list.Add(token.Value, null);
                                }
                            }
                        }

                        array = list.Keys.Select(keyWord => (IObjectName) new NonSqlObjectName(keyWord)).ToList();
                    }
                }
            }
            else
            {
                response.StartPosition = position;
                response.Length        = 0;
            }

            if (array == null)
            {
                var    sqlObject   = sqlStatement.FindSqlObject(previousToken, currentToken);
                string commandText = null;

                if (sqlObject != null)
                {
                    DatabaseObjectMultipartName name;
                    int i;

                    switch (sqlObject.Type)
                    {
                    case SqlObjectTypes.Database:
                        // TODO commandText = SqlServerObject.GetDatabases();
                        break;

                    case SqlObjectTypes.Table:
                    case SqlObjectTypes.View:
                    case SqlObjectTypes.Function:
                    case SqlObjectTypes.Table | SqlObjectTypes.View:
                    case SqlObjectTypes.Table | SqlObjectTypes.View | SqlObjectTypes.Function:
                    {
                        name = new DatabaseObjectMultipartName(connection.Database, sqlObject.Name);
                        var nameParts = sqlObject.Name != null
                                ? new IdentifierParser(new StringReader(sqlObject.Name)).Parse().ToList()
                                : null;
                        var namePartsCount = nameParts != null ? nameParts.Count : 0;
                        var statements     = new List <string>();

                        switch (namePartsCount)
                        {
                        case 0:
                        case 1:
                        {
                            // statements.Add(SqlServerObject.GetDatabases());
                            statements.Add(SqlServerObject.GetSchemas());

                            //var objectTypes = sqlObject.Type.ToObjectTypes();
                            //statements.Add(SqlServerObject.GetObjects(schema: "dbo", objectTypes: objectTypes));
                        }
                        break;

                        case 2:
                            if (nameParts[0] != null)
                            {
                                // TODO statements.Add(SqlServerObject.GetSchemas(database: nameParts[0]));

                                var objectTypes = sqlObject.Type.ToTableTypes();
                                statements.Add(SqlServerObject.GetTables(schema: nameParts[0], tableTypes: objectTypes));
                            }

                            break;

                        case 3:
                        {
                            if (nameParts[0] != null && nameParts[1] != null)
                            {
                                var objectTypes = sqlObject.Type.ToObjectTypes();
                                statements.Add(SqlServerObject.GetObjects(database: nameParts[0], schema: nameParts[1], objectTypes: objectTypes));
                            }
                        }
                        break;
                        }

                        commandText = statements.Count > 0 ? string.Join("\r\n", statements) : null;
                    }
                    break;

                    case SqlObjectTypes.Column:
                        name = new DatabaseObjectMultipartName(connection.Database, sqlObject.ParentName);
                        string[] owners;

                        if (name.Schema != null)
                        {
                            owners = new[] { name.Schema };
                        }
                        else
                        {
                            owners = new[] { "dbo", "sys" };
                        }

                        var sb = new StringBuilder();
                        for (i = 0; i < owners.Length; i++)
                        {
                            if (i > 0)
                            {
                                sb.Append(',');
                            }

                            sb.AppendFormat("'{0}'", owners[i]);
                        }

                        var ownersString = sb.ToString();
                        commandText =
                            $@"select c.column_name
from information_schema.columns c
where
    c.table_schema = '{name.Schema}'
    and c.table_name = '{name.Name}'
order by c.ordinal_position";
                        break;

                    case SqlObjectTypes.Procedure:
                        name = new DatabaseObjectMultipartName(connection.Database, sqlObject.Name);

                        if (name.Schema == null)
                        {
                            name.Schema = "dbo";
                        }

                        commandText = string.Format(@"select
     s.name
    ,o.name
from [{0}].sys.objects o
join [{0}].sys.schemas s
on o.schema_id = s.schema_id
where   o.type in('P','X')
order by 1", name.Database);
                        break;

                    case SqlObjectTypes.Trigger:
                        commandText = "select name from sysobjects where xtype = 'TR' order by name";
                        break;

                    case SqlObjectTypes.Value:
                        var items = sqlObject.ParentName.Split('.');
                        i = items.Length - 1;
                        var    columnName       = items[i];
                        string tableNameOrAlias = null;
                        if (i > 0)
                        {
                            i--;
                            tableNameOrAlias = items[i];
                        }

                        if (tableNameOrAlias != null)
                        {
                            string tableName;
                            var    contains = sqlStatement.Tables.TryGetValue(tableNameOrAlias, out tableName);
                            if (contains)
                            {
                                string where;
                                var tokenIndex = previousToken.Index + 1;
                                if (tokenIndex < tokens.Count)
                                {
                                    var token      = tokens[tokenIndex];
                                    var tokenValue = token.Value;
                                    var indexofAny = tokenValue.IndexOfAny(new[] { '\r', '\n' });
                                    if (indexofAny >= 0)
                                    {
                                        tokenValue = tokenValue.Substring(0, indexofAny);
                                    }

                                    string like;
                                    if (tokenValue.Length > 0)
                                    {
                                        if (tokenValue.Contains('%'))
                                        {
                                            like = tokenValue;
                                        }
                                        else
                                        {
                                            like = tokenValue + '%';
                                        }
                                    }
                                    else
                                    {
                                        like = "%";
                                    }

                                    @where = $"where {columnName} like N'{like}'";
                                }
                                else
                                {
                                    @where = null;
                                }

                                commandText = $"select distinct top 100 {columnName} from {tableName} (readpast) {@where} order by 1";
                            }
                        }

                        break;
                    }
                }

                if (commandText != null)
                {
                    Log.Write(LogLevel.Trace, "commandText:\r\n{0}", commandText);
                    var list = new List <IObjectName>();
                    try
                    {
                        if (connection.State != ConnectionState.Open)
                        {
                            connection.OpenAsync(CancellationToken.None).Wait();
                        }

                        var executor = connection.Connection.CreateCommandExecutor();
                        //new DbTransactionScope(connection.Connection, transaction);
                        executor.ExecuteReader(new ExecuteReaderRequest(commandText), dataReader =>
                        {
                            while (true)
                            {
                                dataReader.ReadResult(() =>
                                {
                                    var fieldCount = dataReader.FieldCount;

                                    string schemaName;
                                    string objectName;

                                    if (fieldCount == 1)
                                    {
                                        schemaName = null;
                                        objectName = dataReader.GetString(0);
                                    }
                                    else
                                    {
                                        schemaName = dataReader.GetStringOrDefault(0);
                                        objectName = dataReader.GetString(1);
                                    }

                                    list.Add(new ObjectName(sqlObject, schemaName, objectName));
                                });

                                if (!dataReader.NextResult())
                                {
                                    break;
                                }
                            }
                        });
                    }
                    catch
                    {
                    }

                    array = list;
                }
            }

            response.Items = array;
            return(response);
        }
예제 #40
0
 GetCompletionResponse IProvider.GetCompletion(ConnectionBase connection, IDbTransaction transaction, string text, int position)
 {
     throw new NotImplementedException();
 }
예제 #41
0
        public async Task <ResponseBase> ExecuteCommand <T>(CommandBase command, IServiceProvider serviceProvider, HttpInformation information, ILogger <T> logger, ConnectionBase connection = null)
        {
            string commandTypeName = command.GetType().Name;

            if (commandHandlerTypes.TryGetValue(commandTypeName, out Type handlerType))
            {
                ResponseBase authResponse = CreateAuthenticationResponseOrNull(handlerType, information, command);

                if (authResponse != null)
                {
                    return(authResponse);
                }

                return(await ExecuteAction(handlerType, serviceProvider, command, logger, information, connection));
            }

            return(null);
        }
 public SearchCommand(ConnectionBase connection) : base(connection)
 {
 }
예제 #43
0
 protected CommandBase(ConnectionBase connection)
 {
     ArgumentAssert.IsNotNull(connection, "connection");
     _connection = connection;
 }
 public SearchCommand(ConnectionBase connection, IEnumerable <SearchQuery> queryList) : base(connection)
 {
     ArgumentAssert.IsNotNull(queryList, "queryList");
     QueryList.AddRange(queryList);
 }
예제 #45
0
 /// <summary>
 /// 异步判断用户是否登陆
 /// </summary>
 /// <returns>登录状态:[-1]未联网 [0]未登录 [1]已登录</returns>
 private async Task<int> HasLogined()
 {
     int retValu = 0;
     string logName = string.Empty, logPlayed = string.Empty, logLiked = string.Empty, logBanned = string.Empty;
     await Task.Run(() =>
         {
             string loginresult = new ConnectionBase().Get(@"http://douban.fm/");
             if (!string.IsNullOrEmpty(loginresult))
             {
                 Match indMatch = Regex.Match(loginresult, @"豆瓣", RegexOptions.IgnoreCase);
                 if (indMatch == null || string.IsNullOrEmpty(indMatch.Groups[0].Value))
                     retValu = -1;
                 else
                 {
                     Match match = Regex.Match(loginresult, @"var\s*globalConfig\s*=\s*{\s*uid\s*:\s*'(\d*)'", RegexOptions.IgnoreCase);
                     string s = match.Groups[1].Value;
                     if (string.IsNullOrEmpty(s))
                         retValu = 0;
                     else
                     {
                         retValu = 1;
                         MatchCollection mc = Regex.Matches(loginresult, @"<span id=""user_name"">([^{].*?)\s");
                         logName = mc[0].Groups[1].Value;
                         match = Regex.Match(loginresult, @"累积收听<span id=""rec_played"">(\d+)</span>首");
                         logPlayed = match.Groups[1].Value + "首";
                         match = Regex.Match(loginresult, @"加红心<span id=""rec_liked"">(\d+)</span>首");
                         logLiked = match.Groups[1].Value + "首";
                         match = Regex.Match(loginresult, @"<span id=""rec_banned"">(\d+)</span>首不再播放");
                         logBanned = match.Groups[1].Value + "首";
                     }
                 }
             }
             else
                 retValu = -1;
         });
     if (retValu == 1)
     {
         loginedName.Content = logName;
         loginedPlayed.Content = logPlayed;
         loginedLiked.Content = logLiked;
         loginedBanned.Content = logBanned;
         loginUserName = logName;
     }
     return retValu;
 }
 public SearchCommand(ConnectionBase connection, SearchQuery query) : base(connection)
 {
     ArgumentAssert.IsNotNull(query, "query");
     QueryList.Add(query);
 }
예제 #47
0
 /// <summary>
 /// 用户登陆
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private async void loginButton_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
 {
     if (string.IsNullOrEmpty(userName.Text.Trim()))
         errorMessage.Content = "用户名不能为空";
     else if (string.IsNullOrEmpty(userPassword.Password.Trim()))
         errorMessage.Content = "密码不能为空";
     else if (string.IsNullOrEmpty(userCaptcha.Text.Trim()))
         errorMessage.Content = "验证码不能为空";
     else
     {
         Parameters parameters = new Parameters();
         parameters.Add("source", "radio");
         parameters.Add("alias", userName.Text.Trim());
         parameters.Add("form_password", userPassword.Password.Trim());
         parameters.Add("captcha_solution", userCaptcha.Text.Trim());
         parameters.Add("captcha_id", CaptchaID);
         parameters.Add("from", "mainsite");
         parameters.Add("remember", "on");
         string LogOnJson = "";
         await Task.Run(() =>
         {
             LogOnJson = new ConnectionBase().Post("http://douban.fm/j/login", Encoding.UTF8.GetBytes(parameters.ToString()));
         });
         if (LogOnJson == string.Empty)
         {
             errorMessage.Content = "网络连接错误";
             return;
         }
         else
         {
             LogOnResult logonresult = LogOnResult.FromJson(LogOnJson);
             if (logonresult.r == 1)
             {
                 errorMessage.Content = logonresult.err_msg;
                 return;
             }
             else if (logonresult.r == 0)
             {
                 loginCanvas.Visibility = Visibility.Collapsed;
                 loginedCanvas.Visibility = Visibility.Visible;
                 loginedName.Content = logonresult.user_info.name;
                 loginedPlayed.Content = logonresult.user_info.play_record.played + "首";
                 loginedLiked.Content = logonresult.user_info.play_record.liked + "首";
                 loginedBanned.Content = logonresult.user_info.play_record.banned + "首";
                 loginTitle.Content = "用户";
                 LoginState = 1;
                 loginUserName = logonresult.user_info.name; 
             }
         }
     }
 }
예제 #48
0
 private static string MakeContext(string subject)
 {
     try
     {
         string file = new ConnectionBase().Get("http://api.douban.com/music/subject/" + subject);
         if (file != null)
         {
             MatchCollection mc = Regex.Matches(file, @"<db:attribute[^>]*index=""\d+""[^>]*>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
             foreach (Match ma in mc)
             {
                 if (ma.Success)
                 {
                     Match ma2 = Regex.Match(ma.Value, @"name=\""tracks?\""", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                     if (ma2.Success)
                     {
                         return "channel:0|subject_id:" + subject;
                     }
                 }
             }
         }
     }
     catch { }
     return null;
 }
예제 #49
0
 /// <summary>
 /// 异步获取歌曲列表
 /// </summary>
 /// <param name="type"></param>
 /// <param name="queryKeywrod"></param>
 private async void getSongs(int type, string queryKeywrod)
 {
     if (queryKeywrod != string.Empty)
     {
         string cate = string.Empty;
         int limit = 175;
         if (type == 0)
             cate = "misc";
         else if (type == 1)
             cate = "name";
         else if (type == 2)
             cate = "album";
         else
             cate = "singer";
         string url = string.Format("http://douban.fm/j/open_channel/creation/search?keyword={0}&cate={1}&limit={2}", queryKeywrod, cate, limit);
         SearchSongResult ssr = new SearchSongResult();
         tipSongLabel.Content = "加载中...";
         await Task.Run(() =>
         {
             string jsonresults = new ConnectionBase().Get(url);
             ssr = SearchSongResult.FromJson(jsonresults);
         });
         if (ssr != null && ssr.status)
         {
             tipSongLabel.Content = "";
             foreach (SimpleSong simpleSong in ssr.data.songs)
             {
                 DefSongInfo defSongInfo = new DefSongInfo(simpleSong);
                 defSongInfo.playButton.MouseLeftButtonDown += delegate
                 {
                     player.Pause();
                     playerPlay.Source = new BitmapImage(new Uri("Images/Play.png", UriKind.RelativeOrAbsolute));
                     player.Tag = "Play";
                     if (!defSongInfo.IsPlaying)
                     {
                         searchplayer.Source = new Uri(defSongInfo.SimpleSongInfo.url, UriKind.Absolute);
                         searchplayer.Play();
                         defSongInfo.IsPlaying = true;
                         defSongInfo.playButton.Source = new BitmapImage(new Uri("Images/Pause.png", UriKind.RelativeOrAbsolute));
                     }
                     else
                     {
                         searchplayer.Pause();
                         defSongInfo.IsPlaying = false;
                         defSongInfo.playButton.Source = new BitmapImage(new Uri("Images/Play.png", UriKind.RelativeOrAbsolute));
                     }
                 };
                 SongsQueryed.Children.Add(defSongInfo);
             }
         }
         else
             tipSongLabel.Content = "加载失败...";
     }
 }
예제 #50
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="connection">The connection to operate through.</param>
 public ConnectionAspectInjector(ConnectionBase connection) : base(connection)
 {
 }
예제 #51
0
        /// <summary>
        /// 根据情况从本地或服务器获取频道列表。
        /// </summary>
        /// <returns>频道列表</returns>
        private static ChannelInfo GetChannelInfo()
        {
            var localPath = Path.Combine(ConnectionBase.DataFolder, "channelinfo");
            ChannelInfo localChannelInfo = null;

            //尝试获取本地频道列表
            try
            {
                if (File.Exists(localPath))
                {
                    var localChannelInfoTime = File.GetLastWriteTime(localPath);
                    var content = File.ReadAllText(localPath);
                    var channelInfo = new ChannelInfo(Json.JsonHelper.FromJson<Json.ChannelInfo>(content));
                    if (channelInfo.IsEffective)
                    {
                        localChannelInfo = channelInfo;
                    }

                    //满足条件时采用本地频道列表
                    var distance = TimeSpan.FromHours(6);
                    if (localChannelInfo != null && DateTime.Now - localChannelInfoTime < distance)
                    {
                        return localChannelInfo;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(DateTime.Now + " 获取本地频道列表失败:" + ex.Message);
            }

            //尝试获取服务器频道列表
            int tryCount = 0;
            while (true)
            {
                //获取服务器频道列表多次失败后采用本地频道列表
                if (tryCount == 5 && localChannelInfo != null) return localChannelInfo;

                ++tryCount;

                Debug.WriteLine(DateTime.Now + " 获取频道列表……");
                var file = new ConnectionBase().Get("http://doubanfmcloud-channelinfo.stor.sinaapp.com/channelinfo");
                Debug.WriteLine(DateTime.Now + " 获取频道列表完成");
                if (string.IsNullOrEmpty(file))
                {
                    TakeABreak();
                    continue;
                }
                var channelInfo = new ChannelInfo(Json.JsonHelper.FromJson<Json.ChannelInfo>(file));
                if (!channelInfo.IsEffective)
                {
                    Debug.WriteLine(DateTime.Now + " 获取频道列表失败");
                    TakeABreak();
                }
                else
                {
                    Debug.WriteLine(DateTime.Now + " 获取频道列表成功");
                    try
                    {
                        File.WriteAllText(localPath, file);
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(DateTime.Now + " 写入本地频道列表失败:" + ex.Message);
                    }
                    return channelInfo;
                }
            }
        }
예제 #52
0
 /// <summary>
 /// Initializes a new instance of the ReadWriteTable class.
 /// </summary>
 /// <param name="connection">The connection the table is opened against.</param>
 /// <param name="table">The name of the table to open.</param>
 public ReadWriteTable(ConnectionBase connection, string table) : base(connection, table)
 {
     this.Tracer.TraceInfo("read-write");
 }
예제 #53
0
        /// <summary>
        ///     Creates a new connection by spawning a new thread.
        /// </summary>
        /// <param name="favorite"> </param>
        /// <param name="TerminalTabPage"> </param>
        /// <param name="parentForm"> </param>
        /// <remarks>
        ///     This method calls the <see cref="ConnectionBase.Connect" /> method and requires it to be thread safe.
        /// </remarks>
        public static void CreateConnection(FavoriteConfigurationElement favorite, IHostingForm parentForm, bool waitforEnd, TerminalTabControlItem terminalTabPage, ConnectionBase conn = null)
        {
            // This might happen if the user is not allowed to
            // use all available connections e.g. 
            // if the user has a freeware version.
            if (Limit.Contains(favorite.Protocol.ToUpper()) || terminalTabPage == null)
            {
                MessageBox.Show("You are not allowed to use that kind of connection! Please upgrade your license.", AssemblyInfo.Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            
            if (!waitforEnd)
            {
               Thread t = new Thread((ThreadStart)delegate
                                                    {
                                                        Code(terminalTabPage, parentForm, favorite, conn);
                                                    });

                t.SetApartmentState(ApartmentState.STA);
                t.Start();
            }
            else
            {
                Code(terminalTabPage, parentForm, favorite, conn);
            }
        }
예제 #54
0
        GetCompletionResponse IProvider.GetCompletion(ConnectionBase connection, IDbTransaction transaction, string text, int position)
        {
            var response = new GetCompletionResponse();

            string[] values       = null;
            var      sqlStatement = new SqlParser(text);
            var      tokens       = sqlStatement.Tokens;

            if (tokens.Count > 0)
            {
                sqlStatement.FindToken(position, out var previousToken, out var currentToken);
                if (currentToken != null)
                {
                    response.StartPosition = currentToken.StartPosition;
                    response.Length        = currentToken.EndPosition - currentToken.StartPosition + 1;
                }
                else
                {
                    response.StartPosition = position;
                    response.Length        = 0;
                }

                if (previousToken != null)
                {
                    var token = previousToken;

                    if (token.Type == TokenType.KeyWord && string.Compare(token.Value, "exec", StringComparison.InvariantCultureIgnoreCase) == 0)
                    {
                        var names = new List <string>();

                        foreach (var name in TfsDataReaderFactory.Dictionary.Keys)
                        {
                            names.Add(name);
                        }

                        values = names.ToArray();
                    }
                    else if (tokens.Count > 1)
                    {
                        token = tokens[0];

                        if (token.Type == TokenType.KeyWord && string.Compare(token.Value, "exec", StringComparison.InvariantCultureIgnoreCase) == 0)
                        {
                            //token = tokens[1];
                            //TfsDataReaderFactory.DataReaderInfo info;
                            //bool contains = TfsDataReaderFactory.Dictionary.TryGetValue(token.Value, out info);

                            //if (contains)
                            //{
                            //    TfsParameterCollection parameters = info.Parameters;
                            //    TfsParameter parameter = parameters[index - 2];
                            //    Type type = parameter.Type;

                            //    if (type.IsEnum)
                            //    {
                            //        string[] names = Enum.GetNames(type);
                            //        values = names;
                            //    }
                            //}
                            var command  = sqlStatement.CreateCommand(this, connection, CommandType.StoredProcedure, 0);
                            var contains = TfsDataReaderFactory.Dictionary.TryGetValue(command.CommandText, out var info);
                            if (contains)
                            {
                                var parameters     = info.Parameters;
                                var parameterIndex = previousToken.Index / 2;
                                if (parameterIndex < parameters.Count)
                                {
                                    var parameter = parameters[parameterIndex];
                                    var type      = parameter.Type;
                                    if (type.IsEnum)
                                    {
                                        var names = Enum.GetNames(type);
                                        values = names;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            response.Items = values.Select(value => (IObjectName) new ObjectName(value)).ToList();
            return(response);
        }
예제 #55
0
 public static Stream CreateSslStream(ConnectionBase connection, Stream baseStream)
 {
     return ConnectionBase.CreateClientSslStream(connection,
                                           baseStream,
                                           clientCertificates,
                                           ServerCertificateValidationCallback,
                                           ClientCertificateSelectionCallback);
 }
예제 #56
0
        GetCompletionResponse IProvider.GetCompletion(ConnectionBase connection, IDbTransaction transaction, string text, int position)
        {
            var response = new GetCompletionResponse
            {
                FromCache = false
            };

            var   sqlStatement = new SqlParser(text);
            var   tokens = sqlStatement.Tokens;
            Token previousToken, currentToken;

            sqlStatement.FindToken(position, out previousToken, out currentToken);

            if (currentToken != null)
            {
                var parts          = new IdentifierParser(new StringReader(currentToken.Value)).Parse();
                var lastPart       = parts.Last();
                var lastPartLength = lastPart != null ? lastPart.Length : 0;
                response.StartPosition = currentToken.EndPosition - lastPartLength + 1;
                response.Length        = lastPartLength;
            }
            else
            {
                response.StartPosition = position;
                response.Length        = 0;
            }

            var sqlObject = sqlStatement.FindSqlObject(previousToken, currentToken);

            if (sqlObject != null)
            {
                var statements = new List <string>();

                switch (sqlObject.Type)
                {
                case SqlObjectTypes.Database:
                    statements.Add(SqlServerObject.GetDatabases());
                    break;

                case SqlObjectTypes.Table | SqlObjectTypes.View | SqlObjectTypes.Function:
                {
                    var nameParts = new IdentifierParser(new StringReader(sqlObject.Name ?? string.Empty)).Parse().ToList();
                    var name      = new DatabaseObjectMultipartName(connection.Database, nameParts);

                    switch (nameParts.Count)
                    {
                    case 0:
                    case 1:
                        statements.Add(SqlServerObject.GetDatabases());
                        statements.Add(SqlServerObject.GetTables(name.Database, new[] { "BASE TABLE", "SYSTEM VIEW" }));
                        break;

                    case 2:
                        statements.Add(SqlServerObject.GetTables(name.Database, new[] { "BASE TABLE", "SYSTEM VIEW" }));
                        break;
                    }
                }
                break;

                case SqlObjectTypes.Column:
                {
                    var nameParts = new IdentifierParser(new StringReader(sqlObject.ParentName ?? string.Empty)).Parse().ToList();
                    var name      = new DatabaseObjectMultipartName(connection.Database, nameParts);
                    statements.Add(SqlServerObject.GetColumns(name.Database, name.Name));
                }
                break;
                }

                var objectNames = new List <IObjectName>();
                var executor    = DbCommandExecutorFactory.Create(connection.Connection);
                foreach (var statement in statements)
                {
                    var items = executor.ExecuteReader(new ExecuteReaderRequest(statement), dataRecord => new ObjectName(null, dataRecord.GetString(0)));
                    objectNames.AddRange(items);
                }
                response.Items = objectNames;
            }

            return(response);
        }
예제 #57
0
        public IDbCommand CreateCommand(IProvider provider, ConnectionBase connection, CommandType commandType, int commandTimeout)
        {
            var command = connection.CreateCommand();

            command.CommandType    = commandType;
            command.CommandTimeout = commandTimeout;
            var commandType2 = commandType;

            if (Tokens.Count > 0)
            {
                var firstToken      = Tokens[0];
                var startTokenIndex = 0;
                var isVbScript      = false;

                if (firstToken.Type == TokenType.KeyWord)
                {
                    var keyWord = firstToken.Value.ToLower();

                    switch (keyWord)
                    {
                    case "exec":
                        commandType2    = CommandType.StoredProcedure;
                        startTokenIndex = 1;
                        break;

                    case "load":
                        commandType2 = CommandType.Text;
                        break;

                    case "main":
                        commandType2 = CommandType.StoredProcedure;
                        isVbScript   = true;
                        break;

                    case "select":
                        commandType2 = CommandType.Text;
                        break;

                    default:
                        break;
                    }
                }

                command.CommandType = commandType2;

                switch (commandType2)
                {
                case CommandType.Text:
                    command.CommandText = _text;
                    break;

                default:
                    if (isVbScript)
                    {
                        //string commandText = query.Substring(firstLine.Length);
                        //command.CommandText = commandText;
                    }
                    else
                    {
                        command.CommandText = Tokens[startTokenIndex].Value;
                    }

                    startTokenIndex++;
                    provider.DeriveParameters(command);

                    var i          = startTokenIndex;
                    var tokenList  = new List <Token>();
                    var parameters = new List <Parameter>();
                    while (i < Tokens.Count)
                    {
                        var token = Tokens[i];
                        if (token.Type == TokenType.OperatorOrPunctuator && token.Value == ",")
                        {
                            parameters.Add(ToParameter(tokenList));
                            tokenList.Clear();
                        }
                        else
                        {
                            tokenList.Add(token);
                        }

                        i++;
                    }

                    if (tokenList.Count > 0)
                    {
                        parameters.Add(ToParameter(tokenList));
                    }

                    var defaultValues = new List <IDataParameter>();
                    foreach (IDataParameter parameter in command.Parameters)
                    {
                        switch (parameter.Direction)
                        {
                        case ParameterDirection.Input:
                        case ParameterDirection.InputOutput:
                            var dataParameter = provider.GetDataParameter(parameter);
                            var first         = parameters.FirstOrDefault(
                                p => string.Compare(p.Name, parameter.ParameterName,
                                                    StringComparison.InvariantCultureIgnoreCase) == 0);
                            if (first == null)
                            {
                                first = parameters.FirstOrDefault(p => p.Name == null);
                                if (first != null)
                                {
                                    parameters.Remove(first);
                                }
                            }

                            if (first != null)
                            {
                                var value = GetParameterValue(dataParameter, first.Value);
                                if (value != null)
                                {
                                    parameter.Value = value;
                                }
                                else
                                {
                                    defaultValues.Add(parameter);
                                }
                            }

                            break;
                        }
                    }

                    foreach (var parameter in defaultValues)
                    {
                        command.Parameters.Remove(parameter);
                    }
                    break;
                }
            }
            else
            {
                command.CommandText = _text;
            }

            return(command);
        }
 internal V3Database(ConnectionBase connection, PipeReader pipe)
     : base(connection, new Parser(pipe))
 {
 }
예제 #59
0
 /// <summary>
 /// Initializes a new instance of the ReadWriteTable class.
 /// </summary>
 /// <param name="connection">The connection the table is opened against.</param>
 /// <param name="table">The name of the table to open.</param>
 public ReadWriteTable(ConnectionBase connection, string table) : base(connection, table)
 {
     this.Tracer.TraceInfo("read-write");
 }
예제 #60
0
 public GnipStreamProcessor(ConnectionBase connection)
     : base(connection)
 {
 }