Tuesday, May 24, 2016

Use twitter API REST with ASP.NET Core

Recently, i have discovered this post about using twiter REST API with C#. Unfortunately, after release  of ASP.NET Core, code don't work in new projects. Apparently, this is because
"System.Web.Script.Serialization" namespace does not exists in the context of new DNX 5.0.

Luckily, there's an  easy fix for this. First, You need to install Newtonsoft.JSon package, either from NuGet GUI or command line with "Install-Package Newtonsoft.Json -Version 8.0.3" command.

After that, change following code in  GetAccessToken():

            var serializer = new JavaScriptSerializer();

            dynamic item = serializer.Deserialize<object>(json);

to 

            dynamic item = JsonConvert.DeserializeObject<object>(json);


and this code in GetTweets(): 

            
              var serializer = new JavaScriptSerializer();
              dynamic json = serializer.Deserialize<object>(await responseUserTimeLine.Content.ReadAsStringAsync());

to 

            dynamic json = JsonConvert.DeserializeObject<object>(await responseUserTimeLine.Content.ReadAsStringAsync());

            

And that's it. With IEnumerable<string> tweets = GetTweets().Result;call, you will get your tweets in a list you can later show on webpage or wherever you want...

Thanks again to www.karpach.com for a very useful post.

Friday, February 12, 2016

How to unminify JS, CSS and HTML Code

Code minification in modern web sites and applications is very useful thing. By removing unnecessary characters from code, you can save lot of space, therefore improve your site loading speed and overall user experience.
On the other side, minifed code is very ugly and almost impossible to understand.

There is many tool on the internet that can help you unminify your's (or someone other's) code, most of them online, a few standalone tools and plugins, but there's also not very known option in google chrome dev tools panel.

First, open site in chrome and open dev tools panel by pressing F12 key.

And now, it's the easy part.

Step 1, open "sources" panel of chrome dev tools,
Step 2, on the left side find file you wan't to unminify
Step 3, click on curly brackets icon in the bottom of your screen with tool-tip "Pretty print".



And that's it. You will get yours (or someone else) code unminified and easily understandable.

Monday, October 26, 2015

Two simple ways to speed up your Windows

I'm using Windows for a long time. Since 3.0 version on intel 286 based PC...
It always has been good, reliable operating system, but always with some flaws bugs and malfunctions. Some of them easy to fix, some of them annoying as hell. One i'm going to tell You about in this blog post is very annoying.

I have noticed, when i power up or reboot my pc, is that sometimes it is unresponsive for a very long time. I have connected this with slow memory, old pc, system full of unneeded startup apps and similar things, but recently i got brand new laptop with tons of memory and intel core i7 processor. Great little thing, that should fire up windows in seconds, you would think... But no. Still, it need several minutes to become fully operational and ready to work.

I have started to look what could cause this and noticed 100% hard disk usage for a very long period of time. I started digging in to this and found a cause of this. It's called BITS - Background Intelligent Transfer Service. BITS is part of windows update and it's service that download windows updates in background, when you are not using computer. But sometimes it can go stupid and just hangs. So, how to fix this?

First, go to "Control Panel/Windows Update/Change settings", and set updates to "Never Check".



After that,go to "Control Panel/Administrative Tools/" and open "Services" widget.
Find BITS service in list, and on General tab set Startup type to "Manual"

Then go to Recovery tab and set all recovery options on "Take no action".


After that, open again "Control Panel/Administrative tools" but this time, open "Task Scheduler" option. In the left hand tree, open "Microsoft", then "Windows", and find "Windows Update" option.


 Disable all enabled tasks, and your windows should be much faster at startup. Atleast, for some time, untill all of this is recreated again. I don't know how and why yet, but BITS service and Windows Update tasks sometimes get back and start run again, so you will need to look for this and repeat whole proccess..


Other thing i have noticed, is that sometimes, Windows Defender is using proccessor for 100% for a very long time for no obvious reason.

Reason for this is, that defender's processes are set to have high priority. But there's simple way to fix this without any security issues.

First, go to "Control Panel/Administrative tools/Task Scheduler". In left hand tree, find option "Windows Defender". Open this and you will see several tasks in the middle part of window.

Open all this tasks, and on every one, uncheck "Run with highest privileges" option.

This way, you will stop defender from using all of your processor power all the time.




Saturday, November 29, 2014

Using different layout for different roles in ASP.NET MVC with Identity2

Few days ago i got request to separate admin layout from user layout in 
ASP.NET MVC5 application using Identity2 feature of new ASP.NET framework...
 
Here's the code i have used to do that... 
 
 
@using Microsoft.AspNet.Identity;
@using Microsoft.AspNet.Identity.EntityFramework
@using MVCApplication.Models;
 
@{
    if (HttpContext.Current.User.Identity.IsAuthenticated)
    {
        var manager = new UserManager<ApplicationUser>
                           (new UserStore<ApplicationUser>(new ApplicationDbContext()));
        var user = manager.FindById(HttpContext.Current.User.Identity.GetUserId());
        var userRoles = manager.GetRoles(user.Id);
        if (userRoles.Any(r => r.Contains("Admin")))
        {
            Layout = "~/Views/Shared/_AdminLayout.cshtml"; ;
        }
        else
        {
            Layout = "~/Views/Shared/_Layout.cshtml"; ;
        }
    } 
 
 
Code should be inside "_ViewStart.cshtml" view.

Thursday, April 24, 2014

Server side validation in ASP.NET MVC and how to preserve it when updating model from database

Server side validation is very useful feature of ASP.NET and Entity Framework technologies. You declare model class and simply put some validation rules for every member of class you need to validate. 

For example: 

    public partial class products
    {
        public int ID { get; set; }
        [Required]
        public string product_name { get; set; }
        [Range(0, 1000)   
        public int product_price { get; set; }
        public string product_description { get; set; }
    }

But when you change something in database, let's say, type of product_price, from int to float, and update model in visual studio, this changes will be lost, and you will need to add them manually again. 

Or maybe not?

Inside your models folder of ASP.NET application, create two new classes called Metadata.cs and Partials.cs.

Inside metadata.cs, declare new class, productsMetadata, and there set fields you need to validate from your "products" class.

using System;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace TestApp.Models
{
    public partial class productsMetaData
    {
        public int ID { get; set; }
        [Required]
        public string product_name { get; set; }
        [Range(0, 1000)   
        public int product_price { get; set; }
    }
}

In Partials.cs file redeclare your "products" class, but with use of  MetaDataType attribute:

   [MetadataType(typeof(productsMetaData))]
   public partial class products
   {}

And that's it. Next time you update your model from database, server side validation rules will be preserved.


Monday, April 14, 2014

Creating multiline edit box in ASP.NET MVC Razor View

Few days ago, i run into a problem with my brand new ASP.NET MVC 5 application. I needed to create edit control that will accept multiple lines and large amount of text.

Usually, edit controls in razor views are created with  @Html.EditorFor(model => model.field) and this will create "<input type="text" value="" name="field" id="field" class="text-box single-line">" HTML.

But, there's "<textarea>" tag in html for creating multiline edits, right? And now, problem is how to instruct EditorFor html extension to produce textarea instead of text.

It's rather simple actually. Go to your model and add "[DataType(DataType.MultilineText)]" before your field declaration so it will look something like this now:

public class myclass
{
        [DataType(DataType.MultilineText)]
        public string pun_opis { get; set; }
}

And that's it. Now html generated by EditorFor helper will look like: 

"<textarea name="field" id="field" class="text-box multi-line input-validation-error" ></textarea>"

Next problem with this is how to preserve this change when you update model from database, but more on that next time :)

Happy coding :)

Thursday, January 26, 2012

Why to avoid Godaddy web hosting...

Thank you for your response. The 302 redirects are filters setup to maintain the integrity of the hosting server while we investigate and resolve an issue(s). These filters are temporary and will be removed as soon as possible. We apologize for any inconvenience this may have caused and appreciate your patience and understanding in this matter.
Please let us know if we can assist you in any other way.

This is message i got from godaddy 4 times after trying to resolve repeating 302 redirect issue on my new website http://skuvajme.com/.


About a month, i noticed my brand new site is loading slow and when i try to load it, page flashes several times before content is shown. I thought it's probably something with my connection, maybe some neighbor is "borrowing" my WiFi... Ok, i'll check my security later...


Few hours later, i check google webmaster tools crawl error page and see one 302 redirect error... 
I did some redesign on site, it's probably that. But when i logged in to GWT again tomorrow, more than half of my pages were redirected... 


WTF??


I check my HTTP headers and i see horror... 
All my pages are redirected from http://mysite.com/mypage to http://mysite.com/xxxxx/mypage... (xxxxx are random 5 characters)
To be even worse, sitemap.xml and robots.txt are also redirected and google can't find then... So, there's no crawler access to my site.


I put error in google and first 20 results i see are from cheated godaddy customers (just like me), and after some research, i found out it's common godaddy hosting issue.. 


So, i contacted their tech support... That was... well, once in a life time experience, and i would not wish to my worst enemy that... I sent them e-mail, waited 4 hours and got e-mail back with my question about that redirects and generic message that redirection is temporary and it will be lifted soon...


Ok i say, some problem i guess, but, there's thousands of people with same problem, all over the web... Lot's of complains... Something is not right there....


One day pass, another, and another one... 3 days and more and more my pages are being redirected... I wrote another e-mail to godaddy support, asking how long this temporary redirect is lasting, and got same answer from beginning of this blog, with addition of unlimited temporary state and something they call "Godaddy Network Protection"... Ok, i say, if this is not fixed i'm leaving godaddy and going to competition...
Few hours after my "threatening" e-mail, my headers got back to 200 response.


And everything was fine until few days ago. I noticed same thing, site flashes several times before loading, long loading times, even unavailable ftp server... I go to http://web-sniffer.net/, check status... and it's 302 again... Only this time it's not redirected to domain.com/xxxxx/ but to domain.com/?xxxxxxxx.

And again, long waiting times for e-mail response and unclear, unprofessional answers, and obvious people in tech support and network administration who don't know almost anything about networking and how hosting should work, and lots of "Godaddy Network Protection" again...

So i google "godaddy network protection" and find out terifying thing...
So called "godaddy network protection" is their way to reduce load on their servers... When a site on shared hosting generate lot's of trafic they just redirect all sites on server hosting that site to reduce load on that server...
So, i decided, i'm moving away from this cheaters...
If you are on godaddy shared hosting, and have similar problems as me, only way to solve them is to move your hosting somewhere else...

If You thinking about purchasing hosting account with godaddy, my advice would be DON'T!!!