Thursday, December 5, 2013

Get Compile-Time View Errors in ASP.NET MVC

ASP.NET MVC developers generally face an issue with compiling their views.  The errors are not reported when compiling views and they eventually turn out to be "Yellow Screen Of Death" issues from client.  Below are the steps to enable compilation errors in views:

  1. Right-click on your project file in Visual Studio’s Solution Explorer and choose Unload Project.
  2. Right-click the project file again and choose Edit YourProject.csproj.
  3. Look for a node called <MvcBuildViews> in the first <PropertyGroup> node (the one without any other attributes). If it’s not there, add it.
  4. Add or update the value inside the <MvcBuildViews> node to true. When you’re done it should look like this: 

    <
    MvcBuildViews>true</MvcBuildViews
  5. Save the project file changes.
  6. Right-click the project file in Solution Explorer one last time and select Reload Project.

How to get the substring of a string that contains HTML tags using C# .Net


public string HtmlSubstring(string html, int maxlength)
        {
            //initialize regular expressions
            string htmltag = "</?\\w+((\\s+\\w+(\\s*=\\s*(?:\".*?\"|'.*?'|[^'\">\\s]+))?)+\\s*|\\s*)/?>";

            //match all html start and end tags, otherwise get each character one by one..
            var expression = new Regex(string.Format("({0})|(.?)", htmltag));
            MatchCollection matches = expression.Matches(html);

            int i = 0;
            StringBuilder content = new StringBuilder();
            foreach (Match match in matches)
            {
                if (match.Value.Length == 1 && i < maxlength)
                {
                    content.Append(match.Value);
                    i++;
                }
                //the match contains a tag
                else if (match.Value.Length > 1 && i < maxlength)
                    content.Append(match.Value);
            }

            return Regex.Replace(content.ToString(), string.Empty, string.Empty);
        }

CSS media queries for all the devices

/* Smartphones (portrait and landscape) ----------- */ @media only screen and (min-device-width : 320px) and (max-device-width : 480px) { /* Styles */ } /* Smartphones (landscape) ----------- */ @media only screen and (min-width : 321px) { /* Styles */ } /* Smartphones (portrait) ----------- */ @media only screen and (max-width : 320px) { /* Styles */ } /* iPads (portrait and landscape) ----------- */ @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) { /* Styles */ } /* iPads (landscape) ----------- */ @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) { /* Styles */ } /* iPads (portrait) ----------- */ @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) { /* Styles */ } /* Desktops and laptops ----------- */ @media only screen and (min-width : 1224px) { /* Styles */ } /* Large screens ----------- */ @media only screen and (min-width : 1824px) { /* Styles */ } /* iPhone 4 ----------- */ @media only screen and (-webkit-min-device-pixel-ratio : 1.5), only screen and (min-device-pixel-ratio : 1.5) { /* Styles */ }

Wednesday, December 4, 2013

CSS3 to display Image in GrayScale mode

CSS3 really made lot of new innovations in styling the HTML objects.  Here is a trick by which you can convert an image to grayscale with pure CSS.


Create a file "filters.svg"  with below content:



<svg xmlns="http://www.w3.org/2000/svg">
 <filter id="grayscale">
  <feColorMatrix type="matrix" values="0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0"/>
 </filter>
</svg>

Use below CSS to refer the above file:

img {
    filter: url(filters.svg#grayscale); /* Firefox 3.5+ */
    filter: gray; /* IE6-9 */
    -webkit-filter: grayscale(1); /* Google Chrome, Safari 6+ & Opera 15+ */
}
You can also disable grayscale effect on hover

img:hover {
    filter: none;
    -webkit-filter: grayscale(0);
}

Wednesday, November 27, 2013

Handling Dynamic Subdomains in ASP.NET MVC

I was doing some research work on implementing dynamic subdomains in an ASP.NET MVC, and I found an interesting article which explains the routing functionality and a trick to test it on local environment:

http://ryanmichaelwilliams.com/articles/2012/11/15/dynamic-sub-domains-in-asp-net-mvc

Thursday, November 14, 2013

Get Twitter Feeds

Twitter has recently changed the way to access the feeds for some security reason.  The old simple way of accessing it through RSS has been depicted.  The new method has few additional steps before you can access your precious tweets. 

Before accessing the tweets, you need to register your twitter account and get their API keys here:


Basically 4 keys are needed:
  1. Token
  2. TokenSecret
  3. ConsumerKey
  4. ConsumerSecret

public string GetTwitterFeed()
        {
            try
            {
                string q = "twitterName";
                string resource_url = "https://api.twitter.com/1.1/statuses/user_timeline.json";

                var oauth_token = ConfigurationManager.AppSettings["twitterAccessToken"];
                var oauth_token_secret = ConfigurationManager.AppSettings["twitterAccessTokenSecret"];
                var oauth_consumer_key = ConfigurationManager.AppSettings["twitterConsumerKey"];
                var oauth_consumer_secret = ConfigurationManager.AppSettings["twitterConsumerSecret"];

                // oauth implementation details
                var oauth_version = "1.0";
                var oauth_signature_method = "HMAC-SHA1";

                // unique request details
                var oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
                var timeSpan = DateTime.UtcNow
                    - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
                var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();


                // create oauth signature
                var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
                                "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&q={6}";

                var baseString = string.Format(baseFormat,
                                            oauth_consumer_key,
                                            oauth_nonce,
                                            oauth_signature_method,
                                            oauth_timestamp,
                                            oauth_token,
                                            oauth_version,
                                            Uri.EscapeDataString(q)
                                            );

                baseString = string.Concat("GET&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString));

                var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
                                        "&", Uri.EscapeDataString(oauth_token_secret));

                string oauth_signature;
                using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
                {
                    oauth_signature = Convert.ToBase64String(
                        hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
                }

                // create the request header
                var headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +
                                   "oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +
                                   "oauth_token=\"{4}\", oauth_signature=\"{5}\", " +
                                   "oauth_version=\"{6}\"";

                var authHeader = string.Format(headerFormat,
                                        Uri.EscapeDataString(oauth_nonce),
                                        Uri.EscapeDataString(oauth_signature_method),
                                        Uri.EscapeDataString(oauth_timestamp),
                                        Uri.EscapeDataString(oauth_consumer_key),
                                        Uri.EscapeDataString(oauth_token),
                                        Uri.EscapeDataString(oauth_signature),
                                        Uri.EscapeDataString(oauth_version)
                                );



                ServicePointManager.Expect100Continue = false;

                // make the request
                var postBody = "q=" + Uri.EscapeDataString(q);//
                resource_url += "?" + postBody;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);
                request.Headers.Add("Authorization", authHeader);
                request.Method = "GET";
                request.ContentType = "application/x-www-form-urlencoded";
                var response = (HttpWebResponse)request.GetResponse();
                var reader = new StreamReader(response.GetResponseStream());
                var objText = reader.ReadToEnd();
                //myDiv.InnerHtml = objText;/**/


                JArray jsonDat = JArray.Parse(objText);
                return Convert.ToString(jsonDat[0]["text"]);

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }



The code above would fetch only one feed out of the list of feeds obtained.  The code highlighted in the bold text can be changed to fetch more tweets.