Wednesday, December 25, 2013

jQuery : clear file input field

Use this to reset the form fields:

$('#form_id').each(function(){
    this.reset();
});

Reference:
http://stackoverflow.com/questions/7769489/clear-file-input-field-using-jquery

Friday, December 13, 2013

.Net: WCF Download file

There is the link of a nice to tutorial to download file from WCF service using stream:

http://www.dotnetcurry.com/showarticle.aspx?ID=723

Wednesday, December 11, 2013

Java: intersect two arrays


int a[] = {3, 10, 4, 2, 8};
int[] b = {10, 4, 12, 3, 23, 1, 8};
List<Integer> aList =  Arrays.asList(a);
List<Integer> bList =  Arrays.asList(b);
aList.retainsAll(bList);
System.out.println(" a intersection b "+aList);

Reference:
http://stackoverflow.com/questions/12919231/finding-the-intersection-of-two-arrays

Jquery: get element by name attribute

Monday, December 9, 2013

Jquery: async form submit plugin

Here is a nice and simple jquery plugin to work with async from submits:

http://malsup.com/jquery/form/

Wednesday, November 6, 2013

C# How to Keep console window Open

There are 2 Ways:

1. And in the last line of your code : Console.Readline() or Console.Read()
2. Run outside of the debugger CTRL+F5

Reference:
http://stackoverflow.com/questions/16952846/c-sharp-how-to-keep-console-window-open

Tuesday, November 5, 2013

log4net c# Tutorial

There is a Great and simple tutorial to work with log4net in a c# project

http://rmottap.blogspot.com/2012/05/tutorial-log4net.html

Wednesday, October 30, 2013

mysql .net Unknown column in 'where clause'

I was having the error :

"Unknown column 'Extent1.Name' in 'where clause'"

The code was:

var companies = (from cp in skydeskDB.Companies
    where cp.OrganizationId == parameters.OrganizationId                                    
    &&  cp.Name.Contains(parameters.Filter)                                                    
      select cp
).OrderBy(cp => cp.Name);


the solution was changing  select cp to select new { cp } :

var companies = (from cp in skydeskDB.Companies

    where cp.OrganizationId == parameters.OrganizationId                                    
    &&  cp.Name.Contains(parameters.Filter)                                                    
      select new { cp } // here
).OrderBy(cp => cp.Name);



Tuesday, October 1, 2013

LINQ - SQL: validate null parameter and apply in where clause

I had the query

 var results =
                        from cs in skydeskDB.Cases
                        where
                        cs.AgentId == AgentId
                        && cs.ClosedAt >= iniDate
                        && cs.ClosedAt < endDate                        
                        select cs;

I wanted to avoid the agentid filter when the agentid filter were null, like

                  var results =
                        from cs in skydeskDB.Cases
                        where                        
                        cs.ClosedAt >= iniDate
                        && cs.ClosedAt < endDate                        
                        select cs;

and, when  agentid filter were different from null apply the agentid filter, like

var results =
                        from cs in skydeskDB.Cases
                        where
                        cs.AgentId == AgentId
                        && cs.ClosedAt >= iniDate
                        && cs.ClosedAt < endDate                        
                        select cs;

The solution is adding the condition (AgentId == null || cs.AgentId == AgentId):

var results =
                        from cs in skydeskDB.Cases
                        where
                        (AgentId == null || cs.AgentId == AgentId)
                        && cs.ClosedAt >= iniDate
                        && cs.ClosedAt < endDate                        

                        select cs;

now I can do both things with one single query:
 - avoid the agentid filter when the agentid filter were null
 - apply agentid filter when the agentid filter were different from null

Resource:
http://stackoverflow.com/questions/9505189/dynamically-generate-linq-queries

Monday, September 30, 2013

.Net: Unknown column 'GroupBy1.K1' in 'field list'

I was having the error

Unknown column 'GroupBy1.K1' in 'field list'

The query was:

                    var results =
                        from cs in skydeskDB.Cases
                        where
                        cs.AgentId == AgentId
                        && cs.ClosedAt >= iniDate
                        && cs.ClosedAt < endDate
                        group cs by cs.ClosedAt.Value.Hour into g
                        select new
                        {
                            closedcasecounter = g.Count(),
                            daynumber = g.Key
                        };

After spending a lot of time on internet I found a post that suggested that the problem was a mysql connector  bug so I updated it from 6.6.5 to 6.7.4. But the problem continued so I had to group the data using a for loop :(

If you find any solution, please let me know in the comments section.

Resources:
http://bugs.mysql.com/bug.php?id=46742

Log4J: Simple File configuration example


## HelloWorld class
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class HelloWorld {

static final Logger logger = Logger.getLogger(HelloWorld.class);

public static void main(String[] args) {
PropertyConfigurator.configure("log4j.properties");
logger.debug("Sample debug message");
logger.info("Sample info message");
logger.warn("Sample warn message");
logger.error("Sample error message");
logger.fatal("Sample fatal message");
}
}

## log4j.properties file
log4j.rootLogger=DEBUG, CA
log4j.appender.CA=org.apache.log4j.FileAppender ## file apenfder configuration
log4j.appender.CA.File=main.log ## log file name
log4j.appender.CA.layout=org.apache.log4j.PatternLayout

log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n 

Referecnes:
http://www.dzone.com/tutorials/java/log4j/log4j-configuration.html
http://www.dzone.com/tutorials/java/log4j/log4j-file-appender-example-1.html

Tuesday, September 24, 2013

MySQL: stored procedures tutorial

Here is the link of a nice ans simple MySQL stored procedures tutorial:

http://www.mysqltutorial.org/stored-procedures-parameters.aspx

C#: get date time given current date and day of week

        /// <summary>
        /// Returns the daytime of the day of the week that the specified date is in. 
        /// </summary>
        public static DateTime GetDayOfWeek(DateTime dayInWeek, DayOfWeek dayOfWeek)
        {            
            DateTime lastDayInWeek = dayInWeek.Date;
            int increment = 1;
            if (dayOfWeek < dayInWeek.DayOfWeek) {
                increment = -1;
            }

            while (lastDayInWeek.DayOfWeek != dayOfWeek)
            {
                lastDayInWeek = lastDayInWeek.AddDays(increment);                                
            }                
            return lastDayInWeek;
        }

implementation samples:

get the first day of the week:
DayOfWeek dayOfWeekPriority = DayOfWeek.Monday;
DateTime iniDatePriority = DateTime.Now;
DateTime endDatePriority =GetDayOfWeek(iniDatePriority, dayOfWeekPriority).AddDays(1);

get the last day of the week:
DayOfWeek dayOfWeekPriority = DayOfWeek.Friday;
DateTime iniDatePriority = DateTime.Now;
DateTime endDatePriority = DashboardManager.GetDayOfWeek(iniDatePriority, dayOfWeekPriority).AddDays(1);

Resource:
http://joelabrahamsson.com/getting-the-first-day-in-a-week-with-c/

Dot Net: translate error

There is a useful page that heps you find the translation of .NET, Windows and Microsoft SQL Server error messages error from many languages to english:

http://finderr.net/

LINQ: LINQ to Entities no reconoce el método y este método no se puede traducir en una expresión de almacén

I was getting the error:

"LINQ to Entities no reconoce el método 'System.DateTime AddHours(Double)'
del método, y este método no se puede traducir en una expresión de almacén."

the code was:
   var results =
       from c in skydeskDB.Cases
       join cs in skydeskDB.CaseStates on c.CaseStateId equals cs.Id
      where
         c.HelpDeskId == new Guid("ee98652e-9fdf-435e-b325-74e7189b6561")
         && cs.Name != "closed"
         && c.EstimatedDate <= DateTime.Now
         && c.EstimatedDate >= DateTime.Now.AddHours(-1.0) // here was the problem
      group cs by cs.Name into g
      select new
      {
         type = "toexpire",
         statuscounter = g.Count(), 
         statusname = g.Key
       };

The solution was defining the DateTime.Now.AddHours(-1.0) outside the query:

       var estimatedDate = DateTime.Now.AddHours(-1); // here,  outside the query
       var results =
                           from c in skydeskDB.Cases
                            join cs in skydeskDB.CaseStates on c.CaseStateId equals cs.Id
                            where
                                c.HelpDeskId == new Guid("ee98652e-9fdf-435e-b325-74e7189b6561")
                                && cs.Name != "closed"
                                && c.EstimatedDate <= DateTime.Now
                                && c.EstimatedDate >= estimatedDate // here is already calculated
                            group cs by cs.Name into g
                            select new
                            {
                                type = "toexpire",
                                statuscounter = g.Count(), 
                                statusname = g.Key
                            };



Friday, September 20, 2013

MySQL: Get total values from a column

At first I had:

SELECT
COUNT(casestates.id) AS statustotal
, casestates.name AS statusname
FROM
cases
INNER JOIN casestates ON cases.casestateid = casestates.id
WHERE
cases.helpdeskid = 'ee98652e-9fdf-435e-b325-74e7189b6561'
AND casestates.name != 'closed'
GROUP BY
casestates.name

The return was:

-----------------------------------------
| statustotal    | statusname |
-----------------------------------------
|       5           |      New     |
-----------------------------------------
|       18         |      Open    |
-----------------------------------------
|       14         |      Solved  |
-----------------------------------------

Know using Use the ROLLUP and IFNULL clauses:

SELECT
 COUNT(casestates.id) AS statustotal
 ,IFNULL(casestates.name,"Total") AS statusname -- changed here
FROM
 cases
INNER JOIN casestates ON cases.casestateid = casestates.id
WHERE
 cases.helpdeskid = 'ee98652e-9fdf-435e-b325-74e7189b6561'
 AND casestates.name != 'closed'
GROUP BY
 casestates.name
WITH ROLLUP; -- changed here

The return is:

statustotal statusname
-----------------------------------------
| statustotal    | statusname |
-----------------------------------------
|       5           |      New     |
-----------------------------------------
|       18         |      Open    |
-----------------------------------------
|       14         |      Solved  |
-----------------------------------------
|       37         |      Total     |
-----------------------------------------

Resources:

Tuesday, September 10, 2013

Visual Studio 2012: "Analyze Solution for Code Clones" option

Here is an interesting article about Visual Studio 2012  "Analyze Solution for Code Clones" option:

http://blogs.msdn.com/b/jasonsingh/archive/2013/03/21/problems-with-copy-pasting-code.aspx

Visual SVN Server: Visual SVN Server service failed to start:

I was getting:

Visual SVN Server: Visual SVN Server service failed to start: El servicio ha devuelto un error especifico del servicio. (0x8007042a).

Please check VisualSVN Server log in Event Viewer for more details.

So, I checked the Event Viewer and It said:

make_sock: could not bind to address 0.0.0.0:443 (OS 10048) Solo se permite un uso de cada dirección de socket (protocolo/dirección de red/puerto)

The error was that Skype had already initiated and was using the port 443. Skype by default try to use ports 80 or 443. So I killed the skype process and tryed to start Visual SVN Server and everything worked fine.

Then, when you try to start skype, it uses another port and starts correctly.

Resources:


Monday, September 9, 2013

jQuery: jquery-1.10.2.min.map is triggering a 404 (Not Found)

"A source map it's a way to map a combined/minified file back to an unbuilt state. When you build for production, along with minifying and combining your JavaScript files, you generate a source map which holds information about your original files. When you query a certain line and column number in your generated JavaScript you can do a lookup in the source map which returns the original location"

So,you have some options:
1. Stop using the .min.js file and use the .js file (recomended for development environmens)
2. Downlad the .map file and add it to your libs: http://jquery.com/download/ Select the option: "Download the map file for jQuery x.xx.x"
3. Delete, from your .min.js file, the  line:
//@ sourceMappingURL=jquery-1.10.2.min.map 

References:
http://stackoverflow.com/questions/18365315/jquerys-jquery-1-10-2-min-map-is-triggering-a-404-not-found
http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/

backboneJs: "change:[attribute]" event is not firing

add default values  to the model :

var testModel = Backbone.Model.extend({
defaults: {
    "attribute":  ""
  }
});

Wednesday, August 28, 2013

Backbone: Request Method:OPTIONS Status Code:405 Method Not Allowed trying to do a POST request with collection.fetch

I had this code:

this.organizationServicesCollection.url = 'http://localhost/SkyDesk.Services/SrvService.svc/rest/service/queryservices/'        
var fetchParameters = {
data: JSON.stringify({
    parameters: {'key':'value'}
}),
        type: 'POST',
        contentType: 'application/json'
};
this.organizationServicesCollection.fetch(fetchParameters);

when executed I was having two resulting requests:

Request URL:http://localhost/SkyDesk.Services/SrvService.svc/rest/service/queryservices/
Request Method:OPTIONS

Request URL:http://localhost/SkyDesk.Services/SrvService.svc/rest/service/queryservices/
Request Method:POST

The problem was that my current proyect was being run in http://localhost:49998/ instead http://localhost/ so there was a cross domain issue. I fixed it running my project in http://localhost/ , now when running the code I had my single POST request:

Request URL:http://localhost/SkyDesk.Services/SrvService.svc/rest/service/queryservices/
Request Method:POST

Tuesday, August 27, 2013

JSON: Online Json pretty printer

Here is a nice and simple online json pretty printer:
http://jsonprettyprint.com/

Friday, August 23, 2013

Convert epub to pdf

Zamzar is great and a free online file conversion site : http://www.zamzar.com/

Oracle Certified Associate, Java SE 7 Programmer 1Z0-803 Java SE 7 Programmer I : Recommended books

Here are a couple of recommended books to study for the Oracle Certified Associate, Java SE 7 Programmer 1Z0-803 Java SE 7 Programmer I Certification Exam:

OCA Java SE 7 Programmer I Study Guide (Exam 1Z0-803) (Oracle Press)
OCA Java SE 7 Programmer I Certification Guide: Prepare for the 1ZO-803 exam

Java Sockets: Simple client and server example source files

The explanation of the source code is here:
http://docs.oracle.com/javase/tutorial/networking/sockets/

You can donwload the source code here
http://www.oracle.com/technetwork/java/javase/downloads/java-se-7-tutorial-2012-02-28-1536013.html

1. Download and unzip the javatutorials.zip file
2. Go to \javatutorials\tutorial\networking\sockets\examples

Now you can access the source files to run the example.



Jquery: select element by name

Thursday, August 22, 2013

SQL Server 2008: Invalid object name SQL Server 2008 R2

I was getting the error:

Internal Exception: com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name 'TRANSACCION'. Error Code: 208

The problem was that the table wasn't created in the database, you can also verify the name of the table you´re trying to manipulate.

Resources:
http://social.msdn.microsoft.com/Forums/sqlserver/en-US/ec184168-ddd1-4df5-b2c7-c6671b602a3d/string-or-binary-data-would-be-truncated-and-field-specifications

Tuesday, August 13, 2013

SQL Server 2008: Cannot establish a connection. The server sqlexpress is not configured to listen with TCP/IP

I was getting the error:

Cannot establish a connection to jdbc:sqlserver://FEMPUTADORA-PC\SQLEXPRESS;databaseName=pichincha using com.microsoft.sqlserver.jdbc.SQLServerDriver (The server sqlexpress is not configured to listen with TCP/IP.)

I solved it by enabling TCP/IP listen:
1. Run: "start" > "all programs" > "Microsoft SQL server 2008" > "configuration tools" > "SQL Server Configuration Manager"
2. Go to SQL Server Network Configuration > Protocols for SQLEXPRESS.
3. enable TCP/IP.

Reference:
http://stackoverflow.com/questions/11278114/enable-remote-connections-for-sql-server-express-2012

SQL Server 2008: Cannot establish a connection. Verify the server and instance names, check that no firewall is blocking UDP traffic to port 1434, and for SQL Server 2005 or later verify that the SQL Server Browser Service is running on the host

I was getting the error:

Cannot establish a connection to jdbc:sqlserver://FEMPUTADORA-PC\SQLEXPRESS;databaseName=pichincha using com.microsoft.sqlserver.jdbc.SQLServerDriver (The connection to the host FEMPUTADORA-PC, named instance sqlexpress has failed. Error: "java.net.SocketTimeoutException: Receive timed out". Verify the server and instance names, check that no firewall is blocking UDP traffic to port 1434, and for SQL Server 2005 or later verify that the SQL Server Browser Service is running on the host.)

I solved it by enabling the SQL server browser:
1. Go to "start" > "contro panel" > "systems and security" > "administrative tools" > "services"
2. Right click in "SQL server browser" > propeties
3. Set Start up type as "automatic"
4. click on "start"
5. click on "ok"


SQL Server 2008: enable login to sa user

  1. Login using Windows Authentication and ".\SQLExpress" as Server Name
  2. Change server authentication mode - Right click on root, choose Properties, from Security tab select "SQL Server and Windows Authentication mode", click OK 
  3. Set sa password - Navigate to Security > Logins > sa, right click on it, choose Properties, from General tab set the Password (don't close the window) 
  4. Grant permission - Go to Status tab, make sure the Grant and Enabled radiobuttons are chosen, click OK 
  5. Restart SQLEXPRESS service from your local services
Source:

Monday, August 12, 2013

IIS8: Unable to star debugging on the web server

I was getting the followong error:

Unable to start debugging on the web server. The web server could not find the requested resource.

I solved the issue enabling ASP in the IIS:
1. Go to "Start" > "control panel" > "programs" > "Turn windows features on or off"
2. Wait while it loads
3. Enable the option : "Internet Information Services" > "world wide services" > "application development features" > "asp"
4. click "ok"

Sunday, August 4, 2013

Java: Simple sample of socket server using InetAddress

public static void main(String[] args) {
        // TODO code application logic here
        String hostIP = "127.0.0.1";
        InetAddress bindAddr; 
        try {
            bindAddr = InetAddress.getByName(hostIP);
            launchServerSocket(4567, 4568, bindAddr );
        } catch (UnknownHostException e) {
            System.out.println("Unknown Host: " + hostIP);
            e.printStackTrace(); 
        }                
    }
 
    public static void launchServerSocket(int portNumber, int backlog, InetAddress bindAddr ){
        try {
            ServerSocket serverSocket = new ServerSocket(portNumber, backlog, bindAddr);
            System.in.read();// prevent console to be closed
        } 
        catch (IOException e) {
            System.out.println("Could not listen on port: " + portNumber);
            e.printStackTrace();            
        }
    }

OAuth V 2.0 resources

Thursday, July 25, 2013

Javascript: Disable backspace key in browsers

Use:

 $(document).keydown(function (e) {
        var nodeName = e.target.nodeName.toLowerCase();

        if (e.which === 8) {
            if (((nodeName === 'input' && (e.target.type === 'text' || e.target.type === 'email')) ||
            nodeName === 'textarea') && e.target.readOnly == false) {
                // do nothing
            } else {
                e.preventDefault();
            }
        }
    });

Reference:
http://stackoverflow.com/questions/6309693/disabling-backspace-key-works-in-all-browsers-but-ie

OAuth Intro

There are the links of a great and simple intro video to understand OAuth:

 - Part1: http://www.youtube.com/watch?v=LRNg4tDtrkE
 - Part2: http://www.youtube.com/watch?v=2KG05SnAYlE
 - Part3: http://www.youtube.com/watch?v=qPHLsLlQ7Rw
 - Part4: http://www.youtube.com/watch?v=0PvQcLzVGF0

Here is the url with a nice explanation about how auth works:

http://hueniverse.com/oauth/guide/workflow/

Wednesday, July 24, 2013

HTML5: Prevent browser form autofill

You hace to use autocomplete="off" in your form tag:

<form name="form1" id="form1" method="post" autocomplete="off"
      action="http://www.example.com/form.cgi">
      Name: <input type="text" name="text1" /><br/>
      Address: <input type="text" name="text2" /><br/>
      Phone: <input type="text" name="text3" /><br/>
      Password: <input type="password" name="password" /><br/>
     <input type="Submit" name="Submit" value="Submit" />
</form>

Reference:
https://developer.mozilla.org/en-US/docs/Mozilla/How_to_Turn_Off_Form_Autocompletion

Tuesday, July 23, 2013

BackboneJS: click event is being triggered twice

In the view definition I had:

...
...
 // events
    ,events: {
        'click ': 'selectServiceEvent',
        'click a': 'learnMoreLinkEvent'
    }
...
...
,selectServiceEvent: function () {
        this.clickCard(); 
}

But when I was clicking the div generated by de view, the selectServiceEvent function was being triggered twice. The solution was add return false; to the selectServiceEvent function:

,selectServiceEvent: function () {
        this.clickCard(); 
        return false;
}

Monday, July 22, 2013

Google Chrome and WOFF font MIME type warnings

There is a link that explains the situation about the Google Chrome and WOFF font MIME type warnings:

 http://zduck.com/2013/google-chrome-and-woff-font-mime-type-warnings/

IIS7: Resource interpreted as Font but transferred with MIME type application/octet-stream:

With a site hosted in IIS I was getting this warning:

Resource interpreted as Font but transferred with MIME type application/octet-stream: "http://localhost/Website/assets/webfonts/mplus-1c-light-webfont.ttf". index.html:6
Resource interpreted as Font but transferred with MIME type application/octet-stream: "http://localhost/Website/assets/webfonts/mplus-1c-regular-webfont.ttf". index.html:6

The solution is:

1. Open IIS manager
2. Go to MIME types
3. Click on "add..."
4. Fill the fields:
   - File name extension: .woff
   - MIME Type: application/x-font-woff
5. Restart IIS.

References:
http://stackoverflow.com/questions/15521130/google-warning-resource-interpreted-as-font-but-transferred-with-mime-type-appl
http://stackoverflow.com/questions/3594823/mime-type-for-woff-fonts

JQuery: simple slider form

Here is a great and simple sample that shows a form using sliders without using any slider lib, just jquery and jqueryui:

http://webexpedition18.com/articles/how-to-create-a-multi-step-signup-form-with-css3-and-jquery/

Wednesday, July 3, 2013

LINQ: filter by two fields concatenation

When you hava an entiy with FirstName and LastName columns, and you need to filter by fullname, a quick solution is to filter by the fields value concatenation:

var agents = from a in DB.Agents
                                 where a.FirstName.Contains(name) ||
                                       a.LastName.Contains(name) ||
                                       String.Concat(a.FirstName, " ", a.LastName).Contains(name)
                                 select a;



Thursday, June 27, 2013

JPQL: parameter using LIKE clause

Example named query:

    @NamedQuery(
        name = "BismarkPlan.findBismarkPlanByClientIdAndBismarkPlanNameOrBismarkPlanCode"
        ,query  = "SELECT bp FROM BismarkPlan bp"
                    + ", BusinessProposalFormalization bpf"
                    + ", BusinessProposalFormalizationItem bpfi"        
                + " WHERE bpfi.businessProposalFormalizationId = bpf.id"
                    + " AND bpfi.bismarkPlanId = bp.id"
                    + " AND bpf.clientId =:clientId"
                    + " AND (bp.code LIKE :code OR bp.name LIKE :name)"
    )

then calling the query:

Long clientId = 2;
String bismarkPlanCode = "PB";
String bismarkPlanName = "Plan";
        
// TODO: use JPA querybuilder instead of namedqueries
Query query = em.createNamedQuery("BismarkPlan.findBismarkPlanByClientIdAndBismarkPlanNameOrBismarkPlanCode");
query.setParameter("clientId", clientId);
query.setParameter("code", "%" + bismarkPlanCode + "%");
query.setParameter("name", "%" + bismarkPlanName + "%");
List<BismarkPlan> returnList = query.getResultList();

Resource:
http://stackoverflow.com/questions/1341104/parameter-in-like-clause-jpql


XAMPP 1.8.1 Apache 2.4 AH00526: Syntax error ProxyPass worker name (...) too long. Bug

I was getting this error:

AH00526: Syntax error on line 228 of E:/Documents/Dropbox/Programs/windows7/xampp-win32-1.8.1-VC9/xampp/apache/conf/extr
a/httpd-proxy.conf:
ProxyPass worker name (http://localhost:8080/SIBismarkRestServer/webresources/com.expertix.bismark.si.entities.orderrequ
est/) too long

In this link https://issues.apache.org/bugzilla/show_bug.cgi?id=53218 Says that increasing in the mod_proxy.h file the PROXY_WORKER_MAX_NAME_SIZE value from 96 to a number that fits in your workername, ie

from
#define PROXY_WORKER_MAX_NAME_SIZE      96

to
#define PROXY_WORKER_MAX_NAME_SIZE      192

But I continue getting that error, no matter my url http://localhost:8080/SIBismarkRestServer/webresources/com.expertix.bismark.si.entities.orderrequ
est/ was 101 characters

So I had to make my url shorter

Thursday, May 30, 2013

HTML5: Custom attributes

Use data- attribute. The format is "data-*", where "*" is replaced with the desired custom attribute name, then set to the desired string value. For example:

<div id="mydiv" data-brand="toyota" data-model="prius">
   John is very happy with his Toyota Prius, because he saves on gas.
</div>

Reference:
http://www.javascriptkit.com/dhtmltutors/customattributes.shtml

Tuesday, May 28, 2013

Java: convert from Long milliseconds to calendar object

Long myLong = entity.getPurchaseOrderDateMilliseconds();// returns 1369717200000
Timestamp timestamp = new Timestamp(myLong);
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTimeInMillis(timestamp.getTime());        

EXTJS 4.X: showing nested data in grid columns

Here is the response:

{"orderRequest":[
   {
      "detail":"dfvdfvdfv"
      ,"id":"1"
      ,"orderRequestStatus":{"id":"1","name":"registrada solicitud de pedido"}
      ,"orderRequestStatusId":"1"
      ,"purchaseOrderDate":"2013-05-28T00:00:00-05:00"
      ,"purchaseOrderNumber":"dfvdfv"
      ,"requestorName":"dfvd"
      ,"subject":"fv"
},{
   "detail":"wef"
   ,"id":"51"
   ,"orderRequestStatus":{"id":"1","name":"registrada solicitud de pedido"}
   ,"orderRequestStatusId":"1","purchaseOrderDate":"2013-05-28T00:00:00-05:00"
   ,"purchaseOrderNumber":"wef"
   ,"requestorName":"wef"
   ,"subject":"wef"
},{
  "detail":"fv"
   ,"id":"101"
   ,"orderRequestStatus":{"id":"1","name":"registrada solicitud de pedido"}
   ,"orderRequestStatusId":"1"
   ,"purchaseOrderDate":"2013-05-28T00:00:00-05:00"
   ,"purchaseOrderNumber":"dfvd"
   ,"requestorName":"dfvd"
   ,"subject":"fv"}
]}

The model:

Ext.define('WebMonitorClass.model.OrderRequestModel', {
    extend: 'Ext.data.Model',
    fields: [
        {
            name: 'id'
            ,type: 'int'
        },{
            name: 'subject'
            ,type: 'string'
        },{
            name: 'detail'
                ,type: 'string'
        },{
            name: 'requestorName'
                ,type: 'string'
        },{
            name: 'orderRequestStatusName'
            ,type: 'string'
            ,mapping: 'orderRequestStatus.name' // here
        }               
    ]
    ,idProperty: 'id'    
});

Grid panel columns:

columns:[
            {
                text     : 'ID',
                flex     : 1,
                sortable : false,
                width    : 300,
                dataIndex: 'id'
            },
            {
                text     : 'Nombre Solicitante',
                width    : 150,
                sortable : true,
                dataIndex: 'requestorName'
            },{
                text     : 'Resumen',
                width    : 150,
                sortable : true,
                dataIndex: 'subject'
            },{
                text     : 'Detalle',
                width    : 150,
                sortable : true,
                dataIndex: 'detail'
            },{
                text     : 'Estado',
                width    : 150,
                sortable : true,
                dataIndex: 'orderRequestStatusName' // here
            }
        ]

Reference:
http://stackoverflow.com/questions/10500367/extjs-model-fields-with-subfields

EclipseLink: disable caching

To disable caching you have to add the following linen to your persistence.xml file:

<property name="eclipselink.cache.shared.default" value="false"/>

Resource:
http://stackoverflow.com/questions/2809275/disable-caching-in-jpa-eclipselink

Netbeans, JPA, Rest: return attribute object in get response

My  orderRequest entity has the following attributes:

Long id (long)
Long orderRequestStatusId
String detail
Calendar purchaseOrderDate
String purchaseOrderNumber
String requestorName
String subject 
OrderRequestStatus orderRequestStatus

Note that orderRequest.orderRequestStatus is OrderRequestStatus type

Calling the entity get request response I got:

{"orderRequest":
 {"detail":"asdasdasd"
  ,"id":"1"
  ,"orderRequestStatusId":"1"
  ,"purchaseOrderDate":"2013-05-28T00:00:00-05:00"
  ,"purchaseOrderNumber":"sdasasd"
  ,"requestorName":"sdasasd"
  ,"subject":"asdasdasd"}
}

Adding the set and get method in the entity class:

public OrderRequestStatus getOrderRequestStatus() {
        return orderRequestStatus;
    }

    public void setOrderRequestStatus(OrderRequestStatus orderRequestStatus) {
        this.orderRequestStatus = orderRequestStatus;
    }

The get request response now has the orderRequestStatus attribute :

{"orderRequest":
  {"detail":"asdasdasd"
   ,"id":"1"
   ,"orderRequestStatus":
      {"id":"1"
      ,"name":"registrada solicitud de pedido"}
   ,"orderRequestStatusId":"1"
   ,"purchaseOrderDate":"2013-05-28T00:00:00-05:00"
   ,"purchaseOrderNumber":"sdasasd"
   ,"requestorName":"sdasasd"
   ,"subject":"asdasdasd"}
}

Monday, May 27, 2013

Netbeans entity - EclipseLink: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails

I was getting this error:

Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`bismarksi/orders`, CONSTRAINT `FK_Orders_CLIENTID` FOREIGN KEY (`CLIENTID`) REFERENCES `clients` (`ID`))Error Code: 1452Call: INSERT INTO Orders (ID, CLIENTID, MODIFIEDDATE, ORDERSTATUSID, PROJECTID, RECEIPTDATE, SELLERID) VALUES (?, ?, ?, ?, ?, ?, ?)bind => [7 parameters bound]Query: InsertObjectQuery(com.expertix.bismark.si.entities.Order[ id=1 , projectId=1 , orderStatusId=1  ])

I solved the error adding to the entity the set and get method for the clientId Attribute:

   public int getClientId() {
        return clientId;
    }

    public void setClientId(int clientId) {
        this.clientId = clientId;
    }


Javascript: Converting .NET DateTime to Javascript Date Object

User this:

var jsonDate = jqueryCall();  // returns "/Date(1245398693390)/"; 
var re = /-?\d+/; 
var m = re.exec(jsonDate); 
var d = new Date(parseInt(m[0]));

Resource:
http://stackoverflow.com/questions/1016847/converting-net-datetime-to-json

MomentJS: convert from javasript date object to formated String

var myDateObject = new Date();
var myMomentJSFormat = "DD/MM/YYYY hh:mm";
        var myMomentObject = moment(myDateObject);
        // formated using moment.js
        var myMomentObjectFormated = myMomentObject.format(myMomentJSFormat);

Resources:
http://momentjs.com/docs/#/displaying/format/


JPA: handling date, time and timestamp

Here is a great article about handling date, time and timestamp

http://www.developerscrappad.com/228/java/java-ee/ejb3-jpa-dealing-with-date-time-and-timestamp/

Thursday, May 23, 2013

Entity Framework: ono to one relation


Example:

public class User
{
    public int UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }      
    public int BillingAddressId { get; set; }

    public Address BillingAddress { get; set; }

}

public class Address
{
    public int AddressId { get; set; }
    public string Street { get; set; }
    public string City { get; set; }
    public string PostalCode { get; set; }
}

// one user one billing adress
modelBuilder.Entity<User>()
                .HasRequired(a => a.BillingAddress)
                .WithMany()
                .HasForeignKey(u => u.BillingAddressId);

Note: this is not going to generate the unique constraint in the db on  BillingAddressId field

Reference:
http://weblogs.asp.net/manavi/archive/2011/01/23/associations-in-ef-code-first-ctp5-part-3-one-to-one-foreign-key-associations.aspx

NetBeans: RestFul Web Services Tutorial

JPA: Many to one relation

Here is a simple example of a Many to one relation using JPA:

http://ayushsuman.blogspot.com/2010/06/jpa-one-to-many-and-many-to-one.html

Tuesday, May 21, 2013

Monday, May 20, 2013

Jquery: add readonly to HMTL5 input tag

Use attr method:

$('#inputId').attr('readonly', true);

Reference:
http://stackoverflow.com/questions/1306708/add-readonly-to-input-jquery

Microsoft Visual Studio: Unable to start debugging on the web server

Using Microsoft Visual Studio, when you try to run the solution, ff you get the error:

Microsoft Visual Studio: Unable to start debugging on the web server. The web server did not respond in a timely manner.  This may be because another debugger is already attached to the web server.


Just reset IIS using iisreset in a console opened as administrator:






Thursday, May 16, 2013

IIS7.5: “405 method not allowed” for “PUT” method

If you get the “405 method not allowed” for “PUT” method You have to disable the ISS webdav option:

In Windows 7
1. Click on "start"
2. clieck on "Control panel"
3. click on "Programs"
4. click on "Turn windows features on or off" and wait some seconds
5. Disable the option : "Internet Information Services" > "world wide web services" > "Common HTTP Feature"s > "webDAV publishing"
6. Click "ok"

Reference:
http://social.msdn.microsoft.com/Forums/en-US/windowsazure/thread/a22b9e60-8353-40c7-af3e-69a8f18240c1

Jquery: get selected item value of a dropdown - combobox element in jQuery

Use $('#{Id} :selected')

var selectedItem = $('#dropDownId :selected') // selected item object
var selectedItemText = $('#dropDownId :selected').text(); // selection text
var selectedItemId = $('#dropDownId :selected').attr('id'); // selection id

Reference:
http://stackoverflow.com/questions/2780566/to-get-selected-value-of-a-dropdown-select-element-in-jquery

Tuesday, May 14, 2013

HTML5: select tag placeholder

Use the disabled selected property:


<select>
    <option value="" disabled selected>Select your option</option>
    <option value="hurr">Durr</option>
</select>

Reference:
http://stackoverflow.com/questions/5805059/select-placeholder

Monday, May 13, 2013

JQuery: remove content of div

To remove all the content of a div you can use .empty() function:

$('#mydiv').empty();

Reference:
http://stackoverflow.com/questions/652917/in-jquery-want-to-remove-all-html-inside-of-a-div


Wednesday, April 24, 2013

MYSQL: ERROR 1045 (28000): Access denied for user 'user'@'localhost' (using password: YES)

When I was trying to connect to mysql typing :

mysql -h localhost -u user -p

After typing the password I was getting this error:


ERROR 1045 (28000): Access denied for user 'user'@'localhost' (using password: YES)

I resolved that issue changing the user host value from % to localhost i.e using sqlyog:


Thursday, April 18, 2013

Maven Error: No plugin found for prefix 'jetty' in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the repositories

To solve the error:

No plugin found for prefix 'jetty' in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the repositories

Just run this command :

mvn org.mortbay.jetty:jetty-maven-plugin:run

Resource:
http://appfuse.547863.n4.nabble.com/No-plugin-found-for-prefix-jetty-in-the-current-project-td3041024.html

Wednesday, April 17, 2013

Javascript i18next example

Here is a link for great and simple examples using javascript i18next, jsperanto and I10n:

https://github.com/tabacha/javascript-i18n-example

Tuesday, April 16, 2013

IIS7: HTTP Error 404.3 - Not Found The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.

To solve this error:


HTTP Error 404.3 - Not Found
The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.

Follow these steps:


1. Open IIS Manager
2. Display properties for the IIS Server
3. Click MIME Types and then add the JSON extension:
    - File name extension: .json
    - MIME type: application/json
4 . Go back to the properties for IIS Server
5. Click on Handler Mappings
    - Add a script map
    - Request path: *.json
    - Executable: C:\WINDOWS\system32\inetsrv\asp.dll
    - Name: JSON

Reference:
http://www.uipress.com/add-json-handler-support-in-iis-7/#.UW2eibVhUmM

Tuesday, April 2, 2013

Jquery: Change div background color using animate

You cannot use animate to animate colors without jQuery UI. So use

...

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
...
...
...

$( "#effect" ).animate({
          backgroundColor: "#fff",
          width: 240
        }, 1000 );


...
...
Resource:
http://stackoverflow.com/questions/6492418/changing-background-of-a-div-using-jquery
http://jqueryui.com/animate/

Javascript: random number in a given range

// Returns a random integer between min and max
// Using Math.round() will give you a non-uniform distribution!
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

Source:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/random

Javascript: Sort Array of Objects by Field Value


var employees=[]
employees[0]={name:"George", age:32, retiredate:"March 12, 2014"}
employees[1]={name:"Edward", age:17, retiredate:"June 2, 2023"}
employees[2]={name:"Christine", age:58, retiredate:"December 20, 2036"}
employees[3]={name:"Sarah", age:62, retiredate:"April 30, 2020"}

- Sort by employee age


employees.sort(function(a, b){
 return a.age-b.age
})


- Sort by employee name


employees.sort(function(a, b){
 var nameA=a.name.toLowerCase(), nameB=b.name.toLowerCase()
 if (nameA < nameB) //sort string ascending
  return -1 
 if (nameA > nameB)
  return 1
 return 0 //default return value (no sorting)
})


- Sort by employee name



employees.sort(function(a, b){
 var nameA=a.name.toLowerCase(), nameB=b.name.toLowerCase()
 if (nameA < nameB) //sort string ascending
  return -1 

 if (nameA > nameB)
  return 1
 return 0 //default return value (no sorting)
})

- Sort by date (retirement date)

employees.sort(function(a, b){
 var dateA=new Date(a.retiredate), dateB=new Date(b.retiredate)
 return dateA-dateB //sort by date ascending
})

References:
http://www.javascriptkit.com/javatutors/arraysort2.shtml
http://stackoverflow.com/questions/1129216/sorting-objects-in-an-array-by-a-field-value-in-javascript






Tuesday, March 19, 2013

JQuery Autocomplete: event when suggestion is selected

There is an event when suggestion is selected, use the select event:

$("#username").autocomplete({
                            source: availableTags
                            , select: function( event, ui ) {
                                alert("hi");
                            }
                        });

Reference:
http://api.jqueryui.com/autocomplete/#event-select
http://stackoverflow.com/questions/7733315/jquery-autocomplete-event-select

Tuesday, February 19, 2013

Friday, February 15, 2013

Can't find Microsoft.Data.Entity.CTP

If you are trying to add a reference froom .NET Microsoft.Data.Entity.CTP but it is not avaliable in the "Add Reference > .NET" list,

Download the file EF4FeatureCTP3.exe from de following link
http://www.microsoft.com/en-us/download/details.aspx?id=13203

Restart Visual Studio and retry the reference adding and the Microsoft.Data.Entity.CTP will be in the list.

Reference:
http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/762277dc-a3b2-44f5-864a-fb5d3b704845/

Thursday, February 14, 2013

DBVisualizer: The JVM could not be started. The maximum heap size (-Xmx) might be to large or an antivirus or firewall tool could block the execution

If you the the folloging error:

"The JVM could not be started. The maximum heap size (-Xmx) might be to large or an antivirus or firewall tool could block the execution"

Modify the -Xmx value in the dbvis.vmoptions file located in the installation directory for DbVisualizer as follows.

-Xmx512m

or

-Xmx1024m

Save the file and restart DbVisualizer.

Resource:
http://www.dbvis.com/forum/thread.jspa?messageID=10472



Thursday, February 7, 2013

Thursday, January 3, 2013

Spring MVC and NetBeans Rest service from database tutorial: 415 Unsupported Media Type



I was doing the Spring MVC and NetBeans Rest service from database tutorial

http://netbeans.org/kb/docs/websvc/rest.html#rest-spring

But now wanted to consume the service with an ajax request in jquery:

                             var data = {"id":"1","identification":"1010182323","name":"jhon"};

                            $.ajax({                                           
                                                url: "/notes/"
                                                ,type: 'POST'
                                                ,dataType: "json"                                        
                                                ,data: data                                               
                                                ,success: function(data, textStatus, jqXHR){                                                  
                                                },
                                                error: function(jqXHR, textStatus, errorThrown){                                                
                                                }
                                            });


And I was getting the error:

 415 Unsupported Media Type

The solution was specifying the contentType and encoding the data to json:

                                     var data = {"id":"1","identification":"1010182323","name":"jhon"};

                                     $.ajax({                                          
                                                url: "/notes/"
                                                ,type: 'POST'
                                                ,dataType: "json"                                                
                                                ,data: Ext.JSON.encode(data) // here
                                                ,contentType: "application/json" // here                                                
                                                ,success: function(data, textStatus, jqXHR){
                                                },
                                                error: function(jqXHR, textStatus, errorThrown){
                                                }
                                            });

Here is an example of how to use the Ext.JSON.encode method

http://jhonjairoroa87.blogspot.com/2012/10/javascripy-simple-encodedecode-json.html

Resources:
http://docs.oracle.com/cd/E19226-01/820-7627/giepu/index.html
http://www.checkupdown.com/status/E415_es.html
http://stackoverflow.com/questions/9754767/cannot-set-content-type-to-application-json-in-jquery-ajax
http://api.jquery.com/jQuery.ajax/


Javascript: clone array

To clone an array in javascript you can use the slice() method:


var a = [ 'apple', 'orange', 'grape' ];
var b = [];

b = a.slice(0);
b[0] = 'cola';

console.log(a);//[ 'apple', 'orange', 'grape' ]
console.log(b);//[ 'cola', 'orange', 'grape' ]


Resource:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/slice
http://www.xenoveritas.org/blog/xeno/the-correct-way-to-clone-javascript-arrays

Spring MVC and NetBeans Rest service from database tutorial: many to many relationship


I was doing the Spring MVC and NetBeans Rest service from database tutorial

http://netbeans.org/kb/docs/websvc/rest.html#rest-spring

But now I applyied the tutorial to do the REST services to this database:


after finishing all the tutorial applied to the previous database, I test the URL

http://localhost:8080/WebApplication1/webresources/entities.incidents/1

and I got

{"datetime":"2012-12-28T00:00:00-05:00","description":"jIMAExx","id":"1","user":{"id":"2","identification":"1010123223","name":"pedros"}}

But now I wanted to get the categories corresponding to the many to many relationship, so I changed the incidents.java file from:
...
...
...
@XmlTransient
    public Collection<Categories> getCategoriesCollection() {
        return categoriesCollection;
    }

    public void setCategoriesCollection(Collection<Categories> categoriesCollection) {
        this.categoriesCollection = categoriesCollection;
    }
...
...
...
to
...
...
...
// @XmlTransient // Here, I just commented this line
    public Collection<Categories> getCategoriesCollection() {
        return categoriesCollection;
    }

    public void setCategoriesCollection(Collection<Categories> categoriesCollection) {
        this.categoriesCollection = categoriesCollection;
    }
...
...
...
Note that the only thing I did was commenting the @XmlTransient line. Then if I test  the url again I get:

{"categoriesCollection":[{"id":"1","name":"Categoria 1 Jaime"},{"id":"1","name":"Categoria 1 Jaime"},{"id":"1","name":"Categoria 1 Jaime"},{"id":"1","name":"Categoria 1 Jaime"},{"id":"1","name":"Categoria 1 Jaime"}],"datetime":"2012-12-28T00:00:00-05:00","description":"jIMAExx","id":"1","user":{"id":"2","identification":"1010123223","name":"pedros"}}

Wednesday, January 2, 2013

Spring MVC and NetBeans Rest service from database tutorial error: java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor

I was doing the Spring MVC and NetBeans Rest service from database tutorial

http://netbeans.org/kb/docs/websvc/rest.html#rest-spring

When I finished all the steps and tryied to run the project and I got:

nested exception is java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor

the detailed log is:

 Error durante el despliegue: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from ServletContext resource [/WEB-INF/applicationContext.xml]; nested exception is java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor. Consulte server.log para obtener más información.
C:\Users\jroa\Documents\NetBeansProjects\WebApplication1\nbproject\build-impl.xml:1032: The module has not been deployed.
See the server log for details.
BUILD FAILED (total time: 37 seconds)

I fixed it by deleting, from the project library, the aopalliance jar downloaded from http://sourceforge.net/projects/aopalliance/files/aopalliance/1.0/.

and adding, to the project library, the aopalliance jar downloaded from the spring web site
http://ebr.springsource.com/repository/app/bundle/version/detail?name=com.springsource.org.aopalliance&version=1.0.0