Modeling and Optimal Control of Networks of Pipes and Canals