Post the code written by you thread. :D

Discussion in 'Web development / Programming' started by raksmey1309, Dec 1, 2009.

  1. @ruantec

    @ruantec Crazy GFX coder Emu Author

    Messages:
    14,732
    Likes Received:
    1,045
    It's been a Long time since i last posted here so i guess is time to post again... here is the code i wrote few minutes ago:

    Youtube query Feeds:
    Code:
            /// <summary>
            /// Query Youtube feeds
            /// </summary>
            /// <param name="keyWord">keyword to search</param>
            /// <param name="startIndex">index to start from</param>
            /// <param name="isHD">load HD only on demand</param>
            /// <param name="isChannel">specified if the keyword is a channel name</param>
            /// <returns>YoutubeQuery class containing the Youtube feeds</returns>
            public async static Task<YoutubeQuery> GetYoutubeQuery(string keyWord, int startIndex, bool isHD = false, bool isChannel = false)
            {
                var queryResult = new YoutubeQuery(100);
                // Replace any empty spaces
                if (!string.IsNullOrEmpty(keyWord))
                    keyWord = keyWord.Replace(' ', '+');
                // Get website
                var s = await ReadWebContent(string.Format(SEARCH, keyWord, startIndex) + (isChannel == true 
                    ? AUTHOR + keyWord 
                    : string.Empty));
                var doc = XDocument.Load(new StringReader(s));
                ////////////////////////////////////////////////////////////////////
                // Namespaces
                XNamespace xmlns = "http://www.w3.org/2005/Atom";
                XNamespace media = "http://search.yahoo.com/mrss/";
                XNamespace yt = "http://gdata.youtube.com/schemas/2007";
                XNamespace opensearch = "http://a9.com/-/spec/opensearch/1.1/";
                XNamespace gd = "http://schemas.google.com/g/2005";
                ///////////////////////////////////////////////////////////////////
                queryResult.TotalResult = doc.Root.Element(opensearch + "totalResults").Value;
                ///////////////////////////////////////////////////////////////////
                // Items query
                var query =
                    from entry in doc.Root.Elements(xmlns + "entry")
                    let grp = entry.Element(media + "group")
                    select new OnlineItem
                    {
                        Provider = "Youtube Stream",
                        Title = (string)grp.Element(media + "title"),
                        Description = (string)grp.Element(media + "description"),
                        File = (string)grp.Element(media + "player").Attribute("url"),
                        ID = (string)grp.Element(yt + "videoid"),
                        Image = GetThumbnailUri((string)grp.Element(yt + "videoid"), YouTubeThumbnailSize.Medium).AbsoluteUri,
                        ImageLarge = GetThumbnailUri((string)grp.Element(yt + "videoid"), YouTubeThumbnailSize.Large).AbsoluteUri,
                        Duration = ParseDuration((string)grp.Element(yt + "duration").Attribute("seconds")),
                        Rating = ParseRating((string)entry.Element(gd + "rating").Attribute("average")),
                        ViewCount = (string)entry.Element(yt + "statistics").Attribute("viewCount"),
                        Uploaded = ParseUploaded((string)grp.Element(yt + "uploaded"))
                    };
                ///////////////////////////////////////////////////////////////////
                // Fill items list
                if(query.Count() > 0)
                    queryResult.Items = new ObservableList<OnlineItem>(query.ToList());
                // Return results
                return queryResult;
            }
            /// <summary>
            /// Parse video uploaded date
            /// </summary>
            /// <param name="value">date string to parse</param>
            /// <returns>uploaded date if available</returns>
            private static DateTime? ParseUploaded(string value)
            {
                DateTime? result = null;
                var ulDate = DateTime.MinValue;
                DateTime.TryParse(value, CultureInfo.CurrentUICulture, DateTimeStyles.None, out ulDate);
                if (ulDate != DateTime.MinValue)
                    result = ulDate;
                return result;
            }
            /// <summary>
            /// Parse video duration
            /// </summary>
            /// <param name="value">duration string to parse</param>
            /// <returns>duration if available</returns>
            private static string ParseDuration(string value)
            {
                string result = string.Empty;
                if (!string.IsNullOrEmpty(value))
                    result = Tools.FormatTime(TimeSpan.FromSeconds(Convert.ToDouble(value)));
                return result;
            }
            /// <summary>
            /// Parse video rating
            /// </summary>
            /// <param name="value">rating string to parse</param>
            /// <returns>rating if available</returns>
            private static decimal ParseRating(string value)
            {
                decimal result = 0;
                if (!string.IsNullOrEmpty(value))
                    result = Convert.ToDecimal(value, CultureInfo.InvariantCulture);
                return result;
            }
            /// <summary>
            /// Get a specified thumbnail size
            /// </summary>
            /// <param name="youTubeId">id of the video</param>
            /// <param name="size">size of the thumbnail</param>
            /// <returns>url of the thumbnail requested</returns>
            public static Uri GetThumbnailUri(string youTubeId, YouTubeThumbnailSize size = YouTubeThumbnailSize.Medium)
            {
                switch (size)
                {
                    case YouTubeThumbnailSize.Small:
                        return new Uri("http://img.youtube.com/vi/" + youTubeId + "/default.jpg", UriKind.Absolute);
                    case YouTubeThumbnailSize.Medium:
                        return new Uri("http://img.youtube.com/vi/" + youTubeId + "/mqdefault.jpg", UriKind.Absolute);
                    case YouTubeThumbnailSize.HighQuality:
                        return new Uri("http://img.youtube.com/vi/" + youTubeId + "/hqdefault.jpg", UriKind.Absolute);
                    case YouTubeThumbnailSize.Large:
                        return new Uri("http://img.youtube.com/vi/" + youTubeId + "/maxresdefault.jpg", UriKind.Absolute);
                    case YouTubeThumbnailSize.Standard:
                        return new Uri("http://img.youtube.com/vi/" + youTubeId + "/sddefault.jpg", UriKind.Absolute);
                    default:
                        return new Uri(string.Empty);
                }
            }
    
    YoutubeQuery class:
    Code:
    using AruanTuber_DarkMoon.Lists;
    using AruanTuber_DarkMoon.ViewModels;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace AruanTuber_DarkMoon.Online
    {
        public class YoutubeQuery : ViewModelBase
        {
            private ObservableList<OnlineItem> items;
            private string totalResult;
            private int totalPages;
            private int currentPage;
            private int pageItemCount;
            /// <summary>
            /// Get or Set the current query page
            /// </summary>
            public int CurrentPage
            {
                get { return currentPage; }
                set { SetProperty(ref currentPage, value); }
            }
            /// <summary>
            /// Get or Set the total of pages available
            /// </summary>
            public int TotalPages
            {
                get { return totalPages; }
                set { SetProperty(ref totalPages, value); }
            }
            /// <summary>
            /// Get or Set the total amount of items
            /// </summary>
            public string TotalResult
            {
                get { return totalResult; }
                set { SetProperty(ref totalResult, value); ParseTotalResult(); }
            }
            /// <summary>
            /// Get or Set the items collection
            /// </summary>
            public ObservableList<OnlineItem> Items
            {
                get { return items; }
                set { SetProperty(ref items, value); }
            }
            /// <summary>
            /// Parse the current amount pages based in the total amount of items
            /// </summary>
            /// <returns></returns>
            private int ParseTotalResult()
            {
                int result = 0;
                if (string.IsNullOrEmpty(TotalResult))
                {
                    int.TryParse(TotalResult, out result);
                    if (result >= pageItemCount)
                        TotalPages = result / pageItemCount;
                }
                return result;
            }
            /// <summary>
            /// Default contructor
            /// </summary>
            /// <param name="itemCount"></param>
            public YoutubeQuery(int itemCount)
            {
                CurrentPage = 1;
                pageItemCount = itemCount;
            }
            /// <summary>
            /// Open next page
            /// </summary>
            public void NextPage()
            {
                // TODO: Write logic
            }
            /// <summary>
            /// Open previous page
            /// </summary>
            public void PreviousPage()
            {
                // TODO: Write logic
            }
        }
    }
    
    Enjoy!
    cooliscool likes this.
  2. cottonvibes

    cottonvibes You're already dead... Emu Author

    Messages:
    5,473
    Likes Received:
    4
    i finally updated my coding blog, after over a year w/o updates:

    The proper way to write multi-statement macros in C++

    I recommend all c/c++ coders here read this article, because its something that you should all learn; and I've seen many professional coders don't know the trick I mentioned in the article.
  3. cooliscool

    cooliscool Super Moderator Staff Member

    Messages:
    7,324
    Likes Received:
    38
    Simple WASD FPS style camera class for VB.NET, graphics API independent.


    Code:
    Imports System.Math
    Public Class OpenGLCamera
        Sub New()
            Reset()
        End Sub
    
        Public Structure KeyStatus
            Dim change As Boolean
            Dim W As Boolean
            Dim S As Boolean
            Dim A As Boolean
            Dim D As Boolean
        End Structure
        Public Structure MouseStatus
            Dim change As Boolean
            Dim msLeft As Boolean
            Dim msRight As Boolean
            Dim oldPos As Point
            Dim newPos As Point
            Dim diff As Point
        End Structure
        PublicEnum MOVE
            UP = 1
            DOWN = 2
            LEFT = 3
            RIGHT = 4
            NONE =0
        EndEnum
    
        Public Structure Vec3D
            Dim x As Double
            Dim y As Double
            Dim z As Double
            Sub New(ByVal tx As Double, ByVal ty As Double, ByVal tz As Double)
                x = tx
                y = ty
                z = tz
            End Sub
        End Structure
        Constant piRad as double = 3.14159265359 / 180.0f
        Public MouseSt as MouseStatus
        Public KeySt as KeyStatus
        Public pos As Vec3D
        Public rot As Vec3D
        Public d As Vec3D
        Public xD As Single = 0.0
        Public yD As Single = 0.0
        Public Spd As Double = 1.0F
        Public Property Speed() As Double
            Get
                Return Spd
            End Get
            Set(value As Double)
                Spd = value * 0.6
            End Set
        End Property
        Public Sub Reset()
            pos = New Vec3D(0, 0, 0)
            rot = New Vec3D(0, 0, 0)
            d = New Vec3D(0, 0, 0)
        End Sub
        Public Sub Update(Optional ByVal xON As Boolean = True, Optional ByVal yON As Boolean = True)
    
            If Not IsNothing(MouseSt) Then
                With MouseSt
                    .diff.X = (.newPos.X - .oldPos.X)
                    .diff.Y = (.newPos.Y - .oldPos.Y)
    
                    If .msLeft Then
                        If xON Then
                            If .newPos.X <> .oldPos.X Then
                                rot.x += .diff.X * Spd
                            End If
                        End If
                        If yON Then
                            If .newPos.Y <> .oldPos.Y Then
                                rot.y += .diff.Y * Spd
                            End If
                        End If
    
                        If rot.x >= 360.0F Then
                            rot.x = 0.0F
                        ElseIf rot.x <= -360.0F Then
                            rot.x = 0.0F
                        End If
                        If rot.y >= 90.0F Then
                            rot.y = 90.0F
                        ElseIf rot.y <= -90.0F Then
                            rot.y = -90.0F
                        End If
    
                        With d
                            .x = rot.x * piRad
                            .y = rot.y * piRad
                        End With
                    End If
                    If .msRight Then
                        If yON Then
                            If .newPos.Y <> .oldPos.Y Then
                                pos.y += .diff.Y * Spd * 0.4
                            End If
                        End If
                        If xON Then
                            If .newPos.X < .oldPos.X Then
                                pos.x += Cos(d.x) * Spd * 0.4
                                pos.z += Sin(d.x) * Spd * 0.4
                            ElseIf .newPos.X > .oldPos.X Then
                                pos.x -= Cos(d.x) * Spd * 0.4
                                pos.z -= Sin(d.x) * Spd * 0.4
                            End If
                        End If
                    End If
                End With
            End If
            If Not IsNothing(KeySt) Then
                With KeySt
                    If .W Then
                        If rot.y = 90.0F Or rot.y = -90.0F Then
                            pos.y += Sin(d.y) * Spd
                        Else
                            pos.x -= Sin(d.x) * Spd
                            pos.z += Cos(d.x) * Spd
                            pos.y += Sin(d.y) * Spd
                        End If
                    ElseIf .S Then
                        If rot.y = 90.0F Or rot.y = -90.0F Then
                            pos.y -= Sin(d.y) * Spd
                        Else
                            pos.x += Sin(d.x) * Spd
                            pos.z -= Cos(d.x) * Spd
                            pos.y -= Sin(d.y) * Spd
                        End If
                    End If
                    If .A Then
                        pos.x += Cos(d.x) * Spd
                        pos.z += Sin(d.x) * Spd
                    ElseIf .D Then
                        pos.x -= Cos(d.x) * Spd
                        pos.z -= Sin(d.x) * Spd
                    End If
                End With
            End If
        End Sub
    End Class
    @ruantec likes this.
  4. @ruantec

    @ruantec Crazy GFX coder Emu Author

    Messages:
    14,732
    Likes Received:
    1,045
    Damn, it's been ages since i last read a Visual Basic code. I can hardly code in VB anymore lol.
  5. cooliscool

    cooliscool Super Moderator Staff Member

    Messages:
    7,324
    Likes Received:
    38
    I find it to have the most beautiful syntax of any language, and it's just as powerful as any other, if not more in a lot of cases (for example, the ReDim statement for dynamically resizing arrays). I hate coding in anything else, despite years of experience with most of the major languages. :p
    Last edited: Jul 8, 2015
  6. @ruantec

    @ruantec Crazy GFX coder Emu Author

    Messages:
    14,732
    Likes Received:
    1,045
    I guess is preference then because i actually find VB not to be best one :p i never worked with VB past 6.0 the "Option Explicit" was removed right??? because that was some crazy stuff lol. Also static variables in methods is one of the things i actually miss from that language which is not present in C# and i understand why.... but was fun :p i have it in C++ but the horrendous syntax annoys me.

Share This Page