terça-feira, 17 de dezembro de 2013

BPM Lombardi - How to set option button

Hi!

On the Coach, your gonna select the Custom HTML Control.




After you place the control on the Coach, follow the example bellow.

<script>
    $(document).ready(function() {
    document.getElementById('RadioButtons0_2').checked = true;
    document.getElementById('RadioButtons1_2').checked = true;
    document.getElementById('RadioButtons2_2').checked = true;
    document.getElementById('RadioButtons3_2').checked = true;
   });
</script>


BPM Lombardi - Current date

Hi!



I was looking for the function that would return to me the current date.
It took me two days, until my friend told me that there's no such function.
All you have to do is:

tw.local.yourdatevariable = new TWDate();

After you instantiate your variable, it automatically holds the current date.
It's really not intuitive!

segunda-feira, 9 de dezembro de 2013

BPM Lombardi - How to use variables on properties

Hi!

I was asking myself how to use the variables on the parameter value of document attachment control.

In fact, it's very simple.


Pay attention to the tags <#= and #>. There are no quotes or double quotes. Just write the variable between the tags.

And that's it.

sexta-feira, 6 de dezembro de 2013

BPM Lombardi - Bind dropdownlist with a result from database

Hi!

After a lot of effort, I found out how to bind a drop downlist with the result form a stored procedure.

1 - My store procedure has result of 2 fields

exec BPM_ListarSistema

nomesistema
valor

2 - Declare a private variable with complextype


As you see on the picture bellow , I created the variable lsistema. The type of this private variable is vartypesistema, wich has two parameters: nomesistema and valor. Those two parameters have the same name of the columns that will be sent by the execution of the stored procedure BPM_ListarSistema.
The parameters and the columns from the database must match. Otherwise you'll no be able to do the binding.

lsqlsistema is the variable in wich I'll set the declaration "EXEC BPM_ListarSistema".



3 - Server Script and Nested Service

First of all, you're gonna initialize the variable lsqlsistema.


After that, you're gonna execute the stored procedure. Fort that I used a nested service. The implementation is SQL Call Stored Procedure with return ANY

4 -  Coach

Now, that you already executed the stored procedure and sotored the result in the lsistema variable with complex type vartypesistema, let's do the binding.


Dynamic Binding: tw.local.lsistema[]
Dynamic Binding value: .valor
Dynamic Binding name: .nomesistema

5 - And you are done!



quinta-feira, 28 de novembro de 2013

Bonitasoft x Processmaker

Hi!!

I have recently tested both products (opensource version) Bonitasoft and Processmaker.
In my opinion, Processmaker is easier to learn and is more intuitive. Besides, the opensource version of Processmaker has many more features than Bonitasoft.
So, that's my decision.
If had to decide between the two opensource versions, I would stick with Processmaker.

Há!

sexta-feira, 22 de novembro de 2013

ProcessMaker - final considerations

Hi!



I have just performed a full proof of concept on ProcessMaker BPM application, and I found something really difficult to overcome.
No matter where you are in the application, the columns you can visualize are

#, Summary, Case Notes, Case, Process, Task, Current User, Last Modify, Status

Well, let's think that in your process there are informations like subject, areas, products and so on.
If you try to use the search functionality, you're gonna find out that this very search doesn't include the dynaform fields. Why? My guess is that those fields are stored at XML structure and for this reason it becomes impossible to search on them.
Imagine you have a lot of inbox messages but you can't search on the content and you can't see the subject. You'll have to open all your messages, one by one, to find out what you are looking for.
But isn't possible to add columns that transform the view in a more intuitive experience? Yes, there is. But they are only available at the paid version, U$ 9.900,00 .
In my opinion, the opensource version of ProcessMaker has this huge problem, the search.
Conclusion:
In my scenario, I should say NO to opensource version of ProcessMaker

 Now I'm gonna try the Bonitasoft.

quinta-feira, 21 de novembro de 2013

Using parameters with OledbCommand - Integration Services

In OledbCommand, parameters are indicated by using question marks.

UPDATE PMT_SOLICITACAO
SET APP_STATUS = ?
WHERE APP_UID =  ?







terça-feira, 19 de novembro de 2013

MySQL / Integration Services

How could you use MySQL with Integration Services?

Step1
Download and install a suitable odbc connector to MySQL
http://dev.mysql.com/downloads/connector/odbc/
Be careful with the version.
If your version is 5.1.5, like mine you should download the odbc connector from here http://downloads.mysql.com/archives.php?p=mysql-connector-odbc-5.1&v=5.1.5

Step2
Create a datasource.
Step3
With datasource created, go back do Integration Services and chose DataRead component.




Step4
Drop the DataReader on the Data Flow and chose one of the connections of connection manager.
You're done. You're ready to work with MySQL data.




ProcessMaker - Example of trigger

Hey!

My brand new addiciton is the BPM tool, ProcessMaker.

The definition of the function I'm gonna use:

PMFNewCase()

PMFNewCase() creates a new case starting in the specified task.
variant PMFNewCase(string processId, string userId, string taskId, array variables)


What does this trigger do?

processId = 790924072528a08df8f5a61099702072
userId =  468963623527b95ba2d4f36042887697

Well, my idea was that in the end of a process a new case, of another process would be started for a specific user.
The user will receive in his inbox a case already started with status "to_do". It would be as if he had received an e-mail.

Very simple and very usefull trigger.

$taskId  = '472503662528a09680c7973093755803'; //lookup the starting task's unique ID
$newCaseId = PMFNewCase('790924072528a08df8f5a61099702072', '468963623527b95ba2d4f36042887697', $taskId, array());
//if a new case was created, change its status in the database
if ($newCaseId) {
   executeQuery("UPDATE APPLICATION SET APP_STATUS='TO_DO' WHERE APP_UID='$newCaseId'");
}
else {
   $msg = "Unable to create new case." . isset(@@__ERROR__) ? @@__ERROR__ : '';
   G::SendMessageText($msg, 'ERROR');
}

quarta-feira, 6 de novembro de 2013

How to install OTRS

1 - Install activeperl
Probably like me you don't have activeperl installed on you machine. OTRS uses a specifice version of activeperl : 5.16.3..1603
http://www.activestate.com/activeperl/downloads

2 - Install otrs-3.2.12-win-installer-3.0.2.exe
https://portal.otrs.com/otrs/public.pl?Action=PublicDownloads#
Notice that there's only 32bits version of OTRS, but I installed the solution on a 64bits machine and it worked perfectly.

3 - After finished installation of otrs you'll have to access
http://[your IP]:8080/otrs/install.pl

4 - follow the steps of installation.

terça-feira, 5 de novembro de 2013

Access denied for user 'otrs'@'localhost' (using password: YES) RemoteAddress: ::1 RequestURI: /otrs/index.pl Traceback (10404): Module: Kernel::System::DB::new (OTRS 3.2.12) Line: 225 Module: Kernel::System::Web::InterfaceAgent::Run (OTRS 3.2.12) Line: 140 Module: PerlEx::Precompiler::c_::otrs::otrs::bin::cgi2dbin::index_pl::__ANON__ (unknown version) Line: 41 Module: (eval) (unknown version) Line: 458 Module: PerlEx::Precompiler::Execute (unknown version) Line: 458



Well, I had just finish the installation of OTRS (wich is a software I'l try to use as change management system) when I received this error

Oops! An Error occurred.
 Error Message: Access denied for user 'otrs'@'localhost' (using password: YES)
 Please contact your administrator.
You can Send a bugreport or go back to the previous page.
Error Details
Backend ERROR: OTRS-CGI-10 Perl: 5.16.3 OS: MSWin32 Time: Tue Nov 5 15:30:47 2013 Message: Access denied for user 'otrs'@'localhost' (using password: YES) RemoteAddress: ::1 RequestURI: /otrs/index.pl Traceback (10404): Module: Kernel::System::DB::new (OTRS 3.2.12) Line: 225 Module: Kernel::System::Web::InterfaceAgent::Run (OTRS 3.2.12) Line: 140 Module: PerlEx::Precompiler::c_::otrs::otrs::bin::cgi2dbin::index_pl::__ANON__ (unknown version) Line: 41 Module: (eval) (unknown version) Line: 458 Module: PerlEx::Precompiler::Execute (unknown version) Line: 458

Delightful, isn't it?

Well, how fix it?

1 - Go to command prompt of mysql and give the grant to otrs

mysql> GRANT ALL PRIVILEGES ON *.* TO 'otrs'@'localhost'
-> IDENTIFIED BY 'some_pass' WITH GRANT OPTION;

2 - Be sure it worked.

SHOW GRANTS FOR 'otrs'@'localhost';

restart OTRS.

quinta-feira, 24 de outubro de 2013

Condorcet's paradox

The voting paradox (also known as Condorcet's paradox or the paradox of voting) is a situation noted by the Marquis de Condorcet in the late 18th century, in which collective preferences can be cyclic (i.e. not transitive), even if the preferences of individual voters are not. This is paradoxical, because it means that majority wishes can be in conflict with each other. When this occurs, it is because the conflicting majorities are each made up of different groups of individuals.
For example, suppose we have three candidates, A, B, and C, and that there are three voters with preferences as follows (candidates being listed in decreasing order of preference):
Voter First preference Second preference Third preference
Voter 1 A B C
Voter 2 B C A
Voter 3 C A B

terça-feira, 15 de outubro de 2013

Placing too much reliance on tools


Placing too much reliance on tools—If you listen to the big tool vendors, and even some open source ones, you can buy SOA governance. Just buy their SOA registry and you have a SOA governance solution. Unfortunately, that isn’t the case. Tools can help immensely in applying SOA governance, but they’ll always support the policies that have been designed, the reference architecture that has been defined, and the processes that have been put into place.

IT project failures


In the previous sidebar I used Enron as an example of why governance within a company is needed. IT projects also have a tendency to go seriously wrong if there isn’t a good governance or control mechanism in place. One of the most talked-about examples is the Denver International Airport’s automated baggage system. This baggage system, created for the new airport, was designed to route all the passenger’s bags to and from aircraft without human intervention. Even though this system was eventually completed ($55 million over budget) it didn’t work. The carts that were used to automatically transfer the bags couldn’t cope with sharp corners, sensors lost track of where bags were in the system, and more problems were present in the system.
All this caused the Denver airport to open 16 months late so that the system could be fixed and added a total of $560 million to the cost of the airport. After a couple of years, though, the system was abandoned completely. Another example is the automated fulfillment system developed for Sainsbury’s, a British supermarket. Sainsbury’s wanted a new system for its main distribution center. This barcode-based system was designed to save a huge amount of money and increase efficiency because a lot of human tasks could be automated. In the end though, the system, installed in 2003, failed because of apparent barcode-reading errors. After two years of bug fixing, Sainsbury’s wrote that the system worked as intended.In 2007,  however, the complete system was scrapped. Total write off: £150 million.

segunda-feira, 14 de outubro de 2013

% Failed Projects


SOA/Governance - One of the main reasons governance has become an important part of how a business operates

The Enron scandal

One of the main reasons governance has become an important part of how a business operates is because of the scandals at the beginning of the last decade. The most prominent was the Enron scandal. Enron, which was an energy corporation from Houston, at its peak had a value of $111 billion; a year later it filed for bankruptcy. In the nineties the energy market in California was deregulated, and Enron quickly became
one of the largest energy companies in the United States. But in 2001 investigations were initiated to look into the financial position of Enron, and all kinds of fraudulent practices were discovered. For instance, Enron stored its debts in foreign accounts and used its political influence to raise the price of energy. To makes matters even worse, high-ranking Enron executives sold most of their stock when the shares were at $90, the highest the shares reached. They did this because they knew Enron was accruing massive losses. On the other hand, the public was encouraged to buy Enron stock, which within a few months dropped to 30 cents per share. The Enron executives were charged with bank fraud, securities fraud, wire fraud, money laundering, conspiracy, and insider trading. As a result of the Enron scandal, the federal government passed the Sarbanes-Oxley act (SOX for short), which forces companies to follow a set of policies with regard to reporting information to their investors and mandates that companies have strict internal financial control mechanisms in place.

sexta-feira, 11 de outubro de 2013

XMLDocument - Going through ChildNodes.


This example is really simple.

The taks is to get the books from the XML.

What I did.

1 - I created a internal class called Book.
2 - A declaration of a list of books
3 - The XML we're gonna use.
4 - Instantiating the XMLDocument class.
5 - LoadXML
6 - Using the method GetElementsByTagName. Very usefull to get lists inside XMLs.
7 - A for to go through the items. It's weird that ChildNodes is after Item(0), but that's the way it is.
8 - Each item is a node of nodes. To access each node of a item, you have to use SelectSingleNode.
9 - Fill the class object with the Nodes' values.
10 - Fill the list of books.
11 - End.

using System.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Data;
using System.Collections;

namespace ConsoleApplication1
{
    /// <summary>
    ///
    /// </summary>
    class Program
    {
        class Book
        {
            public Int32 Number = 0;
            public string Name = "";
            public Decimal Price = 0.0M;
        }
        static void Main(string[] args)
        {

            List<Book> lstBooks = new List<Book>();

            string lStrXML = "";
            lStrXML += "<Library>";
            lStrXML += "<Address type='String'>Washington D.C.</Address>";
            lStrXML += "<Books>";
            lStrXML += "<item>";
            lStrXML += "<Number type='Integer'>1</Number>";
            lStrXML += "<Name type='String'>The Game Of Thrones</Name>";
            lStrXML += "<Price type='Decimal'>7.0</Price>";
            lStrXML += "</item>";
            lStrXML += "<item>";
            lStrXML += "<Number type='Integer'>2</Number>";
            lStrXML += "<Name type='String'>Dune</Name>";
            lStrXML += "<Price type='Decimal'>4.0</Price>";
            lStrXML += "</item>";
            lStrXML += "<item>";
            lStrXML += "<Number type='Integer'>3</Number>";
            lStrXML += "<Name type='String'>The Mists Of Avalon</Name>";
            lStrXML += "<Price type='Decimal'>6.0</Price>";
            lStrXML += "</item>";
            lStrXML += "</Books>";
            lStrXML += "</Library>";

            XmlDocument lobj = new XmlDocument();

            lobj.LoadXml(lStrXML);

            XmlNodeList lObjBooks = lobj.GetElementsByTagName("Books");

            foreach (XmlNode lObjXBook in lObjBooks.Item(0).ChildNodes)
            {
                Book lObjBook = new Book();
                Int32.TryParse(lObjXBook.SelectSingleNode("Number").InnerText, out lObjBook.Number);
                lObjBook.Name = lObjXBook.SelectSingleNode("Name").InnerText;
                Decimal.TryParse(lObjXBook.SelectSingleNode("Price").InnerText, out lObjBook.Price);

                lstBooks.Add(lObjBook);
            }

           

        }


    }
}

sexta-feira, 4 de outubro de 2013

Could not find a base address that matches scheme net.tcp for the endpoint with binding NetTcpBinding . The base address schemes are [ http , https ] .

Hi!

If you are receiving this error when you try to access your webservice, something like http://www.you.com/yourservice.svc?wsdl. The solution might be simple.
 

Could not find a base address that matches scheme net.tcp for the endpoint with binding NetTcpBinding . The base address schemes are [ http , https ] .Description : An unhandled exception occurred during the execution of the current web request Please review the stack trace for more information about the error and where it originated in the code .
Exception Details : System.InvalidOperationException : Could not find a base address that matches scheme net.tcp for the endpoint with binding NetTcpBinding . The base address schemes are [ http , https ] .
Source Error :Unhandled exception was generated during the execution of the current web request Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace :
[ InvalidOperationException : Could not find a base address that matches scheme net.tcp for the endpoint with binding NetTcpBinding . The base address schemes are [ http , https ] . ]
   
System.ServiceModel.ServiceHostBase.MakeAbsoluteUri ( Uri relativeOrAbsoluteUri , Binding binding , UriSchemeKeyedCollection baseAddresses ) +12349612
   
System.ServiceModel.Description.ConfigLoader.LoadServiceDescription ( ServiceHostBase host ServiceDescription description , ServiceElement serviceElement , Action ` 1 AddBaseAddress ) +12346965
   
System.ServiceModel.ServiceHostBase.LoadConfigurationSectionInternal ( ConfigLoader configLoader , ServiceDescription description , ServiceElement serviceSection ) +67
   
System.ServiceModel.ServiceHostBase.ApplyConfiguration ( ) +108
   
System.ServiceModel.ServiceHostBase.InitializeDescription ( UriSchemeKeyedCollection baseAddresses ) +192
   
System.ServiceModel.ServiceHost.InitializeDescription (Type serviceType , UriSchemeKeyedCollection baseAddresses ) +49
   
System.ServiceModel.ServiceHost .. ctor (Type serviceType , Uri [ ] baseAddresses ) +151
   
System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost (Type serviceType , Uri [ ] baseAddresses ) +30
   
System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost ( constructorString String , Uri [ ] baseAddresses ) +422
   
System.ServiceModel.HostingManager.CreateService ( String normalizedVirtualPath ) +1461
   
System.ServiceModel.HostingManager.ActivateService ( String normalizedVirtualPath ) +44
   
System.ServiceModel.HostingManager.EnsureServiceAvailable ( String normalizedVirtualPath ) +651
[ ServiceActivationException : Can not activate service ' / Fibra.Barramento.Calculo / Motor.svc ' due to an exception during compilation . The exception message is : Could not find a base address that matches scheme net.tcp for the endpoint with binding NetTcpBinding . The base address schemes are [ http , https ] ..]
   
System.Runtime.AsyncResult.End ( IAsyncResult result ) +688590
   
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End ( IAsyncResult result ) +190
   
System.ServiceModel.Activation.ServiceHttpModule.EndProcessRequest ( IAsyncResult ar) +310694
   
System.Web.AsyncEventExecutionStep.OnAsyncEventCompletion ( IAsyncResult ar) +94



Maybe, all you have to do is enable the protocol. The default protocol is http. Net.tcp must be enabled manually. So, add net.tcp, clicking on advanced settings and that's it.
 



Could not load type System.ServiceModel.Activation.HttpModule assembly System.ServiceModel, Version = 3.0.0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089.

Well, this error took me a lot of time to understand. The message is completely misleading.
In my case the problem was that IIS had two versions of ServiceModel. For some reason the application was trying to load System.ServiceModel.dll version 3.0.0.0 , but was "suprised" by the version 4.0.0.0.
So, what was my solution? I removed the version 3. Did something crash? Not at all. Everything is working fine.
Never had the error again.
Há!


sexta-feira, 27 de setembro de 2013

Very simple way to transform HTML into Excel - MVC3

Hi!

I was wondering about how to transform HTML into Excel format using Razor. I've been searching on the Internet and a came out with the solution showed on picture 1.

1 - Create a view called Report.cshtml

2 - In the controller I created two methods

        public string RenderRazorViewToString(string viewName, object model)
        {
            ViewData.Model = model;
            using (var sw = new StringWriter())
            {
                var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);
                return sw.GetStringBuilder().ToString();
            }
        }


        public ActionResult TerritoriesInExcel(string searchString)
        {
            string lStrSearchString = searchString == null ? "" : searchString; ;
            var myTerritories = (new TerritoriesDAO()).getAll(1, true, lStrSearchString);
            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment;filename=myTerritories.xls");
            Response.ContentType = "application/excel";   

            Response.Write(RenderRazorViewToString("Report",myTerritories));
            Response.End();
            return View(myTerritories);

        }

3 - I have a Index.cshtml in the folder Views

So, the sequence is

Index -> Controller -> Change header response -> Transform Report.cshtml into a string -> make the call -> return to Index.cshtml.

 Two main points: The change that was made to the header of response and the transformation of the view into a string.

Notice that RenderRazorViewToString is a generic function and can be used in whatever context.


picture 1.

References
http://amitpatelit.com/2013/05/22/export-to-excel-in-asp-net-mvc/
http://akinyusufer.blogspot.in/2011/05/razor-render-mvc3-view-render-to-string.html

quarta-feira, 25 de setembro de 2013

Autocomplete - MVC3, RAZOR, LINQ, JQuery

Hi!
This infernal autocomplete took me two days, but I finally made it. Territories is an entity from Northwind schema.

DAO


        public IQueryable<string> getTerritoryDescription(string searchstring)
        {

            NorthwindDataContext lObjND = new NorthwindDataContext();
            var suggestions = from p in lObjND.Territories select p.TerritoryDescription;
            var namelist = suggestions.Where(n => n.ToLower().StartsWith(searchstring.ToLower()));
            return namelist;
        }

CONTROLLER


        public JsonResult AutoCompleteSuggestions(string term)
        {
            var suggestions = (new TerritoriesDAO()).getTerritoryDescription(term);
            var namelist = suggestions.Where(n => n.ToLower().StartsWith(term.ToLower()));
            return Json(namelist, JsonRequestBehavior.AllowGet);
        }

Attention: if you try to use another parameter name instead of term, it will not work. Something like (string searchstring) doesn't work.

VIEW

<script src="../../Scripts/jquery-ui-1.8.11.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.11.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>

<script type="text/javascript">
    $(function () {
        $("#SearchString").autocomplete({
            source: "/Territories/AutocompleteSuggestions",
            minLength: 1  });
    });
</script>

.
.
@using (Html.BeginForm())
{
    <p>
        Find by name: @Html.TextBox("SearchString") 
        <input type="submit" value="Search" /></p>
}


And that's it!

LINQ - Can't use predicate when joining two or more tables

Hi!

Scenario
Imagine that you're trying (like me) to write a "dynamic" where to your select


            var myTerritories = (from te in lObjDC.Territories
                                 join re in lObjDC.Regions
                                     on te.RegionID equals re.RegionID
                                 select new
                                 {
                                     TerritoryID = te.TerritoryID,
                                     TerritoryDescription = te.TerritoryDescription,
                                     RegionDescription = re.RegionDescription
                                 }).Where(w => w.TerritoryDescription.Contains(pStrSearchString));

To accomplish such thing you'll have to use predicate concept.

var predicate = PredicateBuilder.True<Territory>();

The problem is:
When you execute join using link, it's gonna result in a anonymous type of object. But to build a predicate you need to reference an object. So, if I try something like that:

var predicate = PredicateBuilder.True<Territory>();
predicate = predicate.And(e => e.TerritoryDescription.ToLower().Contains(pStrSearchString.ToLower().Trim()));

            var myTerritories = (from te in lObjDC.Territories
                                 join re in lObjDC.Regions
                                     on te.RegionID equals re.RegionID
                                 select new
                                 {
                                     TerritoryID = te.TerritoryID,
                                     TerritoryDescription = te.TerritoryDescription,
                                     RegionDescription = re.RegionDescription
                                 }).Where(predicate );

pStrSearchString - it's a parameter variable from my code which I borrow and wrote here.

I'm gonna receive  a design mode error. Why? Because the predicate is using Territory as reference. But the result of the select is anonymous.

Solution
So if I can't use predicate when it comes to join, what can I do? Well, why don't you create a view v_Territory . The view will resolve the problem. With that in mind, the select will result in something like taht:

var predicate = PredicateBuilder.True<Territory>();
predicate = predicate.And(e => e.TerritoryDescription.ToLower().Contains(pStrSearchString.ToLower().Trim()));

            var myTerritories = lObjDC.Territories.Where(predicate);

Remember that your view will be something like that

select a.TerritoryID, a.TerritoryDescription, b.RegionDescription
from Territories a
join Region b
on a.RegionID = b.RegionID

Why all of this explanation about predicate? If you are a more or less experienced programmer, you already know that dynamic where will be eventually necessary.

If you don't have the class PredicateBuilder built-in. Here is the code:

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;

public static class PredicateBuilder
{
    public static Expression<Func<T, bool>> True<T>() { return f => true; }
    public static Expression<Func<T, bool>> False<T>() { return f => false; }

    public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,
                                                        Expression<Func<T, bool>> expr2)
    {
        var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
        return Expression.Lambda<Func<T, bool>>
              (Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
    }

    public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
                                                         Expression<Func<T, bool>> expr2)
    {
        var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
        return Expression.Lambda<Func<T, bool>>
              (Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
    }
}

terça-feira, 24 de setembro de 2013

MVC3-RAZOR-LINQ :: searchstring appears null - ERROR

There are many examples of AutoComplete funcionality on the internet like this one bellow

This is a typical method of a controler

        public JsonResult AutoCompleteSuggestions(string searchstring)
        {
            var suggestions = (new TerritoriesDAO()).getTerritoryDescription(term);
            var namelist = suggestions.Where(n => n.ToLower().StartsWith(term.ToLower()));
            return Json(namelist, JsonRequestBehavior.AllowGet);
        }

Problem is: when the method is called by the view, search string always comes null.

Debugging on firefox you're gona find out that the parameter name is term. So, if you name it as searchstring, it will always be null. Why this happens? I have no idea.

--
[16:21:27.306] GET http://localhost:3289/Territories/AutocompleteSuggestions?term=w [HTTP/1.1 200 OK 0 ms]

--



Change the parameter name to term and magically the value will appear!

        public JsonResult AutoCompleteSuggestions(string term)
        {
            var suggestions = (new TerritoriesDAO()).getTerritoryDescription(term);
            var namelist = suggestions.Where(n => n.ToLower().StartsWith(term.ToLower()));
            return Json(namelist, JsonRequestBehavior.AllowGet);
        }

segunda-feira, 23 de setembro de 2013

Dynamic OrderBy using LINQ

It took me hours to figure out how to make dynamic orderby, using LINQ. It's not easy at all.
There are a lot of abstraction which almost fried my brain.

So let's do it step by step.

As schema of database I'm using northwind.
The table I'm using is Territory.
But like me, you probably came to the conclusion that using the model created by LINQ through database bind is not a good idea. So, I created a class called TerritoryModel. This class is in the folder RAZOR. That's why you're seeing  RAZOR.Models.TerritoryModel as the type of the IOrderedEnumerable result.

Notice that the result of the method getAll is a IOrderedEnumerable and not a IQueryable, which would be expected.

1 -  Variables to define.

            //The LINQ context
            NorthwindDataContext lObjDC = new NorthwindDataContext();


           
            //The function you'll need to dynamically change the field by which you're going to order your result.
            Func<TerritoryModel, object> selector = null;



           
            //The variable which will receive the result of the ordered result.
            IOrderedEnumerable<TerritoryModel> lMT = null;

2 - Swtich

            //I wrote a very simple switch. This is the part of the program that does the trick of dynamically change the column which will order the table Territory.

            #region Selector
            switch (pIntSortBy)
            {
                case 1:
                        selector = a => a.TerritoryID;
                    break;
                case 2:
                        selector = a => a.TerritoryDescription;
                    break;
                case 3:
                        selector = a => a.RegionDescription;
                    break;
            }


3 - The IQueryable select

            var myTerritories = (from te in lObjDC.Territories
                                 join re in lObjDC.Regions
                                     on te.RegionID equals re.RegionID
                                 select new
                                 {
                                     TerritoryID = te.TerritoryID,
                                     TerritoryDescription = te.TerritoryDescription,
                                     RegionDescription = re.RegionDescription
                                 });

4 -The orderBy. An IOrderedEnumerable result.

            if (pBlnIsAsc)
            {
                lMT = myTerritories.Select(p => new TerritoryModel(p.TerritoryID, p.TerritoryDescription, p.RegionDescription)).OrderBy(selector);
            }
            else
            {
                lMT = myTerritories.Select(p => new TerritoryModel(p.TerritoryID, p.TerritoryDescription, p.RegionDescription)).OrderByDescending(selector);
            }

 Why am'I working with IOrderedEnumerable? Well, in the moment you type OrderBy or OrderByDescending, it stops to be IQueryable and starts to be IOrderedEnumerable.

In the end, we'll have a function like that:

 
        public IOrderedEnumerable<RAZOR.Models.TerritoryModel> getAll(int pIntSortBy, bool pBlnIsAsc)
        {
            NorthwindDataContext lObjDC = new NorthwindDataContext();

            Func<TerritoryModel, object> selector = null;
            IOrderedEnumerable<TerritoryModel> lMT = null;
           
            #region Selector
            switch (pIntSortBy)
            {
                case 1:
                        selector = a => a.TerritoryID;
                    break;
                case 2:
                        selector = a => a.TerritoryDescription;
                    break;
                case 3:
                        selector = a => a.RegionDescription;
                    break;
            }
            #endregion          

            var myTerritories = (from te in lObjDC.Territories
                                 join re in lObjDC.Regions
                                     on te.RegionID equals re.RegionID
                                 select new
                                 {
                                     TerritoryID = te.TerritoryID,
                                     TerritoryDescription = te.TerritoryDescription,
                                     RegionDescription = re.RegionDescription
                                 });

            if (pBlnIsAsc)
            {
                lMT = myTerritories.Select(p => new TerritoryModel(p.TerritoryID, p.TerritoryDescription, p.RegionDescription)).OrderBy(selector);
            }
            else
            {
                lMT = myTerritories.Select(p => new TerritoryModel(p.TerritoryID, p.TerritoryDescription, p.RegionDescription)).OrderByDescending(selector);
            }
           
            return lMT;
        }

Et voilà!

sexta-feira, 20 de setembro de 2013

Can't create new controller, "No model classes are available"

Don't worry.
Rebuild your project after you create model and it will be available to create the view and the controller.
That's it.

Razor editor (sweet)

Online, browser-based editor
RazorPad is hosted online at http://razorpad.net. The online editor provides a
sandbox for you to test out your Razor snippets and see the resulting rendered
output right in your browser.

Stand-alone application
For those who prefer “rich clients,” RazorPad is also available as a small standalone
WPF application that does not require any installation. You can download
the RazorPad WPF application from http://razorpad.codeplex.com.

quinta-feira, 19 de setembro de 2013

LINQ - Join tables and populate model class

Hi!

I was wandering how to join one or more tables and populate my enumerable result with my class model.

My Class Model - TerrytoryModel
Table - Territory, Region

1 - The result of the join is a anonymous enumerable list.
2 - Populate a class with the result.



            var myTerritories = (from te in lObjDC.Territories
                                 join re in lObjDC.Regions
                                     on te.RegionID equals re.RegionID
                                 select new
                                 {
                                     TerritoryID = te.TerritoryID,
                                     TerritoryDescription = te.TerritoryDescription,
                                     RegionDescription = re.RegionDescription
                                 }
                                 ).Select(p => new TerritoryModel(p.TerritoryID, p.TerritoryDescription, p.RegionDescription));



3 - The result of myTerritories is a Enumerable list of TerritoryModel.



PS:
Territory and Region are tables from the Northwind database.

MVC2 - How to change the property of a textbox

Hi!

This is a very simple example of how to change the property of a textobox. The code bellow is related to a EDIT functionality.

                <%: Html.TextBoxFor(model => model.CustomerID, new { @readonly = "true", @disable = "true", size = 5, maxlength = 5, style = "background-color:yellow"})%>

  Very simple. Isn't it?



<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcApplication5.Models.CustomerModel>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Edit
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Edit</h2>

    <% using (Html.BeginForm()) {%>
        <%: Html.ValidationSummary(true) %>
       
        <fieldset>
            <legend>Fields</legend>
           
            <div class="editor-label">
                <%: Html.LabelFor(model => model.CustomerID) %>
            </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.CustomerID, new { @readonly = "true", @disable = "true", size = 5, maxlength = 5, style = "background-color:yellow"})%>                <%: Html.ValidationMessageFor(model => model.CustomerID) %>
            </div>
           
            <div class="editor-label">
                <%: Html.LabelFor(model => model.CompanyName) %>
            </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.CompanyName) %>
                <%: Html.ValidationMessageFor(model => model.CompanyName) %>
            </div>
           
            <p>
                <input type="submit" value="Save" />
            </p>
        </fieldset>

    <% } %>

    <div>
        <%: Html.ActionLink("Back to List", "Index") %>
    </div>

</asp:Content>

Há!

ITILV3 - Day 39


ITIL Service Lifecycle

The ITIL Service Lifecycle is a public framework and standard that defines the five stages that service goes through during its life -

Service Strategy, 
Service Design, 
Service Transition, 
Service Operation, 
and Continual Service Improvement.

All five stages of the ITIL Service Lifecycle are focused on the value the IT services deliver.

Value is the heart of the service concept. A service should always deliver Value to customers.

terça-feira, 17 de setembro de 2013

Retrieving data using LINQ, creating and populating object at the same time

 Hi!

I found this way of create and populate object and, at the same time, retrieve data using LINQ.


        public CustomerModel find(string id)
        {
            DataClasses1DataContext lObjDC = new DataClasses1DataContext();

            var varCustomerModel = lObjDC.Customers.Where(x => x.CustomerID == id).Select(p => new CustomerModel(p.CustomerID, p.CompanyName)).Single();

            return varCustomerModel;
        }

Insert using LINQ

 Hi!

This is a method from a project I'm currently working at.

        public bool insert(string id, string companyName)
        {
            DataClasses1DataContext lObjDC = new DataClasses1DataContext();

            int lCount = lObjDC.Customers.Where(x => x.CustomerID == id).Count();




            //If customer doesn't exist.
            if (lCount == 0)
            {
                Customer lObjCTM = new Customer();
                lObjCTM.CustomerID = id;
                lObjCTM.CompanyName = companyName;
                lObjDC.Customers.InsertOnSubmit(lObjCTM);
                lObjDC.SubmitChanges();

                return true;
            }
            return false;
        }


PS: I should have written an exist method instead of using Count() inside the insert method.

Update using LINQ

 Hi!

This is a method from a project I'm currently working at.

        public void update(string id, string companyName)
        {
            DataClasses1DataContext lObjDC = new DataClasses1DataContext();
            var lObjCustomer = lObjDC.Customers.Where(x => x.CustomerID == id).Single();
            lObjCustomer.CompanyName = companyName;
            lObjCustomer.CustomerID = id;
            lObjDC.SubmitChanges();         
        }

terça-feira, 3 de setembro de 2013

FTP DOS

If you are using windows as an OS you probably have the ftp (file transfer protocol) available for you to use.

How to access it via DOS?

Very simple.

1 - Go to the start window and type cmd

2 - At the DOS prompt type ftp

3 - Open [the ip address of the other computer you want to access]

4 - Type the user

5 - Type the password

6 - You're logged in.




The commands


!               delete          literal         prompt          send
?               debug           ls              put             status
append          dir             mdelete         pwd             trace
ascii           disconnect      mdir            quit            type
bell            get             mget            quote           user
binary          glob            mkdir           recv            verbose
bye             hash            mls             remotehelp
cd              help            mput            rename
close           lcd             open            rmdir


segunda-feira, 2 de setembro de 2013

ITILV3 - Day 38


IT Service Continuity Management (ITSCM)

IT Service Continuity strategy is based on:

1. Risk assessment
2. Business continuity strategy
3. Business Impact Analysis

ITSCM analyzes and controls the risks that could affect IT Services

A risk is a possibility that something bad might happen as a result of something else happening.

Example: If I build a an oceanfront house, there is a risk that a hurricane could destroy it.

Risk Management ensures that:

1 - Operations continue after a major event. (An earthquake?)
2 - Assets (information, facilities and building) are protected.
3 - Workplace is safe for emplyees and customers.

Some times it seems to me that ITIL says, over and over again, the same thing, only changing the order of the words.

quinta-feira, 29 de agosto de 2013

Format of dates ISO 8601 translated to C#

Formatos ISO 8601 (inclui Atom)

    yyyy-MM-ddTHH:mm:ss.SSSZ
    yyyy-MM-ddTHH:mm:ss.SSS
    yyyy-MM-ddTHH:mm:ssZ
    yyyy-MM-ddTHH:mm:ss
    yyyy-MM-ddTHH:mmZ
    yyyy-MM-ddTHH:mm
    yyyy-MM-dd
    yyyy-MM
    yyyy

Translate to C#

    yyyy-MM-ddTHH:mm:ss.fffz
    yyyy-MM-ddTHH:mm:ss.fff
    yyyy-MM-ddTHH:mm:ssz
    yyyy-MM-ddTHH:mm:ss
    yyyy-MM-ddTHH:mmz
    yyyy-MM-ddTHH:mm
    yyyy-MM-dd
    yyyy-MM
    yyyy


yyyy
     The year shown in 4 digits. For example: 2008.
MM
     The month shown in 2 digits. For example, appear as of April 04. If the month is not given, the default is the first month of the year (01).
dd
     The day, shown in 2 digits. For example, appear as new day 09. If the day is not given, the default is the first day of the month (01).
T
     Designates the beginning of the time component of the representation date / time. If the time is not given, it defaults to 00:00:00.000.
HH
     The time shown in 2 digits. For example, 1 pm appear to 13. If the time is not provided, the default is 00.
mm
     The minutes, shown in 2 digits. For example, 15. If the minute is not provided, the default is 00.
ss
     The second, shown in 2 digits. For example, 49. If seconds are not provided, the default is 00.
SSS (for C# fff)
     Milliseconds, shown in 3 digits. For example, 555. If milliseconds are not provided, the default is 000.
Z (for C# z)
     The assignment for the time zone Zulu, which is the allocation and military aviation for GMT (Greenwich Mean Time).

     With ISO 8601, the time zone can also be expressed as moving to plus (+) or minus (-) from time Coordinated Universal Time (UTC) or GMT. For example: 2008-04-13T17 :25:55.123-08: 00. If the time zone is not provided, the default is the time zone in which the JVM is running MashupHub.