In the portions of Vayeishev and Mikeitz there are many dreams: Joseph's, the chief butler's and chief baker's, and Pharaoh's. All of them were causes that brought about the exile in Egypt — the root of all exiles. Since everything is by Divine Providence, there is a connection between exile and dreams.
What is the connection? As explained in Torah Or, a dream comes from the power of imagination, which can join two opposites — even "an elephant through the eye of a needle". So in exile: a person thinks he loves G-d, and at the same time loves his body and its desires — two things that cannot coexist.
But — do not despair. If after prayer a person behaves the opposite of what he resolved in it, this does not mean that his prayer, Torah and mitzvot are worthless. It is a dream state. And just as a dream comes from a very high place that allows opposites to coexist, so in exile precisely such a lofty place shines. In a dream anything is possible — even good one cannot imagine.
Joseph — a living example: in one moment he went from prisoner to viceroy. "G-d has made me fruitful in the land of my affliction" — precisely in the land of hardship.
And why was the Torah not given before the Egyptian exile? Because precisely in the "iron furnace" of Egypt Israel became vessels to receive the Torah. And at the Giving of the Torah importance was given precisely to the "feet" — each of the 600,000, including the simple people. The foot alludes to accepting the yoke, and through it one connects to "Anochi", G-d's very Essence.
In practice
The hardships of exile are not proof of failure. They are a springboard for growth that would not have been possible any other way.